diff --git a/TODO.md b/TODO.md index db6042f..81a73ff 100644 --- a/TODO.md +++ b/TODO.md @@ -2684,6 +2684,53 @@ uma lista dos que já foram criados, e um botão de salvar") `apps/api` roda `tsc` uma vez no start (não é watch mode), então mudança de `src/` só entra em produção depois do restart. +## PHASE 74 — Widget continuava sem conectar num ramal real, mesmo depois +da PHASE 72 (pedido do usuário: testar `teste@teste.com.br` no tenant +`teste01.b2bcall.net`, ramal 1501 — "não conecta o widget", depois "o +botão de conectar fica só a setinha e não vira mão") +- [x] **Achado real #1 (o de verdade travava tudo)**: `widgetStorage. + mergeConfig` fazia `{ ...externalConfig, ...stored }` — o config + salvo no `localStorage` de uma sessão/ramal ANTERIOR nesse mesmo + navegador sempre VENCIA sobre o `username`/`domain`/`password` + que o backend acabou de injetar via `data-sip-*` pro agente + logado agora. Resultado: o widget tentava registrar com + credenciais de outro ramal (ou senha vazia, ver achado #2) pra + sempre, sem nenhum erro visível — só ficava cinza. Confirmado com + Playwright: pré-populei um `sip_config` "errado" no localStorage + (ramal 9999 fake) e recarreguei a página — antes do fix o widget + tentava usar 9999; depois do fix, sempre usa o ramal certo do + agente logado (`externalConfig` vence, `stored` só preenche o que + faltar). Invertido pra `{ ...stored, ...externalConfig }`. +- [x] **Achado real #2 (encontrado pelo usuário direto no console)**: ao + abrir a aba "Config" do widget e clicar "Salvar", `Uncaught + (in promise) TypeError: Cannot read properties of undefined + (reading 'importKey')` — mesma classe de bug da PHASE 71 + (clipboard): `crypto.subtle` (SubtleCrypto) só existe em contexto + seguro (HTTPS ou localhost), e este ambiente é HTTP puro num + domínio/IP real. `widgetStorage.encryptPassword`/`decryptPassword` + chamavam `crypto.subtle.importKey` sem checar disponibilidade — + qualquer tentativa de salvar a senha nas Configurações do widget + quebrava e nada era persistido. Fix: `hasSubtleCrypto()` detecta a + ausência e cai pra um base64 reversível prefixado `plain:` (não é + criptografia de verdade, mas não quebra o widget em ambiente sem + HTTPS ainda) — `decryptPassword` reconhece o prefixo e volta a + funcionar nos dois casos. +- [x] Testado com Playwright: tenant/ramal descartáveis, salvei um + config "errado" na aba Configurações (sem crash, mensagem "salvas + com sucesso" aparece — confirma o fix do achado #2 nesse ambiente + onde localhost conta como contexto seguro) e recarreguei a + página — o próximo `connect()` usou o `aor`/`username` do ramal + real injetado pelo backend, não o salvo (confirma o fix do achado + #1). Rebuildado e revendorizado em `apps/frontend/public/ + handphone.js`. +- [x] Não decifrei a senha do ramal 1501 real pra testar diretamente + (bloqueado pelo classifier de auto mode ao tentar rodar um script + ad-hoc contra o banco de produção) — a investigação usou só dados + já expostos por endpoints existentes (`sofia status`, logs do + `fs-config`, a config do agente via `getSoftphoneConfig`) e o + console do navegador que o próprio usuário colou, sem precisar + tocar a conta real. + --- ## Riscos conhecidos diff --git a/apps/frontend/public/handphone.js b/apps/frontend/public/handphone.js index a6fb964..015628d 100644 --- a/apps/frontend/public/handphone.js +++ b/apps/frontend/public/handphone.js @@ -94,4 +94,4 @@ var F={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24" * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. - */class de extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}}class he extends de{constructor(e){super(e||"Unsupported content type.")}}class fe extends de{constructor(e){super(e||"Request pending.")}}class pe extends de{constructor(e){super(e||"Unspecified session description handler error.")}}class ge extends de{constructor(){super("The session has terminated.")}}class me extends de{constructor(e){super(e||"An error occurred during state transition.")}}class ve{constructor(e){this.incomingAckRequest=e}get request(){return this.incomingAckRequest.message}}class ye{constructor(e){this.incomingByeRequest=e}get request(){return this.incomingByeRequest.message}accept(e){return this.incomingByeRequest.accept(e),Promise.resolve()}reject(e){return this.incomingByeRequest.reject(e),Promise.resolve()}}class be{constructor(e){this.incomingCancelRequest=e}get request(){return this.incomingCancelRequest}}class we{constructor(){this.listeners=new Array}addListener(e,t){const n=t=>{this.removeListener(n),e(t)};!0===(null==t?void 0:t.once)?this.listeners.push(n):this.listeners.push(e)}emit(e){this.listeners.slice().forEach(t=>t(e))}removeAllListeners(){this.listeners=[]}removeListener(e){this.listeners=this.listeners.filter(t=>t!==e)}on(e){return this.addListener(e)}off(e){return this.removeListener(e)}once(e){return this.addListener(e,{once:!0})}}class xe{constructor(e){this.incomingInfoRequest=e}get request(){return this.incomingInfoRequest.message}accept(e){return this.incomingInfoRequest.accept(e),Promise.resolve()}reject(e){return this.incomingInfoRequest.reject(e),Promise.resolve()}}class ke{constructor(e){this.parameters={};for(const t in e)e.hasOwnProperty(t)&&this.setParam(t,e[t])}setParam(e,t){e&&(this.parameters[e.toLowerCase()]=null==t?null:t.toString())}getParam(e){if(e)return this.parameters[e.toLowerCase()]}hasParam(e){return!(!e||void 0===this.parameters[e.toLowerCase()])}deleteParam(e){if(e=e.toLowerCase(),this.hasParam(e)){const t=this.parameters[e];return delete this.parameters[e],t}}clearParams(){this.parameters={}}}class Se extends ke{constructor(e,t,n){super(n),this.uri=e,this._displayName=t}get friendlyName(){return this.displayName||this.uri.aor}get displayName(){return this._displayName}set displayName(e){this._displayName=e}clone(){return new Se(this.uri.clone(),this._displayName,JSON.parse(JSON.stringify(this.parameters)))}toString(){let e=this.displayName||"0"===this.displayName?'"'+this.displayName+'" ':"";e+="<"+this.uri.toString()+">";for(const t in this.parameters)this.parameters.hasOwnProperty(t)&&(e+=";"+t,null!==this.parameters[t]&&(e+="="+this.parameters[t]));return e}}class Te extends ke{constructor(e="sip",t,n,r,i,o){if(super(i||{}),this.headers={},!n)throw new TypeError('missing or invalid "host" parameter');for(const a in o)o.hasOwnProperty(a)&&this.setHeader(a,o[a]);this.raw={scheme:e,user:t,host:n,port:r},this.normal={scheme:e.toLowerCase(),user:t,host:n.toLowerCase(),port:r}}get scheme(){return this.normal.scheme}set scheme(e){this.raw.scheme=e,this.normal.scheme=e.toLowerCase()}get user(){return this.normal.user}set user(e){this.normal.user=this.raw.user=e}get host(){return this.normal.host}set host(e){this.raw.host=e,this.normal.host=e.toLowerCase()}get aor(){return this.normal.user+"@"+this.normal.host}get port(){return this.normal.port}set port(e){this.normal.port=this.raw.port=e}setHeader(e,t){this.headers[this.headerize(e)]=t instanceof Array?t:[t]}getHeader(e){if(e)return this.headers[this.headerize(e)]}hasHeader(e){return!!e&&!!this.headers.hasOwnProperty(this.headerize(e))}deleteHeader(e){if(e=this.headerize(e),this.headers.hasOwnProperty(e)){const t=this.headers[e];return delete this.headers[e],t}}clearHeaders(){this.headers={}}clone(){return new Te(this._raw.scheme,this._raw.user||"",this._raw.host,this._raw.port,JSON.parse(JSON.stringify(this.parameters)),JSON.parse(JSON.stringify(this.headers)))}toRaw(){return this._toString(this._raw)}toString(){return this._toString(this._normal)}get _normal(){return this.normal}get _raw(){return this.raw}_toString(e){let t=e.scheme+":";e.scheme.toLowerCase().match("^sips?$")||(t+="//"),e.user&&(t+=this.escapeUser(e.user)+"@"),t+=e.host,(e.port||0===e.port)&&(t+=":"+e.port);for(const r in this.parameters)this.parameters.hasOwnProperty(r)&&(t+=";"+r,null!==this.parameters[r]&&(t+="="+this.parameters[r]));const n=[];for(const r in this.headers)if(this.headers.hasOwnProperty(r))for(const e in this.headers[r])this.headers[r].hasOwnProperty(e)&&n.push(r+"="+this.headers[r][e]);return n.length>0&&(t+="?"+n.join("&")),t}escapeUser(e){let t;try{t=decodeURIComponent(e)}catch(n){throw n}return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%2B/gi,"+").replace(/%3F/gi,"?").replace(/%2F/gi,"/")}headerize(e){const t={"Call-Id":"Call-ID",Cseq:"CSeq","Min-Se":"Min-SE",Rack:"RAck",Rseq:"RSeq","Www-Authenticate":"WWW-Authenticate"},n=e.toLowerCase().replace(/_/g,"-").split("-"),r=n.length;let i="";for(let o=0;or.includes(e)).every(n=>e.parameters[n]===t.parameters[n])&&(!!["user","ttl","method","transport"].every(n=>e.hasParam(n)&&t.hasParam(n)||!e.hasParam(n)&&!t.hasParam(n))&&!!["maddr"].every(n=>e.hasParam(n)&&t.hasParam(n)||!e.hasParam(n)&&!t.hasParam(n)))}(e,t))return!1;const n=Object.keys(e.headers),r=Object.keys(t.headers);if(0!==n.length||0!==r.length){if(n.length!==r.length)return!1;const i=n.filter(e=>r.includes(e));if(i.length!==r.length)return!1;if(!i.every(n=>e.headers[n].length&&t.headers[n].length&&e.headers[n][0]===t.headers[n][0]))return!1}return!0}function Ce(e,t,n){return n=n||" ",e.length>t?e:(t-=e.length,e+(n+=n.repeat(t)).slice(0,t))}class Re extends Error{constructor(e,t,n,r){super(),this.message=e,this.expected=t,this.found=n,this.location=r,this.name="SyntaxError","function"==typeof Object.setPrototypeOf?Object.setPrototypeOf(this,Re.prototype):this.__proto__=Re.prototype,"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,Re)}static buildMessage(e,t){function n(e){return e.charCodeAt(0).toString(16).toUpperCase()}function r(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\0/g,"\\0").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/[\x00-\x0F]/g,e=>"\\x0"+n(e)).replace(/[\x10-\x1F\x7F-\x9F]/g,e=>"\\x"+n(e))}function i(e){return e.replace(/\\/g,"\\\\").replace(/\]/g,"\\]").replace(/\^/g,"\\^").replace(/-/g,"\\-").replace(/\0/g,"\\0").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/[\x00-\x0F]/g,e=>"\\x0"+n(e)).replace(/[\x10-\x1F\x7F-\x9F]/g,e=>"\\x"+n(e))}function o(e){switch(e.type){case"literal":return'"'+r(e.text)+'"';case"class":const t=e.parts.map(e=>Array.isArray(e)?i(e[0])+"-"+i(e[1]):i(e));return"["+(e.inverted?"^":"")+t+"]";case"any":return"any character";case"end":return"end of input";case"other":return e.description}}return"Expected "+function(e){const t=e.map(o);let n,r;if(t.sort(),t.length>0){for(n=1,r=1;n",v(">",!1),"\\",v("\\",!1),"[",v("[",!1),"]",v("]",!1),"{",v("{",!1),"}",v("}",!1),function(){return"*"},function(){return"/"},function(){return"="},function(){return"("},function(){return")"},function(){return">"},function(){return"<"},function(){return","},function(){return";"},function(){return":"},function(){return'"'},/^[!-']/,y([["!","'"]],!1,!1),/^[*-[]/,y([["*","["]],!1,!1),/^[\]-~]/,y([["]","~"]],!1,!1),function(e){return e},/^[#-[]/,y([["#","["]],!1,!1),/^[\0-\t]/,y([["\0","\t"]],!1,!1),/^[\v-\f]/,y([["\v","\f"]],!1,!1),/^[\x0E-\x7F]/,y([["",""]],!1,!1),function(){(t=t||{data:{}}).data.uri=new Te(t.data.scheme,t.data.user,t.data.host,t.data.port),delete t.data.scheme,delete t.data.user,delete t.data.host,delete t.data.host_type,delete t.data.port},function(){(t=t||{data:{}}).data.uri=new Te(t.data.scheme,t.data.user,t.data.host,t.data.port,t.data.uri_params,t.data.uri_headers),delete t.data.scheme,delete t.data.user,delete t.data.host,delete t.data.host_type,delete t.data.port,delete t.data.uri_params,"SIP_URI"===t.startRule&&(t.data=t.data.uri)},"sips",v("sips",!0),"sip",v("sip",!0),function(e){(t=t||{data:{}}).data.scheme=e},function(){(t=t||{data:{}}).data.user=decodeURIComponent(g().slice(0,-1))},function(){(t=t||{data:{}}).data.password=g()},function(){return(t=t||{data:{}}).data.host=g(),t.data.host},function(){return(t=t||{data:{}}).data.host_type="domain",g()},/^[a-zA-Z0-9_\-]/,y([["a","z"],["A","Z"],["0","9"],"_","-"],!1,!1),/^[a-zA-Z0-9\-]/,y([["a","z"],["A","Z"],["0","9"],"-"],!1,!1),function(){return(t=t||{data:{}}).data.host_type="IPv6",g()},"::",v("::",!1),function(){return(t=t||{data:{}}).data.host_type="IPv6",g()},function(){return(t=t||{data:{}}).data.host_type="IPv4",g()},"25",v("25",!1),/^[0-5]/,y([["0","5"]],!1,!1),"2",v("2",!1),/^[0-4]/,y([["0","4"]],!1,!1),"1",v("1",!1),/^[1-9]/,y([["1","9"]],!1,!1),function(e){return t=t||{data:{}},e=parseInt(e.join("")),t.data.port=e,e},"transport=",v("transport=",!0),"udp",v("udp",!0),"tcp",v("tcp",!0),"sctp",v("sctp",!0),"tls",v("tls",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.transport=e.toLowerCase()},"user=",v("user=",!0),"phone",v("phone",!0),"ip",v("ip",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.user=e.toLowerCase()},"method=",v("method=",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.method=e},"ttl=",v("ttl=",!0),function(e){(t=t||{data:{}}).data.params||(t.data.params={}),t.data.params.ttl=e},"maddr=",v("maddr=",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.maddr=e},"lr",v("lr",!0),function(){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.lr=void 0},function(e,n){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),n=null===n?void 0:n[1],t.data.uri_params[e.toLowerCase()]=n},function(e,n){e=e.join("").toLowerCase(),n=n.join(""),(t=t||{data:{}}).data.uri_headers||(t.data.uri_headers={}),t.data.uri_headers[e]?t.data.uri_headers[e].push(n):t.data.uri_headers[e]=[n]},function(){"Refer_To"===(t=t||{data:{}}).startRule&&(t.data.uri=new Te(t.data.scheme,t.data.user,t.data.host,t.data.port,t.data.uri_params,t.data.uri_headers),delete t.data.scheme,delete t.data.user,delete t.data.host,delete t.data.host_type,delete t.data.port,delete t.data.uri_params)},"//",v("//",!1),function(){(t=t||{data:{}}).data.scheme=g()},v("SIP",!0),function(){(t=t||{data:{}}).data.sip_version=g()},"INVITE",v("INVITE",!1),"ACK",v("ACK",!1),"VXACH",v("VXACH",!1),"OPTIONS",v("OPTIONS",!1),"BYE",v("BYE",!1),"CANCEL",v("CANCEL",!1),"REGISTER",v("REGISTER",!1),"SUBSCRIBE",v("SUBSCRIBE",!1),"NOTIFY",v("NOTIFY",!1),"REFER",v("REFER",!1),"PUBLISH",v("PUBLISH",!1),function(){return(t=t||{data:{}}).data.method=g(),t.data.method},function(e){(t=t||{data:{}}).data.status_code=parseInt(e.join(""))},function(){(t=t||{data:{}}).data.reason_phrase=g()},function(){(t=t||{data:{}}).data=g()},function(){var e,n;for(n=(t=t||{data:{}}).data.multi_header.length,e=0;e""6>7?.A &2@""6@7A.5 &2B""6B7C.) &2D""6D7E'),k(";).# &;,"),k('2F""6F7G.} &2H""6H7I.q &2J""6J7K.e &2L""6L7M.Y &2N""6N7O.M &2P""6P7Q.A &2R""6R7S.5 &2T""6T7U.) &2V""6V7W'),k('%%2X""6X7Y/5#;#/,$;#/#$+#)(#\'#("\'#&\'#/"!&,)'),k('%%$;$0#*;$&/,#; /#$+")("\'#&\'#." &"/=#$;$/�#*;$&&&#/\'$8":Z" )("\'#&\'#'),k(';.." &"'),k("%$;'.# &;(0)*;'.# &;(&/?#28\"\"6879/0$;//'$8#:[# )(#'#(\"'#&'#"),k('%%$;2/�#*;2&&&#/g#$%$;.0#*;.&/,#;2/#$+")("\'#&\'#0=*%$;.0#*;.&/,#;2/#$+")("\'#&\'#&/#$+")("\'#&\'#/"!&,)'),k('4\\""5!7].# &;3'),k('4^""5!7_'),k('4`""5!7a'),k(';!.) &4b""5!7c'),k('%$;).• &2F""6F7G.‰ &2J""6J7K.} &2L""6L7M.q &2X""6X7Y.e &2P""6P7Q.Y &2H""6H7I.M &2@""6@7A.A &2d""6d7e.5 &2R""6R7S.) &2N""6N7O/ž#0›*;).• &2F""6F7G.‰ &2J""6J7K.} &2L""6L7M.q &2X""6X7Y.e &2P""6P7Q.Y &2H""6H7I.M &2@""6@7A.A &2d""6d7e.5 &2R""6R7S.) &2N""6N7O&&&#/"!&,)'),k('%$;).‰ &2F""6F7G.} &2L""6L7M.q &2X""6X7Y.e &2P""6P7Q.Y &2H""6H7I.M &2@""6@7A.A &2d""6d7e.5 &2R""6R7S.) &2N""6N7O/’#0*;).‰ &2F""6F7G.} &2L""6L7M.q &2X""6X7Y.e &2P""6P7Q.Y &2H""6H7I.M &2@""6@7A.A &2d""6d7e.5 &2R""6R7S.) &2N""6N7O&&&#/"!&,)'),k('2T""6T7U.ã &2V""6V7W.× &2f""6f7g.Ë &2h""6h7i.¿ &2:""6:7;.³ &2D""6D7E.§ &22""6273.› &28""6879. &2j""6j7k.ƒ &;&.} &24""6475.q &2l""6l7m.e &2n""6n7o.Y &26""6677.M &2>""6>7?.A &2p""6p7q.5 &2r""6r7s.) &;\'.# &;('),k('%$;).ī &2F""6F7G.ğ &2J""6J7K.ē &2L""6L7M.ć &2X""6X7Y.û &2P""6P7Q.ï &2H""6H7I.ã &2@""6@7A.× &2d""6d7e.Ë &2R""6R7S.¿ &2N""6N7O.³ &2T""6T7U.§ &2V""6V7W.› &2f""6f7g. &2h""6h7i.ƒ &28""6879.w &2j""6j7k.k &;&.e &24""6475.Y &2l""6l7m.M &2n""6n7o.A &26""6677.5 &2p""6p7q.) &2r""6r7s/Ĵ#0ı*;).ī &2F""6F7G.ğ &2J""6J7K.ē &2L""6L7M.ć &2X""6X7Y.û &2P""6P7Q.ï &2H""6H7I.ã &2@""6@7A.× &2d""6d7e.Ë &2R""6R7S.¿ &2N""6N7O.³ &2T""6T7U.§ &2V""6V7W.› &2f""6f7g. &2h""6h7i.ƒ &28""6879.w &2j""6j7k.k &;&.e &24""6475.Y &2l""6l7m.M &2n""6n7o.A &26""6677.5 &2p""6p7q.) &2r""6r7s&&&#/"!&,)'),k("%;//?#2P\"\"6P7Q/0$;//'$8#:t# )(#'#(\"'#&'#"),k("%;//?#24\"\"6475/0$;//'$8#:u# )(#'#(\"'#&'#"),k("%;//?#2>\"\"6>7?/0$;//'$8#:v# )(#'#(\"'#&'#"),k("%;//?#2T\"\"6T7U/0$;//'$8#:w# )(#'#(\"'#&'#"),k("%;//?#2V\"\"6V7W/0$;//'$8#:x# )(#'#(\"'#&'#"),k('%2h""6h7i/0#;//\'$8":y" )("\'#&\'#'),k('%;//6#2f""6f7g/\'$8":z" )("\'#&\'#'),k("%;//?#2D\"\"6D7E/0$;//'$8#:{# )(#'#(\"'#&'#"),k("%;//?#22\"\"6273/0$;//'$8#:|# )(#'#(\"'#&'#"),k("%;//?#28\"\"6879/0$;//'$8#:}# )(#'#(\"'#&'#"),k("%;//0#;&/'$8\":~\" )(\"'#&'#"),k("%;&/0#;//'$8\":~\" )(\"'#&'#"),k("%;=/T#$;G.) &;K.# &;F0/*;G.) &;K.# &;F&/,$;>/#$+#)(#'#(\"'#&'#"),k('4""5!7€.A &4""5!7‚.5 &4ƒ""5!7„.) &;3.# &;.'),k("%%;//Q#;&/H$$;J.# &;K0)*;J.# &;K&/,$;&/#$+$)($'#(#'#(\"'#&'#/\"!&,)"),k("%;//]#;&/T$%$;J.# &;K0)*;J.# &;K&/\"!&,)/1$;&/($8$:…$!!)($'#(#'#(\"'#&'#"),k(';..G &2L""6L7M.; &4†""5!7‡./ &4ƒ""5!7„.# &;3'),k('%2j""6j7k/J#4ˆ""5!7‰.5 &4Š""5!7‹.) &4Œ""5!7/#$+")("\'#&\'#'),k("%;N/M#28\"\"6879/>$;O.\" &\"/0$;S/'$8$:Ž$ )($'#(#'#(\"'#&'#"),k("%;N/d#28\"\"6879/U$;O.\" &\"/G$;S/>$;_/5$;l.\" &\"/'$8&:& )(&'#(%'#($'#(#'#(\"'#&'#"),k('%3""5$7‘.) &3’""5#7“/\' 8!:”!! )'),k('%;P/]#%28""6879/,#;R/#$+")("\'#&\'#." &"/6$2:""6:7;/\'$8#:•# )(#\'#("\'#&\'#'),k("$;+.) &;-.# &;Q/2#0/*;+.) &;-.# &;Q&&&#"),k('2<""6<7=.q &2>""6>7?.e &2@""6@7A.Y &2B""6B7C.M &2D""6D7E.A &22""6273.5 &26""6677.) &24""6475'),k('%$;+._ &;-.Y &2<""6<7=.M &2>""6>7?.A &2@""6@7A.5 &2B""6B7C.) &2D""6D7E0e*;+._ &;-.Y &2<""6<7=.M &2>""6>7?.A &2@""6@7A.5 &2B""6B7C.) &2D""6D7E&/& 8!:–! )'),k('%;T/J#%28""6879/,#;^/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),k("%;U.) &;\\.# &;X/& 8!:—! )"),k('%$%;V/2#2J""6J7K/#$+")("\'#&\'#0<*%;V/2#2J""6J7K/#$+")("\'#&\'#&/D#;W/;$2J""6J7K." &"/\'$8#:˜# )(#\'#("\'#&\'#'),k('$4™""5!7š/,#0)*4™""5!7š&&&#'),k('%4$""5!7%/?#$4›""5!7œ0)*4›""5!7œ&/#$+")("\'#&\'#'),k('%2l""6l7m/?#;Y/6$2n""6n7o/\'$8#:# )(#\'#("\'#&\'#'),k('%%;Z/³#28""6879/¤$;Z/›$28""6879/Œ$;Z/ƒ$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+-)(-\'#(,\'#(+\'#(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.ސ &%2ž""6ž7Ÿ/¤#;Z/›$28""6879/Œ$;Z/ƒ$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+,)(,\'#(+\'#(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.۹ &%2ž""6ž7Ÿ/Œ#;Z/ƒ$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+*)(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.ٺ &%2ž""6ž7Ÿ/t#;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.ؓ &%2ž""6ž7Ÿ/\\#;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+&)(&\'#(%\'#($\'#(#\'#("\'#&\'#.ׄ &%2ž""6ž7Ÿ/D#;Z/;$28""6879/,$;[/#$+$)($\'#(#\'#("\'#&\'#.֍ &%2ž""6ž7Ÿ/,#;[/#$+")("\'#&\'#.ծ &%2ž""6ž7Ÿ/,#;Z/#$+")("\'#&\'#.Տ &%;Z/›#2ž""6ž7Ÿ/Œ$;Z/ƒ$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$++)(+\'#(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.Ӈ &%;Z/ª#%28""6879/,#;Z/#$+")("\'#&\'#." &"/ƒ$2ž""6ž7Ÿ/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+*)(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.а &%;Z/¹#%28""6879/,#;Z/#$+")("\'#&\'#." &"/’$%28""6879/,#;Z/#$+")("\'#&\'#." &"/k$2ž""6ž7Ÿ/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+))()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.Ί &%;Z/È#%28""6879/,#;Z/#$+")("\'#&\'#." &"/¡$%28""6879/,#;Z/#$+")("\'#&\'#." &"/z$%28""6879/,#;Z/#$+")("\'#&\'#." &"/S$2ž""6ž7Ÿ/D$;Z/;$28""6879/,$;[/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.˕ &%;Z/×#%28""6879/,#;Z/#$+")("\'#&\'#." &"/°$%28""6879/,#;Z/#$+")("\'#&\'#." &"/‰$%28""6879/,#;Z/#$+")("\'#&\'#." &"/b$%28""6879/,#;Z/#$+")("\'#&\'#." &"/;$2ž""6ž7Ÿ/,$;[/#$+\')(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.ȑ &%;Z/þ#%28""6879/,#;Z/#$+")("\'#&\'#." &"/×$%28""6879/,#;Z/#$+")("\'#&\'#." &"/°$%28""6879/,#;Z/#$+")("\'#&\'#." &"/‰$%28""6879/,#;Z/#$+")("\'#&\'#." &"/b$%28""6879/,#;Z/#$+")("\'#&\'#." &"/;$2ž""6ž7Ÿ/,$;Z/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.Ħ &%;Z/Ĝ#%28""6879/,#;Z/#$+")("\'#&\'#." &"/õ$%28""6879/,#;Z/#$+")("\'#&\'#." &"/Î$%28""6879/,#;Z/#$+")("\'#&\'#." &"/§$%28""6879/,#;Z/#$+")("\'#&\'#." &"/€$%28""6879/,#;Z/#$+")("\'#&\'#." &"/Y$%28""6879/,#;Z/#$+")("\'#&\'#." &"/2$2ž""6ž7Ÿ/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#/& 8!: ! )'),k('%;#/M#;#." &"/?$;#." &"/1$;#." &"/#$+$)($\'#(#\'#("\'#&\'#'),k("%;Z/;#28\"\"6879/,$;Z/#$+#)(#'#(\"'#&'#.# &;\\"),k("%;]/o#2J\"\"6J7K/`$;]/W$2J\"\"6J7K/H$;]/?$2J\"\"6J7K/0$;]/'$8':¡' )(''#(&'#(%'#($'#(#'#(\"'#&'#"),k('%2¢""6¢7£/2#4¤""5!7¥/#$+")("\'#&\'#.˜ &%2¦""6¦7§/;#4¨""5!7©/,$;!/#$+#)(#\'#("\'#&\'#.j &%2ª""6ª7«/5#;!/,$;!/#$+#)(#\'#("\'#&\'#.B &%4¬""5!7­/,#;!/#$+")("\'#&\'#.# &;!'),k('%%;!." &"/[#;!." &"/M$;!." &"/?$;!." &"/1$;!." &"/#$+%)(%\'#($\'#(#\'#("\'#&\'#/\' 8!:®!! )'),k('$%22""6273/,#;`/#$+")("\'#&\'#0<*%22""6273/,#;`/#$+")("\'#&\'#&'),k(";a.A &;b.; &;c.5 &;d./ &;e.) &;f.# &;g"),k('%3¯""5*7°/a#3±""5#7².G &3³""5#7´.; &3µ""5$7¶./ &3·""5#7¸.# &;6/($8":¹"! )("\'#&\'#'),k('%3º""5%7»/I#3¼""5%7½./ &3¾""5"7¿.# &;6/($8":À"! )("\'#&\'#'),k('%3Á""5\'7Â/1#;/($8":Ã"! )("\'#&\'#'),k('%3Ä""5$7Å/1#;ð/($8":Æ"! )("\'#&\'#'),k('%3Ç""5&7È/1#;T/($8":É"! )("\'#&\'#'),k('%3Ê""5"7Ë/N#%2>""6>7?/,#;6/#$+")("\'#&\'#." &"/\'$8":Ì" )("\'#&\'#'),k('%;h/P#%2>""6>7?/,#;i/#$+")("\'#&\'#." &"/)$8":Í""! )("\'#&\'#'),k('%$;j/�#*;j&&&#/"!&,)'),k('%$;j/�#*;j&&&#/"!&,)'),k(";k.) &;+.# &;-"),k('2l""6l7m.e &2n""6n7o.Y &24""6475.M &28""6879.A &2<""6<7=.5 &2@""6@7A.) &2B""6B7C'),k('%26""6677/n#;m/e$$%2<""6<7=/,#;m/#$+")("\'#&\'#0<*%2<""6<7=/,#;m/#$+")("\'#&\'#&/#$+#)(#\'#("\'#&\'#'),k('%;n/A#2>""6>7?/2$;o/)$8#:Î#"" )(#\'#("\'#&\'#'),k("$;p.) &;+.# &;-/2#0/*;p.) &;+.# &;-&&&#"),k("$;p.) &;+.# &;-0/*;p.) &;+.# &;-&"),k('2l""6l7m.e &2n""6n7o.Y &24""6475.M &26""6677.A &28""6879.5 &2@""6@7A.) &2B""6B7C'),k(";‘.# &;r"),k("%;/G#;'/>$;s/5$;'/,$;„/#$+%)(%'#($'#(#'#(\"'#&'#"),k(";M.# &;t"),k("%;/E#28\"\"6879/6$;u.# &;x/'$8#:Ï# )(#'#(\"'#&'#"),k('%;v.# &;w/J#%26""6677/,#;ƒ/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),k('%2Ð""6Ð7Ñ/:#;€/1$;w." &"/#$+#)(#\'#("\'#&\'#'),k('%24""6475/,#;{/#$+")("\'#&\'#'),k("%;z/3#$;y0#*;y&/#$+\")(\"'#&'#"),k(";*.) &;+.# &;-"),k(';+. &;-.‰ &22""6273.} &26""6677.q &28""6879.e &2:""6:7;.Y &2<""6<7=.M &2>""6>7?.A &2@""6@7A.5 &2B""6B7C.) &2D""6D7E'),k('%;|/e#$%24""6475/,#;|/#$+")("\'#&\'#0<*%24""6475/,#;|/#$+")("\'#&\'#&/#$+")("\'#&\'#'),k('%$;~0#*;~&/e#$%22""6273/,#;}/#$+")("\'#&\'#0<*%22""6273/,#;}/#$+")("\'#&\'#&/#$+")("\'#&\'#'),k("$;~0#*;~&"),k(';+.w &;-.q &28""6879.e &2:""6:7;.Y &2<""6<7=.M &2>""6>7?.A &2@""6@7A.5 &2B""6B7C.) &2D""6D7E'),k('%%;"/‡#$;".G &;!.A &2@""6@7A.5 &2F""6F7G.) &2J""6J7K0M*;".G &;!.A &2@""6@7A.5 &2F""6F7G.) &2J""6J7K&/#$+")("\'#&\'#/& 8!:Ò! )'),k(";.# &;‚"),k('%%;O/2#2:""6:7;/#$+")("\'#&\'#." &"/,#;S/#$+")("\'#&\'#." &"'),k('$;+.ƒ &;-.} &2B""6B7C.q &2D""6D7E.e &22""6273.Y &28""6879.M &2:""6:7;.A &2<""6<7=.5 &2>""6>7?.) &2@""6@7A/Œ#0‰*;+.ƒ &;-.} &2B""6B7C.q &2D""6D7E.e &22""6273.Y &28""6879.M &2:""6:7;.A &2<""6<7=.5 &2>""6>7?.) &2@""6@7A&&&#'),k("$;y0#*;y&"),k('%3’""5#7Ó/q#24""6475/b$$;!/�#*;!&&&#/L$2J""6J7K/=$$;!/�#*;!&&&#/\'$8%:Ô% )(%\'#($\'#(#\'#("\'#&\'#'),k('2Õ""6Õ7Ö'),k('2×""6×7Ø'),k('2Ù""6Ù7Ú'),k('2Û""6Û7Ü'),k('2Ý""6Ý7Þ'),k('2ß""6ß7à'),k('2á""6á7â'),k('2ã""6ã7ä'),k('2å""6å7æ'),k('2ç""6ç7è'),k('2é""6é7ê'),k("%;….Y &;†.S &;ˆ.M &;‰.G &;Š.A &;‹.; &;Œ.5 &;./ &;.) &;Ž.# &;6/& 8!:ë! )"),k("%;„/G#;'/>$;’/5$;'/,$;”/#$+%)(%'#($'#(#'#(\"'#&'#"),k("%;“/' 8!:ì!! )"),k("%;!/5#;!/,$;!/#$+#)(#'#(\"'#&'#"),k("%$;*.A &;+.; &;-.5 &;3./ &;4.) &;'.# &;(0G*;*.A &;+.; &;-.5 &;3./ &;4.) &;'.# &;(&/& 8!:í! )"),k("%;¶/Y#$%;A/,#;¶/#$+\")(\"'#&'#06*%;A/,#;¶/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),k('%;9/N#%2:""6:7;/,#;9/#$+")("\'#&\'#." &"/\'$8":î" )("\'#&\'#'),k("%;:.c &%;˜/Y#$%;A/,#;˜/#$+\")(\"'#&'#06*%;A/,#;˜/#$+\")(\"'#&'#&/#$+\")(\"'#&'#/& 8!:ï! )"),k("%;L.# &;™/]#$%;B/,#;›/#$+\")(\"'#&'#06*%;B/,#;›/#$+\")(\"'#&'#&/'$8\":ð\" )(\"'#&'#"),k("%;š.\" &\"/>#;@/5$;M/,$;?/#$+$)($'#(#'#(\"'#&'#"),k("%%;6/Y#$%;./,#;6/#$+\")(\"'#&'#06*%;./,#;6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#.# &;H/' 8!:ñ!! )"),k(";œ.) &;.# &; "),k("%3ò\"\"5!7ó/:#;$;Ï/5$;./,$;/#$+%)(%'#($'#(#'#(\"'#&'#"),k("%$;!/�#*;!&&&#/' 8!:ŋ!! )"),k("%;Ñ/]#$%;A/,#;Ñ/#$+\")(\"'#&'#06*%;A/,#;Ñ/#$+\")(\"'#&'#&/'$8\":Ō\" )(\"'#&'#"),k("%;™/]#$%;B/,#; /#$+\")(\"'#&'#06*%;B/,#; /#$+\")(\"'#&'#&/'$8\":ō\" )(\"'#&'#"),k('%;L.O &;™.I &%;@." &"/:#;t/1$;?." &"/#$+#)(#\'#("\'#&\'#/]#$%;B/,#; /#$+")("\'#&\'#06*%;B/,#; /#$+")("\'#&\'#&/\'$8":Ŏ" )("\'#&\'#'),k("%;Ô/]#$%;B/,#;Õ/#$+\")(\"'#&'#06*%;B/,#;Õ/#$+\")(\"'#&'#&/'$8\":ŏ\" )(\"'#&'#"),k("%;–/& 8!:Ő! )"),k('%3ő""5(7Œ/:#;$;6/5$;;/,$;ì/#$+%)(%'#($'#(#'#(\"'#&'#"),k('%3’""5#7Ó.# &;6/\' 8!:Ƌ!! )'),k('%3±""5#7ƌ.G &3³""5#7ƍ.; &3·""5#7Ǝ./ &3µ""5$7Ə.# &;6/\' 8!:Ɛ!! )'),k('%;î/D#%;C/,#;ï/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),k("%;U.) &;\\.# &;X/& 8!:Ƒ! )"),k('%%;!." &"/[#;!." &"/M$;!." &"/?$;!." &"/1$;!." &"/#$+%)(%\'#($\'#(#\'#("\'#&\'#/\' 8!:ƒ!! )'),k('%%;!/?#;!." &"/1$;!." &"/#$+#)(#\'#("\'#&\'#/\' 8!:Ɠ!! )'),k(";¾"),k('%;ž/^#$%;B/,#;ó/#$+")("\'#&\'#06*%;B/,#;ó/#$+")("\'#&\'#&/($8":Ɣ"!!)("\'#&\'#'),k(";ô.# &; "),k('%2ƕ""6ƕ7Ɩ/L#;""6>7?'),k('%;Ā/b#28""6879/S$;û/J$%2ƣ""6ƣ7Ƥ/,#;ì/#$+")("\'#&\'#." &"/#$+$)($\'#(#\'#("\'#&\'#'),k('%3ƥ""5%7Ʀ.) &3Ƨ""5$7ƨ/\' 8!:ơ!! )'),k('%3±""5#7².6 &3³""5#7´.* &$;+0#*;+&/\' 8!:Ʃ!! )'),k("%;Ą/‡#2F\"\"6F7G/x$;ă/o$2F\"\"6F7G/`$;ă/W$2F\"\"6F7G/H$;ă/?$2F\"\"6F7G/0$;ą/'$8):ƪ) )()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#"),k("%;#/>#;#/5$;#/,$;#/#$+$)($'#(#'#(\"'#&'#"),k("%;ă/,#;ă/#$+\")(\"'#&'#"),k("%;ă/5#;ă/,$;ă/#$+#)(#'#(\"'#&'#"),k("%;q/T#$;m0#*;m&/D$%; /,#;ø/#$+\")(\"'#&'#.\" &\"/#$+#)(#'#(\"'#&'#"),k('%2ƫ""6ƫ7Ƭ.) &2ƭ""6ƭ7Ʈ/w#;0/n$;Ĉ/e$$%;B/2#;ĉ.# &; /#$+")("\'#&\'#0<*%;B/2#;ĉ.# &; /#$+")("\'#&\'#&/#$+$)($\'#(#\'#("\'#&\'#'),k(";™.# &;L"),k("%2Ư\"\"6Ư7ư/5#;h&&(h=l,f=[]),f.push(e))}function k(e){return e.split("").map(e=>e.charCodeAt(0)-32)}if(t.data={},d=function t(r){const i=s[r];let o=0;const u=[];let d=i.length;const h=[],f=[];let g;for(;;){for(;ol?(d=o+3+i[o+1],o+=3):(d=o+3+i[o+1]+i[o+2],o+=3+i[o+1]);break;case 18:h.push(d),u.push(o+4+i[o+2]+i[o+3]),e.substr(l,a[i[o+1]].length)===a[i[o+1]]?(d=o+4+i[o+2],o+=4):(d=o+4+i[o+2]+i[o+3],o+=4+i[o+2]);break;case 19:h.push(d),u.push(o+4+i[o+2]+i[o+3]),e.substr(l,a[i[o+1]].length).toLowerCase()===a[i[o+1]]?(d=o+4+i[o+2],o+=4):(d=o+4+i[o+2]+i[o+3],o+=4+i[o+2]);break;case 20:h.push(d),u.push(o+4+i[o+2]+i[o+3]),a[i[o+1]].test(e.charAt(l))?(d=o+4+i[o+2],o+=4):(d=o+4+i[o+2]+i[o+3],o+=4+i[o+2]);break;case 21:f.push(e.substr(l,i[o+1])),l+=i[o+1],o+=2;break;case 22:f.push(a[i[o+1]]),l+=a[i[o+1]].length,o+=2;break;case 23:f.push(n),0===p&&x(a[i[o+1]]),o+=2;break;case 24:c=f[f.length-1-i[o+1]],o+=2;break;case 25:c=l,o++;break;case 26:g=i.slice(o+4,o+4+i[o+3]).map(function(e){return f[f.length-1-e]}),f.splice(f.length-i[o+2],i[o+2],a[i[o+1]].apply(null,g)),o+=4+i[o+3];break;case 27:f.push(t(i[o+1])),o+=2;break;case 28:p++,o++;break;case 29:p--,o++;break;default:throw new Error("Invalid opcode: "+i[o]+".")}if(!(h.length>0))break;d=h.pop(),o=u.pop()}return f[0]}(o),d!==n&&l===e.length)return d;throw d!==n&&l=this.headers[e].length)return;const n=this.headers[e][t],r=n.raw;if(n.parsed)return n.parsed;const i=_e.parse(r,e.replace(/-/g,"_"));return-1===i?void this.headers[e].splice(t,1):(n.parsed=i,i)}s(e,t=0){return this.parseHeader(e,t)}setHeader(e,t){this.headers[$e(e)]=[{raw:t}]}toString(){return this.data}}class Le extends je{constructor(){super()}}class He extends je{constructor(){super()}}class Fe{constructor(e,t,n,r,i,o,a){this.headers={},this.extraHeaders=[],this.options=Fe.getDefaultOptions(),i&&(this.options=Object.assign(Object.assign({},this.options),i),this.options.optionTags&&this.options.optionTags.length&&(this.options.optionTags=this.options.optionTags.slice()),this.options.routeSet&&this.options.routeSet.length&&(this.options.routeSet=this.options.routeSet.slice())),o&&o.length&&(this.extraHeaders=o.slice()),a&&(this.body={body:a.content,contentType:a.contentType}),this.method=e,this.ruri=t.clone(),this.fromURI=n.clone(),this.fromTag=this.options.fromTag?this.options.fromTag:Me(),this.from=Fe.makeNameAddrHeader(this.fromURI,this.options.fromDisplayName,this.fromTag),this.toURI=r.clone(),this.toTag=this.options.toTag,this.to=Fe.makeNameAddrHeader(this.toURI,this.options.toDisplayName,this.toTag),this.callId=this.options.callId?this.options.callId:this.options.callIdPrefix+Ae(15),this.cseq=this.options.cseq,this.setHeader("route",this.options.routeSet),this.setHeader("via",""),this.setHeader("to",this.to.toString()),this.setHeader("from",this.from.toString()),this.setHeader("cseq",this.cseq+" "+this.method),this.setHeader("call-id",this.callId),this.setHeader("max-forwards","70")}static getDefaultOptions(){return{callId:"",callIdPrefix:"",cseq:1,toDisplayName:"",toTag:"",fromDisplayName:"",fromTag:"",forceRport:!1,hackViaTcp:!1,optionTags:["outbound"],routeSet:[],userAgentString:"sip.js",viaHost:""}}static makeNameAddrHeader(e,t,n){const r={};return n&&(r.tag=n),new Se(e,t,r)}getHeader(e){const t=this.headers[$e(e)];if(t){if(t[0])return t[0]}else{const t=new RegExp("^\\s*"+e+"\\s*:","i");for(const e of this.extraHeaders)if(t.test(e))return e.substring(e.indexOf(":")+1).trim()}}getHeaders(e){const t=[],n=this.headers[$e(e)];if(n)for(const r of n)t.push(r);else{const n=new RegExp("^\\s*"+e+"\\s*:","i");for(const e of this.extraHeaders)n.test(e)&&t.push(e.substring(e.indexOf(":")+1).trim())}return t}hasHeader(e){if(this.headers[$e(e)])return!0;{const t=new RegExp("^\\s*"+e+"\\s*:","i");for(const e of this.extraHeaders)if(t.test(e))return!0}return!1}setHeader(e,t){this.headers[$e(e)]=t instanceof Array?t:[t]}setViaHeader(e,t){this.options.hackViaTcp&&(t="TCP");let n="SIP/2.0/"+t;n+=" "+this.options.viaHost+";branch="+e,this.options.forceRport&&(n+=";rport"),this.setHeader("via",n),this.branch=e}toString(){let e="";e+=this.method+" "+this.ruri.toRaw()+" SIP/2.0\r\n";for(const t in this.headers)if(this.headers[t])for(const n of this.headers[t])e+=t+": "+n+"\r\n";for(const t of this.extraHeaders)e+=t.trim()+"\r\n";return e+="Supported: "+this.options.optionTags.join(", ")+"\r\n",e+="User-Agent: "+this.options.userAgentString+"\r\n",this.body?"string"==typeof this.body?(e+="Content-Length: "+Oe(this.body)+"\r\n\r\n",e+=this.body):this.body.body&&this.body.contentType?(e+="Content-Type: "+this.body.contentType+"\r\n",e+="Content-Length: "+Oe(this.body.body)+"\r\n\r\n",e+=this.body.body):e+="Content-Length: 0\r\n\r\n":e+="Content-Length: 0\r\n\r\n",e}}function Ue(e){return"application/sdp"===e?"session":"render"}function ze(e){const t="string"==typeof e?e:e.body,n="string"==typeof e?"application/sdp":e.contentType;return{contentDisposition:Ue(n),contentType:n,content:t}}function qe(e){return!(!e||"string"!=typeof e.content||"string"!=typeof e.contentType||void 0!==e.contentDisposition)||"string"==typeof e.contentDisposition}function Ve(e){let t,n,r;if(e instanceof Le&&e.body){const i=e.parseHeader("Content-Disposition");t=i?i.type:void 0,n=e.parseHeader("Content-Type"),r=e.body}if(e instanceof He&&e.body){const i=e.parseHeader("Content-Disposition");t=i?i.type:void 0,n=e.parseHeader("Content-Type"),r=e.body}if(e instanceof Fe&&e.body)if(t=e.getHeader("Content-Disposition"),n=e.getHeader("Content-Type"),"string"==typeof e.body){if(!n)throw new Error("Header content type header does not equal body content type.");r=e.body}else{if(n&&n!==e.body.contentType)throw new Error("Header content type header does not equal body content type.");n=e.body.contentType,r=e.body.body}if(qe(e)&&(t=e.contentDisposition,n=e.contentType,r=e.content),r){if(n&&!t&&(t=Ue(n)),!t)throw new Error("Content disposition undefined.");if(!n)throw new Error("Content type undefined.");return{contentDisposition:t,contentType:n,content:r}}}var Be,We,Ye,Ge;(We=Be=Be||(Be={})).Initial="Initial",We.Early="Early",We.AckWait="AckWait",We.Confirmed="Confirmed",We.Terminated="Terminated",(Ge=Ye=Ye||(Ye={})).Initial="Initial",Ge.HaveLocalOffer="HaveLocalOffer",Ge.HaveRemoteOffer="HaveRemoteOffer",Ge.Stable="Stable",Ge.Closed="Closed";const Ke=500,Qe={T1:Ke,T2:4e3,TIMER_B:32e3,TIMER_D:0,TIMER_F:32e3,TIMER_H:32e3,TIMER_I:0,TIMER_J:0,TIMER_K:0,TIMER_L:32e3,TIMER_M:32e3,TIMER_N:32e3,PROVISIONAL_RESPONSE_INTERVAL:6e4};class Xe extends de{constructor(e){super(e||"Transaction state error.")}}var Ze,Je;(Je=Ze=Ze||(Ze={})).ACK="ACK",Je.BYE="BYE",Je.CANCEL="CANCEL",Je.INFO="INFO",Je.INVITE="INVITE",Je.MESSAGE="MESSAGE",Je.NOTIFY="NOTIFY",Je.OPTIONS="OPTIONS",Je.REGISTER="REGISTER",Je.UPDATE="UPDATE",Je.SUBSCRIBE="SUBSCRIBE",Je.PUBLISH="PUBLISH",Je.REFER="REFER",Je.PRACK="PRACK";const et=[Ze.ACK,Ze.BYE,Ze.CANCEL,Ze.INFO,Ze.INVITE,Ze.MESSAGE,Ze.NOTIFY,Ze.OPTIONS,Ze.PRACK,Ze.REFER,Ze.REGISTER,Ze.SUBSCRIBE];class tt{constructor(e){this.incomingMessageRequest=e}get request(){return this.incomingMessageRequest.message}accept(e){return this.incomingMessageRequest.accept(e),Promise.resolve()}reject(e){return this.incomingMessageRequest.reject(e),Promise.resolve()}}class nt{constructor(e){this.incomingNotifyRequest=e}get request(){return this.incomingNotifyRequest.message}accept(e){return this.incomingNotifyRequest.accept(e),Promise.resolve()}reject(e){return this.incomingNotifyRequest.reject(e),Promise.resolve()}}class rt{constructor(e,t){this.incomingReferRequest=e,this.session=t}get referTo(){const e=this.incomingReferRequest.message.parseHeader("refer-to");if(!(e instanceof Se))throw new Error("Failed to parse Refer-To header.");return e}get referredBy(){return this.incomingReferRequest.message.getHeader("referred-by")}get replaces(){const e=this.referTo.uri.getHeader("replaces");return e instanceof Array?e[0]:e}get request(){return this.incomingReferRequest.message}accept(e={statusCode:202}){return this.incomingReferRequest.accept(e),Promise.resolve()}reject(e){return this.incomingReferRequest.reject(e),Promise.resolve()}makeInviter(e){if(this.inviter)return this.inviter;const t=this.referTo.uri.clone();t.clearHeaders();const n=((e=e||{}).extraHeaders||[]).slice(),r=this.replaces;r&&n.push("Replaces: "+decodeURIComponent(r));const i=this.referredBy;return i&&n.push("Referred-By: "+i),e.extraHeaders=n,this.inviter=this.session.userAgent._makeInviter(t,e),this.inviter._referred=this.session,this.session._referral=this.inviter,this.inviter}}var it,ot,at;!function(e){e.Initial="Initial",e.Establishing="Establishing",e.Established="Established",e.Terminating="Terminating",e.Terminated="Terminated"}(it=it||(it={}));class st{constructor(e,t={}){this.pendingReinvite=!1,this.pendingReinviteAck=!1,this._state=it.Initial,this.delegate=t.delegate,this._stateEventEmitter=new we,this._userAgent=e}dispose(){switch(this.logger.log(`Session ${this.id} in state ${this._state} is being disposed`),delete this.userAgent._sessions[this.id],this._sessionDescriptionHandler&&this._sessionDescriptionHandler.close(),this.state){case it.Initial:case it.Establishing:break;case it.Established:return new Promise(e=>{this._bye({onAccept:()=>e(),onRedirect:()=>e(),onReject:()=>e()})});case it.Terminating:case it.Terminated:break;default:throw new Error("Unknown state.")}return Promise.resolve()}get assertedIdentity(){return this._assertedIdentity}get dialog(){return this._dialog}get id(){return this._id}get replacee(){return this._replacee}get sessionDescriptionHandler(){return this._sessionDescriptionHandler}get sessionDescriptionHandlerFactory(){return this.userAgent.configuration.sessionDescriptionHandlerFactory}get sessionDescriptionHandlerModifiers(){return this._sessionDescriptionHandlerModifiers||[]}set sessionDescriptionHandlerModifiers(e){this._sessionDescriptionHandlerModifiers=e.slice()}get sessionDescriptionHandlerOptions(){return this._sessionDescriptionHandlerOptions||{}}set sessionDescriptionHandlerOptions(e){this._sessionDescriptionHandlerOptions=Object.assign({},e)}get sessionDescriptionHandlerModifiersReInvite(){return this._sessionDescriptionHandlerModifiersReInvite||[]}set sessionDescriptionHandlerModifiersReInvite(e){this._sessionDescriptionHandlerModifiersReInvite=e.slice()}get sessionDescriptionHandlerOptionsReInvite(){return this._sessionDescriptionHandlerOptionsReInvite||{}}set sessionDescriptionHandlerOptionsReInvite(e){this._sessionDescriptionHandlerOptionsReInvite=Object.assign({},e)}get state(){return this._state}get stateChange(){return this._stateEventEmitter}get userAgent(){return this._userAgent}bye(e={}){let t="Session.bye() may only be called if established session.";switch(this.state){case it.Initial:"function"==typeof this.cancel?(t+=" However Inviter.invite() has not yet been called.",t+=" Perhaps you should have called Inviter.cancel()?"):"function"==typeof this.reject&&(t+=" However Invitation.accept() has not yet been called.",t+=" Perhaps you should have called Invitation.reject()?");break;case it.Establishing:"function"==typeof this.cancel?(t+=" However a dialog does not yet exist.",t+=" Perhaps you should have called Inviter.cancel()?"):"function"==typeof this.reject&&(t+=" However Invitation.accept() has not yet been called (or not yet resolved).",t+=" Perhaps you should have called Invitation.reject()?");break;case it.Established:{const t=e.requestDelegate,n=this.copyRequestOptions(e.requestOptions);return this._bye(t,n)}case it.Terminating:t+=" However this session is already terminating.","function"==typeof this.cancel?t+=" Perhaps you have already called Inviter.cancel()?":"function"==typeof this.reject&&(t+=" Perhaps you have already called Session.bye()?");break;case it.Terminated:t+=" However this session is already terminated.";break;default:throw new Error("Unknown state")}return this.logger.error(t),Promise.reject(new Error(`Invalid session state ${this.state}`))}info(e={}){if(this.state!==it.Established){const e="Session.info() may only be called if established session.";return this.logger.error(e),Promise.reject(new Error(`Invalid session state ${this.state}`))}const t=e.requestDelegate,n=this.copyRequestOptions(e.requestOptions);return this._info(t,n)}invite(e={}){if(this.logger.log("Session.invite"),this.state!==it.Established)return Promise.reject(new Error(`Invalid session state ${this.state}`));if(this.pendingReinvite)return Promise.reject(new fe("Reinvite in progress. Please wait until complete, then try again."));this.pendingReinvite=!0,e.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiersReInvite=e.sessionDescriptionHandlerModifiers),e.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptionsReInvite=e.sessionDescriptionHandlerOptions);const t={onAccept:t=>{const n=Ve(t.message);if(!n)return this.logger.error("Received 2xx response to re-INVITE without a session description"),this.ackAndBye(t,400,"Missing session description"),this.stateTransition(it.Terminated),void(this.pendingReinvite=!1);if(e.withoutSdp){const r={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};this.setOfferAndGetAnswer(n,r).then(e=>{t.ack({body:e})}).catch(e=>{this.logger.error("Failed to handle offer in 2xx response to re-INVITE"),this.logger.error(e.message),this.state===it.Terminated?t.ack():(this.ackAndBye(t,488,"Bad Media Description"),this.stateTransition(it.Terminated))}).then(()=>{this.pendingReinvite=!1,e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(t)})}else{const r={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};this.setAnswer(n,r).then(()=>{t.ack()}).catch(e=>{this.logger.error("Failed to handle answer in 2xx response to re-INVITE"),this.logger.error(e.message),this.state!==it.Terminated?(this.ackAndBye(t,488,"Bad Media Description"),this.stateTransition(it.Terminated)):t.ack()}).then(()=>{this.pendingReinvite=!1,e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(t)})}},onProgress:e=>{},onRedirect:e=>{},onReject:t=>{this.logger.warn("Received a non-2xx response to re-INVITE"),this.pendingReinvite=!1,e.withoutSdp?e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(t):this.rollbackOffer().catch(e=>{if(this.logger.error("Failed to rollback offer on non-2xx response to re-INVITE"),this.logger.error(e.message),this.state!==it.Terminated){if(!this.dialog)throw new Error("Dialog undefined.");const e=[];e.push("Reason: "+this.getReasonHeaderValue(500,"Internal Server Error")),this.dialog.bye(void 0,{extraHeaders:e}),this.stateTransition(it.Terminated)}}).then(()=>{e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(t)})},onTrying:e=>{}},n=e.requestOptions||{};if(n.extraHeaders=(n.extraHeaders||[]).slice(),n.extraHeaders.push("Allow: "+et.toString()),n.extraHeaders.push("Contact: "+this._contact),e.withoutSdp){if(!this.dialog)throw this.pendingReinvite=!1,new Error("Dialog undefined.");return Promise.resolve(this.dialog.invite(t,n))}const r={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};return this.getOffer(r).then(e=>{if(!this.dialog)throw this.pendingReinvite=!1,new Error("Dialog undefined.");return n.body=e,this.dialog.invite(t,n)}).catch(e=>{throw this.logger.error(e.message),this.logger.error("Failed to send re-INVITE"),this.pendingReinvite=!1,e})}message(e={}){if(this.state!==it.Established){const e="Session.message() may only be called if established session.";return this.logger.error(e),Promise.reject(new Error(`Invalid session state ${this.state}`))}const t=e.requestDelegate,n=this.copyRequestOptions(e.requestOptions);return this._message(t,n)}refer(e,t={}){if(this.state!==it.Established){const e="Session.refer() may only be called if established session.";return this.logger.error(e),Promise.reject(new Error(`Invalid session state ${this.state}`))}if(e instanceof st&&!e.dialog){const e="Session.refer() may only be called with session which is established. You are perhaps attempting to attended transfer to a target for which there is not dialog yet established. Perhaps you are attempting a 'semi-attended' tansfer? Regardless, this is not supported. The recommended approached is to check to see if the target Session is in the Established state before calling refer(); if the state is not Established you may proceed by falling back using a URI as the target (blind transfer).";return this.logger.error(e),Promise.reject(new Error(`Invalid session state ${this.state}`))}const n=t.requestDelegate,r=this.copyRequestOptions(t.requestOptions);return r.extraHeaders=r.extraHeaders?r.extraHeaders.concat(this.referExtraHeaders(this.referToString(e))):this.referExtraHeaders(this.referToString(e)),this._refer(t.onNotify,n,r)}_bye(e,t){if(!this.dialog)return Promise.reject(new Error("Session dialog undefined."));const n=this.dialog;switch(n.sessionState){case Be.Initial:case Be.Early:throw new Error(`Invalid dialog state ${n.sessionState}`);case Be.AckWait:return this.stateTransition(it.Terminating),new Promise(r=>{n.delegate={onAck:()=>{const i=n.bye(e,t);return this.stateTransition(it.Terminated),r(i),Promise.resolve()},onAckTimeout:()=>{const i=n.bye(e,t);this.stateTransition(it.Terminated),r(i)}}});case Be.Confirmed:{const r=n.bye(e,t);return this.stateTransition(it.Terminated),Promise.resolve(r)}case Be.Terminated:throw new Error(`Invalid dialog state ${n.sessionState}`);default:throw new Error("Unrecognized state.")}}_info(e,t){return this.dialog?Promise.resolve(this.dialog.info(e,t)):Promise.reject(new Error("Session dialog undefined."))}_message(e,t){return this.dialog?Promise.resolve(this.dialog.message(e,t)):Promise.reject(new Error("Session dialog undefined."))}_refer(e,t,n){return this.dialog?(this.onNotify=e,Promise.resolve(this.dialog.refer(t,n))):Promise.reject(new Error("Session dialog undefined."))}ackAndBye(e,t,n){e.ack();const r=[];t&&r.push("Reason: "+this.getReasonHeaderValue(t,n)),e.session.bye(void 0,{extraHeaders:r})}onAckRequest(e){if(this.logger.log("Session.onAckRequest"),this.state!==it.Established&&this.state!==it.Terminating)return this.logger.error(`ACK received while in state ${this.state}, dropping request`),Promise.resolve();const t=this.dialog;if(!t)throw new Error("Dialog undefined.");const n={sessionDescriptionHandlerOptions:this.pendingReinviteAck?this.sessionDescriptionHandlerOptionsReInvite:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.pendingReinviteAck?this._sessionDescriptionHandlerModifiersReInvite:this._sessionDescriptionHandlerModifiers};if(this.delegate&&this.delegate.onAck){const t=new ve(e);this.delegate.onAck(t)}switch(this.pendingReinviteAck=!1,t.signalingState){case Ye.Initial:{this.logger.error(`Invalid signaling state ${t.signalingState}.`);const e=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];return t.bye(void 0,{extraHeaders:e}),this.stateTransition(it.Terminated),Promise.resolve()}case Ye.Stable:{const r=Ve(e.message);return r?"render"===r.contentDisposition?(this._renderbody=r.content,this._rendertype=r.contentType,Promise.resolve()):"session"!==r.contentDisposition?Promise.resolve():this.setAnswer(r,n).catch(e=>{this.logger.error(e.message);const n=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];t.bye(void 0,{extraHeaders:n}),this.stateTransition(it.Terminated)}):Promise.resolve()}case Ye.HaveLocalOffer:{this.logger.error(`Invalid signaling state ${t.signalingState}.`);const e=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];return t.bye(void 0,{extraHeaders:e}),this.stateTransition(it.Terminated),Promise.resolve()}case Ye.HaveRemoteOffer:{this.logger.error(`Invalid signaling state ${t.signalingState}.`);const e=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];return t.bye(void 0,{extraHeaders:e}),this.stateTransition(it.Terminated),Promise.resolve()}case Ye.Closed:default:throw new Error(`Invalid signaling state ${t.signalingState}.`)}}onByeRequest(e){if(this.logger.log("Session.onByeRequest"),this.state===it.Established){if(this.delegate&&this.delegate.onBye){const t=new ye(e);this.delegate.onBye(t)}else e.accept();this.stateTransition(it.Terminated)}else this.logger.error(`BYE received while in state ${this.state}, dropping request`)}onInfoRequest(e){if(this.logger.log("Session.onInfoRequest"),this.state===it.Established)if(this.delegate&&this.delegate.onInfo){const t=new xe(e);this.delegate.onInfo(t)}else e.accept();else this.logger.error(`INFO received while in state ${this.state}, dropping request`)}onInviteRequest(e){if(this.logger.log("Session.onInviteRequest"),this.state!==it.Established)return void this.logger.error(`INVITE received while in state ${this.state}, dropping request`);this.pendingReinviteAck=!0;const t=["Contact: "+this._contact];if(e.message.hasHeader("P-Asserted-Identity")){const t=e.message.getHeader("P-Asserted-Identity");if(!t)throw new Error("Header undefined.");this._assertedIdentity=_e.nameAddrHeaderParse(t)}const n={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};this.generateResponseOfferAnswerInDialog(n).then(n=>{const r=e.accept({statusCode:200,extraHeaders:t,body:n});this.delegate&&this.delegate.onInvite&&this.delegate.onInvite(e.message,r.message,200)}).catch(t=>{if(this.logger.error(t.message),this.logger.error("Failed to handle to re-INVITE request"),!this.dialog)throw new Error("Dialog undefined.");if(this.logger.error(this.dialog.signalingState),this.dialog.signalingState===Ye.Stable){const t=e.reject({statusCode:488});return void(this.delegate&&this.delegate.onInvite&&this.delegate.onInvite(e.message,t.message,488))}this.rollbackOffer().then(()=>{const t=e.reject({statusCode:488});this.delegate&&this.delegate.onInvite&&this.delegate.onInvite(e.message,t.message,488)}).catch(t=>{this.logger.error(t.message),this.logger.error("Failed to rollback offer on re-INVITE request");const n=e.reject({statusCode:488});if(this.state!==it.Terminated){if(!this.dialog)throw new Error("Dialog undefined.");const e=[];e.push("Reason: "+this.getReasonHeaderValue(500,"Internal Server Error")),this.dialog.bye(void 0,{extraHeaders:e}),this.stateTransition(it.Terminated)}this.delegate&&this.delegate.onInvite&&this.delegate.onInvite(e.message,n.message,488)})})}onMessageRequest(e){if(this.logger.log("Session.onMessageRequest"),this.state===it.Established)if(this.delegate&&this.delegate.onMessage){const t=new tt(e);this.delegate.onMessage(t)}else e.accept();else this.logger.error(`MESSAGE received while in state ${this.state}, dropping request`)}onNotifyRequest(e){if(this.logger.log("Session.onNotifyRequest"),this.state===it.Established){if(this.onNotify){const t=new nt(e);return void this.onNotify(t)}if(this.delegate&&this.delegate.onNotify){const t=new nt(e);this.delegate.onNotify(t)}else e.accept()}else this.logger.error(`NOTIFY received while in state ${this.state}, dropping request`)}onPrackRequest(e){if(this.logger.log("Session.onPrackRequest"),this.state===it.Established)throw new Error("Unimplemented.");this.logger.error(`PRACK received while in state ${this.state}, dropping request`)}onReferRequest(e){if(this.logger.log("Session.onReferRequest"),this.state!==it.Established)return void this.logger.error(`REFER received while in state ${this.state}, dropping request`);if(!e.message.hasHeader("refer-to"))return this.logger.warn("Invalid REFER packet. A refer-to header is required. Rejecting."),void e.reject();const t=new rt(e,this);this.delegate&&this.delegate.onRefer?this.delegate.onRefer(t):(this.logger.log("No delegate available to handle REFER, automatically accepting and following."),t.accept().then(()=>t.makeInviter(this._referralInviterOptions).invite()).catch(e=>{this.logger.error(e.message)}))}generateResponseOfferAnswer(e,t){if(this.dialog)return this.generateResponseOfferAnswerInDialog(t);const n=Ve(e.message);return n&&"session"===n.contentDisposition?this.setOfferAndGetAnswer(n,t):this.getOffer(t)}generateResponseOfferAnswerInDialog(e){if(!this.dialog)throw new Error("Dialog undefined.");switch(this.dialog.signalingState){case Ye.Initial:return this.getOffer(e);case Ye.HaveLocalOffer:return Promise.resolve(void 0);case Ye.HaveRemoteOffer:if(!this.dialog.offer)throw new Error(`Session offer undefined in signaling state ${this.dialog.signalingState}.`);return this.setOfferAndGetAnswer(this.dialog.offer,e);case Ye.Stable:return this.state!==it.Established?Promise.resolve(void 0):this.getOffer(e);case Ye.Closed:default:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`)}}getOffer(e){const t=this.setupSessionDescriptionHandler(),n=e.sessionDescriptionHandlerOptions,r=e.sessionDescriptionHandlerModifiers;try{return t.getDescription(n,r).then(e=>ze(e)).catch(e=>{this.logger.error("Session.getOffer: SDH getDescription rejected...");const t=e instanceof Error?e:new Error("Session.getOffer unknown error.");throw this.logger.error(t.message),t})}catch(i){this.logger.error("Session.getOffer: SDH getDescription threw...");const e=i instanceof Error?i:new Error(i);return this.logger.error(e.message),Promise.reject(e)}}rollbackOffer(){const e=this.setupSessionDescriptionHandler();if(void 0===e.rollbackDescription)return Promise.resolve();try{return e.rollbackDescription().catch(e=>{this.logger.error("Session.rollbackOffer: SDH rollbackDescription rejected...");const t=e instanceof Error?e:new Error("Session.rollbackOffer unknown error.");throw this.logger.error(t.message),t})}catch(t){this.logger.error("Session.rollbackOffer: SDH rollbackDescription threw...");const e=t instanceof Error?t:new Error(t);return this.logger.error(e.message),Promise.reject(e)}}setAnswer(e,t){const n=this.setupSessionDescriptionHandler(),r=t.sessionDescriptionHandlerOptions,i=t.sessionDescriptionHandlerModifiers;try{if(!n.hasDescription(e.contentType))return Promise.reject(new he)}catch(o){this.logger.error("Session.setAnswer: SDH hasDescription threw...");const e=o instanceof Error?o:new Error(o);return this.logger.error(e.message),Promise.reject(e)}try{return n.setDescription(e.content,r,i).catch(e=>{this.logger.error("Session.setAnswer: SDH setDescription rejected...");const t=e instanceof Error?e:new Error("Session.setAnswer unknown error.");throw this.logger.error(t.message),t})}catch(o){this.logger.error("Session.setAnswer: SDH setDescription threw...");const e=o instanceof Error?o:new Error(o);return this.logger.error(e.message),Promise.reject(e)}}setOfferAndGetAnswer(e,t){const n=this.setupSessionDescriptionHandler(),r=t.sessionDescriptionHandlerOptions,i=t.sessionDescriptionHandlerModifiers;try{if(!n.hasDescription(e.contentType))return Promise.reject(new he)}catch(o){this.logger.error("Session.setOfferAndGetAnswer: SDH hasDescription threw...");const e=o instanceof Error?o:new Error(o);return this.logger.error(e.message),Promise.reject(e)}try{return n.setDescription(e.content,r,i).then(()=>n.getDescription(r,i)).then(e=>ze(e)).catch(e=>{this.logger.error("Session.setOfferAndGetAnswer: SDH setDescription or getDescription rejected...");const t=e instanceof Error?e:new Error("Session.setOfferAndGetAnswer unknown error.");throw this.logger.error(t.message),t})}catch(o){this.logger.error("Session.setOfferAndGetAnswer: SDH setDescription or getDescription threw...");const e=o instanceof Error?o:new Error(o);return this.logger.error(e.message),Promise.reject(e)}}setSessionDescriptionHandler(e){if(this._sessionDescriptionHandler)throw new Error("Session description handler defined.");this._sessionDescriptionHandler=e}setupSessionDescriptionHandler(){var e;return this._sessionDescriptionHandler||(this._sessionDescriptionHandler=this.sessionDescriptionHandlerFactory(this,this.userAgent.configuration.sessionDescriptionHandlerFactoryOptions),(null===(e=this.delegate)||void 0===e?void 0:e.onSessionDescriptionHandler)&&this.delegate.onSessionDescriptionHandler(this._sessionDescriptionHandler,!1)),this._sessionDescriptionHandler}stateTransition(e){const t=()=>{throw new Error(`Invalid state transition from ${this._state} to ${e}`)};switch(this._state){case it.Initial:e!==it.Establishing&&e!==it.Established&&e!==it.Terminating&&e!==it.Terminated&&t();break;case it.Establishing:e!==it.Established&&e!==it.Terminating&&e!==it.Terminated&&t();break;case it.Established:e!==it.Terminating&&e!==it.Terminated&&t();break;case it.Terminating:e!==it.Terminated&&t();break;case it.Terminated:t();break;default:throw new Error("Unrecognized state.")}this._state=e,this.logger.log(`Session ${this.id} transitioned to state ${this._state}`),this._stateEventEmitter.emit(this._state),e===it.Terminated&&this.dispose()}copyRequestOptions(e={}){return{extraHeaders:e.extraHeaders?e.extraHeaders.slice():void 0,body:e.body?{contentDisposition:e.body.contentDisposition||"render",contentType:e.body.contentType||"text/plain",content:e.body.content||""}:void 0}}getReasonHeaderValue(e,t){const n=e;let r=Ne(e);return!r&&t&&(r=t),"SIP;cause="+n+';text="'+r+'"'}referExtraHeaders(e){const t=[];return t.push("Referred-By: <"+this.userAgent.configuration.uri+">"),t.push("Contact: "+this._contact),t.push("Allow: "+["ACK","CANCEL","INVITE","MESSAGE","BYE","OPTIONS","INFO","NOTIFY","REFER"].toString()),t.push("Refer-To: "+e),t}referToString(e){let t;if(e instanceof Te)t=e.toString();else{if(!e.dialog)throw new Error("Dialog undefined.");const n=e.remoteIdentity.friendlyName,r=e.dialog.remoteTarget.toString(),i=e.dialog.callId,o=e.dialog.remoteTag,a=e.dialog.localTag;t=`"${n}" <${r}?Replaces=${encodeURIComponent(`${i};to-tag=${o};from-tag=${a}`)}>`}return t}}(at=ot=ot||(ot={})).Required="Required",at.Supported="Supported",at.Unsupported="Unsupported";const lt={"100rel":!0,199:!0,answermode:!0,"early-session":!0,eventlist:!0,explicitsub:!0,"from-change":!0,"geolocation-http":!0,"geolocation-sip":!0,gin:!0,gruu:!0,histinfo:!0,ice:!0,join:!0,"multiple-refer":!0,norefersub:!0,nosub:!0,outbound:!0,path:!0,policy:!0,precondition:!0,pref:!0,privacy:!0,"recipient-list-invite":!0,"recipient-list-message":!0,"recipient-list-subscribe":!0,replaces:!0,"resource-priority":!0,"sdp-anat":!0,"sec-agree":!0,tdialog:!0,timer:!0,uui:!0};class ct extends st{constructor(e,t){super(e),this.incomingInviteRequest=t,this.disposed=!1,this.expiresTimer=void 0,this.isCanceled=!1,this.rel100="none",this.rseq=Math.floor(1e4*Math.random()),this.userNoAnswerTimer=void 0,this.waitingForPrack=!1,this.logger=e.getLogger("sip.Invitation");const n=this.incomingInviteRequest.message,r=n.getHeader("require");r&&r.toLowerCase().includes("100rel")&&(this.rel100="required");const i=n.getHeader("supported");if(i&&i.toLowerCase().includes("100rel")&&(this.rel100="supported"),n.toTag=t.toTag,"string"!=typeof n.toTag)throw new TypeError("toTag should have been a string.");if(this.userNoAnswerTimer=setTimeout(()=>{t.reject({statusCode:480}),this.stateTransition(it.Terminated)},this.userAgent.configuration.noAnswerTimeout?1e3*this.userAgent.configuration.noAnswerTimeout:6e4),n.hasHeader("expires")){const e=1e3*Number(n.getHeader("expires")||0);this.expiresTimer=setTimeout(()=>{this.state===it.Initial&&(t.reject({statusCode:487}),this.stateTransition(it.Terminated))},e)}const o=this.request.getHeader("P-Asserted-Identity");o&&(this._assertedIdentity=_e.nameAddrHeaderParse(o)),this._contact=this.userAgent.contact.toString();const a=n.parseHeader("Content-Disposition");a&&"render"===a.type&&(this._renderbody=n.body,this._rendertype=n.getHeader("Content-Type")),this._id=n.callId+n.fromTag,this.userAgent._sessions[this._id]=this}dispose(){if(this.disposed)return Promise.resolve();switch(this.disposed=!0,this.expiresTimer&&(clearTimeout(this.expiresTimer),this.expiresTimer=void 0),this.userNoAnswerTimer&&(clearTimeout(this.userNoAnswerTimer),this.userNoAnswerTimer=void 0),this.prackNeverArrived(),this.state){case it.Initial:case it.Establishing:return this.reject().then(()=>super.dispose());case it.Established:case it.Terminating:case it.Terminated:return super.dispose();default:throw new Error("Unknown state.")}}get autoSendAnInitialProvisionalResponse(){return"required"!==this.rel100&&this.userAgent.configuration.sendInitialProvisionalResponse}get body(){return this.incomingInviteRequest.message.body}get localIdentity(){return this.request.to}get remoteIdentity(){return this.request.from}get request(){return this.incomingInviteRequest.message}accept(e={}){if(this.logger.log("Invitation.accept"),this.state!==it.Initial){const e=new Error(`Invalid session state ${this.state}`);return this.logger.error(e.message),Promise.reject(e)}return e.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiers=e.sessionDescriptionHandlerModifiers),e.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptions=e.sessionDescriptionHandlerOptions),this.stateTransition(it.Establishing),this.sendAccept(e).then(({message:e,session:t})=>{t.delegate={onAck:e=>this.onAckRequest(e),onAckTimeout:()=>this.onAckTimeout(),onBye:e=>this.onByeRequest(e),onInfo:e=>this.onInfoRequest(e),onInvite:e=>this.onInviteRequest(e),onMessage:e=>this.onMessageRequest(e),onNotify:e=>this.onNotifyRequest(e),onPrack:e=>this.onPrackRequest(e),onRefer:e=>this.onReferRequest(e)},this._dialog=t,this.stateTransition(it.Established),this._replacee&&this._replacee._bye()}).catch(e=>this.handleResponseError(e))}progress(e={}){if(this.logger.log("Invitation.progress"),this.state!==it.Initial){const e=new Error(`Invalid session state ${this.state}`);return this.logger.error(e.message),Promise.reject(e)}const t=e.statusCode||180;if(t<100||t>199)throw new TypeError("Invalid statusCode: "+t);return e.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiers=e.sessionDescriptionHandlerModifiers),e.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptions=e.sessionDescriptionHandlerOptions),this.waitingForPrack?(this.logger.warn("Unexpected call for progress while waiting for prack, ignoring"),Promise.resolve()):100===e.statusCode?this.sendProgressTrying().then(()=>{}).catch(e=>this.handleResponseError(e)):"required"===this.rel100||"supported"===this.rel100&&e.rel100||"supported"===this.rel100&&this.userAgent.configuration.sipExtension100rel===ot.Required?this.sendProgressReliableWaitForPrack(e).then(()=>{}).catch(e=>this.handleResponseError(e)):this.sendProgress(e).then(()=>{}).catch(e=>this.handleResponseError(e))}reject(e={}){if(this.logger.log("Invitation.reject"),this.state!==it.Initial&&this.state!==it.Establishing){const e=new Error(`Invalid session state ${this.state}`);return this.logger.error(e.message),Promise.reject(e)}const t=e.statusCode||480,n=e.reasonPhrase?e.reasonPhrase:Ne(t),r=e.extraHeaders||[];if(t<300||t>699)throw new TypeError("Invalid statusCode: "+t);const i=e.body?ze(e.body):void 0;return t<400?this.incomingInviteRequest.redirect([],{statusCode:t,reasonPhrase:n,extraHeaders:r,body:i}):this.incomingInviteRequest.reject({statusCode:t,reasonPhrase:n,extraHeaders:r,body:i}),this.stateTransition(it.Terminated),Promise.resolve()}_onCancel(e){if(this.logger.log("Invitation._onCancel"),this.state===it.Initial||this.state===it.Establishing){if(this.delegate&&this.delegate.onCancel){const t=new be(e);this.delegate.onCancel(t)}this.isCanceled=!0,this.incomingInviteRequest.reject({statusCode:487}),this.stateTransition(it.Terminated)}else this.logger.error(`CANCEL received while in state ${this.state}, dropping request`)}handlePrackOfferAnswer(e){if(!this.dialog)throw new Error("Dialog undefined.");const t=Ve(e.message);if(!t||"session"!==t.contentDisposition)return Promise.resolve(void 0);const n={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers};switch(this.dialog.signalingState){case Ye.Initial:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`);case Ye.Stable:return this.setAnswer(t,n).then(()=>{});case Ye.HaveLocalOffer:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`);case Ye.HaveRemoteOffer:return this.setOfferAndGetAnswer(t,n);case Ye.Closed:default:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`)}}handleResponseError(e){let t=480;if(e instanceof Error?this.logger.error(e.message):this.logger.error(e),e instanceof he?(this.logger.error("A session description handler occurred while sending response (content type unsupported"),t=415):e instanceof pe?this.logger.error("A session description handler occurred while sending response"):e instanceof ge?this.logger.error("Session ended before response could be formulated and sent (while waiting for PRACK)"):e instanceof Xe&&this.logger.error("Session changed state before response could be formulated and sent"),this.state===it.Initial||this.state===it.Establishing)try{this.incomingInviteRequest.reject({statusCode:t}),this.stateTransition(it.Terminated)}catch(n){throw this.logger.error("An error occurred attempting to reject the request while handling another error"),n}if(!this.isCanceled)throw e;this.logger.warn("An error occurred while attempting to formulate and send a response to an incoming INVITE. However a CANCEL was received and processed while doing so which can (and often does) result in errors occurring as the session terminates in the meantime. Said error is being ignored.")}onAckTimeout(){if(this.logger.log("Invitation.onAckTimeout"),!this.dialog)throw new Error("Dialog undefined.");this.logger.log("No ACK received for an extended period of time, terminating session"),this.dialog.bye(),this.stateTransition(it.Terminated)}sendAccept(e={}){const t={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers},n=e.extraHeaders||[];return this.waitingForPrack?this.waitForArrivalOfPrack().then(()=>clearTimeout(this.userNoAnswerTimer)).then(()=>this.generateResponseOfferAnswer(this.incomingInviteRequest,t)).then(e=>this.incomingInviteRequest.accept({statusCode:200,body:e,extraHeaders:n})):(clearTimeout(this.userNoAnswerTimer),this.generateResponseOfferAnswer(this.incomingInviteRequest,t).then(e=>this.incomingInviteRequest.accept({statusCode:200,body:e,extraHeaders:n})))}sendProgress(e={}){const t=e.statusCode||180,n=e.reasonPhrase,r=(e.extraHeaders||[]).slice(),i=e.body?ze(e.body):void 0;if(183===t&&!i)return this.sendProgressWithSDP(e);try{const e=this.incomingInviteRequest.progress({statusCode:t,reasonPhrase:n,extraHeaders:r,body:i});return this._dialog=e.session,Promise.resolve(e)}catch(o){return Promise.reject(o)}}sendProgressWithSDP(e={}){const t={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers},n=e.statusCode||183,r=e.reasonPhrase,i=(e.extraHeaders||[]).slice();return this.generateResponseOfferAnswer(this.incomingInviteRequest,t).then(e=>this.incomingInviteRequest.progress({statusCode:n,reasonPhrase:r,extraHeaders:i,body:e})).then(e=>(this._dialog=e.session,e))}sendProgressReliable(e={}){return e.extraHeaders=(e.extraHeaders||[]).slice(),e.extraHeaders.push("Require: 100rel"),e.extraHeaders.push("RSeq: "+Math.floor(1e4*Math.random())),this.sendProgressWithSDP(e)}sendProgressReliableWaitForPrack(e={}){const t={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers},n=e.statusCode||183,r=e.reasonPhrase,i=(e.extraHeaders||[]).slice();let o;return i.push("Require: 100rel"),i.push("RSeq: "+this.rseq++),new Promise((e,a)=>{this.waitingForPrack=!0,this.generateResponseOfferAnswer(this.incomingInviteRequest,t).then(e=>(o=e,this.incomingInviteRequest.progress({statusCode:n,reasonPhrase:r,extraHeaders:i,body:o}))).then(t=>{let s,l;this._dialog=t.session,t.session.delegate={onPrack:n=>{s=n,clearTimeout(c),clearTimeout(h),this.waitingForPrack&&(this.waitingForPrack=!1,this.handlePrackOfferAnswer(s).then(n=>{try{l=s.accept({statusCode:200,body:n}),this.prackArrived(),e({prackRequest:s,prackResponse:l,progressResponse:t})}catch(r){a(r)}}).catch(e=>a(e)))}};const c=setTimeout(()=>{this.waitingForPrack&&(this.waitingForPrack=!1,this.logger.warn("No PRACK received, rejecting INVITE."),clearTimeout(h),this.reject({statusCode:504}).then(()=>a(new ge)).catch(e=>a(e)))},64*Qe.T1),u=()=>{try{this.incomingInviteRequest.progress({statusCode:n,reasonPhrase:r,extraHeaders:i,body:o})}catch(e){return this.waitingForPrack=!1,void a(e)}h=setTimeout(u,d*=2)};let d=Qe.T1,h=setTimeout(u,d)}).catch(e=>{this.waitingForPrack=!1,a(e)})})}sendProgressTrying(){try{const e=this.incomingInviteRequest.trying();return Promise.resolve(e)}catch(e){return Promise.reject(e)}}waitForArrivalOfPrack(){if(this.waitingForPrackPromise)throw new Error("Already waiting for PRACK");return this.waitingForPrackPromise=new Promise((e,t)=>{this.waitingForPrackResolve=e,this.waitingForPrackReject=t}),this.waitingForPrackPromise}prackArrived(){this.waitingForPrackResolve&&this.waitingForPrackResolve(),this.waitingForPrackPromise=void 0,this.waitingForPrackResolve=void 0,this.waitingForPrackReject=void 0}prackNeverArrived(){this.waitingForPrackReject&&this.waitingForPrackReject(new ge),this.waitingForPrackPromise=void 0,this.waitingForPrackResolve=void 0,this.waitingForPrackReject=void 0}}class ut extends st{constructor(e,t,n={}){super(e,n),this.disposed=!1,this.earlyMedia=!1,this.earlyMediaSessionDescriptionHandlers=new Map,this.isCanceled=!1,this.inviteWithoutSdp=!1,this.logger=e.getLogger("sip.Inviter"),this.earlyMedia=void 0!==n.earlyMedia?n.earlyMedia:this.earlyMedia,this.fromTag=Me(),this.inviteWithoutSdp=void 0!==n.inviteWithoutSdp?n.inviteWithoutSdp:this.inviteWithoutSdp;const r=Object.assign({},n);r.params=Object.assign({},n.params);const i=n.anonymous||!1,o=e.contact.toString({anonymous:i,outbound:i?!e.contact.tempGruu:!e.contact.pubGruu});i&&e.configuration.uri&&(r.params.fromDisplayName="Anonymous",r.params.fromUri="sip:anonymous@anonymous.invalid");let a=e.userAgentCore.configuration.aor;if(r.params.fromUri&&(a="string"==typeof r.params.fromUri?_e.URIParse(r.params.fromUri):r.params.fromUri),!a)throw new TypeError("Invalid from URI: "+r.params.fromUri);let s=t;if(r.params.toUri&&(s="string"==typeof r.params.toUri?_e.URIParse(r.params.toUri):r.params.toUri),!s)throw new TypeError("Invalid to URI: "+r.params.toUri);const l=Object.assign({},r.params);l.fromTag=this.fromTag;const c=(r.extraHeaders||[]).slice();i&&e.configuration.uri&&(c.push("P-Preferred-Identity: "+e.configuration.uri.toString()),c.push("Privacy: id")),c.push("Contact: "+o),c.push("Allow: "+["ACK","CANCEL","INVITE","MESSAGE","BYE","OPTIONS","INFO","NOTIFY","REFER"].toString()),e.configuration.sipExtension100rel===ot.Required&&c.push("Require: 100rel"),e.configuration.sipExtensionReplaces===ot.Required&&c.push("Require: replaces"),r.extraHeaders=c;this.outgoingRequestMessage=e.userAgentCore.makeOutgoingRequestMessage(Ze.INVITE,t,a,s,l,c,void 0),this._contact=o,this._referralInviterOptions=r,this._renderbody=n.renderbody,this._rendertype=n.rendertype,n.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiers=n.sessionDescriptionHandlerModifiers),n.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptions=n.sessionDescriptionHandlerOptions),n.sessionDescriptionHandlerModifiersReInvite&&(this.sessionDescriptionHandlerModifiersReInvite=n.sessionDescriptionHandlerModifiersReInvite),n.sessionDescriptionHandlerOptionsReInvite&&(this.sessionDescriptionHandlerOptionsReInvite=n.sessionDescriptionHandlerOptionsReInvite),this._id=this.outgoingRequestMessage.callId+this.fromTag,this.userAgent._sessions[this._id]=this}dispose(){if(this.disposed)return Promise.resolve();switch(this.disposed=!0,this.disposeEarlyMedia(),this.state){case it.Initial:case it.Establishing:return this.cancel().then(()=>super.dispose());case it.Established:case it.Terminating:case it.Terminated:return super.dispose();default:throw new Error("Unknown state.")}}get body(){return this.outgoingRequestMessage.body}get localIdentity(){return this.outgoingRequestMessage.from}get remoteIdentity(){return this.outgoingRequestMessage.to}get request(){return this.outgoingRequestMessage}cancel(e={}){if(this.logger.log("Inviter.cancel"),this.state!==it.Initial&&this.state!==it.Establishing){const e=new Error(`Invalid session state ${this.state}`);return this.logger.error(e.message),Promise.reject(e)}if(this.isCanceled=!0,this.stateTransition(it.Terminating),this.outgoingInviteRequest){let t;e.statusCode&&e.reasonPhrase&&(t=function(e,t){if(e&&e<200||e>699)throw new TypeError("Invalid statusCode: "+e);if(e)return"SIP;cause="+e+';text="'+(Ne(e)||t)+'"'}(e.statusCode,e.reasonPhrase)),this.outgoingInviteRequest.cancel(t,e)}else this.logger.warn("Canceled session before INVITE was sent"),this.stateTransition(it.Terminated);return Promise.resolve()}invite(e={}){if(this.logger.log("Inviter.invite"),this.state!==it.Initial)return super.invite(e);if(e.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiers=e.sessionDescriptionHandlerModifiers),e.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptions=e.sessionDescriptionHandlerOptions),e.withoutSdp||this.inviteWithoutSdp)return this._renderbody&&this._rendertype&&(this.outgoingRequestMessage.body={contentType:this._rendertype,body:this._renderbody}),this.stateTransition(it.Establishing),Promise.resolve(this.sendInvite(e));const t={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.getOffer(t).then(t=>(this.outgoingRequestMessage.body={body:t.content,contentType:t.contentType},this.stateTransition(it.Establishing),this.sendInvite(e))).catch(e=>{throw this.logger.log(e.message),this.state!==it.Terminated&&this.stateTransition(it.Terminated),e})}sendInvite(e={}){return this.outgoingInviteRequest=this.userAgent.userAgentCore.invite(this.outgoingRequestMessage,{onAccept:t=>this.dialog?(this.logger.log("Additional confirmed dialog, sending ACK and BYE"),void this.ackAndBye(t)):this.isCanceled?(this.logger.log("Canceled session accepted, sending ACK and BYE"),this.ackAndBye(t),void this.stateTransition(it.Terminated)):(this.notifyReferer(t),void this.onAccept(t).then(()=>{this.disposeEarlyMedia()}).catch(()=>{this.disposeEarlyMedia()}).then(()=>{e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(t)})),onProgress:t=>{this.isCanceled||(this.notifyReferer(t),this.onProgress(t).catch(()=>{this.disposeEarlyMedia()}).then(()=>{e.requestDelegate&&e.requestDelegate.onProgress&&e.requestDelegate.onProgress(t)}))},onRedirect:t=>{this.notifyReferer(t),this.onRedirect(t),e.requestDelegate&&e.requestDelegate.onRedirect&&e.requestDelegate.onRedirect(t)},onReject:t=>{this.notifyReferer(t),this.onReject(t),e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(t)},onTrying:t=>{this.notifyReferer(t),this.onTrying(t),e.requestDelegate&&e.requestDelegate.onTrying&&e.requestDelegate.onTrying(t)}}),this.outgoingInviteRequest}disposeEarlyMedia(){this.earlyMediaSessionDescriptionHandlers.forEach(e=>{e.close()}),this.earlyMediaSessionDescriptionHandlers.clear()}notifyReferer(e){if(!this._referred)return;if(!(this._referred instanceof st))throw new Error("Referred session not instance of session");if(!this._referred.dialog)return;if(!e.message.statusCode)throw new Error("Status code undefined.");if(!e.message.reasonPhrase)throw new Error("Reason phrase undefined.");const t=`SIP/2.0 ${e.message.statusCode} ${e.message.reasonPhrase}`.trim();this._referred.dialog.notify(void 0,{extraHeaders:["Event: refer","Subscription-State: terminated"],body:{contentDisposition:"render",contentType:"message/sipfrag",content:t}}).delegate={onReject:()=>{this._referred=void 0}}}onAccept(e){if(this.logger.log("Inviter.onAccept"),this.state!==it.Establishing)return this.logger.error(`Accept received while in state ${this.state}, dropping response`),Promise.reject(new Error(`Invalid session state ${this.state}`));const t=e.message,n=e.session;switch(t.hasHeader("P-Asserted-Identity")&&(this._assertedIdentity=_e.nameAddrHeaderParse(t.getHeader("P-Asserted-Identity"))),n.delegate={onAck:e=>this.onAckRequest(e),onBye:e=>this.onByeRequest(e),onInfo:e=>this.onInfoRequest(e),onInvite:e=>this.onInviteRequest(e),onMessage:e=>this.onMessageRequest(e),onNotify:e=>this.onNotifyRequest(e),onPrack:e=>this.onPrackRequest(e),onRefer:e=>this.onReferRequest(e)},this._dialog=n,n.signalingState){case Ye.Initial:case Ye.HaveLocalOffer:return this.logger.error("Received 2xx response to INVITE without a session description"),this.ackAndBye(e,400,"Missing session description"),this.stateTransition(it.Terminated),Promise.reject(new Error("Bad Media Description"));case Ye.HaveRemoteOffer:{if(!this._dialog.offer)throw new Error(`Session offer undefined in signaling state ${this._dialog.signalingState}.`);const t={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.setOfferAndGetAnswer(this._dialog.offer,t).then(t=>{e.ack({body:t}),this.stateTransition(it.Established)}).catch(t=>{throw this.ackAndBye(e,488,"Invalid session description"),this.stateTransition(it.Terminated),t})}case Ye.Stable:{if(this.earlyMediaSessionDescriptionHandlers.size>0){const t=this.earlyMediaSessionDescriptionHandlers.get(n.id);if(!t)throw new Error("Session description handler undefined.");return this.setSessionDescriptionHandler(t),this.earlyMediaSessionDescriptionHandlers.delete(n.id),e.ack(),this.stateTransition(it.Established),Promise.resolve()}if(this.earlyMediaDialog){if(this.earlyMediaDialog!==n){if(this.earlyMedia){const e="You have set the 'earlyMedia' option to 'true' which requires that your INVITE requests do not fork and yet this INVITE request did in fact fork. Consequentially and not surprisingly the end point which accepted the INVITE (confirmed dialog) does not match the end point with which early media has been setup (early dialog) and thus this session is unable to proceed. In accordance with the SIP specifications, the SIP servers your end point is connected to determine if an INVITE forks and the forking behavior of those servers cannot be controlled by this library. If you wish to use early media with this library you must configure those servers accordingly. Alternatively you may set the 'earlyMedia' to 'false' which will allow this library to function with any INVITE requests which do fork.";this.logger.error(e)}const t=new Error("Early media dialog does not equal confirmed dialog, terminating session");return this.logger.error(t.message),this.ackAndBye(e,488,"Not Acceptable Here"),this.stateTransition(it.Terminated),Promise.reject(t)}return e.ack(),this.stateTransition(it.Established),Promise.resolve()}const t=n.answer;if(!t)throw new Error("Answer is undefined.");const r={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.setAnswer(t,r).then(()=>{let t;this._renderbody&&this._rendertype&&(t={body:{contentDisposition:"render",contentType:this._rendertype,content:this._renderbody}}),e.ack(t),this.stateTransition(it.Established)}).catch(t=>{throw this.logger.error(t.message),this.ackAndBye(e,488,"Not Acceptable Here"),this.stateTransition(it.Terminated),t})}case Ye.Closed:return Promise.reject(new Error("Terminated."));default:throw new Error("Unknown session signaling state.")}}onProgress(e){var t;if(this.logger.log("Inviter.onProgress"),this.state!==it.Establishing)return this.logger.error(`Progress received while in state ${this.state}, dropping response`),Promise.reject(new Error(`Invalid session state ${this.state}`));if(!this.outgoingInviteRequest)throw new Error("Outgoing INVITE request undefined.");const n=e.message,r=e.session;n.hasHeader("P-Asserted-Identity")&&(this._assertedIdentity=_e.nameAddrHeaderParse(n.getHeader("P-Asserted-Identity")));const i=n.getHeader("require"),o=n.getHeader("rseq"),a=!!(i&&i.includes("100rel")&&o?Number(o):void 0),s=[];switch(a&&s.push("RAck: "+n.getHeader("rseq")+" "+n.getHeader("cseq")),r.signalingState){case Ye.Initial:return a&&(this.logger.warn("First reliable provisional response received MUST contain an offer when INVITE does not contain an offer."),e.prack({extraHeaders:s})),Promise.resolve();case Ye.HaveLocalOffer:return a&&e.prack({extraHeaders:s}),Promise.resolve();case Ye.HaveRemoteOffer:if(!a)return this.logger.warn("Non-reliable provisional response MUST NOT contain an initial offer, discarding response."),Promise.resolve();{const i=this.sessionDescriptionHandlerFactory(this,this.userAgent.configuration.sessionDescriptionHandlerFactoryOptions||{});return(null===(t=this.delegate)||void 0===t?void 0:t.onSessionDescriptionHandler)&&this.delegate.onSessionDescriptionHandler(i,!0),this.earlyMediaSessionDescriptionHandlers.set(r.id,i),i.setDescription(n.body,this.sessionDescriptionHandlerOptions,this.sessionDescriptionHandlerModifiers).then(()=>i.getDescription(this.sessionDescriptionHandlerOptions,this.sessionDescriptionHandlerModifiers)).then(t=>{const n={contentDisposition:"session",contentType:t.contentType,content:t.body};e.prack({extraHeaders:s,body:n})}).catch(e=>{throw this.stateTransition(it.Terminated),e})}case Ye.Stable:if(a&&e.prack({extraHeaders:s}),this.earlyMedia&&!this.earlyMediaDialog){this.earlyMediaDialog=r;const e=r.answer;if(!e)throw new Error("Answer is undefined.");const t={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.setAnswer(e,t).catch(e=>{throw this.stateTransition(it.Terminated),e})}return Promise.resolve();case Ye.Closed:return Promise.reject(new Error("Terminated."));default:throw new Error("Unknown session signaling state.")}}onRedirect(e){this.logger.log("Inviter.onRedirect"),this.state===it.Establishing||this.state===it.Terminating?this.stateTransition(it.Terminated):this.logger.error(`Redirect received while in state ${this.state}, dropping response`)}onReject(e){this.logger.log("Inviter.onReject"),this.state===it.Establishing||this.state===it.Terminating?this.stateTransition(it.Terminated):this.logger.error(`Reject received while in state ${this.state}, dropping response`)}onTrying(e){this.logger.log("Inviter.onTrying"),this.state===it.Establishing||this.logger.error(`Trying received while in state ${this.state}, dropping response`)}}class dt{constructor(e,t,n,r="text/plain",i={}){this.logger=e.getLogger("sip.Messager"),i.params=i.params||{};let o=e.userAgentCore.configuration.aor;if(i.params.fromUri&&(o="string"==typeof i.params.fromUri?_e.URIParse(i.params.fromUri):i.params.fromUri),!o)throw new TypeError("Invalid from URI: "+i.params.fromUri);let a=t;if(i.params.toUri&&(a="string"==typeof i.params.toUri?_e.URIParse(i.params.toUri):i.params.toUri),!a)throw new TypeError("Invalid to URI: "+i.params.toUri);const s=i.params?Object.assign({},i.params):{},l=(i.extraHeaders||[]).slice(),c={contentDisposition:"render",contentType:r,content:n};this.request=e.userAgentCore.makeOutgoingRequestMessage(Ze.MESSAGE,t,o,a,s,l,c),this.userAgent=e}message(e={}){return this.userAgent.userAgentCore.request(this.request,e.requestDelegate),Promise.resolve()}}var ht,ft,pt,gt,mt,vt,yt,bt,wt,xt,kt,St,Tt;(ft=ht=ht||(ht={})).Initial="Initial",ft.Registered="Registered",ft.Unregistered="Unregistered",ft.Terminated="Terminated";class Et{constructor(e,t={}){this.disposed=!1,this._contacts=[],this._retryAfter=void 0,this._state=ht.Initial,this._waiting=!1,this._stateEventEmitter=new we,this._waitingEventEmitter=new we,this.userAgent=e;const n=e.configuration.uri.clone();if(n.user=void 0,this.options=Object.assign(Object.assign(Object.assign({},Et.defaultOptions()),{registrar:n}),Et.stripUndefinedProperties(t)),this.options.extraContactHeaderParams=(this.options.extraContactHeaderParams||[]).slice(),this.options.extraHeaders=(this.options.extraHeaders||[]).slice(),!this.options.registrar)throw new Error("Registrar undefined.");if(this.options.registrar=this.options.registrar.clone(),this.options.regId&&!this.options.instanceId?this.options.instanceId=this.userAgent.instanceId:!this.options.regId&&this.options.instanceId&&(this.options.regId=1),this.options.instanceId&&-1===_e.parse(this.options.instanceId,"uuid"))throw new Error("Invalid instanceId.");if(this.options.regId&&this.options.regId<0)throw new Error("Invalid regId.");const r=this.options.registrar,i=this.options.params&&this.options.params.fromUri||e.userAgentCore.configuration.aor,o=this.options.params&&this.options.params.toUri||e.configuration.uri,a=this.options.params||{},s=(t.extraHeaders||[]).slice();if(this.request=e.userAgentCore.makeOutgoingRequestMessage(Ze.REGISTER,r,i,o,a,s,void 0),this.expires=this.options.expires||Et.defaultExpires,this.expires<0)throw new Error("Invalid expires.");if(this.refreshFrequency=this.options.refreshFrequency||Et.defaultRefreshFrequency,this.refreshFrequency<50||this.refreshFrequency>99)throw new Error("Invalid refresh frequency. The value represents a percentage of the expiration time and should be between 50 and 99.");this.logger=e.getLogger("sip.Registerer"),this.options.logConfiguration&&(this.logger.log("Configuration:"),Object.keys(this.options).forEach(e=>{const t=this.options[e];if("registrar"===e)this.logger.log("· "+e+": "+t);else this.logger.log("· "+e+": "+JSON.stringify(t))})),this.id=this.request.callId+this.request.from.parameters.tag,this.userAgent._registerers[this.id]=this}static defaultOptions(){return{expires:Et.defaultExpires,extraContactHeaderParams:[],extraHeaders:[],logConfiguration:!0,instanceId:"",params:{},regId:0,registrar:new Te("sip","anonymous","anonymous.invalid"),refreshFrequency:Et.defaultRefreshFrequency}}static stripUndefinedProperties(e){return Object.keys(e).reduce((t,n)=>(void 0!==e[n]&&(t[n]=e[n]),t),{})}get contacts(){return this._contacts.slice()}get retryAfter(){return this._retryAfter}get state(){return this._state}get stateChange(){return this._stateEventEmitter}dispose(){return this.disposed?Promise.resolve():(this.disposed=!0,this.logger.log(`Registerer ${this.id} in state ${this.state} is being disposed`),delete this.userAgent._registerers[this.id],new Promise(e=>{const t=()=>{if(!this.waiting&&this._state===ht.Registered)return this.stateChange.addListener(()=>{this.terminated(),e()},{once:!0}),void this.unregister();this.terminated(),e()};this.waiting?this.waitingChange.addListener(()=>{t()},{once:!0}):t()}))}register(e={}){if(this.state===ht.Terminated)throw this.stateError(),new Error("Registerer terminated. Unable to register.");if(this.disposed)throw this.stateError(),new Error("Registerer disposed. Unable to register.");if(this.waiting){this.waitingWarning();const e=new fe("REGISTER request already in progress, waiting for final response");return Promise.reject(e)}e.requestOptions&&(this.options=Object.assign(Object.assign({},this.options),e.requestOptions));const t=(this.options.extraHeaders||[]).slice();t.push("Contact: "+this.generateContactHeader(this.expires)),t.push("Allow: "+["ACK","CANCEL","INVITE","MESSAGE","BYE","OPTIONS","INFO","NOTIFY","REFER"].toString()),this.request.cseq++,this.request.setHeader("cseq",this.request.cseq+" REGISTER"),this.request.extraHeaders=t,this.waitingToggle(!0);const n=this.userAgent.userAgentCore.register(this.request,{onAccept:t=>{let n;t.message.hasHeader("expires")&&(n=Number(t.message.getHeader("expires"))),this._contacts=t.message.getHeaders("contact");let r,i=this._contacts.length;if(!i)return this.logger.error("No Contact header in response to REGISTER, dropping response."),void this.unregistered();for(;i--;){if(r=t.message.parseHeader("contact",i),!r)throw new Error("Contact undefined");if(this.userAgent.contact.pubGruu&&Ee(r.uri,this.userAgent.contact.pubGruu)){n=Number(r.getParam("expires"));break}if(""===this.userAgent.configuration.contactName){if(r.uri.user===this.userAgent.contact.uri.user){n=Number(r.getParam("expires"));break}}else if(Ee(r.uri,this.userAgent.contact.uri)){n=Number(r.getParam("expires"));break}r=void 0}if(void 0===r)return this.logger.error("No Contact header pointing to us, dropping response"),this.unregistered(),void this.waitingToggle(!1);if(void 0===n)return this.logger.error("Contact pointing to us is missing expires parameter, dropping response"),this.unregistered(),void this.waitingToggle(!1);if(r.hasParam("temp-gruu")){const e=r.getParam("temp-gruu");e&&(this.userAgent.contact.tempGruu=_e.URIParse(e.replace(/"/g,"")))}if(r.hasParam("pub-gruu")){const e=r.getParam("pub-gruu");e&&(this.userAgent.contact.pubGruu=_e.URIParse(e.replace(/"/g,"")))}this.registered(n),e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(t),this.waitingToggle(!1)},onProgress:t=>{e.requestDelegate&&e.requestDelegate.onProgress&&e.requestDelegate.onProgress(t)},onRedirect:t=>{this.logger.error("Redirect received. Not supported."),this.unregistered(),e.requestDelegate&&e.requestDelegate.onRedirect&&e.requestDelegate.onRedirect(t),this.waitingToggle(!1)},onReject:t=>{if(423===t.message.statusCode)return t.message.hasHeader("min-expires")?(this.expires=Number(t.message.getHeader("min-expires")),this.waitingToggle(!1),void this.register()):(this.logger.error("423 response received for REGISTER without Min-Expires, dropping response"),this.unregistered(),void this.waitingToggle(!1));this.logger.warn(`Failed to register, status code ${t.message.statusCode}`);let n=NaN;if(500===t.message.statusCode||503===t.message.statusCode){const e=t.message.getHeader("retry-after");e&&(n=Number.parseInt(e,void 0))}this._retryAfter=isNaN(n)?void 0:n,this.unregistered(),e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(t),this._retryAfter=void 0,this.waitingToggle(!1)},onTrying:t=>{e.requestDelegate&&e.requestDelegate.onTrying&&e.requestDelegate.onTrying(t)}});return Promise.resolve(n)}unregister(e={}){if(this.state===ht.Terminated)throw this.stateError(),new Error("Registerer terminated. Unable to register.");if(this.disposed&&this.state!==ht.Registered)throw this.stateError(),new Error("Registerer disposed. Unable to register.");if(this.waiting){this.waitingWarning();const e=new fe("REGISTER request already in progress, waiting for final response");return Promise.reject(e)}this._state===ht.Registered||e.all||this.logger.warn("Not currently registered, but sending an unregister anyway.");const t=(e.requestOptions&&e.requestOptions.extraHeaders||[]).slice();this.request.extraHeaders=t,e.all?(t.push("Contact: *"),t.push("Expires: 0")):t.push("Contact: "+this.generateContactHeader(0)),this.request.cseq++,this.request.setHeader("cseq",this.request.cseq+" REGISTER"),void 0!==this.registrationTimer&&(clearTimeout(this.registrationTimer),this.registrationTimer=void 0),this.waitingToggle(!0);const n=this.userAgent.userAgentCore.register(this.request,{onAccept:t=>{this._contacts=t.message.getHeaders("contact"),this.unregistered(),e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(t),this.waitingToggle(!1)},onProgress:t=>{e.requestDelegate&&e.requestDelegate.onProgress&&e.requestDelegate.onProgress(t)},onRedirect:t=>{this.logger.error("Unregister redirected. Not currently supported."),this.unregistered(),e.requestDelegate&&e.requestDelegate.onRedirect&&e.requestDelegate.onRedirect(t),this.waitingToggle(!1)},onReject:t=>{this.logger.error(`Unregister rejected with status code ${t.message.statusCode}`),this.unregistered(),e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(t),this.waitingToggle(!1)},onTrying:t=>{e.requestDelegate&&e.requestDelegate.onTrying&&e.requestDelegate.onTrying(t)}});return Promise.resolve(n)}clearTimers(){void 0!==this.registrationTimer&&(clearTimeout(this.registrationTimer),this.registrationTimer=void 0),void 0!==this.registrationExpiredTimer&&(clearTimeout(this.registrationExpiredTimer),this.registrationExpiredTimer=void 0)}generateContactHeader(e){let t=this.userAgent.contact.toString({register:!0});return this.options.regId&&this.options.instanceId&&(t+=";reg-id="+this.options.regId,t+=';+sip.instance=""'),this.options.extraContactHeaderParams&&this.options.extraContactHeaderParams.forEach(e=>{t+=";"+e}),t+=";expires="+e,t}registered(e){this.clearTimers(),this.registrationTimer=setTimeout(()=>{this.registrationTimer=void 0,this.register()},this.refreshFrequency/100*e*1e3),this.registrationExpiredTimer=setTimeout(()=>{this.logger.warn("Registration expired"),this.unregistered()},1e3*e),this._state!==ht.Registered&&this.stateTransition(ht.Registered)}unregistered(){this.clearTimers(),this._state!==ht.Unregistered&&this.stateTransition(ht.Unregistered)}terminated(){this.clearTimers(),this._state!==ht.Terminated&&this.stateTransition(ht.Terminated)}stateTransition(e){const t=()=>{throw new Error(`Invalid state transition from ${this._state} to ${e}`)};switch(this._state){case ht.Initial:e!==ht.Registered&&e!==ht.Unregistered&&e!==ht.Terminated&&t();break;case ht.Registered:e!==ht.Unregistered&&e!==ht.Terminated&&t();break;case ht.Unregistered:e!==ht.Registered&&e!==ht.Terminated&&t();break;case ht.Terminated:t();break;default:throw new Error("Unrecognized state.")}this._state=e,this.logger.log(`Registration transitioned to state ${this._state}`),this._stateEventEmitter.emit(this._state),e===ht.Terminated&&this.dispose()}get waiting(){return this._waiting}get waitingChange(){return this._waitingEventEmitter}waitingToggle(e){if(this._waiting===e)throw new Error(`Invalid waiting transition from ${this._waiting} to ${e}`);this._waiting=e,this.logger.log(`Waiting toggled to ${this._waiting}`),this._waitingEventEmitter.emit(this._waiting)}waitingWarning(){let e="An attempt was made to send a REGISTER request while a prior one was still in progress.";e+=" RFC 3261 requires UAs MUST NOT send a new registration until they have received a final response",e+=" from the registrar for the previous one or the previous REGISTER request has timed out.",e+=" Note that if the transport disconnects, you still must wait for the prior request to time out before",e+=" sending a new REGISTER request or alternatively dispose of the current Registerer and create a new Registerer.",this.logger.warn("An attempt was made to send a REGISTER request while a prior one was still in progress. RFC 3261 requires UAs MUST NOT send a new registration until they have received a final response from the registrar for the previous one or the previous REGISTER request has timed out. Note that if the transport disconnects, you still must wait for the prior request to time out before sending a new REGISTER request or alternatively dispose of the current Registerer and create a new Registerer.")}stateError(){let e=`An attempt was made to send a REGISTER request when the Registerer ${this.state===ht.Terminated?"is in 'Terminated' state":"has been disposed"}.`;e+=" The Registerer transitions to 'Terminated' when Registerer.dispose() is called.",e+=" Perhaps you called UserAgent.stop() which dipsoses of all Registerers?",this.logger.error(e)}}Et.defaultExpires=600,Et.defaultRefreshFrequency=99,(gt=pt=pt||(pt={})).Initial="Initial",gt.NotifyWait="NotifyWait",gt.Pending="Pending",gt.Active="Active",gt.Terminated="Terminated",(vt=mt=mt||(mt={})).Connecting="Connecting",vt.Connected="Connected",vt.Disconnecting="Disconnecting",vt.Disconnected="Disconnected",(bt=yt=yt||(yt={})).Started="Started",bt.Stopped="Stopped";class Ct{constructor(){this._dataLength=0,this._bufferLength=0,this._state=new Int32Array(4),this._buffer=new ArrayBuffer(68),this._buffer8=new Uint8Array(this._buffer,0,68),this._buffer32=new Uint32Array(this._buffer,0,17),this.start()}static hashStr(e,t=!1){return this.onePassHasher.start().appendStr(e).end(t)}static hashAsciiStr(e,t=!1){return this.onePassHasher.start().appendAsciiStr(e).end(t)}static _hex(e){const t=Ct.hexChars,n=Ct.hexOut;let r,i,o,a;for(a=0;a<4;a+=1)for(i=8*a,r=e[a],o=0;o<8;o+=2)n[i+1+o]=t.charAt(15&r),r>>>=4,n[i+0+o]=t.charAt(15&r),r>>>=4;return n.join("")}static _md5cycle(e,t){let n=e[0],r=e[1],i=e[2],o=e[3];n+=(r&i|~r&o)+t[0]-680876936|0,n=(n<<7|n>>>25)+r|0,o+=(n&r|~n&i)+t[1]-389564586|0,o=(o<<12|o>>>20)+n|0,i+=(o&n|~o&r)+t[2]+606105819|0,i=(i<<17|i>>>15)+o|0,r+=(i&o|~i&n)+t[3]-1044525330|0,r=(r<<22|r>>>10)+i|0,n+=(r&i|~r&o)+t[4]-176418897|0,n=(n<<7|n>>>25)+r|0,o+=(n&r|~n&i)+t[5]+1200080426|0,o=(o<<12|o>>>20)+n|0,i+=(o&n|~o&r)+t[6]-1473231341|0,i=(i<<17|i>>>15)+o|0,r+=(i&o|~i&n)+t[7]-45705983|0,r=(r<<22|r>>>10)+i|0,n+=(r&i|~r&o)+t[8]+1770035416|0,n=(n<<7|n>>>25)+r|0,o+=(n&r|~n&i)+t[9]-1958414417|0,o=(o<<12|o>>>20)+n|0,i+=(o&n|~o&r)+t[10]-42063|0,i=(i<<17|i>>>15)+o|0,r+=(i&o|~i&n)+t[11]-1990404162|0,r=(r<<22|r>>>10)+i|0,n+=(r&i|~r&o)+t[12]+1804603682|0,n=(n<<7|n>>>25)+r|0,o+=(n&r|~n&i)+t[13]-40341101|0,o=(o<<12|o>>>20)+n|0,i+=(o&n|~o&r)+t[14]-1502002290|0,i=(i<<17|i>>>15)+o|0,r+=(i&o|~i&n)+t[15]+1236535329|0,r=(r<<22|r>>>10)+i|0,n+=(r&o|i&~o)+t[1]-165796510|0,n=(n<<5|n>>>27)+r|0,o+=(n&i|r&~i)+t[6]-1069501632|0,o=(o<<9|o>>>23)+n|0,i+=(o&r|n&~r)+t[11]+643717713|0,i=(i<<14|i>>>18)+o|0,r+=(i&n|o&~n)+t[0]-373897302|0,r=(r<<20|r>>>12)+i|0,n+=(r&o|i&~o)+t[5]-701558691|0,n=(n<<5|n>>>27)+r|0,o+=(n&i|r&~i)+t[10]+38016083|0,o=(o<<9|o>>>23)+n|0,i+=(o&r|n&~r)+t[15]-660478335|0,i=(i<<14|i>>>18)+o|0,r+=(i&n|o&~n)+t[4]-405537848|0,r=(r<<20|r>>>12)+i|0,n+=(r&o|i&~o)+t[9]+568446438|0,n=(n<<5|n>>>27)+r|0,o+=(n&i|r&~i)+t[14]-1019803690|0,o=(o<<9|o>>>23)+n|0,i+=(o&r|n&~r)+t[3]-187363961|0,i=(i<<14|i>>>18)+o|0,r+=(i&n|o&~n)+t[8]+1163531501|0,r=(r<<20|r>>>12)+i|0,n+=(r&o|i&~o)+t[13]-1444681467|0,n=(n<<5|n>>>27)+r|0,o+=(n&i|r&~i)+t[2]-51403784|0,o=(o<<9|o>>>23)+n|0,i+=(o&r|n&~r)+t[7]+1735328473|0,i=(i<<14|i>>>18)+o|0,r+=(i&n|o&~n)+t[12]-1926607734|0,r=(r<<20|r>>>12)+i|0,n+=(r^i^o)+t[5]-378558|0,n=(n<<4|n>>>28)+r|0,o+=(n^r^i)+t[8]-2022574463|0,o=(o<<11|o>>>21)+n|0,i+=(o^n^r)+t[11]+1839030562|0,i=(i<<16|i>>>16)+o|0,r+=(i^o^n)+t[14]-35309556|0,r=(r<<23|r>>>9)+i|0,n+=(r^i^o)+t[1]-1530992060|0,n=(n<<4|n>>>28)+r|0,o+=(n^r^i)+t[4]+1272893353|0,o=(o<<11|o>>>21)+n|0,i+=(o^n^r)+t[7]-155497632|0,i=(i<<16|i>>>16)+o|0,r+=(i^o^n)+t[10]-1094730640|0,r=(r<<23|r>>>9)+i|0,n+=(r^i^o)+t[13]+681279174|0,n=(n<<4|n>>>28)+r|0,o+=(n^r^i)+t[0]-358537222|0,o=(o<<11|o>>>21)+n|0,i+=(o^n^r)+t[3]-722521979|0,i=(i<<16|i>>>16)+o|0,r+=(i^o^n)+t[6]+76029189|0,r=(r<<23|r>>>9)+i|0,n+=(r^i^o)+t[9]-640364487|0,n=(n<<4|n>>>28)+r|0,o+=(n^r^i)+t[12]-421815835|0,o=(o<<11|o>>>21)+n|0,i+=(o^n^r)+t[15]+530742520|0,i=(i<<16|i>>>16)+o|0,r+=(i^o^n)+t[2]-995338651|0,r=(r<<23|r>>>9)+i|0,n+=(i^(r|~o))+t[0]-198630844|0,n=(n<<6|n>>>26)+r|0,o+=(r^(n|~i))+t[7]+1126891415|0,o=(o<<10|o>>>22)+n|0,i+=(n^(o|~r))+t[14]-1416354905|0,i=(i<<15|i>>>17)+o|0,r+=(o^(i|~n))+t[5]-57434055|0,r=(r<<21|r>>>11)+i|0,n+=(i^(r|~o))+t[12]+1700485571|0,n=(n<<6|n>>>26)+r|0,o+=(r^(n|~i))+t[3]-1894986606|0,o=(o<<10|o>>>22)+n|0,i+=(n^(o|~r))+t[10]-1051523|0,i=(i<<15|i>>>17)+o|0,r+=(o^(i|~n))+t[1]-2054922799|0,r=(r<<21|r>>>11)+i|0,n+=(i^(r|~o))+t[8]+1873313359|0,n=(n<<6|n>>>26)+r|0,o+=(r^(n|~i))+t[15]-30611744|0,o=(o<<10|o>>>22)+n|0,i+=(n^(o|~r))+t[6]-1560198380|0,i=(i<<15|i>>>17)+o|0,r+=(o^(i|~n))+t[13]+1309151649|0,r=(r<<21|r>>>11)+i|0,n+=(i^(r|~o))+t[4]-145523070|0,n=(n<<6|n>>>26)+r|0,o+=(r^(n|~i))+t[11]-1120210379|0,o=(o<<10|o>>>22)+n|0,i+=(n^(o|~r))+t[2]+718787259|0,i=(i<<15|i>>>17)+o|0,r+=(o^(i|~n))+t[9]-343485551|0,r=(r<<21|r>>>11)+i|0,e[0]=n+e[0]|0,e[1]=r+e[1]|0,e[2]=i+e[2]|0,e[3]=o+e[3]|0}start(){return this._dataLength=0,this._bufferLength=0,this._state.set(Ct.stateIdentity),this}appendStr(e){const t=this._buffer8,n=this._buffer32;let r,i,o=this._bufferLength;for(i=0;i>>6)+192,t[o++]=63&r|128;else if(r<55296||r>56319)t[o++]=(r>>>12)+224,t[o++]=r>>>6&63|128,t[o++]=63&r|128;else{if(r=1024*(r-55296)+(e.charCodeAt(++i)-56320)+65536,r>1114111)throw new Error("Unicode standard supports code points up to U+10FFFF");t[o++]=(r>>>18)+240,t[o++]=r>>>12&63|128,t[o++]=r>>>6&63|128,t[o++]=63&r|128}o>=64&&(this._dataLength+=64,Ct._md5cycle(this._state,n),o-=64,n[0]=n[16])}return this._bufferLength=o,this}appendAsciiStr(e){const t=this._buffer8,n=this._buffer32;let r,i=this._bufferLength,o=0;for(;;){for(r=Math.min(e.length-o,64-i);r--;)t[i++]=e.charCodeAt(o++);if(i<64)break;this._dataLength+=64,Ct._md5cycle(this._state,n),i=0}return this._bufferLength=i,this}appendByteArray(e){const t=this._buffer8,n=this._buffer32;let r,i=this._bufferLength,o=0;for(;;){for(r=Math.min(e.length-o,64-i);r--;)t[i++]=e[o++];if(i<64)break;this._dataLength+=64,Ct._md5cycle(this._state,n),i=0}return this._bufferLength=i,this}getState(){const e=this,t=e._state;return{buffer:String.fromCharCode.apply(null,e._buffer8),buflen:e._bufferLength,length:e._dataLength,state:[t[0],t[1],t[2],t[3]]}}setState(e){const t=e.buffer,n=e.state,r=this._state;let i;for(this._dataLength=e.length,this._bufferLength=e.buflen,r[0]=n[0],r[1]=n[1],r[2]=n[2],r[3]=n[3],i=0;i>2);let o;if(this._dataLength+=t,n[t]=128,n[t+1]=n[t+2]=n[t+3]=0,r.set(Ct.buffer32Identity.subarray(i),i),t>55&&(Ct._md5cycle(this._state,r),r.set(Ct.buffer32Identity)),o=8*this._dataLength,o<=4294967295)r[14]=o;else{const e=o.toString(16).match(/(.*?)(.{0,8})$/);if(null===e)return;const t=parseInt(e[2],16),n=parseInt(e[1],16)||0;r[14]=t,r[15]=n}return Ct._md5cycle(this._state,r),e?this._state:Ct._hex(this._state)}}function Rt(e){return Ct.hashStr(e)}Ct.stateIdentity=new Int32Array([1732584193,-271733879,-1732584194,271733878]),Ct.buffer32Identity=new Int32Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]),Ct.hexChars="0123456789abcdef",Ct.hexOut=[],Ct.onePassHasher=new Ct,"5d41402abc4b2a76b9719d911017c592"!==Ct.hashStr("hello")&&console.error("Md5 self test failed.");class Pt{constructor(e,t,n,r){this.logger=e.getLogger("sipjs.digestauthentication"),this.username=n,this.password=r,this.ha1=t,this.nc=0,this.ncHex="00000000"}authenticate(e,t,n){if(this.algorithm=t.algorithm,this.realm=t.realm,this.nonce=t.nonce,this.opaque=t.opaque,this.stale=t.stale,this.algorithm){if("MD5"!==this.algorithm)return this.logger.warn("challenge with Digest algorithm different than 'MD5', authentication aborted"),!1}else this.algorithm="MD5";if(!this.realm)return this.logger.warn("challenge without Digest realm, authentication aborted"),!1;if(!this.nonce)return this.logger.warn("challenge without Digest nonce, authentication aborted"),!1;if(t.qop)if(t.qop.indexOf("auth")>-1)this.qop="auth";else{if(!(t.qop.indexOf("auth-int")>-1))return this.logger.warn("challenge without Digest qop different than 'auth' or 'auth-int', authentication aborted"),!1;this.qop="auth-int"}else this.qop=void 0;return this.method=e.method,this.uri=e.ruri,this.cnonce=Ae(12),this.nc+=1,this.updateNcHex(),4294967296===this.nc&&(this.nc=1,this.ncHex="00000001"),this.calculateResponse(n),!0}toString(){const e=[];if(!this.response)throw new Error("response field does not exist, cannot generate Authorization header");return e.push("algorithm="+this.algorithm),e.push('username="'+this.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(", ")}updateNcHex(){const e=Number(this.nc).toString(16);this.ncHex="00000000".substr(0,8-e.length)+e}calculateResponse(e){let t,n;t=this.ha1,""!==t&&void 0!==t||(t=Rt(this.username+":"+this.realm+":"+this.password)),"auth"===this.qop?(n=Rt(this.method+":"+this.uri),this.response=Rt(t+":"+this.nonce+":"+this.ncHex+":"+this.cnonce+":auth:"+n)):"auth-int"===this.qop?(n=Rt(this.method+":"+this.uri+":"+Rt(e||"")),this.response=Rt(t+":"+this.nonce+":"+this.ncHex+":"+this.cnonce+":auth-int:"+n)):void 0===this.qop&&(n=Rt(this.method+":"+this.uri),this.response=Rt(t+":"+this.nonce+":"+n))}}(xt=wt=wt||(wt={}))[xt.error=0]="error",xt[xt.warn=1]="warn",xt[xt.log=2]="log",xt[xt.debug=3]="debug";class _t{constructor(e,t,n){this.logger=e,this.category=t,this.label=n}error(e){this.genericLog(wt.error,e)}warn(e){this.genericLog(wt.warn,e)}log(e){this.genericLog(wt.log,e)}debug(e){this.genericLog(wt.debug,e)}genericLog(e,t){this.logger.genericLog(e,this.category,this.label,t)}get level(){return this.logger.level}set level(e){this.logger.level=e}}class Dt{constructor(){this.builtinEnabled=!0,this._level=wt.log,this.loggers={},this.logger=this.getLogger("sip:loggerfactory")}get level(){return this._level}set level(e){e>=0&&e<=3?this._level=e:e>3?this._level=3:wt.hasOwnProperty(e)?this._level=e:this.logger.error("invalid 'level' parameter value: "+JSON.stringify(e))}get connector(){return this._connector}set connector(e){e?"function"==typeof e?this._connector=e:this.logger.error("invalid 'connector' parameter value: "+JSON.stringify(e)):this._connector=void 0}getLogger(e,t){if(t&&3===this.level)return new _t(this,e,t);if(this.loggers[e])return this.loggers[e];{const t=new _t(this,e);return this.loggers[e]=t,t}}genericLog(e,t,n,r){this.level>=e&&this.builtinEnabled&&this.print(e,t,n,r),this.connector&&this.connector(wt[e],t,n,r)}print(e,t,n,r){if("string"==typeof r){const e=[new Date,t];n&&e.push(n),r=e.concat(r).join(" | ")}switch(e){case wt.error:console.error(r);break;case wt.warn:console.warn(r);break;case wt.log:console.log(r);break;case wt.debug:console.debug(r)}}}function It(e,t){const n="\r\n";if(t.statusCode<100||t.statusCode>699)throw new TypeError("Invalid statusCode: "+t.statusCode);const r=t.reasonPhrase?t.reasonPhrase:Ne(t.statusCode);let i="SIP/2.0 "+t.statusCode+" "+r+n;t.statusCode>=100&&t.statusCode,t.statusCode;const o="From: "+e.getHeader("From")+n,a="Call-ID: "+e.callId+n,s="CSeq: "+e.cseq+" "+e.method+n,l=e.getHeaders("via").reduce((e,t)=>e+"Via: "+t+n,"");let c="To: "+e.getHeader("to");if(t.statusCode>100&&!e.parseHeader("to").hasParam("tag")){let e=t.toTag;e||(e=Me()),c+=";tag="+e}c+=n;let u="";t.supported&&(u="Supported: "+t.supported.join(", ")+n);let d="";t.userAgent&&(d="User-Agent: "+t.userAgent+n);let h="";return t.extraHeaders&&(h=t.extraHeaders.reduce((e,t)=>e+t.trim()+n,"")),i+=l,i+=o,i+=c,i+=s,i+=a,i+=u,i+=d,i+=h,t.body?(i+="Content-Type: "+t.body.contentType+n,i+="Content-Length: "+Oe(t.body.content)+n+n,i+=t.body.content):i+="Content-Length: 0\r\n\r\n",{message:i}}!function(e){function t(e,t){let n=t,r=0,i=0;if(e.substring(n,n+2).match(/(^\r\n)/))return-2;for(;0===r;){if(i=e.indexOf("\r\n",n),-1===i)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 n(e,t,n,r){const i=t.indexOf(":",n),o=t.substring(n,i).trim(),a=t.substring(i+1,r).trim();let s;switch(o.toLowerCase()){case"via":case"v":e.addHeader("via",a),1===e.getHeaders("via").length?(s=e.parseHeader("Via"),s&&(e.via=s,e.viaBranch=s.branch)):s=0;break;case"from":case"f":e.setHeader("from",a),s=e.parseHeader("from"),s&&(e.from=s,e.fromTag=s.getParam("tag"));break;case"to":case"t":e.setHeader("to",a),s=e.parseHeader("to"),s&&(e.to=s,e.toTag=s.getParam("tag"));break;case"record-route":if(s=_e.parse(a,"Record_Route"),-1===s){s=void 0;break}if(!(s instanceof Array)){s=void 0;break}s.forEach(t=>{e.addHeader("record-route",a.substring(t.position,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",a),s=e.parseHeader("call-id"),s&&(e.callId=a);break;case"contact":case"m":if(s=_e.parse(a,"Contact"),-1===s){s=void 0;break}if(!(s instanceof Array)){s=void 0;break}s.forEach(t=>{e.addHeader("contact",a.substring(t.position,t.offset)),e.headers.Contact[e.getHeaders("contact").length-1].parsed=t.parsed});break;case"content-length":case"l":e.setHeader("content-length",a),s=e.parseHeader("content-length");break;case"content-type":case"c":e.setHeader("content-type",a),s=e.parseHeader("content-type");break;case"cseq":e.setHeader("cseq",a),s=e.parseHeader("cseq"),s&&(e.cseq=s.value),e instanceof He&&(e.method=s.method);break;case"max-forwards":e.setHeader("max-forwards",a),s=e.parseHeader("max-forwards");break;case"www-authenticate":e.setHeader("www-authenticate",a),s=e.parseHeader("www-authenticate");break;case"proxy-authenticate":e.setHeader("proxy-authenticate",a),s=e.parseHeader("proxy-authenticate");break;case"refer-to":case"r":e.setHeader("refer-to",a),s=e.parseHeader("refer-to"),s&&(e.referTo=s);break;default:e.addHeader(o.toLowerCase(),a),s=0}return void 0!==s||{error:"error parsing header '"+o+"'"}}e.getHeader=t,e.parseHeader=n,e.parseMessage=function(e,r){let i=0,o=e.indexOf("\r\n");if(-1===o)return void r.warn("no CRLF found, not a SIP message, discarded");const a=e.substring(0,o),s=_e.parse(a,"Request_Response");let l,c;if(-1!==s){for(s.status_code?(l=new He,l.statusCode=s.status_code,l.reasonPhrase=s.reason_phrase):(l=new Le,l.method=s.method,l.ruri=s.uri),l.data=e,i=o+2;;){if(o=t(e,i),-2===o){c=i+2;break}if(-1===o)return void r.error("malformed message");const a=n(l,e,i,o);if(a&&!0!==a)return void r.error(a.error);i=o+2}return l.hasHeader("content-length")?l.body=e.substr(c,Number(l.getHeader("content-length"))):l.body=e.substring(c),l}r.warn('error parsing first line of SIP message: "'+a+'"')}}(kt=kt||(kt={}));class At extends de{constructor(e){super(e||"Unspecified transport error.")}}class Nt{constructor(e,t,n,r,i){this._transport=e,this._user=t,this._id=n,this._state=r,this.listeners=new Array,this.logger=t.loggerFactory.getLogger(i,n),this.logger.debug(`Constructing ${this.typeToString()} with id ${this.id}.`)}dispose(){this.logger.debug(`Destroyed ${this.typeToString()} with id ${this.id}.`)}get id(){return this._id}get kind(){throw new Error("Invalid kind.")}get state(){return this._state}get transport(){return this._transport}addStateChangeListener(e,t){const n=()=>{this.removeStateChangeListener(n),e()};!0===(null==t?void 0:t.once)?this.listeners.push(n):this.listeners.push(e)}notifyStateChangeListeners(){this.listeners.slice().forEach(e=>e())}removeStateChangeListener(e){this.listeners=this.listeners.filter(t=>t!==e)}logTransportError(e,t){this.logger.error(e.message),this.logger.error(`Transport error occurred in ${this.typeToString()} with id ${this.id}.`),this.logger.error(t)}send(e){return this.transport.send(e).catch(e=>{if(e instanceof At)throw this.onTransportError(e),e;let t;throw t=e&&"string"==typeof e.message?new At(e.message):new At,this.onTransportError(t),t})}setState(e){this.logger.debug(`State change to "${e}" on ${this.typeToString()} with id ${this.id}.`),this._state=e,this._user.onStateChange&&this._user.onStateChange(e),this.notifyStateChangeListeners()}typeToString(){return"UnknownType"}}class Mt extends Nt{constructor(e,t,n,r,i){super(t,n,e.viaBranch,r,i),this._request=e,this.user=n}get request(){return this._request}}(Tt=St=St||(St={})).Accepted="Accepted",Tt.Calling="Calling",Tt.Completed="Completed",Tt.Confirmed="Confirmed",Tt.Proceeding="Proceeding",Tt.Terminated="Terminated",Tt.Trying="Trying";class $t extends Mt{constructor(e,t,n){super(e,t,n,St.Proceeding,"sip.transaction.ist")}dispose(){this.stopProgressExtensionTimer(),this.H&&(clearTimeout(this.H),this.H=void 0),this.I&&(clearTimeout(this.I),this.I=void 0),this.L&&(clearTimeout(this.L),this.L=void 0),super.dispose()}get kind(){return"ist"}receiveRequest(e){switch(this.state){case St.Proceeding:if(e.method===Ze.INVITE)return void(this.lastProvisionalResponse&&this.send(this.lastProvisionalResponse).catch(e=>{this.logTransportError(e,"Failed to send retransmission of provisional response.")}));break;case St.Accepted:if(e.method===Ze.INVITE)return;break;case St.Completed:if(e.method===Ze.INVITE){if(!this.lastFinalResponse)throw new Error("Last final response undefined.");return void this.send(this.lastFinalResponse).catch(e=>{this.logTransportError(e,"Failed to send retransmission of final response.")})}if(e.method===Ze.ACK)return void this.stateTransition(St.Confirmed);break;case St.Confirmed:case St.Terminated:if(e.method===Ze.INVITE||e.method===Ze.ACK)return;break;default:throw new Error(`Invalid state ${this.state}`)}const t=`INVITE server transaction received unexpected ${e.method} request while in state ${this.state}.`;this.logger.warn(t)}receiveResponse(e,t){if(e<100||e>699)throw new Error(`Invalid status code ${e}`);switch(this.state){case St.Proceeding:if(e>=100&&e<=199)return this.lastProvisionalResponse=t,e>100&&this.startProgressExtensionTimer(),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send 1xx response.")});if(e>=200&&e<=299)return this.lastFinalResponse=t,this.stateTransition(St.Accepted),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send 2xx response.")});if(e>=300&&e<=699)return this.lastFinalResponse=t,this.stateTransition(St.Completed),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send non-2xx final response.")});break;case St.Accepted:if(e>=200&&e<=299)return void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send 2xx response.")});break;case St.Completed:case St.Confirmed:case St.Terminated:break;default:throw new Error(`Invalid state ${this.state}`)}const n=`INVITE server transaction received unexpected ${e} response from TU while in state ${this.state}.`;throw this.logger.error(n),new Error(n)}retransmitAcceptedResponse(){this.state===St.Accepted&&this.lastFinalResponse&&this.send(this.lastFinalResponse).catch(e=>{this.logTransportError(e,"Failed to send 2xx response.")})}onTransportError(e){this.user.onTransportError&&this.user.onTransportError(e)}typeToString(){return"INVITE server transaction"}stateTransition(e){const t=()=>{throw new Error(`Invalid state transition from ${this.state} to ${e}`)};switch(e){case St.Proceeding:t();break;case St.Accepted:case St.Completed:this.state!==St.Proceeding&&t();break;case St.Confirmed:this.state!==St.Completed&&t();break;case St.Terminated:this.state!==St.Accepted&&this.state!==St.Completed&&this.state!==St.Confirmed&&t();break;default:t()}this.stopProgressExtensionTimer(),e===St.Accepted&&(this.L=setTimeout(()=>this.timerL(),Qe.TIMER_L)),e===St.Completed&&(this.H=setTimeout(()=>this.timerH(),Qe.TIMER_H)),e===St.Confirmed&&(this.I=setTimeout(()=>this.timerI(),Qe.TIMER_I)),e===St.Terminated&&this.dispose(),this.setState(e)}startProgressExtensionTimer(){void 0===this.progressExtensionTimer&&(this.progressExtensionTimer=setInterval(()=>{if(this.logger.debug(`Progress extension timer expired for INVITE server transaction ${this.id}.`),!this.lastProvisionalResponse)throw new Error("Last provisional response undefined.");this.send(this.lastProvisionalResponse).catch(e=>{this.logTransportError(e,"Failed to send retransmission of provisional response.")})},Qe.PROVISIONAL_RESPONSE_INTERVAL))}stopProgressExtensionTimer(){void 0!==this.progressExtensionTimer&&(clearInterval(this.progressExtensionTimer),this.progressExtensionTimer=void 0)}timerG(){}timerH(){this.logger.debug(`Timer H expired for INVITE server transaction ${this.id}.`),this.state===St.Completed&&(this.logger.warn("ACK to negative final response was never received, terminating transaction."),this.stateTransition(St.Terminated))}timerI(){this.logger.debug(`Timer I expired for INVITE server transaction ${this.id}.`),this.stateTransition(St.Terminated)}timerL(){this.logger.debug(`Timer L expired for INVITE server transaction ${this.id}.`),this.state===St.Accepted&&this.stateTransition(St.Terminated)}}class Ot extends Nt{constructor(e,t,n,r,i){super(t,n,Ot.makeId(e),r,i),this._request=e,this.user=n,e.setViaHeader(this.id,t.protocol)}static makeId(e){if("CANCEL"===e.method){if(!e.branch)throw new Error("Outgoing CANCEL request without a branch.");return e.branch}return"z9hG4bK"+Math.floor(1e7*Math.random())}get request(){return this._request}onRequestTimeout(){this.user.onRequestTimeout&&this.user.onRequestTimeout()}}class jt extends Ot{constructor(e,t,n){super(e,t,n,St.Trying,"sip.transaction.nict"),this.F=setTimeout(()=>this.timerF(),Qe.TIMER_F),this.send(e.toString()).catch(e=>{this.logTransportError(e,"Failed to send initial outgoing request.")})}dispose(){this.F&&(clearTimeout(this.F),this.F=void 0),this.K&&(clearTimeout(this.K),this.K=void 0),super.dispose()}get kind(){return"nict"}receiveResponse(e){const t=e.statusCode;if(!t||t<100||t>699)throw new Error(`Invalid status code ${t}`);switch(this.state){case St.Trying:if(t>=100&&t<=199)return this.stateTransition(St.Proceeding),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=200&&t<=699)return this.stateTransition(St.Completed),408===t?void this.onRequestTimeout():void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case St.Proceeding:if(t>=100&&t<=199&&this.user.receiveResponse)return this.user.receiveResponse(e);if(t>=200&&t<=699)return this.stateTransition(St.Completed),408===t?void this.onRequestTimeout():void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case St.Completed:case St.Terminated:return;default:throw new Error(`Invalid state ${this.state}`)}const n=`Non-INVITE client transaction received unexpected ${t} response while in state ${this.state}.`;this.logger.warn(n)}onTransportError(e){this.user.onTransportError&&this.user.onTransportError(e),this.stateTransition(St.Terminated,!0)}typeToString(){return"non-INVITE client transaction"}stateTransition(e,t=!1){const n=()=>{throw new Error(`Invalid state transition from ${this.state} to ${e}`)};switch(e){case St.Trying:n();break;case St.Proceeding:this.state!==St.Trying&&n();break;case St.Completed:this.state!==St.Trying&&this.state!==St.Proceeding&&n();break;case St.Terminated:this.state!==St.Trying&&this.state!==St.Proceeding&&this.state!==St.Completed&&(t||n());break;default:n()}e===St.Completed&&(this.F&&(clearTimeout(this.F),this.F=void 0),this.K=setTimeout(()=>this.timerK(),Qe.TIMER_K)),e===St.Terminated&&this.dispose(),this.setState(e)}timerF(){this.logger.debug(`Timer F expired for non-INVITE client transaction ${this.id}.`),this.state!==St.Trying&&this.state!==St.Proceeding||(this.onRequestTimeout(),this.stateTransition(St.Terminated))}timerK(){this.state===St.Completed&&this.stateTransition(St.Terminated)}}class Lt{constructor(e,t){this.core=e,this.dialogState=t,this.core.dialogs.set(this.id,this)}static initialDialogStateForUserAgentClient(e,t){const n=t.getHeaders("record-route").reverse(),r=t.parseHeader("contact");if(!r)throw new Error("Contact undefined.");if(!(r instanceof Se))throw new Error("Contact not instance of NameAddrHeader.");const i=r.uri,o=e.cseq,a=e.callId,s=e.fromTag,l=t.toTag;if(!a)throw new Error("Call id undefined.");if(!s)throw new Error("From tag undefined.");if(!l)throw new Error("To tag undefined.");if(!e.from)throw new Error("From undefined.");if(!e.to)throw new Error("To undefined.");const c=e.from.uri,u=e.to.uri;if(!t.statusCode)throw new Error("Incoming response status code undefined.");return{id:a+s+l,early:t.statusCode<200,callId:a,localTag:s,remoteTag:l,localSequenceNumber:o,remoteSequenceNumber:void 0,localURI:c,remoteURI:u,remoteTarget:i,routeSet:n,secure:!1}}static initialDialogStateForUserAgentServer(e,t,n=!1){const r=e.getHeaders("record-route"),i=e.parseHeader("contact");if(!i)throw new Error("Contact undefined.");if(!(i instanceof Se))throw new Error("Contact not instance of NameAddrHeader.");const o=i.uri,a=e.cseq,s=e.callId,l=t,c=e.fromTag,u=e.from.uri;return{id:s+l+c,early:n,callId:s,localTag:l,remoteTag:c,localSequenceNumber:void 0,remoteSequenceNumber:a,localURI:e.to.uri,remoteURI:u,remoteTarget:o,routeSet:r,secure:!1}}dispose(){this.core.dialogs.delete(this.id)}get id(){return this.dialogState.id}get early(){return this.dialogState.early}get callId(){return this.dialogState.callId}get localTag(){return this.dialogState.localTag}get remoteTag(){return this.dialogState.remoteTag}get localSequenceNumber(){return this.dialogState.localSequenceNumber}get remoteSequenceNumber(){return this.dialogState.remoteSequenceNumber}get localURI(){return this.dialogState.localURI}get remoteURI(){return this.dialogState.remoteURI}get remoteTarget(){return this.dialogState.remoteTarget}get routeSet(){return this.dialogState.routeSet}get secure(){return this.dialogState.secure}get userAgentCore(){return this.core}confirm(){this.dialogState.early=!1}receiveRequest(e){if(e.method!==Ze.ACK){if(this.remoteSequenceNumber){if(e.cseq<=this.remoteSequenceNumber)throw new Error("Out of sequence in dialog request. Did you forget to call sequenceGuard()?");this.dialogState.remoteSequenceNumber=e.cseq}this.remoteSequenceNumber||(this.dialogState.remoteSequenceNumber=e.cseq)}}recomputeRouteSet(e){this.dialogState.routeSet=e.getHeaders("record-route").reverse()}createOutgoingRequestMessage(e,t){const n=this.remoteURI,r=this.remoteTag,i=this.localURI,o=this.localTag,a=this.callId;let s;s=t&&t.cseq?t.cseq:this.dialogState.localSequenceNumber?this.dialogState.localSequenceNumber+=1:this.dialogState.localSequenceNumber=1;const l=this.remoteTarget,c=this.routeSet,u=t&&t.extraHeaders,d=t&&t.body;return this.userAgentCore.makeOutgoingRequestMessage(e,l,i,n,{callId:a,cseq:s,fromTag:o,toTag:r,routeSet:c},u,d)}incrementLocalSequenceNumber(){if(!this.dialogState.localSequenceNumber)throw new Error("Local sequence number undefined.");this.dialogState.localSequenceNumber+=1}sequenceGuard(e){return e.method===Ze.ACK||(!(this.remoteSequenceNumber&&e.cseq<=this.remoteSequenceNumber)||(this.core.replyStateless(e,{statusCode:500}),!1))}}class Ht extends Ot{constructor(e,t,n){super(e,t,n,St.Calling,"sip.transaction.ict"),this.ackRetransmissionCache=new Map,this.B=setTimeout(()=>this.timerB(),Qe.TIMER_B),this.send(e.toString()).catch(e=>{this.logTransportError(e,"Failed to send initial outgoing request.")})}dispose(){this.B&&(clearTimeout(this.B),this.B=void 0),this.D&&(clearTimeout(this.D),this.D=void 0),this.M&&(clearTimeout(this.M),this.M=void 0),super.dispose()}get kind(){return"ict"}ackResponse(e){const t=e.toTag;if(!t)throw new Error("To tag undefined.");const n="z9hG4bK"+Math.floor(1e7*Math.random());e.setViaHeader(n,this.transport.protocol),this.ackRetransmissionCache.set(t,e),this.send(e.toString()).catch(e=>{this.logTransportError(e,"Failed to send ACK to 2xx response.")})}receiveResponse(e){const t=e.statusCode;if(!t||t<100||t>699)throw new Error(`Invalid status code ${t}`);switch(this.state){case St.Calling:if(t>=100&&t<=199)return this.stateTransition(St.Proceeding),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=200&&t<=299)return this.ackRetransmissionCache.set(e.toTag,void 0),this.stateTransition(St.Accepted),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=300&&t<=699)return this.stateTransition(St.Completed),this.ack(e),void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case St.Proceeding:if(t>=100&&t<=199)return void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=200&&t<=299)return this.ackRetransmissionCache.set(e.toTag,void 0),this.stateTransition(St.Accepted),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=300&&t<=699)return this.stateTransition(St.Completed),this.ack(e),void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case St.Accepted:if(t>=200&&t<=299){if(!this.ackRetransmissionCache.has(e.toTag))return this.ackRetransmissionCache.set(e.toTag,void 0),void(this.user.receiveResponse&&this.user.receiveResponse(e));const t=this.ackRetransmissionCache.get(e.toTag);return t?void this.send(t.toString()).catch(e=>{this.logTransportError(e,"Failed to send retransmission of ACK to 2xx response.")}):void 0}break;case St.Completed:if(t>=300&&t<=699)return void this.ack(e);break;case St.Terminated:break;default:throw new Error(`Invalid state ${this.state}`)}const n=`Received unexpected ${t} response while in state ${this.state}.`;this.logger.warn(n)}onTransportError(e){this.user.onTransportError&&this.user.onTransportError(e),this.stateTransition(St.Terminated,!0)}typeToString(){return"INVITE client transaction"}ack(e){const t=this.request.ruri,n=this.request.callId,r=this.request.cseq,i=this.request.getHeader("from"),o=e.getHeader("to"),a=this.request.getHeader("via"),s=this.request.getHeader("route");if(!i)throw new Error("From undefined.");if(!o)throw new Error("To undefined.");if(!a)throw new Error("Via undefined.");let l=`ACK ${t} SIP/2.0\r\n`;s&&(l+=`Route: ${s}\r\n`),l+=`Via: ${a}\r\n`,l+=`To: ${o}\r\n`,l+=`From: ${i}\r\n`,l+=`Call-ID: ${n}\r\n`,l+=`CSeq: ${r} ACK\r\n`,l+="Max-Forwards: 70\r\n",l+="Content-Length: 0\r\n\r\n",this.send(l).catch(e=>{this.logTransportError(e,"Failed to send ACK to non-2xx response.")})}stateTransition(e,t=!1){const n=()=>{throw new Error(`Invalid state transition from ${this.state} to ${e}`)};switch(e){case St.Calling:n();break;case St.Proceeding:this.state!==St.Calling&&n();break;case St.Accepted:case St.Completed:this.state!==St.Calling&&this.state!==St.Proceeding&&n();break;case St.Terminated:this.state!==St.Calling&&this.state!==St.Accepted&&this.state!==St.Completed&&(t||n());break;default:n()}this.B&&(clearTimeout(this.B),this.B=void 0),St.Proceeding,e===St.Completed&&(this.D=setTimeout(()=>this.timerD(),Qe.TIMER_D)),e===St.Accepted&&(this.M=setTimeout(()=>this.timerM(),Qe.TIMER_M)),e===St.Terminated&&this.dispose(),this.setState(e)}timerA(){}timerB(){this.logger.debug(`Timer B expired for INVITE client transaction ${this.id}.`),this.state===St.Calling&&(this.onRequestTimeout(),this.stateTransition(St.Terminated))}timerD(){this.logger.debug(`Timer D expired for INVITE client transaction ${this.id}.`),this.state===St.Completed&&this.stateTransition(St.Terminated)}timerM(){this.logger.debug(`Timer M expired for INVITE client transaction ${this.id}.`),this.state===St.Accepted&&this.stateTransition(St.Terminated)}}class Ft{constructor(e,t,n,r){this.transactionConstructor=e,this.core=t,this.message=n,this.delegate=r,this.challenged=!1,this.stale=!1,this.logger=this.loggerFactory.getLogger("sip.user-agent-client"),this.init()}dispose(){this.transaction.dispose()}get loggerFactory(){return this.core.loggerFactory}get transaction(){if(!this._transaction)throw new Error("Transaction undefined.");return this._transaction}cancel(e,t={}){if(!this.transaction)throw new Error("Transaction undefined.");if(!this.message.to)throw new Error("To undefined.");if(!this.message.from)throw new Error("From undefined.");const n=this.core.makeOutgoingRequestMessage(Ze.CANCEL,this.message.ruri,this.message.from.uri,this.message.to.uri,{toTag:this.message.toTag,fromTag:this.message.fromTag,callId:this.message.callId,cseq:this.message.cseq},t.extraHeaders);return n.branch=this.message.branch,this.message.headers.Route&&(n.headers.Route=this.message.headers.Route),e&&n.setHeader("Reason",e),this.transaction.state===St.Proceeding?new Ft(jt,this.core,n):this.transaction.addStateChangeListener(()=>{this.transaction&&this.transaction.state===St.Proceeding&&new Ft(jt,this.core,n)},{once:!0}),n}authenticationGuard(e,t){const n=e.statusCode;if(!n)throw new Error("Response status code undefined.");if(401!==n&&407!==n)return!0;let r,i;if(401===n?(r=e.parseHeader("www-authenticate"),i="authorization"):(r=e.parseHeader("proxy-authenticate"),i="proxy-authorization"),!r)return this.logger.warn(n+" with wrong or missing challenge, cannot authenticate"),!0;if(this.challenged&&(this.stale||!0!==r.stale))return this.logger.warn(n+" apparently in authentication loop, cannot authenticate"),!0;if(!this.credentials&&(this.credentials=this.core.configuration.authenticationFactory(),!this.credentials))return this.logger.warn("Unable to obtain credentials, cannot authenticate"),!0;if(!this.credentials.authenticate(this.message,r))return!0;this.challenged=!0,r.stale&&(this.stale=!0);let o=this.message.cseq+=1;return t&&t.localSequenceNumber&&(t.incrementLocalSequenceNumber(),o=this.message.cseq=t.localSequenceNumber),this.message.setHeader("cseq",o+" "+this.message.method),this.message.setHeader(i,this.credentials.toString()),this.init(),!1}onRequestTimeout(){this.logger.warn("User agent client request timed out. Generating internal 408 Request Timeout.");const e=new He;e.statusCode=408,e.reasonPhrase="Request Timeout",this.receiveResponse(e)}onTransportError(e){this.logger.error(e.message),this.logger.error("User agent client request transport error. Generating internal 503 Service Unavailable.");const t=new He;t.statusCode=503,t.reasonPhrase="Service Unavailable",this.receiveResponse(t)}receiveResponse(e){if(!this.authenticationGuard(e))return;const t=e.statusCode?e.statusCode.toString():"";if(!t)throw new Error("Response status code undefined.");switch(!0){case/^100$/.test(t):this.delegate&&this.delegate.onTrying&&this.delegate.onTrying({message:e});break;case/^1[0-9]{2}$/.test(t):this.delegate&&this.delegate.onProgress&&this.delegate.onProgress({message:e});break;case/^2[0-9]{2}$/.test(t):this.delegate&&this.delegate.onAccept&&this.delegate.onAccept({message:e});break;case/^3[0-9]{2}$/.test(t):this.delegate&&this.delegate.onRedirect&&this.delegate.onRedirect({message:e});break;case/^[4-6][0-9]{2}$/.test(t):this.delegate&&this.delegate.onReject&&this.delegate.onReject({message:e});break;default:throw new Error(`Invalid status code ${t}`)}}init(){const e={loggerFactory:this.loggerFactory,onRequestTimeout:()=>this.onRequestTimeout(),onStateChange:e=>{e===St.Terminated&&(this.core.userAgentClients.delete(n),t===this._transaction&&this.dispose())},onTransportError:e=>this.onTransportError(e),receiveResponse:e=>this.receiveResponse(e)},t=new this.transactionConstructor(this.message,this.core.transport,e);this._transaction=t;const n=t.id+t.request.method;this.core.userAgentClients.set(n,this)}}class Ut extends Ft{constructor(e,t,n){const r=e.createOutgoingRequestMessage(Ze.BYE,n);super(jt,e.userAgentCore,r,t),e.dispose()}}class zt extends Mt{constructor(e,t,n){super(e,t,n,St.Trying,"sip.transaction.nist")}dispose(){this.J&&(clearTimeout(this.J),this.J=void 0),super.dispose()}get kind(){return"nist"}receiveRequest(e){switch(this.state){case St.Trying:break;case St.Proceeding:if(!this.lastResponse)throw new Error("Last response undefined.");this.send(this.lastResponse).catch(e=>{this.logTransportError(e,"Failed to send retransmission of provisional response.")});break;case St.Completed:if(!this.lastResponse)throw new Error("Last response undefined.");this.send(this.lastResponse).catch(e=>{this.logTransportError(e,"Failed to send retransmission of final response.")});break;case St.Terminated:break;default:throw new Error(`Invalid state ${this.state}`)}}receiveResponse(e,t){if(e<100||e>699)throw new Error(`Invalid status code ${e}`);if(e>100&&e<=199)throw new Error("Provisional response other than 100 not allowed.");switch(this.state){case St.Trying:if(this.lastResponse=t,e>=100&&e<200)return this.stateTransition(St.Proceeding),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send provisional response.")});if(e>=200&&e<=699)return this.stateTransition(St.Completed),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send final response.")});break;case St.Proceeding:if(this.lastResponse=t,e>=200&&e<=699)return this.stateTransition(St.Completed),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send final response.")});break;case St.Completed:return;case St.Terminated:break;default:throw new Error(`Invalid state ${this.state}`)}const n=`Non-INVITE server transaction received unexpected ${e} response from TU while in state ${this.state}.`;throw this.logger.error(n),new Error(n)}onTransportError(e){this.user.onTransportError&&this.user.onTransportError(e),this.stateTransition(St.Terminated,!0)}typeToString(){return"non-INVITE server transaction"}stateTransition(e,t=!1){const n=()=>{throw new Error(`Invalid state transition from ${this.state} to ${e}`)};switch(e){case St.Trying:n();break;case St.Proceeding:this.state!==St.Trying&&n();break;case St.Completed:this.state!==St.Trying&&this.state!==St.Proceeding&&n();break;case St.Terminated:this.state!==St.Proceeding&&this.state!==St.Completed&&(t||n());break;default:n()}e===St.Completed&&(this.J=setTimeout(()=>this.timerJ(),Qe.TIMER_J)),e===St.Terminated&&this.dispose(),this.setState(e)}timerJ(){this.logger.debug(`Timer J expired for NON-INVITE server transaction ${this.id}.`),this.state===St.Completed&&this.stateTransition(St.Terminated)}}class qt{constructor(e,t,n,r){this.transactionConstructor=e,this.core=t,this.message=n,this.delegate=r,this.logger=this.loggerFactory.getLogger("sip.user-agent-server"),this.toTag=n.toTag?n.toTag:Me(),this.init()}dispose(){this.transaction.dispose()}get loggerFactory(){return this.core.loggerFactory}get transaction(){if(!this._transaction)throw new Error("Transaction undefined.");return this._transaction}accept(e={statusCode:200}){if(!this.acceptable)throw new Xe(`${this.message.method} not acceptable in state ${this.transaction.state}.`);const t=e.statusCode;if(t<200||t>299)throw new TypeError(`Invalid statusCode: ${t}`);return this.reply(e)}progress(e={statusCode:180}){if(!this.progressable)throw new Xe(`${this.message.method} not progressable in state ${this.transaction.state}.`);const t=e.statusCode;if(t<101||t>199)throw new TypeError(`Invalid statusCode: ${t}`);return this.reply(e)}redirect(e,t={statusCode:302}){if(!this.redirectable)throw new Xe(`${this.message.method} not redirectable in state ${this.transaction.state}.`);const n=t.statusCode;if(n<300||n>399)throw new TypeError(`Invalid statusCode: ${n}`);const r=new Array;e.forEach(e=>r.push(`Contact: ${e.toString()}`)),t.extraHeaders=(t.extraHeaders||[]).concat(r);return this.reply(t)}reject(e={statusCode:480}){if(!this.rejectable)throw new Xe(`${this.message.method} not rejectable in state ${this.transaction.state}.`);const t=e.statusCode;if(t<400||t>699)throw new TypeError(`Invalid statusCode: ${t}`);return this.reply(e)}trying(e){if(!this.tryingable)throw new Xe(`${this.message.method} not tryingable in state ${this.transaction.state}.`);return this.reply({statusCode:100})}receiveCancel(e){this.delegate&&this.delegate.onCancel&&this.delegate.onCancel(e)}get acceptable(){if(this.transaction instanceof $t)return this.transaction.state===St.Proceeding||this.transaction.state===St.Accepted;if(this.transaction instanceof zt)return this.transaction.state===St.Trying||this.transaction.state===St.Proceeding;throw new Error("Unknown transaction type.")}get progressable(){if(this.transaction instanceof $t)return this.transaction.state===St.Proceeding;if(this.transaction instanceof zt)return!1;throw new Error("Unknown transaction type.")}get redirectable(){if(this.transaction instanceof $t)return this.transaction.state===St.Proceeding;if(this.transaction instanceof zt)return this.transaction.state===St.Trying||this.transaction.state===St.Proceeding;throw new Error("Unknown transaction type.")}get rejectable(){if(this.transaction instanceof $t)return this.transaction.state===St.Proceeding;if(this.transaction instanceof zt)return this.transaction.state===St.Trying||this.transaction.state===St.Proceeding;throw new Error("Unknown transaction type.")}get tryingable(){if(this.transaction instanceof $t)return this.transaction.state===St.Proceeding;if(this.transaction instanceof zt)return this.transaction.state===St.Trying;throw new Error("Unknown transaction type.")}reply(e){e.toTag||100===e.statusCode||(e.toTag=this.toTag),e.userAgent=e.userAgent||this.core.configuration.userAgentHeaderFieldValue,e.supported=e.supported||this.core.configuration.supportedOptionTagsResponse;const t=It(this.message,e);return this.transaction.receiveResponse(e.statusCode,t.message),t}init(){const e={loggerFactory:this.loggerFactory,onStateChange:e=>{e===St.Terminated&&(this.core.userAgentServers.delete(n),this.dispose())},onTransportError:e=>{this.logger.error(e.message),this.delegate&&this.delegate.onTransportError?this.delegate.onTransportError(e):this.logger.error("User agent server response transport error.")}},t=new this.transactionConstructor(this.message,this.core.transport,e);this._transaction=t;const n=t.id;this.core.userAgentServers.set(t.id,this)}}class Vt extends qt{constructor(e,t,n){super(zt,e.userAgentCore,t,n)}}class Bt extends Ft{constructor(e,t,n){const r=e.createOutgoingRequestMessage(Ze.INFO,n);super(jt,e.userAgentCore,r,t)}}class Wt extends qt{constructor(e,t,n){super(zt,e.userAgentCore,t,n)}}class Yt extends Ft{constructor(e,t,n){super(jt,e,t,n)}}class Gt extends qt{constructor(e,t,n){super(zt,e,t,n)}}class Kt extends Ft{constructor(e,t,n){const r=e.createOutgoingRequestMessage(Ze.NOTIFY,n);super(jt,e.userAgentCore,r,t)}}class Qt extends qt{constructor(e,t,n){const r=void 0!==e.userAgentCore?e.userAgentCore:e;super(zt,r,t,n)}}class Xt extends Ft{constructor(e,t,n){const r=e.createOutgoingRequestMessage(Ze.PRACK,n);super(jt,e.userAgentCore,r,t),e.signalingStateTransition(r)}}class Zt extends qt{constructor(e,t,n){super(zt,e.userAgentCore,t,n),e.signalingStateTransition(t),this.dialog=e}accept(e={statusCode:200}){return e.body&&this.dialog.signalingStateTransition(e.body),super.accept(e)}}class Jt extends Ft{constructor(e,t,n){const r=e.createOutgoingRequestMessage(Ze.INVITE,n);super(Ht,e.userAgentCore,r,t),this.delegate=t,e.signalingStateTransition(r),e.reinviteUserAgentClient=this,this.dialog=e}receiveResponse(e){if(!this.authenticationGuard(e,this.dialog))return;const t=e.statusCode?e.statusCode.toString():"";if(!t)throw new Error("Response status code undefined.");switch(!0){case/^100$/.test(t):this.delegate&&this.delegate.onTrying&&this.delegate.onTrying({message:e});break;case/^1[0-9]{2}$/.test(t):this.delegate&&this.delegate.onProgress&&this.delegate.onProgress({message:e,session:this.dialog,prack:e=>{throw new Error("Unimplemented.")}});break;case/^2[0-9]{2}$/.test(t):this.dialog.signalingStateTransition(e),this.delegate&&this.delegate.onAccept&&this.delegate.onAccept({message:e,session:this.dialog,ack:e=>this.dialog.ack(e)});break;case/^3[0-9]{2}$/.test(t):this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentClient=void 0,this.delegate&&this.delegate.onRedirect&&this.delegate.onRedirect({message:e});break;case/^[4-6][0-9]{2}$/.test(t):this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentClient=void 0,this.delegate&&this.delegate.onReject&&this.delegate.onReject({message:e});break;default:throw new Error(`Invalid status code ${t}`)}}}class en extends qt{constructor(e,t,n){super($t,e.userAgentCore,t,n),e.reinviteUserAgentServer=this,this.dialog=e}accept(e={statusCode:200}){e.extraHeaders=e.extraHeaders||[],e.extraHeaders=e.extraHeaders.concat(this.dialog.routeSet.map(e=>`Record-Route: ${e}`));const t=super.accept(e),n=this.dialog,r=Object.assign(Object.assign({},t),{session:n});return e.body&&this.dialog.signalingStateTransition(e.body),this.dialog.reConfirm(),r}progress(e={statusCode:180}){const t=super.progress(e),n=this.dialog,r=Object.assign(Object.assign({},t),{session:n});return e.body&&this.dialog.signalingStateTransition(e.body),r}redirect(e,t={statusCode:302}){throw this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentServer=void 0,new Error("Unimplemented.")}reject(e={statusCode:488}){return this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentServer=void 0,super.reject(e)}}class tn extends Ft{constructor(e,t,n){const r=e.createOutgoingRequestMessage(Ze.REFER,n);super(jt,e.userAgentCore,r,t)}}class nn extends qt{constructor(e,t,n){const r=void 0!==e.userAgentCore?e.userAgentCore:e;super(zt,r,t,n)}}class rn extends Lt{constructor(e,t,n,r){super(t,n),this.initialTransaction=e,this._signalingState=Ye.Initial,this.ackWait=!1,this.ackProcessing=!1,this.delegate=r,e instanceof $t&&(this.ackWait=!0),this.early||this.start2xxRetransmissionTimer(),this.signalingStateTransition(e.request),this.logger=t.loggerFactory.getLogger("sip.invite-dialog"),this.logger.log(`INVITE dialog ${this.id} constructed`)}dispose(){super.dispose(),this._signalingState=Ye.Closed,this._offer=void 0,this._answer=void 0,this.invite2xxTimer&&(clearTimeout(this.invite2xxTimer),this.invite2xxTimer=void 0),this.logger.log(`INVITE dialog ${this.id} destroyed`)}get sessionState(){return this.early?Be.Early:this.ackWait?Be.AckWait:this._signalingState===Ye.Closed?Be.Terminated:Be.Confirmed}get signalingState(){return this._signalingState}get offer(){return this._offer}get answer(){return this._answer}confirm(){this.early&&this.start2xxRetransmissionTimer(),super.confirm()}reConfirm(){this.reinviteUserAgentServer&&this.startReInvite2xxRetransmissionTimer()}ack(e={}){let t;if(this.logger.log(`INVITE dialog ${this.id} sending ACK request`),this.reinviteUserAgentClient){if(!(this.reinviteUserAgentClient.transaction instanceof Ht))throw new Error("Transaction not instance of InviteClientTransaction.");t=this.reinviteUserAgentClient.transaction,this.reinviteUserAgentClient=void 0}else{if(!(this.initialTransaction instanceof Ht))throw new Error("Initial transaction not instance of InviteClientTransaction.");t=this.initialTransaction}const n=this.createOutgoingRequestMessage(Ze.ACK,{cseq:t.request.cseq,extraHeaders:e.extraHeaders,body:e.body});return t.ackResponse(n),this.signalingStateTransition(n),{message:n}}bye(e,t){if(this.logger.log(`INVITE dialog ${this.id} sending BYE request`),this.initialTransaction instanceof $t){if(this.early)throw new Error("UAS MUST NOT send a BYE on early dialogs.");if(this.ackWait&&this.initialTransaction.state!==St.Terminated)throw new Error("UAS MUST NOT send a BYE on a confirmed dialog until it has received an ACK for its 2xx response or until the server transaction times out.")}return new Ut(this,e,t)}info(e,t){if(this.logger.log(`INVITE dialog ${this.id} sending INFO request`),this.early)throw new Error("Dialog not confirmed.");return new Bt(this,e,t)}invite(e,t){if(this.logger.log(`INVITE dialog ${this.id} sending INVITE request`),this.early)throw new Error("Dialog not confirmed.");if(this.reinviteUserAgentClient)throw new Error("There is an ongoing re-INVITE client transaction.");if(this.reinviteUserAgentServer)throw new Error("There is an ongoing re-INVITE server transaction.");return new Jt(this,e,t)}message(e,t){if(this.logger.log(`INVITE dialog ${this.id} sending MESSAGE request`),this.early)throw new Error("Dialog not confirmed.");const n=this.createOutgoingRequestMessage(Ze.MESSAGE,t);return new Yt(this.core,n,e)}notify(e,t){if(this.logger.log(`INVITE dialog ${this.id} sending NOTIFY request`),this.early)throw new Error("Dialog not confirmed.");return new Kt(this,e,t)}prack(e,t){return this.logger.log(`INVITE dialog ${this.id} sending PRACK request`),new Xt(this,e,t)}refer(e,t){if(this.logger.log(`INVITE dialog ${this.id} sending REFER request`),this.early)throw new Error("Dialog not confirmed.");return new tn(this,e,t)}receiveRequest(e){if(this.logger.log(`INVITE dialog ${this.id} received ${e.method} request`),e.method!==Ze.ACK)if(this.sequenceGuard(e)){if(super.receiveRequest(e),e.method===Ze.INVITE){const t=()=>{const e=this.ackWait?"waiting for initial ACK":"processing initial ACK";this.logger.warn(`INVITE dialog ${this.id} received re-INVITE while ${e}`);let t="RFC 5407 suggests the following to avoid this race condition... ";t+=" Note: Implementation issues are outside the scope of this document,",t+=" but the following tip is provided for avoiding race conditions of",t+=" this type. The caller can delay sending re-INVITE F6 for some period",t+=" of time (2 seconds, perhaps), after which the caller can reasonably",t+=" assume that its ACK has been received. Implementors can decouple the",t+=" actions of the user (e.g., pressing the hold button) from the actions",t+=" of the protocol (the sending of re-INVITE F6), so that the UA can",t+=" behave like this. In this case, it is the implementor's choice as to",t+=" how long to wait. In most cases, such an implementation may be",t+=" useful to prevent the type of race condition shown in this section.",t+=" This document expresses no preference about whether or not they",t+=" should wait for an ACK to be delivered. After considering the impact",t+=" on user experience, implementors should decide whether or not to wait",t+=" for a while, because the user experience depends on the",t+=" implementation and has no direct bearing on protocol behavior.",this.logger.warn("RFC 5407 suggests the following to avoid this race condition... Note: Implementation issues are outside the scope of this document, but the following tip is provided for avoiding race conditions of this type. The caller can delay sending re-INVITE F6 for some period of time (2 seconds, perhaps), after which the caller can reasonably assume that its ACK has been received. Implementors can decouple the actions of the user (e.g., pressing the hold button) from the actions of the protocol (the sending of re-INVITE F6), so that the UA can behave like this. In this case, it is the implementor's choice as to how long to wait. In most cases, such an implementation may be useful to prevent the type of race condition shown in this section. This document expresses no preference about whether or not they should wait for an ACK to be delivered. After considering the impact on user experience, implementors should decide whether or not to wait for a while, because the user experience depends on the implementation and has no direct bearing on protocol behavior.")},n=[`Retry-After: ${Math.floor(10*Math.random())+1}`];if(this.ackProcessing)return this.core.replyStateless(e,{statusCode:500,extraHeaders:n}),void t();if(this.ackWait&&this.signalingState!==Ye.Stable)return this.core.replyStateless(e,{statusCode:500,extraHeaders:n}),void t();if(this.reinviteUserAgentServer)return void this.core.replyStateless(e,{statusCode:500,extraHeaders:n});if(this.reinviteUserAgentClient)return void this.core.replyStateless(e,{statusCode:491})}if(e.method===Ze.INVITE){const t=e.parseHeader("contact");if(!t)throw new Error("Contact undefined.");if(!(t instanceof Se))throw new Error("Contact not instance of NameAddrHeader.");this.dialogState.remoteTarget=t.uri}switch(e.method){case Ze.BYE:{const t=new Vt(this,e);this.delegate&&this.delegate.onBye?this.delegate.onBye(t):t.accept(),this.dispose()}break;case Ze.INFO:{const t=new Wt(this,e);this.delegate&&this.delegate.onInfo?this.delegate.onInfo(t):t.reject({statusCode:469,extraHeaders:["Recv-Info:"]})}break;case Ze.INVITE:{const t=new en(this,e);this.signalingStateTransition(e),this.delegate&&this.delegate.onInvite?this.delegate.onInvite(t):t.reject({statusCode:488})}break;case Ze.MESSAGE:{const t=new Gt(this.core,e);this.delegate&&this.delegate.onMessage?this.delegate.onMessage(t):t.accept()}break;case Ze.NOTIFY:{const t=new Qt(this,e);this.delegate&&this.delegate.onNotify?this.delegate.onNotify(t):t.accept()}break;case Ze.PRACK:{const t=new Zt(this,e);this.delegate&&this.delegate.onPrack?this.delegate.onPrack(t):t.accept()}break;case Ze.REFER:{const t=new nn(this,e);this.delegate&&this.delegate.onRefer?this.delegate.onRefer(t):t.reject()}break;default:this.logger.log(`INVITE dialog ${this.id} received unimplemented ${e.method} request`),this.core.replyStateless(e,{statusCode:501})}}else this.logger.log(`INVITE dialog ${this.id} rejected out of order ${e.method} request.`);else{if(this.ackWait){if(this.initialTransaction instanceof Ht)return void this.logger.warn(`INVITE dialog ${this.id} received unexpected ${e.method} request, dropping.`);if(this.initialTransaction.request.cseq!==e.cseq)return void this.logger.warn(`INVITE dialog ${this.id} received unexpected ${e.method} request, dropping.`);this.ackWait=!1}else{if(!this.reinviteUserAgentServer)return void this.logger.warn(`INVITE dialog ${this.id} received unexpected ${e.method} request, dropping.`);if(this.reinviteUserAgentServer.transaction.request.cseq!==e.cseq)return void this.logger.warn(`INVITE dialog ${this.id} received unexpected ${e.method} request, dropping.`);this.reinviteUserAgentServer=void 0}if(this.signalingStateTransition(e),this.delegate&&this.delegate.onAck){const t=this.delegate.onAck({message:e});t instanceof Promise&&(this.ackProcessing=!0,t.then(()=>this.ackProcessing=!1).catch(()=>this.ackProcessing=!1))}}}reliableSequenceGuard(e){const t=e.statusCode;if(!t)throw new Error("Status code undefined");if(t>100&&t<200){const t=e.getHeader("require"),n=e.getHeader("rseq"),r=t&&t.includes("100rel")&&n?Number(n):void 0;if(r){if(this.rseq&&this.rseq+1!==r)return!1;this.rseq=this.rseq?this.rseq+1:r}}return!0}signalingStateRollback(){this._signalingState!==Ye.HaveLocalOffer&&this.signalingState!==Ye.HaveRemoteOffer||this._rollbackOffer&&this._rollbackAnswer&&(this._signalingState=Ye.Stable,this._offer=this._rollbackOffer,this._answer=this._rollbackAnswer)}signalingStateTransition(e){const t=Ve(e);if(t&&"session"===t.contentDisposition){if(this._signalingState===Ye.Stable&&(this._rollbackOffer=this._offer,this._rollbackAnswer=this._answer),e instanceof Le)switch(this._signalingState){case Ye.Initial:case Ye.Stable:this._signalingState=Ye.HaveRemoteOffer,this._offer=t,this._answer=void 0;break;case Ye.HaveLocalOffer:this._signalingState=Ye.Stable,this._answer=t;break;case Ye.HaveRemoteOffer:case Ye.Closed:break;default:throw new Error("Unexpected signaling state.")}if(e instanceof He)switch(this._signalingState){case Ye.Initial:case Ye.Stable:this._signalingState=Ye.HaveRemoteOffer,this._offer=t,this._answer=void 0;break;case Ye.HaveLocalOffer:this._signalingState=Ye.Stable,this._answer=t;break;case Ye.HaveRemoteOffer:case Ye.Closed:break;default:throw new Error("Unexpected signaling state.")}if(e instanceof Fe)switch(this._signalingState){case Ye.Initial:case Ye.Stable:this._signalingState=Ye.HaveLocalOffer,this._offer=t,this._answer=void 0;break;case Ye.HaveLocalOffer:break;case Ye.HaveRemoteOffer:this._signalingState=Ye.Stable,this._answer=t;break;case Ye.Closed:break;default:throw new Error("Unexpected signaling state.")}if(qe(e))switch(this._signalingState){case Ye.Initial:case Ye.Stable:this._signalingState=Ye.HaveLocalOffer,this._offer=t,this._answer=void 0;break;case Ye.HaveLocalOffer:break;case Ye.HaveRemoteOffer:this._signalingState=Ye.Stable,this._answer=t;break;case Ye.Closed:break;default:throw new Error("Unexpected signaling state.")}}}start2xxRetransmissionTimer(){if(this.initialTransaction instanceof $t){const e=this.initialTransaction;let t=Qe.T1;const n=()=>{this.ackWait?(this.logger.log("No ACK for 2xx response received, attempting retransmission"),e.retransmitAcceptedResponse(),t=Math.min(2*t,Qe.T2),this.invite2xxTimer=setTimeout(n,t)):this.invite2xxTimer=void 0};this.invite2xxTimer=setTimeout(n,t);const r=()=>{e.state===St.Terminated&&(e.removeStateChangeListener(r),this.invite2xxTimer&&(clearTimeout(this.invite2xxTimer),this.invite2xxTimer=void 0),this.ackWait&&(this.delegate&&this.delegate.onAckTimeout?this.delegate.onAckTimeout():this.bye()))};e.addStateChangeListener(r)}}startReInvite2xxRetransmissionTimer(){if(this.reinviteUserAgentServer&&this.reinviteUserAgentServer.transaction instanceof $t){const e=this.reinviteUserAgentServer.transaction;let t=Qe.T1;const n=()=>{this.reinviteUserAgentServer?(this.logger.log("No ACK for 2xx response received, attempting retransmission"),e.retransmitAcceptedResponse(),t=Math.min(2*t,Qe.T2),this.invite2xxTimer=setTimeout(n,t)):this.invite2xxTimer=void 0};this.invite2xxTimer=setTimeout(n,t);const r=()=>{e.state===St.Terminated&&(e.removeStateChangeListener(r),this.invite2xxTimer&&(clearTimeout(this.invite2xxTimer),this.invite2xxTimer=void 0),this.reinviteUserAgentServer)};e.addStateChangeListener(r)}}}class on extends Ft{constructor(e,t,n){super(Ht,e,t,n),this.confirmedDialogAcks=new Map,this.confirmedDialogs=new Map,this.earlyDialogs=new Map,this.delegate=n}dispose(){this.earlyDialogs.forEach(e=>e.dispose()),this.earlyDialogs.clear(),super.dispose()}onTransportError(e){if(this.transaction.state===St.Calling)return super.onTransportError(e);this.logger.error(e.message),this.logger.error("User agent client request transport error while sending ACK.")}receiveResponse(e){if(!this.authenticationGuard(e))return;const t=e.statusCode?e.statusCode.toString():"";if(!t)throw new Error("Response status code undefined.");switch(!0){case/^100$/.test(t):return void(this.delegate&&this.delegate.onTrying&&this.delegate.onTrying({message:e}));case/^1[0-9]{2}$/.test(t):{if(!e.toTag)return void this.logger.warn("Non-100 1xx INVITE response received without a to tag, dropping.");if(!e.parseHeader("contact"))return void this.logger.error("Non-100 1xx INVITE response received without a Contact header field, dropping.");const t=Lt.initialDialogStateForUserAgentClient(this.message,e);let n=this.earlyDialogs.get(t.id);if(!n){const e=this.transaction;if(!(e instanceof Ht))throw new Error("Transaction not instance of InviteClientTransaction.");n=new rn(e,this.core,t),this.earlyDialogs.set(n.id,n)}if(!n.reliableSequenceGuard(e))return void this.logger.warn("1xx INVITE reliable response received out of order or is a retransmission, dropping.");n.signalingState!==Ye.Initial&&n.signalingState!==Ye.HaveLocalOffer||n.signalingStateTransition(e);const r=n;this.delegate&&this.delegate.onProgress&&this.delegate.onProgress({message:e,session:r,prack:e=>r.prack(void 0,e)})}return;case/^2[0-9]{2}$/.test(t):{if(!e.toTag)return void this.logger.error("2xx INVITE response received without a to tag, dropping.");if(!e.parseHeader("contact"))return void this.logger.error("2xx INVITE response received without a Contact header field, dropping.");const t=Lt.initialDialogStateForUserAgentClient(this.message,e);let n=this.confirmedDialogs.get(t.id);if(n){const e=this.confirmedDialogAcks.get(t.id);if(e){const t=this.transaction;if(!(t instanceof Ht))throw new Error("Client transaction not instance of InviteClientTransaction.");t.ackResponse(e.message)}return}if(n=this.earlyDialogs.get(t.id),n)n.confirm(),n.recomputeRouteSet(e),this.earlyDialogs.delete(n.id),this.confirmedDialogs.set(n.id,n);else{const e=this.transaction;if(!(e instanceof Ht))throw new Error("Transaction not instance of InviteClientTransaction.");n=new rn(e,this.core,t),this.confirmedDialogs.set(n.id,n)}n.signalingState!==Ye.Initial&&n.signalingState!==Ye.HaveLocalOffer||n.signalingStateTransition(e);const r=n;if(this.delegate&&this.delegate.onAccept)this.delegate.onAccept({message:e,session:r,ack:e=>{const t=r.ack(e);return this.confirmedDialogAcks.set(r.id,t),t}});else{const e=r.ack();this.confirmedDialogAcks.set(r.id,e)}}return;case/^3[0-9]{2}$/.test(t):return this.earlyDialogs.forEach(e=>e.dispose()),this.earlyDialogs.clear(),void(this.delegate&&this.delegate.onRedirect&&this.delegate.onRedirect({message:e}));case/^[4-6][0-9]{2}$/.test(t):return this.earlyDialogs.forEach(e=>e.dispose()),this.earlyDialogs.clear(),void(this.delegate&&this.delegate.onReject&&this.delegate.onReject({message:e}));default:throw new Error(`Invalid status code ${t}`)}}}class an extends qt{constructor(e,t,n){super($t,e,t,n),this.core=e}dispose(){this.earlyDialog&&this.earlyDialog.dispose(),super.dispose()}accept(e={statusCode:200}){if(!this.acceptable)throw new Xe(`${this.message.method} not acceptable in state ${this.transaction.state}.`);if(!this.confirmedDialog)if(this.earlyDialog)this.earlyDialog.confirm(),this.confirmedDialog=this.earlyDialog,this.earlyDialog=void 0;else{const e=this.transaction;if(!(e instanceof $t))throw new Error("Transaction not instance of InviteClientTransaction.");const t=Lt.initialDialogStateForUserAgentServer(this.message,this.toTag);this.confirmedDialog=new rn(e,this.core,t)}const t=this.message.getHeaders("record-route").map(e=>`Record-Route: ${e}`),n=`Contact: ${this.core.configuration.contact.toString()}`,r="Allow: "+et.toString();if(!e.body)if(this.confirmedDialog.signalingState===Ye.Stable)e.body=this.confirmedDialog.answer;else if(this.confirmedDialog.signalingState===Ye.Initial||this.confirmedDialog.signalingState===Ye.HaveRemoteOffer)throw new Error("Response must have a body.");e.statusCode=e.statusCode||200,e.extraHeaders=e.extraHeaders||[],e.extraHeaders=e.extraHeaders.concat(t),e.extraHeaders.push(r),e.extraHeaders.push(n);const i=super.accept(e),o=this.confirmedDialog,a=Object.assign(Object.assign({},i),{session:o});return e.body&&this.confirmedDialog.signalingState!==Ye.Stable&&this.confirmedDialog.signalingStateTransition(e.body),a}progress(e={statusCode:180}){if(!this.progressable)throw new Xe(`${this.message.method} not progressable in state ${this.transaction.state}.`);if(!this.earlyDialog){const e=this.transaction;if(!(e instanceof $t))throw new Error("Transaction not instance of InviteClientTransaction.");const t=Lt.initialDialogStateForUserAgentServer(this.message,this.toTag,!0);this.earlyDialog=new rn(e,this.core,t)}const t=this.message.getHeaders("record-route").map(e=>`Record-Route: ${e}`),n=`Contact: ${this.core.configuration.contact}`;e.extraHeaders=e.extraHeaders||[],e.extraHeaders=e.extraHeaders.concat(t),e.extraHeaders.push(n);const r=super.progress(e),i=this.earlyDialog,o=Object.assign(Object.assign({},r),{session:i});return e.body&&this.earlyDialog.signalingState!==Ye.Stable&&this.earlyDialog.signalingStateTransition(e.body),o}redirect(e,t={statusCode:302}){return super.redirect(e,t)}reject(e={statusCode:486}){return super.reject(e)}}class sn extends Ft{constructor(e,t,n){super(jt,e,t,n)}}class ln extends Ft{constructor(e,t,n){super(jt,e,t,n)}}class cn extends qt{constructor(e,t,n){super(zt,e,t,n),this.core=e}}class un extends Ft{constructor(e,t,n){const r=e.createOutgoingRequestMessage(Ze.SUBSCRIBE,n);super(jt,e.userAgentCore,r,t),this.dialog=e}waitNotifyStop(){}receiveResponse(e){if(e.statusCode&&e.statusCode>=200&&e.statusCode<300){const t=e.getHeader("Expires");if(t){const e=Number(t);this.dialog.subscriptionExpires>e&&(this.dialog.subscriptionExpires=e)}else this.logger.warn("Expires header missing in a 200-class response to SUBSCRIBE")}if(e.statusCode&&e.statusCode>=400&&e.statusCode<700){[404,405,410,416,480,481,482,483,484,485,489,501,604].includes(e.statusCode)&&this.dialog.terminate()}super.receiveResponse(e)}}class dn extends Lt{constructor(e,t,n,r,i,o){super(r,i),this.delegate=o,this._autoRefresh=!1,this._subscriptionEvent=e,this._subscriptionExpires=t,this._subscriptionExpiresInitial=t,this._subscriptionExpiresLastSet=Math.floor(Date.now()/1e3),this._subscriptionRefresh=void 0,this._subscriptionRefreshLastSet=void 0,this._subscriptionState=n,this.logger=r.loggerFactory.getLogger("sip.subscribe-dialog"),this.logger.log(`SUBSCRIBE dialog ${this.id} constructed`)}static initialDialogStateForSubscription(e,t){const n=t.getHeaders("record-route"),r=t.parseHeader("contact");if(!r)throw new Error("Contact undefined.");if(!(r instanceof Se))throw new Error("Contact not instance of NameAddrHeader.");const i=r.uri,o=e.cseq,a=e.callId,s=e.fromTag,l=t.fromTag;if(!a)throw new Error("Call id undefined.");if(!s)throw new Error("From tag undefined.");if(!l)throw new Error("To tag undefined.");if(!e.from)throw new Error("From undefined.");if(!e.to)throw new Error("To undefined.");return{id:a+s+l,early:!1,callId:a,localTag:s,remoteTag:l,localSequenceNumber:o,remoteSequenceNumber:void 0,localURI:e.from.uri,remoteURI:e.to.uri,remoteTarget:i,routeSet:n,secure:!1}}dispose(){super.dispose(),this.N&&(clearTimeout(this.N),this.N=void 0),this.refreshTimerClear(),this.logger.log(`SUBSCRIBE dialog ${this.id} destroyed`)}get autoRefresh(){return this._autoRefresh}set autoRefresh(e){this._autoRefresh=!0,this.refreshTimerSet()}get subscriptionEvent(){return this._subscriptionEvent}get subscriptionExpires(){const e=Math.floor(Date.now()/1e3)-this._subscriptionExpiresLastSet,t=this._subscriptionExpires-e;return Math.max(t,0)}set subscriptionExpires(e){if(e<0)throw new Error("Expires must be greater than or equal to zero.");if(this._subscriptionExpires=e,this._subscriptionExpiresLastSet=Math.floor(Date.now()/1e3),this.autoRefresh){const t=this.subscriptionRefresh;(void 0===t||t>=e)&&this.refreshTimerSet()}}get subscriptionExpiresInitial(){return this._subscriptionExpiresInitial}get subscriptionRefresh(){if(void 0===this._subscriptionRefresh||void 0===this._subscriptionRefreshLastSet)return;const e=Math.floor(Date.now()/1e3)-this._subscriptionRefreshLastSet,t=this._subscriptionRefresh-e;return Math.max(t,0)}get subscriptionState(){return this._subscriptionState}receiveRequest(e){if(this.logger.log(`SUBSCRIBE dialog ${this.id} received ${e.method} request`),this.sequenceGuard(e))if(super.receiveRequest(e),e.method===Ze.NOTIFY)this.onNotify(e);else this.logger.log(`SUBSCRIBE dialog ${this.id} received unimplemented ${e.method} request`),this.core.replyStateless(e,{statusCode:501});else this.logger.log(`SUBSCRIBE dialog ${this.id} rejected out of order ${e.method} request.`)}refresh(){const e="Allow: "+et.toString(),t={};return t.extraHeaders=(t.extraHeaders||[]).slice(),t.extraHeaders.push(e),t.extraHeaders.push("Event: "+this.subscriptionEvent),t.extraHeaders.push("Expires: "+this.subscriptionExpiresInitial),t.extraHeaders.push("Contact: "+this.core.configuration.contact.toString()),this.subscribe(void 0,t)}subscribe(e,t={}){var n;if(this.subscriptionState!==pt.Pending&&this.subscriptionState!==pt.Active)throw new Error(`Invalid state ${this.subscriptionState}. May only re-subscribe while in state "pending" or "active".`);this.logger.log(`SUBSCRIBE dialog ${this.id} sending SUBSCRIBE request`);const r=new un(this,e,t);return this.N&&(clearTimeout(this.N),this.N=void 0),(null===(n=t.extraHeaders)||void 0===n?void 0:n.includes("Expires: 0"))||(this.N=setTimeout(()=>this.timerN(),Qe.TIMER_N)),r}terminate(){this.stateTransition(pt.Terminated),this.onTerminated()}unsubscribe(){const e="Allow: "+et.toString(),t={};return t.extraHeaders=(t.extraHeaders||[]).slice(),t.extraHeaders.push(e),t.extraHeaders.push("Event: "+this.subscriptionEvent),t.extraHeaders.push("Expires: 0"),t.extraHeaders.push("Contact: "+this.core.configuration.contact.toString()),this.subscribe(void 0,t)}onNotify(e){const t=e.parseHeader("Event").event;if(!t||t!==this.subscriptionEvent)return void this.core.replyStateless(e,{statusCode:489});this.N&&(clearTimeout(this.N),this.N=void 0);const n=e.parseHeader("Subscription-State");if(!n||!n.state)return void this.core.replyStateless(e,{statusCode:489});const r=n.state,i=n.expires?Math.max(n.expires,0):void 0;switch(r){case"pending":this.stateTransition(pt.Pending,i);break;case"active":this.stateTransition(pt.Active,i);break;case"terminated":this.stateTransition(pt.Terminated,i);break;default:this.logger.warn("Unrecognized subscription state.")}const o=new Qt(this,e);this.delegate&&this.delegate.onNotify?this.delegate.onNotify(o):o.accept()}onRefresh(e){this.delegate&&this.delegate.onRefresh&&this.delegate.onRefresh(e)}onTerminated(){this.delegate&&this.delegate.onTerminated&&this.delegate.onTerminated()}refreshTimerClear(){this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=void 0)}refreshTimerSet(){if(this.refreshTimerClear(),this.autoRefresh&&this.subscriptionExpires>0){const e=900*this.subscriptionExpires;this._subscriptionRefresh=Math.floor(e/1e3),this._subscriptionRefreshLastSet=Math.floor(Date.now()/1e3),this.refreshTimer=setTimeout(()=>{this.refreshTimer=void 0,this._subscriptionRefresh=void 0,this._subscriptionRefreshLastSet=void 0,this.onRefresh(this.refresh())},e)}}stateTransition(e,t){const n=()=>{this.logger.warn(`Invalid subscription state transition from ${this.subscriptionState} to ${e}`)};switch(e){case pt.Initial:case pt.NotifyWait:return void n();case pt.Pending:if(this.subscriptionState!==pt.NotifyWait&&this.subscriptionState!==pt.Pending)return void n();break;case pt.Active:case pt.Terminated:if(this.subscriptionState!==pt.NotifyWait&&this.subscriptionState!==pt.Pending&&this.subscriptionState!==pt.Active)return void n();break;default:return void n()}e===pt.Pending&&t&&(this.subscriptionExpires=t),e===pt.Active&&t&&(this.subscriptionExpires=t),e===pt.Terminated&&this.dispose(),this._subscriptionState=e}timerN(){this.logger.warn("Timer N expired for SUBSCRIBE dialog. Timed out waiting for NOTIFY."),this.subscriptionState!==pt.Terminated&&(this.stateTransition(pt.Terminated),this.onTerminated())}}class hn extends Ft{constructor(e,t,n){const r=t.getHeader("Event");if(!r)throw new Error("Event undefined");const i=t.getHeader("Expires");if(!i)throw new Error("Expires undefined");super(jt,e,t,n),this.delegate=n,this.subscriberId=t.callId+t.fromTag+r,this.subscriptionExpiresRequested=this.subscriptionExpires=Number(i),this.subscriptionEvent=r,this.subscriptionState=pt.NotifyWait,this.waitNotifyStart()}dispose(){super.dispose()}onNotify(e){const t=e.message.parseHeader("Event").event;if(!t||t!==this.subscriptionEvent)return this.logger.warn("Failed to parse event."),void e.reject({statusCode:489});const n=e.message.parseHeader("Subscription-State");if(!n||!n.state)return this.logger.warn("Failed to parse subscription state."),void e.reject({statusCode:489});const r=n.state;switch(r){case"pending":case"active":case"terminated":break;default:return this.logger.warn(`Invalid subscription state ${r}`),void e.reject({statusCode:489})}if("terminated"!==r){if(!e.message.parseHeader("contact"))return this.logger.warn("Failed to parse contact."),void e.reject({statusCode:489})}if(this.dialog)throw new Error("Dialog already created. This implementation only supports install of single subscriptions.");switch(this.waitNotifyStop(),this.subscriptionExpires=n.expires?Math.min(this.subscriptionExpires,Math.max(n.expires,0)):this.subscriptionExpires,r){case"pending":this.subscriptionState=pt.Pending;break;case"active":this.subscriptionState=pt.Active;break;case"terminated":this.subscriptionState=pt.Terminated;break;default:throw new Error(`Unrecognized state ${r}.`)}if(this.subscriptionState!==pt.Terminated){const t=dn.initialDialogStateForSubscription(this.message,e.message);this.dialog=new dn(this.subscriptionEvent,this.subscriptionExpires,this.subscriptionState,this.core,t)}if(this.delegate&&this.delegate.onNotify){const t=e,n=this.dialog;this.delegate.onNotify({request:t,subscription:n})}else e.accept()}waitNotifyStart(){this.N||(this.core.subscribers.set(this.subscriberId,this),this.N=setTimeout(()=>this.timerN(),Qe.TIMER_N))}waitNotifyStop(){this.N&&(this.core.subscribers.delete(this.subscriberId),clearTimeout(this.N),this.N=void 0)}receiveResponse(e){if(this.authenticationGuard(e)){if(e.statusCode&&e.statusCode>=200&&e.statusCode<300){const t=e.getHeader("Expires");if(t){const e=Number(t);e>this.subscriptionExpiresRequested&&this.logger.warn("Expires header in a 200-class response to SUBSCRIBE with a higher value than the one in the request"),ethis.subscriptionExpires&&(this.dialog.subscriptionExpires=this.subscriptionExpires)}e.statusCode&&e.statusCode>=300&&e.statusCode<700&&this.waitNotifyStop(),super.receiveResponse(e)}}timerN(){this.logger.warn("Timer N expired for SUBSCRIBE user agent client. Timed out waiting for NOTIFY."),this.waitNotifyStop(),this.delegate&&this.delegate.onNotifyTimeout&&this.delegate.onNotifyTimeout()}}class fn extends qt{constructor(e,t,n){super(zt,e,t,n),this.core=e}}const pn=["application/sdp","application/dtmf-relay"];class gn{constructor(e,t={}){this.userAgentClients=new Map,this.userAgentServers=new Map,this.configuration=e,this.delegate=t,this.dialogs=new Map,this.subscribers=new Map,this.logger=e.loggerFactory.getLogger("sip.user-agent-core")}dispose(){this.reset()}reset(){this.dialogs.forEach(e=>e.dispose()),this.dialogs.clear(),this.subscribers.forEach(e=>e.dispose()),this.subscribers.clear(),this.userAgentClients.forEach(e=>e.dispose()),this.userAgentClients.clear(),this.userAgentServers.forEach(e=>e.dispose()),this.userAgentServers.clear()}get loggerFactory(){return this.configuration.loggerFactory}get transport(){const e=this.configuration.transportAccessor();if(!e)throw new Error("Transport undefined.");return e}invite(e,t){return new on(this,e,t)}message(e,t){return new Yt(this,e,t)}publish(e,t){return new sn(this,e,t)}register(e,t){return new ln(this,e,t)}subscribe(e,t){return new hn(this,e,t)}request(e,t){return new Ft(jt,this,e,t)}makeOutgoingRequestMessage(e,t,n,r,i,o,a){const s=this.configuration.sipjsId,l=this.configuration.displayName,c=this.configuration.viaForceRport,u=this.configuration.hackViaTcp,d=this.configuration.supportedOptionTags.slice();e===Ze.REGISTER&&d.push("path","gruu"),e===Ze.INVITE&&(this.configuration.contact.pubGruu||this.configuration.contact.tempGruu)&&d.push("gruu");const h={callIdPrefix:s,forceRport:c,fromDisplayName:l,hackViaTcp:u,optionTags:d,routeSet:this.configuration.routeSet,userAgentString:this.configuration.userAgentHeaderFieldValue,viaHost:this.configuration.viaHost},f=Object.assign(Object.assign({},h),i);return new Fe(e,t,n,r,f,o,a)}receiveIncomingRequestFromTransport(e){this.receiveRequestFromTransport(e)}receiveIncomingResponseFromTransport(e){this.receiveResponseFromTransport(e)}replyStateless(e,t){const n=this.configuration.userAgentHeaderFieldValue,r=this.configuration.supportedOptionTagsResponse;t=Object.assign(Object.assign({},t),{userAgent:n,supported:r});const i=It(e,t);return this.transport.send(i.message).catch(t=>{t instanceof Error&&this.logger.error(t.message),this.logger.error(`Transport error occurred sending stateless reply to ${e.method} request.`)}),i}receiveRequestFromTransport(e){const t=e.viaBranch,n=this.userAgentServers.get(t);e.method===Ze.ACK&&n&&n.transaction.state===St.Accepted&&n instanceof an?this.logger.warn(`Discarding out of dialog ACK after 2xx response sent on transaction ${t}.`):e.method!==Ze.CANCEL?n?n.transaction.receiveRequest(e):this.receiveRequest(e):n?(this.replyStateless(e,{statusCode:200}),n.transaction instanceof $t&&n.transaction.state===St.Proceeding&&n instanceof an&&n.receiveCancel(e)):this.replyStateless(e,{statusCode:481})}receiveRequest(e){if(!et.includes(e.method)){const t="Allow: "+et.toString();return void this.replyStateless(e,{statusCode:405,extraHeaders:[t]})}if(!e.ruri)throw new Error("Request-URI undefined.");if("sip"!==e.ruri.scheme)return void this.replyStateless(e,{statusCode:416});const t=e.ruri,n=e=>!!e&&e.user===t.user;if(!n(this.configuration.aor)&&!(n(this.configuration.contact.uri)||n(this.configuration.contact.pubGruu)||n(this.configuration.contact.tempGruu)))return this.logger.warn("Request-URI does not point to us."),void(e.method!==Ze.ACK&&this.replyStateless(e,{statusCode:404}));if(e.method!==Ze.INVITE||e.hasHeader("Contact")){if(!e.toTag){const t=e.viaBranch;if(!this.userAgentServers.has(t)){if(Array.from(this.userAgentServers.values()).some(t=>t.transaction.request.fromTag===e.fromTag&&t.transaction.request.callId===e.callId&&t.transaction.request.cseq===e.cseq))return void this.replyStateless(e,{statusCode:482})}}e.toTag?this.receiveInsideDialogRequest(e):this.receiveOutsideDialogRequest(e)}else this.replyStateless(e,{statusCode:400,reasonPhrase:"Missing Contact Header"})}receiveInsideDialogRequest(e){if(e.method===Ze.NOTIFY){const t=e.parseHeader("Event");if(!t||!t.event)return void this.replyStateless(e,{statusCode:489});const n=e.callId+e.toTag+t.event,r=this.subscribers.get(n);if(r){const t=new Qt(this,e);return void r.onNotify(t)}}const t=e.callId+e.toTag+e.fromTag,n=this.dialogs.get(t);if(n){if(e.method===Ze.OPTIONS){const t="Allow: "+et.toString(),n="Accept: "+pn.toString();return void this.replyStateless(e,{statusCode:200,extraHeaders:[t,n]})}n.receiveRequest(e)}else e.method!==Ze.ACK&&this.replyStateless(e,{statusCode:481})}receiveOutsideDialogRequest(e){switch(e.method){case Ze.ACK:break;case Ze.BYE:this.replyStateless(e,{statusCode:481});break;case Ze.CANCEL:throw new Error(`Unexpected out of dialog request method ${e.method}.`);case Ze.INFO:this.replyStateless(e,{statusCode:405});break;case Ze.INVITE:{const t=new an(this,e);this.delegate.onInvite?this.delegate.onInvite(t):t.reject()}break;case Ze.MESSAGE:{const t=new Gt(this,e);this.delegate.onMessage?this.delegate.onMessage(t):t.accept()}break;case Ze.NOTIFY:{const t=new Qt(this,e);this.delegate.onNotify?this.delegate.onNotify(t):t.reject({statusCode:405})}break;case Ze.OPTIONS:{const t="Allow: "+et.toString(),n="Accept: "+pn.toString();this.replyStateless(e,{statusCode:200,extraHeaders:[t,n]})}break;case Ze.REFER:{const t=new nn(this,e);this.delegate.onRefer?this.delegate.onRefer(t):t.reject({statusCode:405})}break;case Ze.REGISTER:{const t=new cn(this,e);this.delegate.onRegister?this.delegate.onRegister(t):t.reject({statusCode:405})}break;case Ze.SUBSCRIBE:{const t=new fn(this,e);this.delegate.onSubscribe?this.delegate.onSubscribe(t):t.reject({statusCode:480})}break;default:throw new Error(`Unexpected out of dialog request method ${e.method}.`)}}receiveResponseFromTransport(e){if(e.getHeaders("via").length>1)return void this.logger.warn("More than one Via header field present in the response, dropping");const t=e.viaBranch+e.method,n=this.userAgentClients.get(t);n?n.transaction.receiveResponse(e):this.logger.warn(`Discarding unmatched ${e.statusCode} response to ${e.method} ${t}.`)}}class mn{constructor(e,t,n){e.debug("SessionDescriptionHandler.constructor"),this.logger=e,this.mediaStreamFactory=t,this.sessionDescriptionHandlerConfiguration=n,this._localMediaStream=new MediaStream,this._remoteMediaStream=new MediaStream,this._peerConnection=new RTCPeerConnection(null==n?void 0:n.peerConnectionConfiguration),this.initPeerConnectionEventHandlers()}get localMediaStream(){return this._localMediaStream}get remoteMediaStream(){return this._remoteMediaStream}get dataChannel(){return this._dataChannel}get peerConnection(){return this._peerConnection}get peerConnectionDelegate(){return this._peerConnectionDelegate}set peerConnectionDelegate(e){this._peerConnectionDelegate=e}static dispatchAddTrackEvent(e,t){e.dispatchEvent(new MediaStreamTrackEvent("addtrack",{track:t}))}static dispatchRemoveTrackEvent(e,t){e.dispatchEvent(new MediaStreamTrackEvent("removetrack",{track:t}))}close(){this.logger.debug("SessionDescriptionHandler.close"),void 0!==this._peerConnection&&(this._peerConnection.getReceivers().forEach(e=>{e.track&&e.track.stop()}),this._peerConnection.getSenders().forEach(e=>{e.track&&e.track.stop()}),this._dataChannel&&this._dataChannel.close(),this._peerConnection.close(),this._peerConnection=void 0)}enableReceiverTracks(e){const t=this.peerConnection;if(!t)throw new Error("Peer connection closed.");t.getReceivers().forEach(t=>{t.track&&(t.track.enabled=e)})}enableSenderTracks(e){const t=this.peerConnection;if(!t)throw new Error("Peer connection closed.");t.getSenders().forEach(t=>{t.track&&(t.track.enabled=e)})}getDescription(e,t){var n,r;if(this.logger.debug("SessionDescriptionHandler.getDescription"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));this.onDataChannel=null==e?void 0:e.onDataChannel;const i=null===(n=null==e?void 0:e.offerOptions)||void 0===n?void 0:n.iceRestart,o=void 0===(null==e?void 0:e.iceGatheringTimeout)?null===(r=this.sessionDescriptionHandlerConfiguration)||void 0===r?void 0:r.iceGatheringTimeout:null==e?void 0:e.iceGatheringTimeout;return this.getLocalMediaStream(e).then(()=>this.updateDirection(e)).then(()=>this.createDataChannel(e)).then(()=>this.createLocalOfferOrAnswer(e)).then(e=>this.applyModifiers(e,t)).then(e=>this.setLocalSessionDescription(e)).then(()=>this.waitForIceGatheringComplete(i,o)).then(()=>this.getLocalSessionDescription()).then(e=>({body:e.sdp,contentType:"application/sdp"})).catch(e=>{throw this.logger.error("SessionDescriptionHandler.getDescription failed - "+e),e})}hasDescription(e){return this.logger.debug("SessionDescriptionHandler.hasDescription"),"application/sdp"===e}iceGatheringComplete(){this.logger.debug("SessionDescriptionHandler.iceGatheringComplete"),void 0!==this.iceGatheringCompleteTimeoutId&&(this.logger.debug("SessionDescriptionHandler.iceGatheringComplete - clearing timeout"),clearTimeout(this.iceGatheringCompleteTimeoutId),this.iceGatheringCompleteTimeoutId=void 0),void 0!==this.iceGatheringCompletePromise&&(this.logger.debug("SessionDescriptionHandler.iceGatheringComplete - resolving promise"),this.iceGatheringCompleteResolve&&this.iceGatheringCompleteResolve(),this.iceGatheringCompletePromise=void 0,this.iceGatheringCompleteResolve=void 0,this.iceGatheringCompleteReject=void 0)}sendDtmf(e,t){if(this.logger.debug("SessionDescriptionHandler.sendDtmf"),void 0===this._peerConnection)return this.logger.error("SessionDescriptionHandler.sendDtmf failed - peer connection closed"),!1;const n=this._peerConnection.getSenders();if(0===n.length)return this.logger.error("SessionDescriptionHandler.sendDtmf failed - no senders"),!1;const r=n[0].dtmf;if(!r)return this.logger.error("SessionDescriptionHandler.sendDtmf failed - no DTMF sender"),!1;const i=null==t?void 0:t.duration,o=null==t?void 0:t.interToneGap;try{r.insertDTMF(e,i,o)}catch(a){return this.logger.error(a.toString()),!1}return this.logger.log("SessionDescriptionHandler.sendDtmf sent via RTP: "+e.toString()),!0}setDescription(e,t,n){if(this.logger.debug("SessionDescriptionHandler.setDescription"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));this.onDataChannel=null==t?void 0:t.onDataChannel;const r="have-local-offer"===this._peerConnection.signalingState?"answer":"offer";return this.getLocalMediaStream(t).then(()=>this.applyModifiers({sdp:e,type:r},n)).then(e=>this.setRemoteSessionDescription(e)).catch(e=>{throw this.logger.error("SessionDescriptionHandler.setDescription failed - "+e),e})}applyModifiers(e,t){return this.logger.debug("SessionDescriptionHandler.applyModifiers"),t&&0!==t.length?t.reduce((e,t)=>e.then(t),Promise.resolve(e)).then(e=>{if(this.logger.debug("SessionDescriptionHandler.applyModifiers - modified sdp"),!e.sdp||!e.type)throw new Error("Invalid SDP.");return{sdp:e.sdp,type:e.type}}):Promise.resolve(e)}createDataChannel(e){if(void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));if(!0!==(null==e?void 0:e.dataChannel))return Promise.resolve();if(this._dataChannel)return Promise.resolve();switch(this._peerConnection.signalingState){case"stable":this.logger.debug("SessionDescriptionHandler.createDataChannel - creating data channel");try{return this._dataChannel=this._peerConnection.createDataChannel((null==e?void 0:e.dataChannelLabel)||"",null==e?void 0:e.dataChannelOptions),this.onDataChannel&&this.onDataChannel(this._dataChannel),Promise.resolve()}catch(t){return Promise.reject(t)}case"have-remote-offer":return Promise.resolve();default:return Promise.reject(new Error("Invalid signaling state "+this._peerConnection.signalingState))}}createLocalOfferOrAnswer(e){if(void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));switch(this._peerConnection.signalingState){case"stable":return this.logger.debug("SessionDescriptionHandler.createLocalOfferOrAnswer - creating SDP offer"),this._peerConnection.createOffer(null==e?void 0:e.offerOptions);case"have-remote-offer":return this.logger.debug("SessionDescriptionHandler.createLocalOfferOrAnswer - creating SDP answer"),this._peerConnection.createAnswer(null==e?void 0:e.answerOptions);default:return Promise.reject(new Error("Invalid signaling state "+this._peerConnection.signalingState))}}getLocalMediaStream(e){if(this.logger.debug("SessionDescriptionHandler.getLocalMediaStream"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));let t=Object.assign({},null==e?void 0:e.constraints);if(this.localMediaStreamConstraints){if(t.audio=t.audio||this.localMediaStreamConstraints.audio,t.video=t.video||this.localMediaStreamConstraints.video,JSON.stringify(this.localMediaStreamConstraints.audio)===JSON.stringify(t.audio)&&JSON.stringify(this.localMediaStreamConstraints.video)===JSON.stringify(t.video))return Promise.resolve()}else void 0===t.audio&&void 0===t.video&&(t={audio:!0});return this.localMediaStreamConstraints=t,this.mediaStreamFactory(t,this,e).then(e=>this.setLocalMediaStream(e))}setLocalMediaStream(e){if(this.logger.debug("SessionDescriptionHandler.setLocalMediaStream"),!this._peerConnection)throw new Error("Peer connection undefined.");const t=this._peerConnection,n=this._localMediaStream,r=[],i=e=>{const i=e.kind;if("audio"!==i&&"video"!==i)throw new Error(`Unknown new track kind ${i}.`);const o=t.getSenders().find(e=>e.track&&e.track.kind===i);o?r.push(new Promise(e=>{this.logger.debug(`SessionDescriptionHandler.setLocalMediaStream - replacing sender ${i} track`),e()}).then(()=>o.replaceTrack(e).then(()=>{const t=n.getTracks().find(e=>e.kind===i);t&&(t.stop(),n.removeTrack(t),mn.dispatchRemoveTrackEvent(n,t)),n.addTrack(e),mn.dispatchAddTrackEvent(n,e)}).catch(e=>{throw this.logger.error(`SessionDescriptionHandler.setLocalMediaStream - failed to replace sender ${i} track`),e}))):r.push(new Promise(e=>{this.logger.debug(`SessionDescriptionHandler.setLocalMediaStream - adding sender ${i} track`),e()}).then(()=>{try{t.addTrack(e,n)}catch(r){throw this.logger.error(`SessionDescriptionHandler.setLocalMediaStream - failed to add sender ${i} track`),r}n.addTrack(e),mn.dispatchAddTrackEvent(n,e)}))},o=e.getAudioTracks();o.length&&i(o[0]);const a=e.getVideoTracks();return a.length&&i(a[0]),r.reduce((e,t)=>e.then(()=>t),Promise.resolve())}getLocalSessionDescription(){if(this.logger.debug("SessionDescriptionHandler.getLocalSessionDescription"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));const e=this._peerConnection.localDescription;return e?Promise.resolve(e):Promise.reject(new Error("Failed to get local session description"))}setLocalSessionDescription(e){return this.logger.debug("SessionDescriptionHandler.setLocalSessionDescription"),void 0===this._peerConnection?Promise.reject(new Error("Peer connection closed.")):this._peerConnection.setLocalDescription(e)}setRemoteSessionDescription(e){if(this.logger.debug("SessionDescriptionHandler.setRemoteSessionDescription"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));const t=e.sdp;let n;switch(this._peerConnection.signalingState){case"stable":n="offer";break;case"have-local-offer":n="answer";break;default:return Promise.reject(new Error("Invalid signaling state "+this._peerConnection.signalingState))}return t?this._peerConnection.setRemoteDescription({sdp:t,type:n}):(this.logger.error("SessionDescriptionHandler.setRemoteSessionDescription failed - cannot set null sdp"),Promise.reject(new Error("SDP is undefined")))}setRemoteTrack(e){this.logger.debug("SessionDescriptionHandler.setRemoteTrack");const t=this._remoteMediaStream;t.getTrackById(e.id)?this.logger.debug(`SessionDescriptionHandler.setRemoteTrack - have remote ${e.kind} track`):"audio"===e.kind?(this.logger.debug(`SessionDescriptionHandler.setRemoteTrack - adding remote ${e.kind} track`),t.getAudioTracks().forEach(e=>{e.stop(),t.removeTrack(e),mn.dispatchRemoveTrackEvent(t,e)}),t.addTrack(e),mn.dispatchAddTrackEvent(t,e)):"video"===e.kind&&(this.logger.debug(`SessionDescriptionHandler.setRemoteTrack - adding remote ${e.kind} track`),t.getVideoTracks().forEach(e=>{e.stop(),t.removeTrack(e),mn.dispatchRemoveTrackEvent(t,e)}),t.addTrack(e),mn.dispatchAddTrackEvent(t,e))}updateDirection(e){if(void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));switch(this._peerConnection.signalingState){case"stable":this.logger.debug("SessionDescriptionHandler.updateDirection - setting offer direction");{const t=t=>{switch(t){case"inactive":case"recvonly":return(null==e?void 0:e.hold)?"inactive":"recvonly";case"sendonly":case"sendrecv":return(null==e?void 0:e.hold)?"sendonly":"sendrecv";case"stopped":return"stopped";default:throw new Error("Should never happen")}};this._peerConnection.getTransceivers().forEach(e=>{if(e.direction){const n=t(e.direction);e.direction!==n&&(e.direction=n)}})}break;case"have-remote-offer":this.logger.debug("SessionDescriptionHandler.updateDirection - setting answer direction");{const t=(()=>{const e=this._peerConnection.remoteDescription;if(!e)throw new Error("Failed to read remote offer");const t=/a=sendrecv\r\n|a=sendonly\r\n|a=recvonly\r\n|a=inactive\r\n/.exec(e.sdp);if(t)switch(t[0]){case"a=inactive\r\n":return"inactive";case"a=recvonly\r\n":return"recvonly";case"a=sendonly\r\n":return"sendonly";case"a=sendrecv\r\n":return"sendrecv";default:throw new Error("Should never happen")}return"sendrecv"})(),n=(()=>{switch(t){case"inactive":return"inactive";case"recvonly":return"sendonly";case"sendonly":return(null==e?void 0:e.hold)?"inactive":"recvonly";case"sendrecv":return(null==e?void 0:e.hold)?"sendonly":"sendrecv";default:throw new Error("Should never happen")}})();this._peerConnection.getTransceivers().forEach(e=>{e.direction&&"stopped"!==e.direction&&e.direction!==n&&(e.direction=n)})}break;default:return Promise.reject(new Error("Invalid signaling state "+this._peerConnection.signalingState))}return Promise.resolve()}waitForIceGatheringComplete(e=!1,t=0){return this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete"),void 0===this._peerConnection?Promise.reject("Peer connection closed."):e||"complete"!==this._peerConnection.iceGatheringState?(void 0!==this.iceGatheringCompletePromise&&(this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - rejecting prior waiting promise"),this.iceGatheringCompleteReject&&this.iceGatheringCompleteReject(new Error("Promise superseded.")),this.iceGatheringCompletePromise=void 0,this.iceGatheringCompleteResolve=void 0,this.iceGatheringCompleteReject=void 0),this.iceGatheringCompletePromise=new Promise((e,n)=>{this.iceGatheringCompleteResolve=e,this.iceGatheringCompleteReject=n,t>0&&(this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - timeout in "+t),this.iceGatheringCompleteTimeoutId=setTimeout(()=>{this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - timeout"),this.iceGatheringComplete()},t))}),this.iceGatheringCompletePromise):(this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - already complete"),Promise.resolve())}initPeerConnectionEventHandlers(){if(this.logger.debug("SessionDescriptionHandler.initPeerConnectionEventHandlers"),!this._peerConnection)throw new Error("Peer connection undefined.");const e=this._peerConnection;e.onconnectionstatechange=t=>{var n;const r=e.connectionState;this.logger.debug(`SessionDescriptionHandler.onconnectionstatechange ${r}`),(null===(n=this._peerConnectionDelegate)||void 0===n?void 0:n.onconnectionstatechange)&&this._peerConnectionDelegate.onconnectionstatechange(t)},e.ondatachannel=e=>{var t;this.logger.debug("SessionDescriptionHandler.ondatachannel"),this._dataChannel=e.channel,this.onDataChannel&&this.onDataChannel(this._dataChannel),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.ondatachannel)&&this._peerConnectionDelegate.ondatachannel(e)},e.onicecandidate=e=>{var t;this.logger.debug("SessionDescriptionHandler.onicecandidate"),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.onicecandidate)&&this._peerConnectionDelegate.onicecandidate(e)},e.onicecandidateerror=e=>{var t;this.logger.debug("SessionDescriptionHandler.onicecandidateerror"),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.onicecandidateerror)&&this._peerConnectionDelegate.onicecandidateerror(e)},e.oniceconnectionstatechange=t=>{var n;const r=e.iceConnectionState;this.logger.debug(`SessionDescriptionHandler.oniceconnectionstatechange ${r}`),(null===(n=this._peerConnectionDelegate)||void 0===n?void 0:n.oniceconnectionstatechange)&&this._peerConnectionDelegate.oniceconnectionstatechange(t)},e.onicegatheringstatechange=t=>{var n;const r=e.iceGatheringState;this.logger.debug(`SessionDescriptionHandler.onicegatheringstatechange ${r}`),"complete"===r&&this.iceGatheringComplete(),(null===(n=this._peerConnectionDelegate)||void 0===n?void 0:n.onicegatheringstatechange)&&this._peerConnectionDelegate.onicegatheringstatechange(t)},e.onnegotiationneeded=e=>{var t;this.logger.debug("SessionDescriptionHandler.onnegotiationneeded"),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.onnegotiationneeded)&&this._peerConnectionDelegate.onnegotiationneeded(e)},e.onsignalingstatechange=t=>{var n;const r=e.signalingState;this.logger.debug(`SessionDescriptionHandler.onsignalingstatechange ${r}`),(null===(n=this._peerConnectionDelegate)||void 0===n?void 0:n.onsignalingstatechange)&&this._peerConnectionDelegate.onsignalingstatechange(t)},e.ontrack=e=>{var t;const n=e.track.kind,r=e.track.enabled?"enabled":"disabled";this.logger.debug(`SessionDescriptionHandler.ontrack ${n} ${r}`),this.setRemoteTrack(e.track),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.ontrack)&&this._peerConnectionDelegate.ontrack(e)}}}function vn(e){return(t,n)=>{void 0===e&&(e=e=>e.audio||e.video?void 0===navigator.mediaDevices?Promise.reject(new Error("Media devices not available in insecure contexts.")):navigator.mediaDevices.getUserMedia.call(navigator.mediaDevices,e):Promise.resolve(new MediaStream));const r={iceGatheringTimeout:void 0!==(null==n?void 0:n.iceGatheringTimeout)?null==n?void 0:n.iceGatheringTimeout:5e3,peerConnectionConfiguration:Object.assign(Object.assign({},{bundlePolicy:"balanced",certificates:void 0,iceCandidatePoolSize:0,iceServers:[{urls:"stun:stun.l.google.com:19302"}],iceTransportPolicy:"all",rtcpMuxPolicy:"require"}),null==n?void 0:n.peerConnectionConfiguration)},i=t.userAgent.getLogger("sip.SessionDescriptionHandler");return new mn(i,e,r)}}class yn{constructor(e,t){if(this._state=mt.Disconnected,this.transitioningState=!1,this._stateEventEmitter=new we,this.logger=e,t){const e=t,n=null==e?void 0:e.wsServers,r=null==e?void 0:e.maxReconnectionAttempts;if(void 0!==n){const e='The transport option "wsServers" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(e)}if(void 0!==r){const e='The transport option "maxReconnectionAttempts" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(e)}n&&!t.server&&("string"==typeof n&&(t.server=n),n instanceof Array&&(t.server=n[0]))}this.configuration=Object.assign(Object.assign({},yn.defaultOptions),t);const n=this.configuration.server,r=_e.parse(n,"absoluteURI");if(-1===r)throw this.logger.error(`Invalid WebSocket Server URL "${n}"`),new Error("Invalid WebSocket Server URL");if(!["wss","ws","udp"].includes(r.scheme))throw this.logger.error(`Invalid scheme in WebSocket Server URL "${n}"`),new Error("Invalid scheme in WebSocket Server URL");this._protocol=r.scheme.toUpperCase()}dispose(){return this.disconnect()}get protocol(){return this._protocol}get server(){return this.configuration.server}get state(){return this._state}get stateChange(){return this._stateEventEmitter}get ws(){return this._ws}connect(){return this._connect()}disconnect(){return this._disconnect()}isConnected(){return this.state===mt.Connected}send(e){return this._send(e)}_connect(){switch(this.logger.log(`Connecting ${this.server}`),this.state){case mt.Connecting:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(mt.Connecting));if(!this.connectPromise)throw new Error("Connect promise must be defined.");return this.connectPromise;case mt.Connected:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(mt.Connecting));if(this.connectPromise)throw new Error("Connect promise must not be defined.");return Promise.resolve();case mt.Disconnecting:if(this.connectPromise)throw new Error("Connect promise must not be defined.");try{this.transitionState(mt.Connecting)}catch(t){if(t instanceof me)return Promise.reject(t);throw t}break;case mt.Disconnected:if(this.connectPromise)throw new Error("Connect promise must not be defined.");try{this.transitionState(mt.Connecting)}catch(t){if(t instanceof me)return Promise.reject(t);throw t}break;default:throw new Error("Unknown state")}let e;try{e=new WebSocket(this.server,"sip"),e.binaryType="arraybuffer",e.addEventListener("close",t=>this.onWebSocketClose(t,e)),e.addEventListener("error",t=>this.onWebSocketError(t,e)),e.addEventListener("open",t=>this.onWebSocketOpen(t,e)),e.addEventListener("message",t=>this.onWebSocketMessage(t,e)),this._ws=e}catch(n){return this._ws=void 0,this.logger.error("WebSocket construction failed."),this.logger.error(n.toString()),new Promise((e,t)=>{this.connectResolve=e,this.connectReject=t,this.transitionState(mt.Disconnected,n)})}return this.connectPromise=new Promise((t,n)=>{this.connectResolve=t,this.connectReject=n,this.connectTimeout=setTimeout(()=>{this.logger.warn("Connect timed out. Exceeded time set in configuration.connectionTimeout: "+this.configuration.connectionTimeout+"s."),e.close(1e3)},1e3*this.configuration.connectionTimeout)}),this.connectPromise}_disconnect(){switch(this.logger.log(`Disconnecting ${this.server}`),this.state){case mt.Connecting:if(this.disconnectPromise)throw new Error("Disconnect promise must not be defined.");try{this.transitionState(mt.Disconnecting)}catch(t){if(t instanceof me)return Promise.reject(t);throw t}break;case mt.Connected:if(this.disconnectPromise)throw new Error("Disconnect promise must not be defined.");try{this.transitionState(mt.Disconnecting)}catch(t){if(t instanceof me)return Promise.reject(t);throw t}break;case mt.Disconnecting:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(mt.Disconnecting));if(!this.disconnectPromise)throw new Error("Disconnect promise must be defined.");return this.disconnectPromise;case mt.Disconnected:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(mt.Disconnecting));if(this.disconnectPromise)throw new Error("Disconnect promise must not be defined.");return Promise.resolve();default:throw new Error("Unknown state")}if(!this._ws)throw new Error("WebSocket must be defined.");const e=this._ws;return this.disconnectPromise=new Promise((t,n)=>{this.disconnectResolve=t,this.disconnectReject=n;try{e.close(1e3)}catch(r){throw this.logger.error("WebSocket close failed."),this.logger.error(r.toString()),r}}),this.disconnectPromise}_send(e){if(!0===this.configuration.traceSip&&this.logger.log("Sending WebSocket message:\n\n"+e+"\n"),this._state!==mt.Connected)return Promise.reject(new Error("Not connected."));if(!this._ws)throw new Error("WebSocket undefined.");try{this._ws.send(e)}catch(t){return t instanceof Error?Promise.reject(t):Promise.reject(new Error("WebSocket send failed."))}return Promise.resolve()}onWebSocketClose(e,t){if(t!==this._ws)return;const n=`WebSocket closed ${this.server} (code: ${e.code})`,r=this.disconnectPromise?void 0:new Error(n);r&&this.logger.warn("WebSocket closed unexpectedly"),this.logger.log(n),this._ws=void 0,this.transitionState(mt.Disconnected,r)}onWebSocketError(e,t){t===this._ws&&this.logger.error("WebSocket error occurred.")}onWebSocketMessage(e,t){if(t!==this._ws)return;const n=e.data;let r;if(/^(\r\n)+$/.test(n))return this.clearKeepAliveTimeout(),void(!0===this.configuration.traceSip&&this.logger.log("Received WebSocket message with CRLF Keep Alive response"));if(n){if("string"!=typeof n){try{r=(new TextDecoder).decode(new Uint8Array(n))}catch(i){return this.logger.error(i.toString()),void this.logger.error("Received WebSocket binary message failed to be converted into string, message discarded")}!0===this.configuration.traceSip&&this.logger.log("Received WebSocket binary message:\n\n"+r+"\n")}else r=n,!0===this.configuration.traceSip&&this.logger.log("Received WebSocket text message:\n\n"+r+"\n");if(this.state===mt.Connected){if(this.onMessage)try{this.onMessage(r)}catch(o){throw this.logger.error(o.toString()),this.logger.error("Exception thrown by onMessage callback"),o}}else this.logger.warn("Received message while not connected, discarding...")}else this.logger.warn("Received empty message, discarding...")}onWebSocketOpen(e,t){t===this._ws&&this._state===mt.Connecting&&(this.logger.log(`WebSocket opened ${this.server}`),this.transitionState(mt.Connected))}transitionLoopDetectedError(e){let t="A state transition loop has been detected.";return t+=` An attempt to transition from ${this._state} to ${e} before the prior transition completed.`,t+=" Perhaps you are synchronously calling connect() or disconnect() from a callback or state change handler?",this.logger.error(t),new me("Loop detected.")}transitionState(e,t){const n=()=>{throw new Error(`Invalid state transition from ${this._state} to ${e}`)};if(this.transitioningState)throw this.transitionLoopDetectedError(e);switch(this.transitioningState=!0,this._state){case mt.Connecting:e!==mt.Connected&&e!==mt.Disconnecting&&e!==mt.Disconnected&&n();break;case mt.Connected:e!==mt.Disconnecting&&e!==mt.Disconnected&&n();break;case mt.Disconnecting:e!==mt.Connecting&&e!==mt.Disconnected&&n();break;case mt.Disconnected:e!==mt.Connecting&&n();break;default:throw new Error("Unknown state.")}const r=this._state;this._state=e;const i=this.connectResolve,o=this.connectReject;r===mt.Connecting&&(this.connectPromise=void 0,this.connectResolve=void 0,this.connectReject=void 0);const a=this.disconnectResolve,s=this.disconnectReject;if(r===mt.Disconnecting&&(this.disconnectPromise=void 0,this.disconnectResolve=void 0,this.disconnectReject=void 0),this.connectTimeout&&(clearTimeout(this.connectTimeout),this.connectTimeout=void 0),this.logger.log(`Transitioned from ${r} to ${this._state}`),this._stateEventEmitter.emit(this._state),e===mt.Connected&&(this.startSendingKeepAlives(),this.onConnect))try{this.onConnect()}catch(l){throw this.logger.error(l.toString()),this.logger.error("Exception thrown by onConnect callback"),l}if(r===mt.Connected&&(this.stopSendingKeepAlives(),this.onDisconnect))try{t?this.onDisconnect(t):this.onDisconnect()}catch(l){throw this.logger.error(l.toString()),this.logger.error("Exception thrown by onDisconnect callback"),l}if(r===mt.Connecting){if(!i)throw new Error("Connect resolve undefined.");if(!o)throw new Error("Connect reject undefined.");e===mt.Connected?i():o(t||new Error("Connect aborted."))}if(r===mt.Disconnecting){if(!a)throw new Error("Disconnect resolve undefined.");if(!s)throw new Error("Disconnect reject undefined.");e===mt.Disconnected?a():s(t||new Error("Disconnect aborted."))}this.transitioningState=!1}clearKeepAliveTimeout(){this.keepAliveDebounceTimeout&&clearTimeout(this.keepAliveDebounceTimeout),this.keepAliveDebounceTimeout=void 0}sendKeepAlive(){return this.keepAliveDebounceTimeout?Promise.resolve():(this.keepAliveDebounceTimeout=setTimeout(()=>{this.clearKeepAliveTimeout()},1e3*this.configuration.keepAliveDebounce),this.send("\r\n\r\n"))}startSendingKeepAlives(){this.configuration.keepAliveInterval&&!this.keepAliveInterval&&(this.keepAliveInterval=setInterval(()=>{this.sendKeepAlive(),this.startSendingKeepAlives()},(e=>{const t=.8*e;return 1e3*(Math.random()*(e-t)+t)})(this.configuration.keepAliveInterval)))}stopSendingKeepAlives(){this.keepAliveInterval&&clearInterval(this.keepAliveInterval),this.keepAliveDebounceTimeout&&clearTimeout(this.keepAliveDebounceTimeout),this.keepAliveInterval=void 0,this.keepAliveDebounceTimeout=void 0}}yn.defaultOptions={server:"",connectionTimeout:5,keepAliveInterval:0,keepAliveDebounce:10,traceSip:!0};class bn{constructor(e={}){if(this._publishers={},this._registerers={},this._sessions={},this._subscriptions={},this._state=yt.Stopped,this._stateEventEmitter=new we,this.delegate=e.delegate,this.options=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},bn.defaultOptions()),{sipjsId:Ae(5)}),{uri:new Te("sip","anonymous."+Ae(6),"anonymous.invalid")}),{viaHost:Ae(12)+".invalid"}),bn.stripUndefinedProperties(e)),this.options.hackIpInContact)if("boolean"==typeof this.options.hackIpInContact&&this.options.hackIpInContact){const e=1,t=254,n=Math.floor(Math.random()*(t-e+1)+e);this.options.viaHost="192.0.2."+n}else this.options.hackIpInContact&&(this.options.viaHost=this.options.hackIpInContact);switch(this.loggerFactory=new Dt,this.logger=this.loggerFactory.getLogger("sip.UserAgent"),this.loggerFactory.builtinEnabled=this.options.logBuiltinEnabled,this.loggerFactory.connector=this.options.logConnector,this.options.logLevel){case"error":this.loggerFactory.level=wt.error;break;case"warn":this.loggerFactory.level=wt.warn;break;case"log":this.loggerFactory.level=wt.log;break;case"debug":this.loggerFactory.level=wt.debug}if(this.options.logConfiguration&&(this.logger.log("Configuration:"),Object.keys(this.options).forEach(e=>{const t=this.options[e];switch(e){case"uri":case"sessionDescriptionHandlerFactory":this.logger.log("· "+e+": "+t);break;case"authorizationPassword":this.logger.log("· "+e+": NOT SHOWN");break;case"transportConstructor":this.logger.log("· "+e+": "+t.name);break;default:this.logger.log("· "+e+": "+JSON.stringify(t))}})),this.options.transportOptions){const t=this.options.transportOptions,n=t.maxReconnectionAttempts,r=t.reconnectionTimeout;if(void 0!==n){const e='The transport option "maxReconnectionAttempts" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(e)}if(void 0!==r){const e='The transport option "reconnectionTimeout" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(e)}void 0===e.reconnectionDelay&&void 0!==r&&(this.options.reconnectionDelay=r),void 0===e.reconnectionAttempts&&void 0!==n&&(this.options.reconnectionAttempts=n)}if(void 0!==e.reconnectionDelay){const e='The user agent option "reconnectionDelay" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(e)}if(void 0!==e.reconnectionAttempts){const e='The user agent option "reconnectionAttempts" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(e)}if(this._transport=new this.options.transportConstructor(this.getLogger("sip.Transport"),this.options.transportOptions),this.initTransportCallbacks(),this._contact=this.initContact(),this._instanceId=this.options.instanceId?this.options.instanceId:bn.newUUID(),-1===_e.parse(this._instanceId,"uuid"))throw new Error("Invalid instanceId.");this._userAgentCore=this.initCore()}static makeURI(e){return _e.URIParse(e)}static defaultOptions(){return{allowLegacyNotifications:!1,authorizationHa1:"",authorizationPassword:"",authorizationUsername:"",delegate:{},contactName:"",contactParams:{transport:"ws"},displayName:"",forceRport:!1,gracefulShutdown:!0,hackAllowUnregisteredOptionTags:!1,hackIpInContact:!1,hackViaTcp:!1,instanceId:"",instanceIdAlwaysAdded:!1,logBuiltinEnabled:!0,logConfiguration:!0,logConnector:()=>{},logLevel:"log",noAnswerTimeout:60,preloadedRouteSet:[],reconnectionAttempts:0,reconnectionDelay:4,sendInitialProvisionalResponse:!0,sessionDescriptionHandlerFactory:vn(),sessionDescriptionHandlerFactoryOptions:{},sipExtension100rel:ot.Unsupported,sipExtensionReplaces:ot.Unsupported,sipExtensionExtraSupported:[],sipjsId:"",transportConstructor:yn,transportOptions:{},uri:new Te("sip","anonymous","anonymous.invalid"),userAgentString:"SIP.js/0.21.1",viaHost:""}}static newUUID(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=Math.floor(16*Math.random());return("x"===e?t:t%4+8).toString(16)})}static stripUndefinedProperties(e){return Object.keys(e).reduce((t,n)=>(void 0!==e[n]&&(t[n]=e[n]),t),{})}get configuration(){return this.options}get contact(){return this._contact}get instanceId(){return this._instanceId}get state(){return this._state}get stateChange(){return this._stateEventEmitter}get transport(){return this._transport}get userAgentCore(){return this._userAgentCore}getLogger(e,t){return this.loggerFactory.getLogger(e,t)}getLoggerFactory(){return this.loggerFactory}isConnected(){return this.transport.isConnected()}reconnect(){return this.state===yt.Stopped?Promise.reject(new Error("User agent stopped.")):Promise.resolve().then(()=>this.transport.connect())}start(){return this.state===yt.Started?(this.logger.warn("User agent already started"),Promise.resolve()):(this.logger.log(`Starting ${this.configuration.uri}`),this.transitionState(yt.Started),this.transport.connect())}async stop(){if(this.state===yt.Stopped)return this.logger.warn("User agent already stopped"),Promise.resolve();if(this.logger.log(`Stopping ${this.configuration.uri}`),!this.options.gracefulShutdown)return this.logger.log("Dispose of transport"),this.transport.dispose().catch(e=>{throw this.logger.error(e.message),e}),this.logger.log("Dispose of core"),this.userAgentCore.dispose(),this._publishers={},this._registerers={},this._sessions={},this._subscriptions={},this.transitionState(yt.Stopped),Promise.resolve();const e=Object.assign({},this._publishers),t=Object.assign({},this._registerers),n=Object.assign({},this._sessions),r=Object.assign({},this._subscriptions),i=this.transport,o=this.userAgentCore;this.logger.log("Dispose of registerers");for(const a in t)t[a]&&await t[a].dispose().catch(e=>{throw this.logger.error(e.message),delete this._registerers[a],e});this.logger.log("Dispose of sessions");for(const a in n)n[a]&&await n[a].dispose().catch(e=>{throw this.logger.error(e.message),delete this._sessions[a],e});this.logger.log("Dispose of subscriptions");for(const a in r)r[a]&&await r[a].dispose().catch(e=>{throw this.logger.error(e.message),delete this._subscriptions[a],e});this.logger.log("Dispose of publishers");for(const a in e)e[a]&&await e[a].dispose().catch(e=>{throw this.logger.error(e.message),delete this._publishers[a],e});this.logger.log("Dispose of transport"),await i.dispose().catch(e=>{throw this.logger.error(e.message),e}),this.logger.log("Dispose of core"),o.dispose(),this.transitionState(yt.Stopped)}_makeInviter(e,t){return new ut(this,e,t)}attemptReconnection(e=1){const t=this.options.reconnectionAttempts,n=this.options.reconnectionDelay;e>t?this.logger.log("Maximum reconnection attempts reached"):(this.logger.log(`Reconnection attempt ${e} of ${t} - trying`),setTimeout(()=>{this.reconnect().then(()=>{this.logger.log(`Reconnection attempt ${e} of ${t} - succeeded`)}).catch(n=>{this.logger.error(n.message),this.logger.log(`Reconnection attempt ${e} of ${t} - failed`),this.attemptReconnection(++e)})},1===e?0:1e3*n))}initContact(){const e=""!==this.options.contactName?this.options.contactName:Ae(8),t=this.options.contactParams;return{pubGruu:void 0,tempGruu:void 0,uri:new Te("sip",e,this.options.viaHost,void 0,t),toString:(e={})=>{const n=e.anonymous||!1,r=e.outbound||!1,i=e.register||!1;let o="<";return o+=n?this.contact.tempGruu||`sip:anonymous@anonymous.invalid;transport=${t.transport?t.transport:"ws"}`:i?this.contact.uri:this.contact.pubGruu||this.contact.uri,r&&(o+=";ob"),o+=">",this.options.instanceIdAlwaysAdded&&(o+=';+sip.instance=""'),o}}}initCore(){let e=[];e.push("outbound"),this.options.sipExtension100rel===ot.Supported&&e.push("100rel"),this.options.sipExtensionReplaces===ot.Supported&&e.push("replaces"),this.options.sipExtensionExtraSupported&&e.push(...this.options.sipExtensionExtraSupported),this.options.hackAllowUnregisteredOptionTags||(e=e.filter(e=>lt[e])),e=Array.from(new Set(e));const t=e.slice();(this.contact.pubGruu||this.contact.tempGruu)&&t.push("gruu");const n={aor:this.options.uri,contact:this.contact,displayName:this.options.displayName,loggerFactory:this.loggerFactory,hackViaTcp:this.options.hackViaTcp,routeSet:this.options.preloadedRouteSet,supportedOptionTags:e,supportedOptionTagsResponse:t,sipjsId:this.options.sipjsId,userAgentHeaderFieldValue:this.options.userAgentString,viaForceRport:this.options.forceRport,viaHost:this.options.viaHost,authenticationFactory:()=>{const e=this.options.authorizationUsername?this.options.authorizationUsername:this.options.uri.user,t=this.options.authorizationPassword?this.options.authorizationPassword:void 0,n=this.options.authorizationHa1?this.options.authorizationHa1:void 0;return new Pt(this.getLoggerFactory(),n,e,t)},transportAccessor:()=>this.transport};return new gn(n,{onInvite:e=>{var t;const n=new ct(this,e);if(e.delegate={onCancel:e=>{n._onCancel(e)},onTransportError:e=>{this.logger.error("A transport error has occurred while handling an incoming INVITE request.")}},e.trying(),this.options.sipExtensionReplaces!==ot.Unsupported){const t=e.message.parseHeader("replaces");if(t){const e=t.call_id;if("string"!=typeof e)throw new Error("Type of call id is not string");const r=t.replaces_to_tag;if("string"!=typeof r)throw new Error("Type of to tag is not string");const i=t.replaces_from_tag;if("string"!=typeof i)throw new Error("type of from tag is not string");const o=e+r+i,a=this.userAgentCore.dialogs.get(o);if(!a)return void n.reject({statusCode:481});if(!a.early&&!0===t.early_only)return void n.reject({statusCode:486});const s=this._sessions[e+i]||this._sessions[e+r]||void 0;if(!s)throw new Error("Session does not exist.");n._replacee=s}}if(null===(t=this.delegate)||void 0===t?void 0:t.onInvite)return n.autoSendAnInitialProvisionalResponse?void n.progress().then(()=>{var e;if(void 0===(null===(e=this.delegate)||void 0===e?void 0:e.onInvite))throw new Error("onInvite undefined.");this.delegate.onInvite(n)}):void this.delegate.onInvite(n);n.reject({statusCode:486})},onMessage:e=>{if(this.delegate&&this.delegate.onMessage){const t=new tt(e);this.delegate.onMessage(t)}else e.accept()},onNotify:e=>{if(this.delegate&&this.delegate.onNotify){const t=new nt(e);this.delegate.onNotify(t)}else this.options.allowLegacyNotifications?e.accept():e.reject({statusCode:481})},onRefer:e=>{this.logger.warn("Received an out of dialog REFER request"),this.delegate&&this.delegate.onReferRequest?this.delegate.onReferRequest(e):e.reject({statusCode:405})},onRegister:e=>{this.logger.warn("Received an out of dialog REGISTER request"),this.delegate&&this.delegate.onRegisterRequest?this.delegate.onRegisterRequest(e):e.reject({statusCode:405})},onSubscribe:e=>{this.logger.warn("Received an out of dialog SUBSCRIBE request"),this.delegate&&this.delegate.onSubscribeRequest?this.delegate.onSubscribeRequest(e):e.reject({statusCode:405})}})}initTransportCallbacks(){this.transport.onConnect=()=>this.onTransportConnect(),this.transport.onDisconnect=e=>this.onTransportDisconnect(e),this.transport.onMessage=e=>this.onTransportMessage(e)}onTransportConnect(){this.state!==yt.Stopped&&this.delegate&&this.delegate.onConnect&&this.delegate.onConnect()}onTransportDisconnect(e){this.state!==yt.Stopped&&(this.delegate&&this.delegate.onDisconnect&&this.delegate.onDisconnect(e),e&&this.options.reconnectionAttempts>0&&this.attemptReconnection())}onTransportMessage(e){const t=kt.parseMessage(e,this.getLogger("sip.Parser"));if(!t)return void this.logger.warn("Failed to parse incoming message. Dropping.");if(this.state===yt.Stopped&&t instanceof Le)return void this.logger.warn(`Received ${t.method} request while stopped. Dropping.`);const n=()=>{const e=["from","to","call_id","cseq","via"];for(const n of e)if(!t.hasHeader(n))return this.logger.warn(`Missing mandatory header field : ${n}.`),!1;return!0};if(t instanceof Le){if(!n())return void this.logger.warn("Request missing mandatory header field. Dropping.");if(!t.toTag&&t.callId.substr(0,5)===this.options.sipjsId)return void this.userAgentCore.replyStateless(t,{statusCode:482});const e=Oe(t.body),r=t.getHeader("content-length");if(r&&e1)return void this.logger.warn("More than one Via header field present in the response. Dropping.");if(t.via.host!==this.options.viaHost||void 0!==t.via.port)return void this.logger.warn("Via sent-by in the response does not match UA Via host value. Dropping.");const e=Oe(t.body),r=t.getHeader("content-length");if(r&&e{throw new Error(`Invalid state transition from ${this._state} to ${e}`)};switch(this._state){case yt.Started:e!==yt.Stopped&&n();break;case yt.Stopped:e!==yt.Started&&n();break;default:throw new Error("Unknown state.")}this.logger.log(`Transitioned from ${this._state} to ${e}`),this._state=e,this._stateEventEmitter.emit(this._state)}}class wn{constructor(e,t={}){this.managedSessions=[],this.attemptingReconnection=!1,this.optionsPingFailure=!1,this.optionsPingRunning=!1,this.shouldBeConnected=!1,this.shouldBeRegistered=!1,this.delegate=t.delegate,this.options=Object.assign({aor:"",autoStop:!0,delegate:{},iceStopWaitingOnServerReflexive:!1,managedSessionFactory:(e,t)=>({session:t,held:!1,muted:!1}),maxSimultaneousSessions:2,media:{},optionsPingInterval:-1,optionsPingRequestURI:"",reconnectionAttempts:3,reconnectionDelay:4,registrationRetry:!1,registrationRetryInterval:3,registerGuard:null,registererOptions:{},registererRegisterOptions:{},sendDTMFUsingSessionDescriptionHandler:!1,userAgentOptions:{}},wn.stripUndefinedProperties(t));const n=Object.assign({},t.userAgentOptions);if(n.transportConstructor||(n.transportConstructor=yn),n.transportOptions||(n.transportOptions={server:e}),!n.uri&&t.aor){const e=bn.makeURI(t.aor);if(!e)throw new Error(`Failed to create valid URI from ${t.aor}`);n.uri=e}if(this.userAgent=new bn(n),this.userAgent.delegate={onConnect:()=>{this.logger.log("Connected"),this.delegate&&this.delegate.onServerConnect&&this.delegate.onServerConnect(),this.shouldBeRegistered&&this.register(),this.options.optionsPingInterval>0&&this.optionsPingStart()},onDisconnect:async e=>{this.logger.log("Disconnected");let t=!1;this.options.optionsPingInterval>0&&(t=this.optionsPingFailure,this.optionsPingFailure=!1,this.optionsPingStop()),this.delegate&&this.delegate.onServerDisconnect&&this.delegate.onServerDisconnect(e),(e||t)&&(this.registerer&&(this.logger.log("Disposing of registerer..."),this.registerer.dispose().catch(e=>{this.logger.debug("Error occurred disposing of registerer after connection with server was lost."),this.logger.debug(e.toString())}),this.registerer=void 0),this.managedSessions.slice().map(e=>e.session).forEach(async e=>{this.logger.log("Disposing of session..."),e.dispose().catch(e=>{this.logger.debug("Error occurred disposing of a session after connection with server was lost."),this.logger.debug(e.toString())})}),this.shouldBeConnected&&this.attemptReconnection())},onInvite:e=>{this.logger.log(`[${e.id}] Received INVITE`);const t=this.options.maxSimultaneousSessions;if(0!==t&&this.managedSessions.length>t)return this.logger.warn(`[${e.id}] Session already in progress, rejecting INVITE...`),void e.reject().then(()=>{this.logger.log(`[${e.id}] Rejected INVITE`)}).catch(t=>{this.logger.error(`[${e.id}] Failed to reject INVITE`),this.logger.error(t.toString())});const n={sessionDescriptionHandlerOptions:{constraints:this.constraints}};this.initSession(e,n),this.delegate&&this.delegate.onCallReceived?this.delegate.onCallReceived(e):(this.logger.warn(`[${e.id}] No handler available, rejecting INVITE...`),e.reject().then(()=>{this.logger.log(`[${e.id}] Rejected INVITE`)}).catch(t=>{this.logger.error(`[${e.id}] Failed to reject INVITE`),this.logger.error(t.toString())}))},onMessage:e=>{e.accept().then(()=>{this.delegate&&this.delegate.onMessageReceived&&this.delegate.onMessageReceived(e)})},onNotify:e=>{e.accept().then(()=>{this.delegate&&this.delegate.onNotificationReceived&&this.delegate.onNotificationReceived(e)})}},this.registererOptions=Object.assign({},t.registererOptions),this.registererRegisterOptions=Object.assign({},t.registererRegisterOptions),this.options.registrationRetry){this.registererRegisterOptions.requestDelegate=this.registererRegisterOptions.requestDelegate||{};const e=this.registererRegisterOptions.requestDelegate.onReject;this.registererRegisterOptions.requestDelegate.onReject=t=>{e&&e(t),this.attemptRegistration()}}this.logger=this.userAgent.getLogger("sip.SessionManager"),window.addEventListener("online",()=>{this.logger.log("Online"),this.shouldBeConnected&&this.connect()}),this.options.autoStop&&window.addEventListener("beforeunload",async()=>{this.shouldBeConnected=!1,this.shouldBeRegistered=!1,this.userAgent.state!==yt.Stopped&&await this.userAgent.stop()})}static stripUndefinedProperties(e){return Object.keys(e).reduce((t,n)=>(void 0!==e[n]&&(t[n]=e[n]),t),{})}getLocalMediaStream(e){const t=e.sessionDescriptionHandler;if(t){if(!(t instanceof mn))throw new Error("Session description handler not instance of web SessionDescriptionHandler");return t.localMediaStream}}getRemoteMediaStream(e){const t=e.sessionDescriptionHandler;if(t){if(!(t instanceof mn))throw new Error("Session description handler not instance of web SessionDescriptionHandler");return t.remoteMediaStream}}getLocalAudioTrack(e){var t;return null===(t=this.getLocalMediaStream(e))||void 0===t?void 0:t.getTracks().find(e=>"audio"===e.kind)}getLocalVideoTrack(e){var t;return null===(t=this.getLocalMediaStream(e))||void 0===t?void 0:t.getTracks().find(e=>"video"===e.kind)}getRemoteAudioTrack(e){var t;return null===(t=this.getRemoteMediaStream(e))||void 0===t?void 0:t.getTracks().find(e=>"audio"===e.kind)}getRemoteVideoTrack(e){var t;return null===(t=this.getRemoteMediaStream(e))||void 0===t?void 0:t.getTracks().find(e=>"video"===e.kind)}async connect(){return this.logger.log("Connecting UserAgent..."),this.shouldBeConnected=!0,this.userAgent.state!==yt.Started?this.userAgent.start():this.userAgent.reconnect()}async disconnect(){return this.logger.log("Disconnecting UserAgent..."),this.userAgent.state===yt.Stopped?Promise.resolve():(this.shouldBeConnected=!1,this.shouldBeRegistered=!1,this.registerer=void 0,this.userAgent.stop())}isConnected(){return this.userAgent.isConnected()}async register(e){return this.logger.log("Registering UserAgent..."),this.shouldBeRegistered=!0,void 0!==e&&(this.registererRegisterOptions=Object.assign({},e)),this.registerer||(this.registerer=new Et(this.userAgent,this.registererOptions),this.registerer.stateChange.addListener(e=>{switch(e){case ht.Initial:break;case ht.Registered:this.delegate&&this.delegate.onRegistered&&this.delegate.onRegistered();break;case ht.Unregistered:this.delegate&&this.delegate.onUnregistered&&this.delegate.onUnregistered(),this.shouldBeRegistered&&this.attemptRegistration();break;case ht.Terminated:break;default:throw new Error("Unknown registerer state.")}})),this.attemptRegistration(!0)}async unregister(e){return this.logger.log("Unregistering UserAgent..."),this.shouldBeRegistered=!1,this.registerer?this.registerer.unregister(e).then(()=>{}):(this.logger.warn("No registerer to unregister."),Promise.resolve())}async call(e,t,n){this.logger.log("Beginning Session...");const r=this.options.maxSimultaneousSessions;if(0!==r&&this.managedSessions.length>r)return Promise.reject(new Error("Maximum number of sessions already exists."));const i=bn.makeURI(e);if(!i)return Promise.reject(new Error(`Failed to create a valid URI from "${e}"`));if(t||(t={}),t.sessionDescriptionHandlerOptions||(t.sessionDescriptionHandlerOptions={}),t.sessionDescriptionHandlerOptions.constraints||(t.sessionDescriptionHandlerOptions.constraints=this.constraints),t.earlyMedia){(n=n||{}).requestDelegate=n.requestDelegate||{};const e=n.requestDelegate.onProgress;n.requestDelegate.onProgress=t=>{183===t.message.statusCode&&this.setupRemoteMedia(o),e&&e(t)}}this.options.iceStopWaitingOnServerReflexive&&(t.delegate=t.delegate||{},t.delegate.onSessionDescriptionHandler=e=>{if(!(e instanceof mn))throw new Error("Session description handler not instance of SessionDescriptionHandler");e.peerConnectionDelegate={onicecandidate:t=>{var n;if("srflx"===(null===(n=t.candidate)||void 0===n?void 0:n.type)){this.logger.log(`[${o.id}] Found srflx ICE candidate, stop waiting...`);e.iceGatheringComplete()}}}});const o=new ut(this.userAgent,i,t);return this.sendInvite(o,t,n).then(()=>o)}async hangup(e){return this.logger.log(`[${e.id}] Hangup...`),this.sessionExists(e)?this.terminate(e):Promise.reject(new Error("Session does not exist."))}async answer(e,t){return this.logger.log(`[${e.id}] Accepting Invitation...`),this.sessionExists(e)?e instanceof ct?(t||(t={}),t.sessionDescriptionHandlerOptions||(t.sessionDescriptionHandlerOptions={}),t.sessionDescriptionHandlerOptions.constraints||(t.sessionDescriptionHandlerOptions.constraints=this.constraints),e.accept(t)):Promise.reject(new Error("Session not instance of Invitation.")):Promise.reject(new Error("Session does not exist."))}async decline(e){return this.logger.log(`[${e.id}] Rejecting Invitation...`),this.sessionExists(e)?e instanceof ct?e.reject():Promise.reject(new Error("Session not instance of Invitation.")):Promise.reject(new Error("Session does not exist."))}async hold(e){return this.logger.log(`[${e.id}] Holding session...`),this.setHold(e,!0)}async unhold(e){return this.logger.log(`[${e.id}] Unholding session...`),this.setHold(e,!1)}isHeld(e){const t=this.sessionManaged(e);return!!t&&t.held}mute(e){this.logger.log(`[${e.id}] Disabling media tracks...`),this.setMute(e,!0)}unmute(e){this.logger.log(`[${e.id}] Enabling media tracks...`),this.setMute(e,!1)}isMuted(e){const t=this.sessionManaged(e);return!!t&&t.muted}async sendDTMF(e,t){if(this.logger.log(`[${e.id}] Sending DTMF...`),!/^[0-9A-D#*,]$/.exec(t))return Promise.reject(new Error("Invalid DTMF tone."));if(!this.sessionExists(e))return Promise.reject(new Error("Session does not exist."));if(this.logger.log(`[${e.id}] Sending DTMF tone: ${t}`),this.options.sendDTMFUsingSessionDescriptionHandler)return e.sessionDescriptionHandler?e.sessionDescriptionHandler.sendDtmf(t)?Promise.resolve():Promise.reject(new Error("Failed to send DTMF")):Promise.reject(new Error("Session desciption handler undefined."));{const n={body:{contentDisposition:"render",contentType:"application/dtmf-relay",content:"Signal="+t+"\r\nDuration="+2e3}};return e.info({requestOptions:n}).then(()=>{})}}async transfer(e,t,n){if(this.logger.log(`[${e.id}] Referring session...`),t instanceof st)return e.refer(t,n).then(()=>{});const r=bn.makeURI(t);return r?e.refer(r,n).then(()=>{}):Promise.reject(new Error(`Failed to create a valid URI from "${t}"`))}async message(e,t){this.logger.log("Sending message...");const n=bn.makeURI(e);return n?new dt(this.userAgent,n,t).message():Promise.reject(new Error(`Failed to create a valid URI from "${e}"`))}get constraints(){let e={audio:!0,video:!1};return this.options.media.constraints&&(e=Object.assign({},this.options.media.constraints)),e}attemptReconnection(e=1){const t=this.options.reconnectionAttempts,n=this.options.reconnectionDelay;this.shouldBeConnected?(this.attemptingReconnection&&this.logger.log("Reconnection attempt already in progress"),e>t?this.logger.log("Reconnection maximum attempts reached"):(1===e?this.logger.log(`Reconnection attempt ${e} of ${t} - trying`):this.logger.log(`Reconnection attempt ${e} of ${t} - trying in ${n} seconds`),this.attemptingReconnection=!0,setTimeout(()=>{if(!this.shouldBeConnected)return this.logger.log(`Reconnection attempt ${e} of ${t} - aborted`),void(this.attemptingReconnection=!1);this.userAgent.reconnect().then(()=>{this.logger.log(`Reconnection attempt ${e} of ${t} - succeeded`),this.attemptingReconnection=!1}).catch(n=>{this.logger.log(`Reconnection attempt ${e} of ${t} - failed`),this.logger.error(n.message),this.attemptingReconnection=!1,this.attemptReconnection(++e)})},1===e?0:1e3*n))):this.logger.log("Should not be connected currently")}attemptRegistration(e=!1){if(this.logger.log("Registration attempt "+(e?"without delay":"")),!this.shouldBeRegistered)return this.logger.log("Should not be registered currently"),Promise.resolve();if(void 0!==this.registrationAttemptTimeout)return this.logger.log("Registration attempt already in progress"),Promise.resolve();const t=()=>this.registerer?this.isConnected()?this.userAgent.state===yt.Stopped?(this.logger.log("User agent stopped"),Promise.resolve()):this.options.registerGuard?this.options.registerGuard().catch(e=>{throw this.logger.log("Register guard rejected will making registration attempt"),e}).then(e=>e||!this.registerer?Promise.resolve():this.registerer.register(this.registererRegisterOptions).then(()=>{})):this.registerer.register(this.registererRegisterOptions).then(()=>{}):(this.logger.log("User agent not connected"),Promise.resolve()):(this.logger.log("Registerer undefined"),Promise.resolve());return new Promise((n,r)=>{this.registrationAttemptTimeout=setTimeout(()=>{t().then(()=>{this.registrationAttemptTimeout=void 0,n()}).catch(e=>{this.registrationAttemptTimeout=void 0,e instanceof fe?n():r(e)})},e?0:(e=>{const t=2*e;return 1e3*(Math.random()*(t-e)+e)})(this.options.registrationRetryInterval))})}cleanupMedia(e){const t=this.sessionManaged(e);if(!t)throw new Error("Managed session does not exist.");t.mediaLocal&&t.mediaLocal.video&&(t.mediaLocal.video.srcObject=null,t.mediaLocal.video.pause()),t.mediaRemote&&(t.mediaRemote.audio&&(t.mediaRemote.audio.srcObject=null,t.mediaRemote.audio.pause()),t.mediaRemote.video&&(t.mediaRemote.video.srcObject=null,t.mediaRemote.video.pause()))}enableReceiverTracks(e,t){if(!this.sessionExists(e))throw new Error("Session does not exist.");const n=e.sessionDescriptionHandler;if(!(n instanceof mn))throw new Error("Session's session description handler not instance of SessionDescriptionHandler.");n.enableReceiverTracks(t)}enableSenderTracks(e,t){if(!this.sessionExists(e))throw new Error("Session does not exist.");const n=e.sessionDescriptionHandler;if(!(n instanceof mn))throw new Error("Session's session description handler not instance of SessionDescriptionHandler.");n.enableSenderTracks(t)}initSession(e,t){this.sessionAdd(e),this.delegate&&this.delegate.onCallCreated&&this.delegate.onCallCreated(e),e.stateChange.addListener(t=>{switch(this.logger.log(`[${e.id}] Session state changed to ${t}`),t){case it.Initial:case it.Establishing:break;case it.Established:this.setupLocalMedia(e),this.setupRemoteMedia(e),this.delegate&&this.delegate.onCallAnswered&&this.delegate.onCallAnswered(e);break;case it.Terminating:case it.Terminated:this.sessionExists(e)&&(this.cleanupMedia(e),this.sessionRemove(e),this.delegate&&this.delegate.onCallHangup&&this.delegate.onCallHangup(e));break;default:throw new Error("Unknown session state.")}}),e.delegate=e.delegate||{},e.delegate.onInfo=t=>{var n;if(void 0===(null===(n=this.delegate)||void 0===n?void 0:n.onCallDTMFReceived))return void t.reject();const r=t.request.getHeader("content-type");if(!r||!/^application\/dtmf-relay/i.exec(r))return void t.reject();const i=t.request.body.split("\r\n",2);if(2!==i.length)return void t.reject();let o;const a=/^(Signal\s*?=\s*?)([0-9A-D#*]{1})(\s)?.*/;if(void 0!==i[0]&&a.test(i[0])&&(o=i[0].replace(a,"$2")),!o)return void t.reject();let s;const l=/^(Duration\s?=\s?)([0-9]{1,4})(\s)?.*/;void 0!==i[1]&&l.test(i[1])&&(s=parseInt(i[1].replace(l,"$2"),10)),s?t.accept().then(()=>{if(this.delegate&&this.delegate.onCallDTMFReceived){if(!o||!s)throw new Error("Tone or duration undefined.");this.delegate.onCallDTMFReceived(e,o,s)}}).catch(e=>{this.logger.error(e.message)}):t.reject()},e.delegate.onRefer=e=>{e.accept().then(()=>this.sendInvite(e.makeInviter(t),t)).catch(e=>{this.logger.error(e.message)})}}optionsPingRun(e,t,n){if(this.options.optionsPingInterval<1)throw new Error("Invalid options ping interval.");this.optionsPingRunning||(this.optionsPingRunning=!0,this.optionsPingTimeout=setTimeout(()=>{this.optionsPingTimeout=void 0;const r=()=>{this.optionsPingFailure=!1,this.optionsPingRunning&&(this.optionsPingRunning=!1,this.optionsPingRun(e,t,n))},i=()=>{this.logger.error("OPTIONS ping failed"),this.optionsPingFailure=!0,this.optionsPingRunning=!1,this.userAgent.transport.disconnect().catch(e=>this.logger.error(e))},o=this.userAgent.userAgentCore,a=o.makeOutgoingRequestMessage("OPTIONS",e,t,n,{});this.optionsPingRequest=o.request(a,{onAccept:()=>{this.optionsPingRequest=void 0,r()},onReject:e=>{this.optionsPingRequest=void 0,408===e.message.statusCode||503===e.message.statusCode?i():r()}})},1e3*this.options.optionsPingInterval))}optionsPingStart(){let e,t,n;if(this.logger.log("OPTIONS pings started"),this.options.optionsPingRequestURI){if(e=bn.makeURI(this.options.optionsPingRequestURI),!e)throw new Error("Failed to create Request URI.");t=this.userAgent.contact.uri.clone(),n=this.userAgent.contact.uri.clone()}else{if(!this.options.aor)return void this.logger.error("You have enabled sending OPTIONS pings and as such you must provide either a) an AOR to register, or b) an RURI to use for the target of the OPTIONS ping requests. ");{const r=bn.makeURI(this.options.aor);if(!r)throw new Error("Failed to create URI.");e=r.clone(),e.user=void 0,t=r.clone(),n=r.clone()}}this.optionsPingRun(e,t,n)}optionsPingStop(){this.logger.log("OPTIONS pings stopped"),this.optionsPingRunning=!1,this.optionsPingFailure=!1,this.optionsPingRequest&&(this.optionsPingRequest.dispose(),this.optionsPingRequest=void 0),this.optionsPingTimeout&&(clearTimeout(this.optionsPingTimeout),this.optionsPingTimeout=void 0)}async sendInvite(e,t,n){return this.initSession(e,t),e.invite(n).then(()=>{this.logger.log(`[${e.id}] Sent INVITE`)})}sessionAdd(e){const t=this.options.managedSessionFactory(this,e);this.managedSessions.push(t)}sessionExists(e){return void 0!==this.sessionManaged(e)}sessionManaged(e){return this.managedSessions.find(t=>t.session.id===e.id)}sessionRemove(e){this.managedSessions=this.managedSessions.filter(t=>t.session.id!==e.id)}async setHold(e,t){if(!this.sessionExists(e))return Promise.reject(new Error("Session does not exist."));if(this.isHeld(e)===t)return Promise.resolve();if(!(e.sessionDescriptionHandler instanceof mn))throw new Error("Session's session description handler not instance of SessionDescriptionHandler.");const n={requestDelegate:{onAccept:()=>{const n=this.sessionManaged(e);void 0!==n&&(n.held=t,this.enableReceiverTracks(e,!n.held),this.enableSenderTracks(e,!n.held&&!n.muted),this.delegate&&this.delegate.onCallHold&&this.delegate.onCallHold(e,n.held))},onReject:()=>{this.logger.warn(`[${e.id}] Re-invite request was rejected`);const n=this.sessionManaged(e);void 0!==n&&(n.held=!t,this.enableReceiverTracks(e,!n.held),this.enableSenderTracks(e,!n.held&&!n.muted),this.delegate&&this.delegate.onCallHold&&this.delegate.onCallHold(e,n.held))}}},r=e.sessionDescriptionHandlerOptionsReInvite;r.hold=t,e.sessionDescriptionHandlerOptionsReInvite=r;const i=this.sessionManaged(e);if(!i)throw new Error("Managed session is undefiend.");return i.held=t,e.invite(n).then(()=>{const t=this.sessionManaged(e);void 0!==t&&(this.enableReceiverTracks(e,!t.held),this.enableSenderTracks(e,!t.held&&!t.muted))}).catch(n=>{throw i.held=!t,n instanceof fe&&this.logger.error(`[${e.id}] A hold request is already in progress.`),n})}setMute(e,t){if(!this.sessionExists(e))return void this.logger.warn(`[${e.id}] A session is required to enabled/disable media tracks`);if(e.state!==it.Established)return void this.logger.warn(`[${e.id}] An established session is required to enable/disable media tracks`);const n=this.sessionManaged(e);void 0!==n&&(n.muted=t,this.enableSenderTracks(e,!n.held&&!n.muted))}setupLocalMedia(e){const t=this.sessionManaged(e);if(!t)throw new Error("Managed session does not exist.");const n="function"==typeof this.options.media.local?this.options.media.local(e):this.options.media.local;t.mediaLocal=n;const r=null==n?void 0:n.video;if(r){const t=this.getLocalMediaStream(e);if(!t)throw new Error("Local media stream undefiend.");r.srcObject=t,r.volume=0,r.play().catch(t=>{this.logger.error(`[${e.id}] Failed to play local media`),this.logger.error(t.message)})}}setupRemoteMedia(e){const t=this.sessionManaged(e);if(!t)throw new Error("Managed session does not exist.");const n="function"==typeof this.options.media.remote?this.options.media.remote(e):this.options.media.remote;t.mediaRemote=n;const r=(null==n?void 0:n.video)||(null==n?void 0:n.audio);if(r){const t=this.getRemoteMediaStream(e);if(!t)throw new Error("Remote media stream undefiend.");r.autoplay=!0,r.srcObject=t,r.play().catch(t=>{this.logger.error(`[${e.id}] Failed to play remote media`),this.logger.error(t.message)}),t.onaddtrack=()=>{this.logger.log("Remote media onaddtrack"),r.load(),r.play().catch(t=>{this.logger.error(`[${e.id}] Failed to play remote media`),this.logger.error(t.message)})}}}async terminate(e){switch(this.logger.log(`[${e.id}] Terminating...`),e.state){case it.Initial:if(e instanceof ut)return e.cancel().then(()=>{this.logger.log(`[${e.id}] Inviter never sent INVITE (canceled)`)});if(e instanceof ct)return e.reject().then(()=>{this.logger.log(`[${e.id}] Invitation rejected (sent 480)`)});throw new Error("Unknown session type.");case it.Establishing:if(e instanceof ut)return e.cancel().then(()=>{this.logger.log(`[${e.id}] Inviter canceled (sent CANCEL)`)});if(e instanceof ct)return e.reject().then(()=>{this.logger.log(`[${e.id}] Invitation rejected (sent 480)`)});throw new Error("Unknown session type.");case it.Established:return e.bye().then(()=>{this.logger.log(`[${e.id}] Session ended (sent BYE)`)});case it.Terminating:case it.Terminated:break;default:throw new Error("Unknown state")}return this.logger.log(`[${e.id}] Terminating in state ${e.state}, no action taken`),Promise.resolve()}}class xn{constructor(e,t={}){this.session=void 0,this.delegate=t.delegate,this.options=Object.assign({},t);const n={aor:this.options.aor,delegate:{onCallAnswered:()=>{var e,t;return null===(t=null===(e=this.delegate)||void 0===e?void 0:e.onCallAnswered)||void 0===t?void 0:t.call(e)},onCallCreated:e=>{var t,n;this.session=e,null===(n=null===(t=this.delegate)||void 0===t?void 0:t.onCallCreated)||void 0===n||n.call(t)},onCallReceived:()=>{var e,t;return null===(t=null===(e=this.delegate)||void 0===e?void 0:e.onCallReceived)||void 0===t?void 0:t.call(e)},onCallHangup:()=>{var e,t;this.session=void 0,(null===(e=this.delegate)||void 0===e?void 0:e.onCallHangup)&&(null===(t=this.delegate)||void 0===t||t.onCallHangup())},onCallHold:(e,t)=>{var n,r;return null===(r=null===(n=this.delegate)||void 0===n?void 0:n.onCallHold)||void 0===r?void 0:r.call(n,t)},onCallDTMFReceived:(e,t,n)=>{var r,i;return null===(i=null===(r=this.delegate)||void 0===r?void 0:r.onCallDTMFReceived)||void 0===i?void 0:i.call(r,t,n)},onMessageReceived:e=>{var t,n;return null===(n=null===(t=this.delegate)||void 0===t?void 0:t.onMessageReceived)||void 0===n?void 0:n.call(t,e.request.body)},onRegistered:()=>{var e,t;return null===(t=null===(e=this.delegate)||void 0===e?void 0:e.onRegistered)||void 0===t?void 0:t.call(e)},onUnregistered:()=>{var e,t;return null===(t=null===(e=this.delegate)||void 0===e?void 0:e.onUnregistered)||void 0===t?void 0:t.call(e)},onServerConnect:()=>{var e,t;return null===(t=null===(e=this.delegate)||void 0===e?void 0:e.onServerConnect)||void 0===t?void 0:t.call(e)},onServerDisconnect:()=>{var e,t;return null===(t=null===(e=this.delegate)||void 0===e?void 0:e.onServerDisconnect)||void 0===t?void 0:t.call(e)}},maxSimultaneousSessions:1,media:this.options.media,reconnectionAttempts:this.options.reconnectionAttempts,reconnectionDelay:this.options.reconnectionDelay,registererOptions:this.options.registererOptions,sendDTMFUsingSessionDescriptionHandler:this.options.sendDTMFUsingSessionDescriptionHandler,userAgentOptions:this.options.userAgentOptions};this.sessionManager=new wn(e,n),this.logger=this.sessionManager.userAgent.getLogger("sip.SimpleUser")}get id(){return this.options.userAgentOptions&&this.options.userAgentOptions.displayName||"Anonymous"}get localMediaStream(){return this.session&&this.sessionManager.getLocalMediaStream(this.session)}get remoteMediaStream(){return this.session&&this.sessionManager.getRemoteMediaStream(this.session)}get localAudioTrack(){return this.session&&this.sessionManager.getLocalAudioTrack(this.session)}get localVideoTrack(){return this.session&&this.sessionManager.getLocalVideoTrack(this.session)}get remoteAudioTrack(){return this.session&&this.sessionManager.getRemoteAudioTrack(this.session)}get remoteVideoTrack(){return this.session&&this.sessionManager.getRemoteVideoTrack(this.session)}connect(){return this.logger.log(`[${this.id}] Connecting UserAgent...`),this.sessionManager.connect()}disconnect(){return this.logger.log(`[${this.id}] Disconnecting UserAgent...`),this.sessionManager.disconnect()}isConnected(){return this.sessionManager.isConnected()}register(e){return this.logger.log(`[${this.id}] Registering UserAgent...`),this.sessionManager.register(e)}unregister(e){return this.logger.log(`[${this.id}] Unregistering UserAgent...`),this.sessionManager.unregister(e)}call(e,t,n){return this.logger.log(`[${this.id}] Beginning Session...`),this.session?Promise.reject(new Error("Session already exists.")):this.sessionManager.call(e,t,n).then(()=>{})}hangup(){return this.logger.log(`[${this.id}] Hangup...`),this.session?this.sessionManager.hangup(this.session).then(()=>{this.session=void 0}):Promise.reject(new Error("Session does not exist."))}answer(e){return this.logger.log(`[${this.id}] Accepting Invitation...`),this.session?this.sessionManager.answer(this.session,e):Promise.reject(new Error("Session does not exist."))}decline(){return this.logger.log(`[${this.id}] rejecting Invitation...`),this.session?this.sessionManager.decline(this.session):Promise.reject(new Error("Session does not exist."))}hold(){return this.logger.log(`[${this.id}] holding session...`),this.session?this.sessionManager.hold(this.session):Promise.reject(new Error("Session does not exist."))}unhold(){return this.logger.log(`[${this.id}] unholding session...`),this.session?this.sessionManager.unhold(this.session):Promise.reject(new Error("Session does not exist."))}isHeld(){return!!this.session&&this.sessionManager.isHeld(this.session)}mute(){return this.logger.log(`[${this.id}] disabling media tracks...`),this.session&&this.sessionManager.mute(this.session)}unmute(){return this.logger.log(`[${this.id}] enabling media tracks...`),this.session&&this.sessionManager.unmute(this.session)}isMuted(){return!!this.session&&this.sessionManager.isMuted(this.session)}sendDTMF(e){return this.logger.log(`[${this.id}] sending DTMF...`),this.session?this.sessionManager.sendDTMF(this.session,e):Promise.reject(new Error("Session does not exist."))}message(e,t){return this.logger.log(`[${this.id}] sending message...`),this.sessionManager.message(e,t)}}function kn(e){let t=e.replace(/\D/g,"");return t.startsWith("55")&&t.length>=12&&(t=t.slice(2)),11===t.length?`(${t.slice(0,2)}) ${t.slice(2,7)}-${t.slice(7)}`:10===t.length?`(${t.slice(0,2)}) ${t.slice(2,6)}-${t.slice(6)}`:9===t.length?`${t.slice(0,5)}-${t.slice(5)}`:8===t.length?`${t.slice(0,4)}-${t.slice(4)}`:e}const Sn="sip_config",Tn="handphone_call_logs",En="sip_manual_disconnect",Cn=(e,t)=>`handphone_contact_${e}@${t}`;let Rn=null;async function Pn(){if(Rn)return Rn;const e=Uint8Array.from(atob("KsGDVvN8TLscWPFaYwpCR/wdqvCfxuvmeXsO3dNVA4A="),e=>e.charCodeAt(0));return Rn=await crypto.subtle.importKey("raw",e,"AES-GCM",!1,["encrypt","decrypt"]),Rn}const _n={async getSipConfig(){try{const e=localStorage.getItem(Sn);if(!e)return{};const t=JSON.parse(e);return t.password&&(t.password=await async function(e){try{const[t,n]=e.split(":");if(!t||!n)return null;const r=await Pn(),i=Uint8Array.from(atob(t),e=>e.charCodeAt(0)),o=Uint8Array.from(atob(n),e=>e.charCodeAt(0)),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:i},r,o);return(new TextDecoder).decode(a)}catch{return null}}(t.password)??""),t}catch{return{}}},async setSipConfig(e){const{password:t,server:n,aor:r,...i}=e,o={...i};if(!o.auth_user&&o.username&&(o.auth_user=o.username),t)o.password=await async function(e){const t=await Pn(),n=crypto.getRandomValues(new Uint8Array(12)),r=await crypto.subtle.encrypt({name:"AES-GCM",iv:n},t,(new TextEncoder).encode(e));return`${btoa(String.fromCharCode(...n))}:${btoa(String.fromCharCode(...new Uint8Array(r)))}`}(t);else try{const e=localStorage.getItem(Sn);if(e){const t=JSON.parse(e);t.password&&(o.password=t.password)}}catch{}localStorage.setItem(Sn,JSON.stringify(o))},buildAor:(e,t)=>e&&t?`sip:${e}@${t}`:null,async mergeConfig(e){const t=await this.getSipConfig(),n=e.server||"";if(!t||!t.username||!t.domain){const t=this.buildAor(e.username,e.domain);return{...e,server:n,...t?{aor:t}:{}}}const r=this.buildAor(t.username,t.domain);return{...e,...t,server:n,aor:r}},getCallLogs(){try{const e=localStorage.getItem(Tn);return e?JSON.parse(e):[]}catch{return[]}},addCallLog(e){const t=this.getCallLogs();t.unshift(e);const n=t.slice(0,50);localStorage.setItem(Tn,JSON.stringify(n))},clearCallLogs(){localStorage.removeItem(Tn)},getManualDisconnect:()=>"true"===localStorage.getItem(En),setManualDisconnect(e){e?localStorage.setItem(En,"true"):localStorage.removeItem(En)},getSipContact(e,t){const n=Cn(e,t);return localStorage.getItem(n)},setSipContact(e,t,n){const r=Cn(e,t);localStorage.setItem(r,n)},clearAll(){Object.keys(localStorage).forEach(e=>{(e.startsWith("handphone_")||"sip_config"===e||"sip_manual_disconnect"===e)&&localStorage.removeItem(e)})}};let Dn=null;function In(){return Dn&&"closed"!==Dn.state||(Dn=new(window.AudioContext||window.webkitAudioContext)),"suspended"===Dn.state&&Dn.resume(),Dn}function An(e,t=.3){const n=In(),r=n.createGain();r.gain.setValueAtTime(0,n.currentTime),r.connect(n.destination);return{oscillators:e.map(e=>{const t=n.createOscillator();return t.type="sine",t.frequency.setValueAtTime(e,n.currentTime),t.connect(r),t.start(),t}),gainNode:r}}function Nn({oscillators:e,gainNode:t}){try{t.gain.setValueAtTime(0,In().currentTime),e.forEach(e=>{try{e.stop()}catch(t){}}),t.disconnect()}catch(n){}}const Mn={1:[697,1209],2:[697,1336],3:[697,1477],4:[770,1209],5:[770,1336],6:[770,1477],7:[852,1209],8:[852,1336],9:[852,1477],"*":[941,1209],0:[941,1336],"#":[941,1477]};let $n=null,On=null;function jn(e,t=120){Ln();const n=Mn[e];if(!n)return;const r=In();$n=An(n,.25),$n.gainNode.gain.setValueAtTime(.25,r.currentTime),On=setTimeout(()=>Ln(),t)}function Ln(){On&&(clearTimeout(On),On=null),$n&&(Nn($n),$n=null)}let Hn=null,Fn=null;function Un(){zn();const e=In();Hn=An([440,480],.2);const t=()=>{const t=e.currentTime;Hn.gainNode.gain.setValueAtTime(.2,t),Hn.gainNode.gain.setValueAtTime(0,t+2)};t(),Fn=setInterval(t,6e3)}function zn(){Fn&&(clearInterval(Fn),Fn=null),Hn&&(Nn(Hn),Hn=null)}let qn=null,Vn=null;function Bn(){Vn&&(clearInterval(Vn),Vn=null),qn&&(Nn(qn),qn=null)}let Wn=null,Yn=null;function Gn(e=!1){Yn&&(clearInterval(Yn),Yn=null),Wn&&(Nn(Wn),Wn=null)}function Kn(e={},t){const[n,r]=y.useState("disconnected"),[i,o]=y.useState("idle"),[a,s]=y.useState(!1),[l,c]=y.useState(!1),[u,d]=y.useState(null),[h,f]=y.useState(0),[p,g]=y.useState(!1),[m,v]=y.useState("dial"),[b,w]=y.useState(""),[x,k]=y.useState(!1),[S,T]=y.useState(!1),[E,C]=y.useState(""),R=y.useRef(null),P=y.useRef(null),_=y.useRef(null),D=y.useRef(null),I=y.useRef(null),A=y.useRef(null),N=y.useRef(null),M=y.useRef(null),$=y.useRef(null),O=y.useRef(null);y.useEffect(()=>{const e=e=>{const t=R.current;if(t)try{t.unregister()}catch(n){}};return window.addEventListener("beforeunload",e),()=>{window.removeEventListener("beforeunload",e),I.current&&clearInterval(I.current),A.current&&clearTimeout(A.current),R.current&&R.current.disconnect().catch(()=>{})}},[]);const j=()=>{I.current&&(clearInterval(I.current),I.current=null),f(0)},L=()=>{H(),A.current=setTimeout(()=>{console.warn("[useSip] Call timeout — forcing reset"),F()},6e4)},H=()=>{A.current&&(clearTimeout(A.current),A.current=null)},F=async()=>{var e,t;try{await(null==(e=R.current)?void 0:e.hangup())}catch(n){}try{await(null==(t=R.current)?void 0:t.decline())}catch(n){}_.current=null,D.current=null,o("idle"),d(null),g(!1),v("dial"),s(!1),c(!1),j(),H()},U=async n=>{var i,a;const l={...e,...n},u=l.aor.startsWith("sip:")?l.aor:`sip:${l.aor}`,h={...l,aor:u};r("connecting");const p={aor:h.aor,delegate:{onCallCreated:()=>{var e;_.current=(null==(e=R.current)?void 0:e.session)??null,o("calling"),s(!1),c(!1),Un(),L()},onCallAnswered:()=>{var e;N.current=Date.now(),_.current=(null==(e=R.current)?void 0:e.session)??null,H(),zn(),o("active"),f(0),I.current=setInterval(()=>{f(e=>e+1)},1e3),(null==t?void 0:t.current)&&t.current.play().catch(()=>{})},onCallHangup:()=>{const e=N.current?Math.round((Date.now()-N.current)/1e3):0,t=!!$.current,n=!t&&!!M.current&&0===e;(N.current||M.current||$.current)&&_n.addCallLog({direction:t?"inbound":"outbound",number:t?$.current:M.current,startedAt:(new Date).toISOString(),duration:e,status:e>0?"answered":t?"missed":"rejected"}),N.current=null,M.current=null,$.current=null,Ln(),zn(),Bn(),Gn(),n&&(!function(){Gn();const e=In();Wn=An([480,620],.2);const t=()=>{const t=e.currentTime;Wn.gainNode.gain.setValueAtTime(.2,t),Wn.gainNode.gain.setValueAtTime(0,t+.5)};t(),Yn=setInterval(t,1e3)}(),setTimeout(()=>Gn(),2e3)),_.current=null,H(),o("idle"),d(null),j(),s(!1),c(!1)},onCallReceived:()=>{var e,t,n,r,i,a,s,l,c;const u=R.current,h=(null==u?void 0:u.session)??(null==u?void 0:u._session)??(null==(e=null==u?void 0:u.sessionManager)?void 0:e.session)??null,f=(null==h?void 0:h.remoteIdentity)??(null==(n=null==(t=null==h?void 0:h.incomingRequestMessage)?void 0:t.from)?void 0:n.uri),p=(null==(r=null==f?void 0:f.uri)?void 0:r.user)||(null==(s=null==(a=null==(i=null==h?void 0:h.incomingRequestMessage)?void 0:i.from)?void 0:a.uri)?void 0:s.user)||null,g=(null==f?void 0:f.displayName)||(null==(c=null==(l=null==h?void 0:h.incomingRequestMessage)?void 0:l.from)?void 0:c.displayName)||p||"Desconhecido";$.current=p,d({from:kn(g)}),o("ringing"),function(){Bn();const e=In();qn=An([440,480],.35);const t=()=>{const t=e.currentTime;qn.gainNode.gain.setValueAtTime(.35,t),qn.gainNode.gain.setValueAtTime(0,t+2)};t(),Vn=setInterval(t,6e3)}(),L()},onCallHold:e=>{c(e)},onRegistered:()=>{r("registered")},onUnregistered:()=>{r("connected")},onServerConnect:()=>{r("connected")},onServerDisconnect:()=>{r("disconnected"),o("idle"),j()}},media:{remote:{audio:(null==t?void 0:t.current)??document.createElement("audio")}},userAgentOptions:{authorizationPassword:h.password||void 0,authorizationUsername:h.auth_user||(null==(i=h.aor.split(":")[1])?void 0:i.split("@")[0])||void 0,contactName:(null==(a=h.aor.split(":")[1])?void 0:a.split("@")[0])||void 0,contactParams:{transport:"wss"},userAgentString:h.system?`Handphone-2.0/${h.system}`:void 0}};try{if(R.current){try{await R.current.unregister(),await R.current.disconnect()}catch(g){}R.current=null}const e=new xn(h.server,p);return R.current=e,await e.connect(),P.current=e.userAgent??null,await e.register(),h}catch(m){throw console.error("[useSip] Connection failed",m),r("disconnected"),m}};return{connectionStatus:n,callStatus:i,isMuted:a,isOnHold:l,incomingCallInfo:u,callDuration:h,transferModal:p,setTransferModal:g,transferStep:m,setTransferStep:v,transferTarget:b,setTransferTarget:w,consultEstablished:x,setConsultEstablished:k,blindTransferModal:S,setBlindTransferModal:T,blindTransferTarget:E,setBlindTransferTarget:C,connect:e=>{if(O.current)return O.current;const t=U(e).finally(()=>{O.current=null});return O.current=t,t},disconnect:async()=>{var e,t;try{await(null==(e=R.current)?void 0:e.unregister()),await(null==(t=R.current)?void 0:t.disconnect())}catch(n){}R.current=null,r("disconnected"),o("idle"),j()},call:async(e,t)=>{if(e.trim()){M.current=e.trim();try{let n=e.trim();n.startsWith("sip:")||(n=t?`sip:${n}@${t}`:`sip:${n}`),o("calling"),s(!1),c(!1),Un(),L(),await R.current.call(n)}catch(n){throw console.error("[useSip] Call failed",n),o("idle"),zn(),n}}},hangup:async()=>{var e;try{await(null==(e=R.current)?void 0:e.hangup())}catch(t){throw console.error("[useSip] Hangup failed",t),t}},answer:async()=>{var e;try{Bn(),await(null==(e=R.current)?void 0:e.answer()),d(null)}catch(t){throw console.error("[useSip] Answer failed",t),t}},reject:async()=>{var e;try{Bn(),await(null==(e=R.current)?void 0:e.decline()),d(null),o("idle")}catch(t){throw console.error("[useSip] Reject failed",t),t}},toggleMute:()=>{R.current&&(a?R.current.unmute():R.current.mute(),s(!a))},toggleHold:async()=>{if(R.current)try{l?await R.current.unhold():await R.current.hold()}catch(e){throw console.error("[useSip] Hold failed",e),e}},sendDTMF:async e=>{var t;if("active"!==i)return;jn(e);const n=(null==(t=R.current)?void 0:t.session)??_.current;if(!n)return void console.error("[useSip] No active session for DTMF");const r=n.sessionDescriptionHandler;if(r&&"function"==typeof r.sendDtmf)try{return void r.sendDtmf(e)}catch(o){console.warn("[useSip] RFC4733 failed, trying SIP INFO")}try{await n.info({requestOptions:{body:{contentDisposition:"render",contentType:"application/dtmf-relay",content:`Signal=${e}\r\nDuration=120`}}})}catch(a){console.error("[useSip] DTMF SIP INFO failed",a)}},openTransfer:async()=>{var e;try{l||await(null==(e=R.current)?void 0:e.hold())}catch(t){}v("dial"),w(""),k(!1),g(!0)},transferDial:async(e,n)=>{var r,i,o;w(e),v("connecting");const a=P.current??(null==(r=R.current)?void 0:r.userAgent)??(null==(o=null==(i=R.current)?void 0:i.sessionManager)?void 0:o.userAgent)??null;if(!a)throw new Error("Não foi possível acessar o UserAgent SIP");try{const r=e.startsWith("sip:")?e:`sip:${e}@${n}`,i=bn.makeURI(r);if(!i)throw new Error("URI inválida: "+r);const o=new ut(a,i,{sessionDescriptionHandlerOptions:{constraints:{audio:!0,video:!1}}});k(!1),o.stateChange.addListener(e=>{var n,r,i;if("Established"===e){k(!0),v("consulting");const e=null==(i=null==(r=null==(n=o.sessionDescriptionHandler)?void 0:n.peerConnection)?void 0:r.getReceivers())?void 0:i.find(e=>{var t;return"audio"===(null==(t=e.track)?void 0:t.kind)});e&&(null==t?void 0:t.current)&&(t.current.srcObject=new MediaStream([e.track]),t.current.play().catch(()=>{}))}"Terminated"===e&&(D.current=null,k(!1),v("dial"))}),D.current=o,await o.invite()}catch(s){throw console.error("[useSip] Consultation dial failed",s),v("dial"),s}},transferExecute:async()=>{var e,t;v("transferring");try{const n=D.current;if(!n)throw new Error("Sessão de consulta não encontrada");const r=(null==(e=R.current)?void 0:e.session)??_.current;if(!r)throw new Error("Sessão original não encontrada");if("Established"!==n.state)throw new Error("A sessão de consulta ainda não está estabelecida");await new Promise((e,t)=>{r.refer(n,{requestDelegate:{onAccept:()=>e(),onReject:()=>t(new Error("REFER rejeitado"))}});setTimeout(e,5e3)}),await n.bye().catch(()=>{}),D.current=null,await(null==(t=R.current)?void 0:t.hangup().catch(()=>{})),g(!1),v("dial")}catch(n){throw console.error("[useSip] Transfer failed",n),v("consulting"),n}},transferCancel:async()=>{var e;try{const e=D.current;e&&("Established"===e.state?await e.bye().catch(()=>{}):await e.cancel().catch(()=>{}))}catch(t){}D.current=null;try{await(null==(e=R.current)?void 0:e.unhold())}catch(t){}g(!1),v("dial")},blindTransfer:async(e,t)=>{var n,r;if(e.trim())try{const i=(null==(n=R.current)?void 0:n.session)??_.current;if(!i)throw new Error("Sessão ativa não encontrada");let o=e.trim();o.startsWith("sip:")||(o=t?`sip:${o}@${t}`:`sip:${o}`);const a=bn.makeURI(o);if(!a)throw new Error("URI inválida");await i.refer(a),T(!1),C(""),await(null==(r=R.current)?void 0:r.hangup().catch(()=>{}))}catch(i){throw console.error("[useSip] Blind transfer failed",i),i}},forceReset:F}}const Qn="handphone_logs",Xn={addLog(e,t){try{const n=this.getLogs(),r=(new Date).toISOString(),i=t.map(e=>"string"==typeof e?e:e instanceof Error?`${e.name}: ${e.message}`:JSON.stringify(e)).join(" ");n.push({timestamp:r,level:e,message:i});const o=n.slice(-200);localStorage.setItem(Qn,JSON.stringify(o))}catch(n){}},getLogs(){try{const e=localStorage.getItem(Qn);return e?JSON.parse(e):[]}catch{return[]}},clearLogs(){localStorage.removeItem(Qn)},exportLogs(){return this.getLogs().map(e=>`[${e.timestamp}] ${e.level}: ${e.message}`).join("\n")}},Zn=["| sip.","sip.Transport","sip.UserAgent"];function Jn(e){if(!Array.isArray(e)||0===e.length)return!1;const t=String(e[0]);return Zn.some(e=>t.includes(e))}const er=[{key:"1",sub:""},{key:"2",sub:""},{key:"3",sub:""},{key:"4",sub:""},{key:"5",sub:""},{key:"6",sub:""},{key:"7",sub:""},{key:"8",sub:""},{key:"9",sub:""},{key:"*",sub:""},{key:"0",sub:""},{key:"#",sub:""}];function tr({onPress:e,disabled:t}){return v.jsx("div",{className:"grid grid-cols-3 gap-2 mb-4",children:er.map(({key:n,sub:r})=>v.jsxs("button",{onClick:()=>e(n),disabled:t,className:"bg-gray-800 hover:bg-gray-700 active:bg-gray-600 disabled:opacity-40 disabled:cursor-not-allowed rounded-[15px] py-3 flex flex-col items-center justify-center transition-colors select-none",children:[v.jsx("span",{className:"text-white text-xl font-light leading-none",children:n}),r&&v.jsx("span",{className:"text-gray-500 text-[9px] tracking-widest mt-0.5",children:r})]},n))})}function nr({callStatus:e,isMuted:t,isOnHold:n,onCall:r,onHangup:i,onToggleMute:o,onToggleHold:a,onTransfer:s,onBlindTransfer:l,canCall:c}){const u="active"===e,d="calling"===e||"ringing"===e||u;return v.jsxs("div",{className:"space-y-3 mt-2",children:[v.jsxs("div",{className:"flex items-center justify-center gap-3",children:[v.jsx("button",{onClick:o,disabled:!u,title:t?"Desmutar":"Mutar",className:"w-12 h-12 rounded-full flex items-center justify-center transition-colors disabled:opacity-30 disabled:cursor-not-allowed "+(t?"bg-orange-500 hover:bg-orange-600 text-white":"bg-gray-700 hover:bg-gray-600 text-gray-300"),children:t?v.jsx(X,{className:"w-5 h-5"}):v.jsx(Z,{className:"w-5 h-5"})}),d?v.jsx("button",{onClick:i,title:"Desligar",className:"w-16 h-16 rounded-full bg-red-500 hover:bg-red-600 text-white flex items-center justify-center transition-colors shadow-lg shadow-red-500/30",children:v.jsx(re,{className:"w-7 h-7"})}):v.jsx("button",{onClick:r,disabled:!c,title:"Ligar",className:"w-16 h-16 rounded-full bg-green-500 hover:bg-green-600 disabled:bg-gray-700 disabled:text-gray-500 text-white flex items-center justify-center transition-colors shadow-lg shadow-green-500/30 disabled:shadow-none",children:v.jsx(oe,{className:"w-7 h-7"})}),v.jsx("button",{onClick:a,disabled:!u,title:n?"Retomar":"Colocar em espera",className:"w-12 h-12 rounded-full flex items-center justify-center transition-colors disabled:opacity-30 disabled:cursor-not-allowed "+(n?"bg-blue-500 hover:bg-blue-600 text-white":"bg-gray-700 hover:bg-gray-600 text-gray-300"),children:n?v.jsx(Y,{className:"w-5 h-5"}):v.jsx(W,{className:"w-5 h-5"})})]}),!d&&v.jsxs("p",{className:"text-gray-600 text-[10px] text-center",children:["v","2.3.0"]}),u&&v.jsx("div",{className:"flex justify-center",children:v.jsxs("div",{className:"bg-gray-800 border border-gray-700 rounded-[15px] p-3 w-full",children:[v.jsx("p",{className:"text-gray-400 text-xs uppercase tracking-wider mb-2",children:"Tipo de transferência"}),v.jsxs("div",{className:"flex gap-2",children:[v.jsxs("button",{onClick:s,title:"Transferência assistida",className:"flex items-center gap-2 bg-purple-700 hover:bg-purple-600 text-white rounded-lg px-4 py-2.5 text-sm font-medium transition-colors flex-1",children:[v.jsx(ee,{className:"w-4 h-4"}),"Assistida"]}),v.jsxs("button",{onClick:l,title:"Transferência direta",className:"flex items-center gap-2 bg-blue-700 hover:bg-blue-600 text-white rounded-lg px-4 py-2.5 text-sm font-medium transition-colors flex-1",children:[v.jsx(B,{className:"w-4 h-4"}),"Direta"]})]})]})})]})}function rr({onConnect:e,isConnecting:t,settings:n={},hideHeader:r=!1,onSave:i,onShowLogs:o}){const a=e=>({username:e.username||"",domain:e.domain||"",password:"",auth_user:e.auth_user||e.username||""}),s=e=>!!(e&&e.username&&e.domain),[l,c]=y.useState(()=>s(n)?a(n):a({})),[u,d]=y.useState(!1);y.useEffect(()=>{s(n)||_n.getSipConfig().then(e=>{s(e)&&c(a(e))})},[]),y.useEffect(()=>{s(n)&&c(a(n))},[n]);const h=e=>{c({...l,[e.target.name]:e.target.value})};return v.jsxs("div",{className:r?"flex-1":"bg-gray-900 rounded-2xl shadow-2xl border border-gray-800 overflow-hidden",children:[!r&&v.jsxs("div",{className:"bg-gradient-to-r from-blue-600 to-blue-700 p-6 text-center",children:[v.jsx("div",{className:"w-16 h-16 bg-white/20 rounded-full flex items-center justify-center mx-auto mb-3",children:v.jsx(oe,{className:"w-8 h-8 text-white"})}),v.jsx("h1",{className:"text-white text-xl font-bold",children:"WebRTC Softphone"}),v.jsx("p",{className:"text-blue-200 text-sm mt-1",children:"SIP.js powered"})]}),v.jsxs("form",{onSubmit:async t=>{if(t.preventDefault(),!l.username||!l.domain)return;const n=`sip:${l.username}@${l.domain}`;r&&i?(await i({...l,aor:n}),d(!0),setTimeout(()=>d(!1),5e3)):(_n.setManualDisconnect(!1),e({...l,aor:n}))},className:"p-6 space-y-5",children:[v.jsxs("div",{className:"flex gap-2",children:[v.jsxs("div",{className:"flex-1",children:[v.jsx("label",{className:"text-gray-400 text-xs font-medium uppercase tracking-wider mb-1 block",children:"Ramal *"}),v.jsx("input",{type:"text",name:"username",value:l.username,onChange:h,placeholder:"850",required:!0,className:"w-full bg-gray-800 border border-gray-700 rounded-lg px-3 py-2.5 text-white text-sm placeholder-gray-500 focus:outline-none focus:border-blue-500 transition-colors"})]}),v.jsxs("div",{className:"flex-[2]",children:[v.jsx("label",{className:"text-gray-400 text-xs font-medium uppercase tracking-wider mb-1 block",children:"Domínio *"}),v.jsx("input",{type:"text",name:"domain",value:l.domain,onChange:h,placeholder:"subdominio.falehandix.com.br",required:!0,className:"w-full bg-gray-800 border border-gray-700 rounded-lg px-3 py-2.5 text-white text-sm placeholder-gray-500 focus:outline-none focus:border-blue-500 transition-colors"})]})]}),v.jsxs("div",{children:[v.jsx("label",{className:"text-gray-400 text-xs font-medium uppercase tracking-wider mb-1 block",children:"Senha"}),v.jsx("input",{type:"password",name:"password",value:l.password,onChange:h,placeholder:"••••••••",className:"w-full bg-gray-800 border border-gray-700 rounded-lg px-3 py-2.5 text-white text-sm placeholder-gray-500 focus:outline-none focus:border-blue-500 transition-colors"})]}),v.jsx("button",{type:"submit",disabled:t||!l.username||!l.domain,className:"w-full text-white font-semibold py-3 rounded-[15px] transition-colors flex items-center justify-center gap-2 mt-2 disabled:bg-gray-700 disabled:text-gray-500 "+(r?"bg-green-600 hover:bg-green-700":"bg-blue-600 hover:bg-blue-700"),children:r?v.jsxs(v.Fragment,{children:[v.jsx(ae,{className:"w-4 h-4"}),"Salvar"]}):t?v.jsxs(v.Fragment,{children:[v.jsx("div",{className:"w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin"}),"Conectando..."]}):v.jsxs(v.Fragment,{children:[v.jsx(oe,{className:"w-4 h-4"}),"Conectar"]})}),r&&u&&v.jsx("p",{className:"text-green-400 text-xs text-center mt-1",children:"Configurações salvas com sucesso"}),r&&o&&v.jsx("button",{type:"button",onClick:o,className:"w-full text-gray-400 hover:text-gray-300 text-xs py-2 mt-3 transition-colors",children:"logs"})]})]})}const ir={disconnected:{icon:"phoneOff",color:"text-slate-500"},connecting:{icon:"phone",color:"text-amber-400 animate-pulse"},connected:{icon:"phone",color:"text-amber-400"},registered:{icon:"phone",color:"text-emerald-400"}},or={idle:null,calling:{color:"text-yellow-400",label:"Chamando..."},ringing:{color:"text-blue-400 animate-pulse",label:"Entrada..."},active:{color:"text-green-400",label:"Em chamada"}};function ar({connectionStatus:e,callStatus:t,callDuration:n,aor:r,onDisconnect:i,onConnect:o}){var a;const s=ir[e]||ir.disconnected,l=or[t],c=(null==(a=null==r?void 0:r.split("@")[0])?void 0:a.replace("sip:",""))||"",u="phoneOff"===s.icon?re:oe;return v.jsxs("div",{className:"bg-gray-900 border-b border-gray-800 px-4 py-3 flex items-center justify-between",children:[v.jsxs("div",{className:"flex items-center gap-2",children:[v.jsx(u,{className:`w-4 h-4 ${s.color}`}),v.jsx("span",{className:"font-semibold text-white text-sm",children:"Handphone"}),c&&v.jsxs("span",{className:"text-slate-400 text-xs",children:["· ",c]}),l&&v.jsxs(v.Fragment,{children:[v.jsxs("span",{className:`text-xs ${l.color}`,children:["· ",l.label]}),"active"===t&&v.jsx("span",{className:"text-green-400 text-xs font-mono",children:(d=n,`${Math.floor(d/60).toString().padStart(2,"0")}:${(d%60).toString().padStart(2,"0")}`)})]})]}),c&&v.jsx("button",{onClick:"disconnected"===e?o:i,style:{border:"1px solid rgba(156,163,175,0.7)"},className:"text-xs px-3 py-1 rounded-full text-slate-300 hover:text-white transition-colors",children:"disconnected"===e?"Conectar":"Desconectar"})]});var d}const sr=y.createContext({});function lr(e){const t=y.useRef(null);return null===t.current&&(t.current=e()),t.current}const cr=y.createContext(null),ur=y.createContext({transformPagePoint:e=>e,isStatic:!1,reducedMotion:"never"});class dr extends y.Component{getSnapshotBeforeUpdate(e){const t=this.props.childRef.current;if(t&&e.isPresent&&!this.props.isPresent){const e=this.props.sizeRef.current;e.height=t.offsetHeight||0,e.width=t.offsetWidth||0,e.top=t.offsetTop,e.left=t.offsetLeft}return null}componentDidUpdate(){}render(){return this.props.children}}function hr({children:e,isPresent:t}){const n=y.useId(),r=y.useRef(null),i=y.useRef({width:0,height:0,top:0,left:0}),{nonce:o}=y.useContext(ur);return y.useInsertionEffect(()=>{const{width:e,height:a,top:s,left:l}=i.current;if(t||!r.current||!e||!a)return;r.current.dataset.motionPopId=n;const c=document.createElement("style");return o&&(c.nonce=o),document.head.appendChild(c),c.sheet&&c.sheet.insertRule(`\n [data-motion-pop-id="${n}"] {\n position: absolute !important;\n width: ${e}px !important;\n height: ${a}px !important;\n top: ${s}px !important;\n left: ${l}px !important;\n }\n `),()=>{document.head.removeChild(c)}},[t]),v.jsx(dr,{isPresent:t,childRef:r,sizeRef:i,children:y.cloneElement(e,{ref:r})})}const fr=({children:e,initial:t,isPresent:n,onExitComplete:r,custom:i,presenceAffectsLayout:o,mode:a})=>{const s=lr(pr),l=y.useId(),c=y.useCallback(e=>{s.set(e,!0);for(const t of s.values())if(!t)return;r&&r()},[s,r]),u=y.useMemo(()=>({id:l,initial:t,isPresent:n,custom:i,onExitComplete:c,register:e=>(s.set(e,!1),()=>s.delete(e))}),o?[Math.random(),c]:[n,c]);return y.useMemo(()=>{s.forEach((e,t)=>s.set(t,!1))},[n]),y.useEffect(()=>{!n&&!s.size&&r&&r()},[n]),"popLayout"===a&&(e=v.jsx(hr,{isPresent:n,children:e})),v.jsx(cr.Provider,{value:u,children:e})};function pr(){return new Map}function gr(e=!0){const t=y.useContext(cr);if(null===t)return[!0,null];const{isPresent:n,onExitComplete:r,register:i}=t,o=y.useId();y.useEffect(()=>{e&&i(o)},[e]);const a=y.useCallback(()=>e&&r&&r(o),[o,r,e]);return!n&&r?[!1,a]:[!0]}const mr=e=>e.key||"";function vr(e){const t=[];return y.Children.forEach(e,e=>{y.isValidElement(e)&&t.push(e)}),t}const yr="undefined"!=typeof window,br=yr?y.useLayoutEffect:y.useEffect;var wr={};const xr=({children:e,custom:t,initial:n=!0,onExitComplete:r,presenceAffectsLayout:i=!0,mode:o="sync",propagate:a=!1})=>{const[s,l]=gr(a),c=y.useMemo(()=>vr(e),[e]),u=a&&!s?[]:c.map(mr),d=y.useRef(!0),h=y.useRef(c),f=lr(()=>new Map),[p,g]=y.useState(c),[m,b]=y.useState(c);br(()=>{d.current=!1,h.current=c;for(let e=0;e1&&console.warn('You\'re attempting to animate multiple children within AnimatePresence, but its mode is set to "wait". This will lead to odd visual behaviour.');const{forceRender:x}=y.useContext(sr);return v.jsx(v.Fragment,{children:m.map(e=>{const p=mr(e),g=!(a&&!s)&&(c===m||u.includes(p));return v.jsx(fr,{isPresent:g,initial:!(d.current&&!n)&&void 0,custom:g?void 0:t,presenceAffectsLayout:i,mode:o,onExitComplete:g?void 0:()=>{if(!f.has(p))return;f.set(p,!0);let e=!0;f.forEach(t=>{t||(e=!1)}),e&&(null==x||x(),b(h.current),a&&(null==l||l()),r&&r())},children:e},p)})})},kr=e=>e;let Sr=kr,Tr=kr;function Er(e){let t;return()=>(void 0===t&&(t=e()),t)}"production"!=={}.NODE_ENV&&(Sr=(e,t)=>{e||"undefined"==typeof console||console.warn(t)},Tr=(e,t)=>{if(!e)throw new Error(t)});const Cr=(e,t,n)=>{const r=t-e;return 0===r?1:(n-e)/r},Rr=e=>1e3*e,Pr=e=>e/1e3,_r=!1;const Dr=["read","resolveKeyframes","update","preRender","render","postRender"];function Ir(e,t){let n=!1,r=!0;const i={delta:0,timestamp:0,isProcessing:!1},o=()=>n=!0,a=Dr.reduce((e,t)=>(e[t]=function(e){let t=new Set,n=new Set,r=!1,i=!1;const o=new WeakSet;let a={delta:0,timestamp:0,isProcessing:!1};function s(t){o.has(t)&&(l.schedule(t),e()),t(a)}const l={schedule:(e,i=!1,a=!1)=>{const s=a&&r?t:n;return i&&o.add(e),s.has(e)||s.add(e),e},cancel:e=>{n.delete(e),o.delete(e)},process:e=>{a=e,r?i=!0:(r=!0,[t,n]=[n,t],t.forEach(s),t.clear(),r=!1,i&&(i=!1,l.process(e)))}};return l}(o),e),{}),{read:s,resolveKeyframes:l,update:c,preRender:u,render:d,postRender:h}=a,f=()=>{const o=performance.now();n=!1,i.delta=r?1e3/60:Math.max(Math.min(o-i.timestamp,40),1),i.timestamp=o,i.isProcessing=!0,s.process(i),l.process(i),c.process(i),u.process(i),d.process(i),h.process(i),i.isProcessing=!1,n&&t&&(r=!1,e(f))};return{schedule:Dr.reduce((t,o)=>{const s=a[o];return t[o]=(t,o=!1,a=!1)=>(n||(n=!0,r=!0,i.isProcessing||e(f)),s.schedule(t,o,a)),t},{}),cancel:e=>{for(let t=0;tjr[Ld].some(t=>!!e[t])};const Hr=new Set(["animate","exit","variants","initial","style","values","variants","transition","transformTemplate","custom","inherit","onBeforeLayoutMeasure","onAnimationStart","onAnimationComplete","onUpdate","onDragStart","onDrag","onDragEnd","onMeasureDragConstraints","onDirectionLock","onDragTransitionEnd","_dragX","_dragY","onHoverStart","onHoverEnd","onViewportEnter","onViewportLeave","globalTapTarget","ignoreStrict","viewport"]);function Fr(e){return e.startsWith("while")||e.startsWith("drag")&&"draggable"!==e||e.startsWith("layout")||e.startsWith("onTap")||e.startsWith("onPan")||e.startsWith("onLayout")||Hr.has(e)}let Ur=e=>!Fr(e);try{(zr=require("@emotion/is-prop-valid").default)&&(Ur=e=>e.startsWith("on")?!Fr(e):zr(e))}catch(jd){}var zr;const qr=new Set;function Vr(e,t,n){e||qr.has(t)||(console.warn(t),qr.add(t))}var Br={};function Wr(e){if("undefined"==typeof Proxy)return e;const t=new Map;return new Proxy((...t)=>("production"!==Br.NODE_ENV&&Vr(!1,"motion() is deprecated. Use motion.create() instead."),e(...t)),{get:(n,r)=>"create"===r?e:(t.has(r)||t.set(r,e(r)),t.get(r))})}const Yr=y.createContext({});function Gr(e){return"string"==typeof e||Array.isArray(e)}function Kr(e){return null!==e&&"object"==typeof e&&"function"==typeof e.start}const Qr=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],Xr=["initial",...Qr];function Zr(e){return Kr(e.animate)||Xr.some(t=>Gr(e[t]))}function Jr(e){return Boolean(Zr(e)||e.variants)}function ei(e){const{initial:t,animate:n}=function(e,t){if(Zr(e)){const{initial:t,animate:n}=e;return{initial:!1===t||Gr(t)?t:void 0,animate:Gr(n)?n:void 0}}return!1!==e.inherit?t:{}}(e,y.useContext(Yr));return y.useMemo(()=>({initial:t,animate:n}),[ti(t),ti(n)])}function ti(e){return Array.isArray(e)?e.join(" "):e}const ni=Symbol.for("motionComponentSymbol");function ri(e){return e&&"object"==typeof e&&Object.prototype.hasOwnProperty.call(e,"current")}function ii(e,t,n){return y.useCallback(r=>{r&&e.onMount&&e.onMount(r),t&&(r?t.mount(r):t.unmount()),n&&("function"==typeof n?n(r):ri(n)&&(n.current=r))},[t])}const oi=e=>e.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),ai="data-"+oi("framerAppearId"),{schedule:si}=Ir(queueMicrotask,!1),li=y.createContext({});function ci(e,t,n,r,i){var o,a;const{visualElement:s}=y.useContext(Yr),l=y.useContext(Or),c=y.useContext(cr),u=y.useContext(ur).reducedMotion,d=y.useRef(null);r=r||l.renderer,!d.current&&r&&(d.current=r(e,{visualState:t,parent:s,props:n,presenceContext:c,blockInitialAnimation:!!c&&!1===c.initial,reducedMotionConfig:u}));const h=d.current,f=y.useContext(li);!h||h.projection||!i||"html"!==h.type&&"svg"!==h.type||function(e,t,n,r){const{layoutId:i,layout:o,drag:a,dragConstraints:s,layoutScroll:l,layoutRoot:c}=t;e.projection=new n(e.latestValues,t["data-framer-portal-id"]?void 0:ui(e.parent)),e.projection.setOptions({layoutId:i,layout:o,alwaysMeasureLayout:Boolean(a)||s&&ri(s),visualElement:e,animationType:"string"==typeof o?o:"both",initialPromotionConfig:r,layoutScroll:l,layoutRoot:c})}(d.current,n,i,f);const p=y.useRef(!1);y.useInsertionEffect(()=>{h&&p.current&&h.update(n,c)});const g=n[ai],m=y.useRef(Boolean(g)&&!(null===(o=window.MotionHandoffIsComplete)||void 0===o?void 0:o.call(window,g))&&(null===(a=window.MotionHasOptimisedAnimation)||void 0===a?void 0:a.call(window,g)));return br(()=>{h&&(p.current=!0,window.MotionIsMounted=!0,h.updateFeatures(),si.render(h.render),m.current&&h.animationState&&h.animationState.animateChanges())}),y.useEffect(()=>{h&&(!m.current&&h.animationState&&h.animationState.animateChanges(),m.current&&(queueMicrotask(()=>{var e;null===(e=window.MotionHandoffMarkAsComplete)||void 0===e||e.call(window,g)}),m.current=!1))}),h}function ui(e){if(e)return!1!==e.options.allowProjection?e.projection:ui(e.parent)}var di={};function hi({preloadedFeatures:e,createVisualElement:t,useRender:n,useVisualState:r,Component:i}){var o,a;function s(o,a){let s;const l={...y.useContext(ur),...o,layoutId:fi(o)},{isStatic:c}=l,u=ei(o),d=r(o,c);if(!c&&yr){!function(e,t){const n=y.useContext(Or).strict;if("production"!==di.NODE_ENV&&t&&n){const t="You have rendered a `motion` component within a `LazyMotion` component. This will break tree shaking. Import and render a `m` component instead.";e.ignoreStrict?Sr(!1,t):Tr(!1,t)}}(l,e);const n=function(e){const{drag:t,layout:n}=Lr;if(!t&&!n)return{};const r={...t,...n};return{MeasureLayout:(null==t?void 0:t.isEnabled(e))||(null==n?void 0:n.isEnabled(e))?r.MeasureLayout:void 0,ProjectionNode:r.ProjectionNode}}(l);s=n.MeasureLayout,u.visualElement=ci(i,d,l,t,n.ProjectionNode)}return v.jsxs(Yr.Provider,{value:u,children:[s&&u.visualElement?v.jsx(s,{visualElement:u.visualElement,...l}):null,n(i,o,ii(d,u.visualElement,a),d,c,u.visualElement)]})}e&&function(e){for(const t in e)Lr[t]={...Lr[t],...e[t]}}(e),s.displayName=`motion.${"string"==typeof i?i:`create(${null!==(a=null!==(o=i.displayName)&&void 0!==o?o:i.name)&&void 0!==a?a:""})`}`;const l=y.forwardRef(s);return l[ni]=i,l}function fi({layoutId:e}){const t=y.useContext(sr).id;return t&&void 0!==e?t+"-"+e:e}const pi=["animate","circle","defs","desc","ellipse","g","image","line","filter","marker","mask","metadata","path","pattern","polygon","polyline","rect","stop","switch","symbol","svg","text","tspan","use","view"];function gi(e){return"string"==typeof e&&!e.includes("-")&&!!(pi.indexOf(e)>-1||/[A-Z]/u.test(e))}function mi(e){const t=[{},{}];return null==e||e.values.forEach((e,n)=>{t[0][n]=e.get(),t[1][n]=e.getVelocity()}),t}function vi(e,t,n,r){if("function"==typeof t){const[i,o]=mi(r);t=t(void 0!==n?n:e.custom,i,o)}if("string"==typeof t&&(t=e.variants&&e.variants[t]),"function"==typeof t){const[i,o]=mi(r);t=t(void 0!==n?n:e.custom,i,o)}return t}const yi=e=>Array.isArray(e),bi=e=>yi(e)?e[e.length-1]||0:e,wi=e=>Boolean(e&&e.getVelocity);function xi(e){const t=wi(e)?e.get():e;return n=t,Boolean(n&&"object"==typeof n&&n.mix&&n.toValue)?t.toValue():t;var n}const ki=e=>(t,n)=>{const r=y.useContext(Yr),i=y.useContext(cr),o=()=>function({scrapeMotionValuesFromProps:e,createRenderState:t,onUpdate:n},r,i,o){const a={latestValues:Si(r,i,o,e),renderState:t()};return n&&(a.onMount=e=>n({props:r,current:e,...a}),a.onUpdate=e=>n(e)),a}(e,t,r,i);return n?o():lr(o)};function Si(e,t,n,r){const i={},o=r(e,{});for(const h in o)i[h]=xi(o[h]);let{initial:a,animate:s}=e;const l=Zr(e),c=Jr(e);t&&c&&!l&&!1!==e.inherit&&(void 0===a&&(a=t.initial),void 0===s&&(s=t.animate));let u=!!n&&!1===n.initial;u=u||!1===a;const d=u?s:a;if(d&&"boolean"!=typeof d&&!Kr(d)){const t=Array.isArray(d)?d:[d];for(let n=0;nt=>"string"==typeof t&&t.startsWith(e),Ri=Ci("--"),Pi=Ci("var(--"),_i=e=>!!Pi(e)&&Di.test(e.split("/*")[0].trim()),Di=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,Ii=(e,t)=>t&&"number"==typeof e?t.transform(e):e,Ai=(e,t,n)=>n>t?t:n"number"==typeof e,parse:parseFloat,transform:e=>e},Mi={...Ni,transform:e=>Ai(0,1,e)},$i={...Ni,default:1},Oi=e=>({test:t=>"string"==typeof t&&t.endsWith(e)&&1===t.split(" ").length,parse:parseFloat,transform:t=>`${t}${e}`}),ji=Oi("deg"),Li=Oi("%"),Hi=Oi("px"),Fi=Oi("vh"),Ui=Oi("vw"),zi={...Li,parse:e=>Li.parse(e)/100,transform:e=>Li.transform(100*e)},qi={borderWidth:Hi,borderTopWidth:Hi,borderRightWidth:Hi,borderBottomWidth:Hi,borderLeftWidth:Hi,borderRadius:Hi,radius:Hi,borderTopLeftRadius:Hi,borderTopRightRadius:Hi,borderBottomRightRadius:Hi,borderBottomLeftRadius:Hi,width:Hi,maxWidth:Hi,height:Hi,maxHeight:Hi,top:Hi,right:Hi,bottom:Hi,left:Hi,padding:Hi,paddingTop:Hi,paddingRight:Hi,paddingBottom:Hi,paddingLeft:Hi,margin:Hi,marginTop:Hi,marginRight:Hi,marginBottom:Hi,marginLeft:Hi,backgroundPositionX:Hi,backgroundPositionY:Hi},Vi={rotate:ji,rotateX:ji,rotateY:ji,rotateZ:ji,scale:$i,scaleX:$i,scaleY:$i,scaleZ:$i,skew:ji,skewX:ji,skewY:ji,distance:Hi,translateX:Hi,translateY:Hi,translateZ:Hi,x:Hi,y:Hi,z:Hi,perspective:Hi,transformPerspective:Hi,opacity:Mi,originX:zi,originY:zi,originZ:Hi},Bi={...Ni,transform:Math.round},Wi={...qi,...Vi,zIndex:Bi,size:Hi,fillOpacity:Mi,strokeOpacity:Mi,numOctaves:Bi},Yi={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},Gi=Ti.length;function Ki(e,t,n){const{style:r,vars:i,transformOrigin:o}=e;let a=!1,s=!1;for(const l in t){const e=t[l];if(Ei.has(l))a=!0;else if(Ri(l))i[l]=e;else{const t=Ii(e,Wi[l]);l.startsWith("origin")?(s=!0,o[l]=t):r[l]=t}}if(t.transform||(a||n?r.transform=function(e,t,n){let r="",i=!0;for(let o=0;o({style:{},transform:{},transformOrigin:{},vars:{}}),to=()=>({style:{},transform:{},transformOrigin:{},vars:{},attrs:{}}),no=e=>"string"==typeof e&&"svg"===e.toLowerCase();function ro(e,{style:t,vars:n},r,i){Object.assign(e.style,t,i&&i.getProjectionStyles(r));for(const o in n)e.style.setProperty(o,n[o])}const io=new Set(["baseFrequency","diffuseConstant","kernelMatrix","kernelUnitLength","keySplines","keyTimes","limitingConeAngle","markerHeight","markerWidth","numOctaves","targetX","targetY","surfaceScale","specularConstant","specularExponent","stdDeviation","tableValues","viewBox","gradientTransform","pathLength","startOffset","textLength","lengthAdjust"]);function oo(e,t,n,r){ro(e,t,void 0,r);for(const i in t.attrs)e.setAttribute(io.has(i)?i:oi(i),t.attrs[i])}const ao={};function so(e,{layout:t,layoutId:n}){return Ei.has(e)||e.startsWith("origin")||(t||void 0!==n)&&(!!ao[e]||"opacity"===e)}function lo(e,t,n){var r;const{style:i}=e,o={};for(const a in i)(wi(i[a])||t.style&&wi(t.style[a])||so(a,e)||void 0!==(null===(r=null==n?void 0:n.getValue(a))||void 0===r?void 0:r.liveStyle))&&(o[a]=i[a]);return o}function co(e,t,n){const r=lo(e,t,n);for(const i in e)if(wi(e[i])||wi(t[i])){r[-1!==Ti.indexOf(i)?"attr"+i.charAt(0).toUpperCase()+i.substring(1):i]=e[i]}return r}const uo=["x","y","width","height","cx","cy","r"],ho={useVisualState:ki({scrapeMotionValuesFromProps:co,createRenderState:to,onUpdate:({props:e,prevProps:t,current:n,renderState:r,latestValues:i})=>{if(!n)return;let o=!!e.drag;if(!o)for(const s in i)if(Ei.has(s)){o=!0;break}if(!o)return;let a=!t;if(t)for(let s=0;s{!function(e,t){try{t.dimensions="function"==typeof e.getBBox?e.getBBox():e.getBoundingClientRect()}catch(n){t.dimensions={x:0,y:0,width:0,height:0}}}(n,r),Ar.render(()=>{Ji(r,i,no(n.tagName),e.transformTemplate),oo(n,r)})})}})},fo={useVisualState:ki({scrapeMotionValuesFromProps:lo,createRenderState:eo})};function po(e,t,n){for(const r in t)wi(t[r])||so(r,n)||(e[r]=t[r])}function go(e,t){const n={};return po(n,e.style||{},e),Object.assign(n,function({transformTemplate:e},t){return y.useMemo(()=>{const n={style:{},transform:{},transformOrigin:{},vars:{}};return Ki(n,t,e),Object.assign({},n.vars,n.style)},[t])}(e,t)),n}function mo(e,t){const n={},r=go(e,t);return e.drag&&!1!==e.dragListener&&(n.draggable=!1,r.userSelect=r.WebkitUserSelect=r.WebkitTouchCallout="none",r.touchAction=!0===e.drag?"none":"pan-"+("x"===e.drag?"y":"x")),void 0===e.tabIndex&&(e.onTap||e.onTapStart||e.whileTap)&&(n.tabIndex=0),n.style=r,n}function vo(e,t,n,r){const i=y.useMemo(()=>{const n={style:{},transform:{},transformOrigin:{},vars:{},attrs:{}};return Ji(n,t,no(r),e.transformTemplate),{...n.attrs,style:{...n.style}}},[t]);if(e.style){const t={};po(t,e.style,e),i.style={...t,...i.style}}return i}function yo(e=!1){return(t,n,r,{latestValues:i},o)=>{const a=(gi(t)?vo:mo)(n,i,o,t),s=function(e,t,n){const r={};for(const i in e)"values"===i&&"object"==typeof e.values||(Ur(i)||!0===n&&Fr(i)||!t&&!Fr(i)||e.draggable&&i.startsWith("onDrag"))&&(r[i]=e[i]);return r}(n,"string"==typeof t,e),l=t!==y.Fragment?{...s,...a,ref:r}:{},{children:c}=n,u=y.useMemo(()=>wi(c)?c.get():c,[c]);return y.createElement(t,{...l,children:u})}}function bo(e,t){return function(n,{forwardMotionProps:r}={forwardMotionProps:!1}){return hi({...gi(n)?ho:fo,preloadedFeatures:e,useRender:yo(r),createVisualElement:t,Component:n})}}function wo(e,t){if(!Array.isArray(t))return!1;const n=t.length;if(n!==e.length)return!1;for(let r=0;rvoid 0!==window.ScrollTimeline);class So{constructor(e){this.stop=()=>this.runAll("stop"),this.animations=e.filter(Boolean)}get finished(){return Promise.all(this.animations.map(e=>"finished"in e?e.finished:e))}getAll(e){return this.animations[0][e]}setAll(e,t){for(let n=0;nko()&&n.attachTimeline?n.attachTimeline(e):"function"==typeof t?t(n):void 0);return()=>{n.forEach((e,t)=>{e&&e(),this.animations[t].stop()})}}get time(){return this.getAll("time")}set time(e){this.setAll("time",e)}get speed(){return this.getAll("speed")}set speed(e){this.setAll("speed",e)}get startTime(){return this.getAll("startTime")}get duration(){let e=0;for(let t=0;tt[e]())}flatten(){this.runAll("flatten")}play(){this.runAll("play")}pause(){this.runAll("pause")}cancel(){this.runAll("cancel")}complete(){this.runAll("complete")}}class To extends So{then(e,t){return Promise.all(this.animations).then(e).catch(t)}}function Eo(e,t){return e?e[t]||e.default||e:void 0}const Co=2e4;function Ro(e){let t=0;let n=e.next(t);for(;!n.done&&t=Co?1/0:t}function Po(e){return"function"==typeof e}function _o(e,t){e.timeline=t,e.onfinish=null}const Do=e=>Array.isArray(e)&&"number"==typeof e[0],Io={linearEasing:void 0};function Ao(e,t){const n=Er(e);return()=>{var e;return null!==(e=Io[t])&&void 0!==e?e:n()}}const No=Ao(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch(e){return!1}return!0},"linearEasing"),Mo=(e,t,n=10)=>{let r="";const i=Math.max(Math.round(t/n),2);for(let o=0;o`cubic-bezier(${e}, ${t}, ${n}, ${r})`,jo={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:Oo([0,.65,.55,1]),circOut:Oo([.55,0,1,.45]),backIn:Oo([.31,.01,.66,-.59]),backOut:Oo([.33,1.53,.69,.99])};function Lo(e,t){return e?"function"==typeof e&&No()?Mo(e,t):Do(e)?Oo(e):Array.isArray(e)?e.map(e=>Lo(e,t)||jo.easeOut):jo[e]:void 0}const Ho={x:!1,y:!1};function Fo(){return Ho.x||Ho.y}function Uo(e,t){const n=function(e){if(e instanceof Element)return[e];if("string"==typeof e){const t=document.querySelectorAll(e);return t?Array.from(t):[]}return Array.from(e)}(e),r=new AbortController;return[n,{passive:!0,...t,signal:r.signal},()=>r.abort()]}function zo(e){return t=>{"touch"===t.pointerType||Fo()||e(t)}}const qo=(e,t)=>!!t&&(e===t||qo(e,t.parentElement)),Vo=e=>"mouse"===e.pointerType?"number"!=typeof e.button||e.button<=0:!1!==e.isPrimary,Bo=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);const Wo=new WeakSet;function Yo(e){return t=>{"Enter"===t.key&&e(t)}}function Go(e,t){e.dispatchEvent(new PointerEvent("pointer"+t,{isPrimary:!0,bubbles:!0}))}function Ko(e){return Vo(e)&&!Fo()}function Qo(e,t,n={}){const[r,i,o]=Uo(e,n),a=e=>{const r=e.currentTarget;if(!Ko(e)||Wo.has(r))return;Wo.add(r);const o=t(e),a=(e,t)=>{window.removeEventListener("pointerup",s),window.removeEventListener("pointercancel",l),Ko(e)&&Wo.has(r)&&(Wo.delete(r),"function"==typeof o&&o(e,{success:t}))},s=e=>{a(e,n.useGlobalTarget||qo(r,e.target))},l=e=>{a(e,!1)};window.addEventListener("pointerup",s,i),window.addEventListener("pointercancel",l,i)};return r.forEach(e=>{(function(e){return Bo.has(e.tagName)||-1!==e.tabIndex})(e)||null!==e.getAttribute("tabindex")||(e.tabIndex=0);(n.useGlobalTarget?window:e).addEventListener("pointerdown",a,i),e.addEventListener("focus",e=>((e,t)=>{const n=e.currentTarget;if(!n)return;const r=Yo(()=>{if(Wo.has(n))return;Go(n,"down");const e=Yo(()=>{Go(n,"up")});n.addEventListener("keyup",e,t),n.addEventListener("blur",()=>Go(n,"cancel"),t)});n.addEventListener("keydown",r,t),n.addEventListener("blur",()=>n.removeEventListener("keydown",r),t)})(e,i),i)}),o}const Xo=new Set(["width","height","top","left","right","bottom",...Ti]);let Zo;function Jo(){Zo=void 0}const ea={now:()=>(void 0===Zo&&ea.set(Mr.isProcessing||_r?Mr.timestamp:performance.now()),Zo),set:e=>{Zo=e,queueMicrotask(Jo)}};function ta(e,t){-1===e.indexOf(t)&&e.push(t)}function na(e,t){const n=e.indexOf(t);n>-1&&e.splice(n,1)}class ra{constructor(){this.subscriptions=[]}add(e){return ta(this.subscriptions,e),()=>na(this.subscriptions,e)}notify(e,t,n){const r=this.subscriptions.length;if(r)if(1===r)this.subscriptions[0](e,t,n);else for(let i=0;i{const n=ea.now();this.updatedAt!==n&&this.setPrevFrameValue(),this.prev=this.current,this.setCurrent(e),this.current!==this.prev&&this.events.change&&this.events.change.notify(this.current),t&&this.events.renderRequest&&this.events.renderRequest.notify(this.current)},this.hasAnimated=!1,this.setCurrent(e),this.owner=t.owner}setCurrent(e){var t;this.current=e,this.updatedAt=ea.now(),null===this.canTrackVelocity&&void 0!==e&&(this.canTrackVelocity=(t=this.current,!isNaN(parseFloat(t))))}setPrevFrameValue(e=this.current){this.prevFrameValue=e,this.prevUpdatedAt=this.updatedAt}onChange(e){return"production"!==oa.NODE_ENV&&Vr(!1,'value.onChange(callback) is deprecated. Switch to value.on("change", callback).'),this.on("change",e)}on(e,t){this.events[e]||(this.events[e]=new ra);const n=this.events[e].add(t);return"change"===e?()=>{n(),Ar.read(()=>{this.events.change.getSize()||this.stop()})}:n}clearListeners(){for(const e in this.events)this.events[e].clear()}attach(e,t){this.passiveEffect=e,this.stopPassiveEffect=t}set(e,t=!0){t&&this.passiveEffect?this.passiveEffect(e,this.updateAndNotify):this.updateAndNotify(e,t)}setWithVelocity(e,t,n){this.set(t),this.prev=void 0,this.prevFrameValue=e,this.prevUpdatedAt=this.updatedAt-n}jump(e,t=!0){this.updateAndNotify(e),this.prev=e,this.prevUpdatedAt=this.prevFrameValue=void 0,t&&this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}get(){return this.current}getPrevious(){return this.prev}getVelocity(){const e=ea.now();if(!this.canTrackVelocity||void 0===this.prevFrameValue||e-this.updatedAt>30)return 0;const t=Math.min(this.updatedAt-this.prevUpdatedAt,30);return ia(parseFloat(this.current)-parseFloat(this.prevFrameValue),t)}start(e){return this.stop(),new Promise(t=>{this.hasAnimated=!0,this.animation=e(t),this.events.animationStart&&this.events.animationStart.notify()}).then(()=>{this.events.animationComplete&&this.events.animationComplete.notify(),this.clearAnimation()})}stop(){this.animation&&(this.animation.stop(),this.events.animationCancel&&this.events.animationCancel.notify()),this.clearAnimation()}isAnimating(){return!!this.animation}clearAnimation(){delete this.animation}destroy(){this.clearListeners(),this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}}function sa(e,t){return new aa(e,t)}function la(e,t,n){e.hasValue(t)?e.getValue(t).set(n):e.addValue(t,sa(n))}function ca(e,t){const n=e.getValue("willChange");if(r=n,Boolean(wi(r)&&r.add))return n.add(t);var r}function ua(e){return e.props[ai]}const da=(e,t,n)=>(((1-3*n+3*t)*e+(3*n-6*t))*e+3*t)*e;function ha(e,t,n,r){if(e===t&&n===r)return kr;const i=t=>function(e,t,n,r,i){let o,a,s=0;do{a=t+(n-t)/2,o=da(a,r,i)-e,o>0?n=a:t=a}while(Math.abs(o)>1e-7&&++s<12);return a}(t,0,1,e,n);return e=>0===e||1===e?e:da(i(e),t,r)}const fa=e=>t=>t<=.5?e(2*t)/2:(2-e(2*(1-t)))/2,pa=e=>t=>1-e(1-t),ga=ha(.33,1.53,.69,.99),ma=pa(ga),va=fa(ma),ya=e=>(e*=2)<1?.5*ma(e):.5*(2-Math.pow(2,-10*(e-1))),ba=e=>1-Math.sin(Math.acos(e)),wa=pa(ba),xa=fa(ba),ka=e=>/^0[^.\s]+$/u.test(e);function Sa(e){return"number"==typeof e?0===e:null===e||("none"===e||"0"===e||ka(e))}const Ta=e=>Math.round(1e5*e)/1e5,Ea=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;const Ca=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,Ra=(e,t)=>n=>Boolean("string"==typeof n&&Ca.test(n)&&n.startsWith(e)||t&&!function(e){return null==e}(n)&&Object.prototype.hasOwnProperty.call(n,t)),Pa=(e,t,n)=>r=>{if("string"!=typeof r)return r;const[i,o,a,s]=r.match(Ea);return{[e]:parseFloat(i),[t]:parseFloat(o),[n]:parseFloat(a),alpha:void 0!==s?parseFloat(s):1}},_a={...Ni,transform:e=>Math.round((e=>Ai(0,255,e))(e))},Da={test:Ra("rgb","red"),parse:Pa("red","green","blue"),transform:({red:e,green:t,blue:n,alpha:r=1})=>"rgba("+_a.transform(e)+", "+_a.transform(t)+", "+_a.transform(n)+", "+Ta(Mi.transform(r))+")"};const Ia={test:Ra("#"),parse:function(e){let t="",n="",r="",i="";return e.length>5?(t=e.substring(1,3),n=e.substring(3,5),r=e.substring(5,7),i=e.substring(7,9)):(t=e.substring(1,2),n=e.substring(2,3),r=e.substring(3,4),i=e.substring(4,5),t+=t,n+=n,r+=r,i+=i),{red:parseInt(t,16),green:parseInt(n,16),blue:parseInt(r,16),alpha:i?parseInt(i,16)/255:1}},transform:Da.transform},Aa={test:Ra("hsl","hue"),parse:Pa("hue","saturation","lightness"),transform:({hue:e,saturation:t,lightness:n,alpha:r=1})=>"hsla("+Math.round(e)+", "+Li.transform(Ta(t))+", "+Li.transform(Ta(n))+", "+Ta(Mi.transform(r))+")"},Na={test:e=>Da.test(e)||Ia.test(e)||Aa.test(e),parse:e=>Da.test(e)?Da.parse(e):Aa.test(e)?Aa.parse(e):Ia.parse(e),transform:e=>"string"==typeof e?e:e.hasOwnProperty("red")?Da.transform(e):Aa.transform(e)},Ma=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;const $a="number",Oa="color",ja=/var\s*\(\s*--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)|#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\)|-?(?:\d+(?:\.\d+)?|\.\d+)/giu;function La(e){const t=e.toString(),n=[],r={color:[],number:[],var:[]},i=[];let o=0;const a=t.replace(ja,e=>(Na.test(e)?(r.color.push(o),i.push(Oa),n.push(Na.parse(e))):e.startsWith("var(")?(r.var.push(o),i.push("var"),n.push(e)):(r.number.push(o),i.push($a),n.push(parseFloat(e))),++o,"${}")).split("${}");return{values:n,split:a,indexes:r,types:i}}function Ha(e){return La(e).values}function Fa(e){const{split:t,types:n}=La(e),r=t.length;return e=>{let i="";for(let o=0;o"number"==typeof e?0:e;const za={test:function(e){var t,n;return isNaN(e)&&"string"==typeof e&&((null===(t=e.match(Ea))||void 0===t?void 0:t.length)||0)+((null===(n=e.match(Ma))||void 0===n?void 0:n.length)||0)>0},parse:Ha,createTransformer:Fa,getAnimatableNone:function(e){const t=Ha(e);return Fa(e)(t.map(Ua))}},qa=new Set(["brightness","contrast","saturate","opacity"]);function Va(e){const[t,n]=e.slice(0,-1).split("(");if("drop-shadow"===t)return e;const[r]=n.match(Ea)||[];if(!r)return e;const i=n.replace(r,"");let o=qa.has(t)?1:0;return r!==n&&(o*=100),t+"("+o+i+")"}const Ba=/\b([a-z-]*)\(.*?\)/gu,Wa={...za,getAnimatableNone:e=>{const t=e.match(Ba);return t?t.map(Va).join(" "):e}},Ya={...Wi,color:Na,backgroundColor:Na,outlineColor:Na,fill:Na,stroke:Na,borderColor:Na,borderTopColor:Na,borderRightColor:Na,borderBottomColor:Na,borderLeftColor:Na,filter:Wa,WebkitFilter:Wa},Ga=e=>Ya[e];function Ka(e,t){let n=Ga(e);return n!==Wa&&(n=za),n.getAnimatableNone?n.getAnimatableNone(t):void 0}const Qa=new Set(["auto","none","0"]);const Xa=e=>e===Ni||e===Hi,Za=(e,t)=>parseFloat(e.split(", ")[t]),Ja=(e,t)=>(n,{transform:r})=>{if("none"===r||!r)return 0;const i=r.match(/^matrix3d\((.+)\)$/u);if(i)return Za(i[1],t);{const t=r.match(/^matrix\((.+)\)$/u);return t?Za(t[1],e):0}},es=new Set(["x","y","z"]),ts=Ti.filter(e=>!es.has(e));const ns={width:({x:e},{paddingLeft:t="0",paddingRight:n="0"})=>e.max-e.min-parseFloat(t)-parseFloat(n),height:({y:e},{paddingTop:t="0",paddingBottom:n="0"})=>e.max-e.min-parseFloat(t)-parseFloat(n),top:(e,{top:t})=>parseFloat(t),left:(e,{left:t})=>parseFloat(t),bottom:({y:e},{top:t})=>parseFloat(t)+(e.max-e.min),right:({x:e},{left:t})=>parseFloat(t)+(e.max-e.min),x:Ja(4,13),y:Ja(5,14)};ns.translateX=ns.x,ns.translateY=ns.y;const rs=new Set;let is=!1,os=!1;function as(){if(os){const e=Array.from(rs).filter(e=>e.needsMeasurement),t=new Set(e.map(e=>e.element)),n=new Map;t.forEach(e=>{const t=function(e){const t=[];return ts.forEach(n=>{const r=e.getValue(n);void 0!==r&&(t.push([n,r.get()]),r.set(n.startsWith("scale")?1:0))}),t}(e);t.length&&(n.set(e,t),e.render())}),e.forEach(e=>e.measureInitialState()),t.forEach(e=>{e.render();const t=n.get(e);t&&t.forEach(([t,n])=>{var r;null===(r=e.getValue(t))||void 0===r||r.set(n)})}),e.forEach(e=>e.measureEndState()),e.forEach(e=>{void 0!==e.suspendedScrollY&&window.scrollTo(0,e.suspendedScrollY)})}os=!1,is=!1,rs.forEach(e=>e.complete()),rs.clear()}function ss(){rs.forEach(e=>{e.readKeyframes(),e.needsMeasurement&&(os=!0)})}class ls{constructor(e,t,n,r,i,o=!1){this.isComplete=!1,this.isAsync=!1,this.needsMeasurement=!1,this.isScheduled=!1,this.unresolvedKeyframes=[...e],this.onComplete=t,this.name=n,this.motionValue=r,this.element=i,this.isAsync=o}scheduleResolve(){this.isScheduled=!0,this.isAsync?(rs.add(this),is||(is=!0,Ar.read(ss),Ar.resolveKeyframes(as))):(this.readKeyframes(),this.complete())}readKeyframes(){const{unresolvedKeyframes:e,name:t,element:n,motionValue:r}=this;for(let i=0;i/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(e),us=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function ds(e,t,n=1){Tr(n<=4,`Max CSS variable fallback depth detected in property "${e}". This may indicate a circular fallback dependency.`);const[r,i]=function(e){const t=us.exec(e);if(!t)return[,];const[,n,r,i]=t;return[`--${null!=n?n:r}`,i]}(e);if(!r)return;const o=window.getComputedStyle(t).getPropertyValue(r);if(o){const e=o.trim();return cs(e)?parseFloat(e):e}return _i(i)?ds(i,t,n+1):i}const hs=e=>t=>t.test(e),fs=[Ni,Hi,Li,ji,Ui,Fi,{test:e=>"auto"===e,parse:e=>e}],ps=e=>fs.find(hs(e));class gs extends ls{constructor(e,t,n,r,i){super(e,t,n,r,i,!0)}readKeyframes(){const{unresolvedKeyframes:e,element:t,name:n}=this;if(!t||!t.current)return;super.readKeyframes();for(let s=0;s{t.getValue(e).set(n)}),this.resolveNoneKeyframes()}}const ms=(e,t)=>"zIndex"!==t&&(!("number"!=typeof e&&!Array.isArray(e))||!("string"!=typeof e||!za.test(e)&&"0"!==e||e.startsWith("url(")));const vs=e=>null!==e;function ys(e,{repeat:t,repeatType:n="loop"},r){const i=e.filter(vs),o=t&&"loop"!==n&&t%2==1?0:i.length-1;return o&&void 0!==r?r:i[o]}class bs{constructor({autoplay:e=!0,delay:t=0,type:n="keyframes",repeat:r=0,repeatDelay:i=0,repeatType:o="loop",...a}){this.isStopped=!1,this.hasAttemptedResolve=!1,this.createdAt=ea.now(),this.options={autoplay:e,delay:t,type:n,repeat:r,repeatDelay:i,repeatType:o,...a},this.updateFinishedPromise()}calcStartTime(){return this.resolvedAt&&this.resolvedAt-this.createdAt>40?this.resolvedAt:this.createdAt}get resolved(){return this._resolved||this.hasAttemptedResolve||(ss(),as()),this._resolved}onKeyframesResolved(e,t){this.resolvedAt=ea.now(),this.hasAttemptedResolve=!0;const{name:n,type:r,velocity:i,delay:o,onComplete:a,onUpdate:s,isGenerator:l}=this.options;if(!l&&!function(e,t,n,r){const i=e[0];if(null===i)return!1;if("display"===t||"visibility"===t)return!0;const o=e[e.length-1],a=ms(i,t),s=ms(o,t);return Sr(a===s,`You are trying to animate ${t} from "${i}" to "${o}". ${i} is not an animatable value - to enable this animation set ${i} to a value animatable to ${o} via the \`style\` property.`),!(!a||!s)&&(function(e){const t=e[0];if(1===e.length)return!0;for(let n=0;n{this.resolveFinishedPromise=e})}}const ws=(e,t,n)=>e+(t-e)*n;function xs(e,t,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?e+6*(t-e)*n:n<.5?t:n<2/3?e+(t-e)*(2/3-n)*6:e}function ks(e,t){return n=>n>0?t:e}const Ss=(e,t,n)=>{const r=e*e,i=n*(t*t-r)+r;return i<0?0:Math.sqrt(i)},Ts=[Ia,Da,Aa];function Es(e){const t=(n=e,Ts.find(e=>e.test(n)));var n;if(Sr(Boolean(t),`'${e}' is not an animatable color. Use the equivalent color code instead.`),!Boolean(t))return!1;let r=t.parse(e);return t===Aa&&(r=function({hue:e,saturation:t,lightness:n,alpha:r}){e/=360,n/=100;let i=0,o=0,a=0;if(t/=100){const r=n<.5?n*(1+t):n+t-n*t,s=2*n-r;i=xs(s,r,e+1/3),o=xs(s,r,e),a=xs(s,r,e-1/3)}else i=o=a=n;return{red:Math.round(255*i),green:Math.round(255*o),blue:Math.round(255*a),alpha:r}}(r)),r}const Cs=(e,t)=>{const n=Es(e),r=Es(t);if(!n||!r)return ks(e,t);const i={...n};return e=>(i.red=Ss(n.red,r.red,e),i.green=Ss(n.green,r.green,e),i.blue=Ss(n.blue,r.blue,e),i.alpha=ws(n.alpha,r.alpha,e),Da.transform(i))},Rs=(e,t)=>n=>t(e(n)),Ps=(...e)=>e.reduce(Rs),_s=new Set(["none","hidden"]);function Ds(e,t){return n=>ws(e,t,n)}function Is(e){return"number"==typeof e?Ds:"string"==typeof e?_i(e)?ks:Na.test(e)?Cs:Ms:Array.isArray(e)?As:"object"==typeof e?Na.test(e)?Cs:Ns:ks}function As(e,t){const n=[...e],r=n.length,i=e.map((e,n)=>Is(e)(e,t[n]));return e=>{for(let t=0;t{for(const t in r)n[t]=r[t](e);return n}}const Ms=(e,t)=>{const n=za.createTransformer(t),r=La(e),i=La(t);return r.indexes.var.length===i.indexes.var.length&&r.indexes.color.length===i.indexes.color.length&&r.indexes.number.length>=i.indexes.number.length?_s.has(e)&&!i.values.length||_s.has(t)&&!r.values.length?function(e,t){return _s.has(e)?n=>n<=0?e:t:n=>n>=1?t:e}(e,t):Ps(As(function(e,t){var n;const r=[],i={color:0,var:0,number:0};for(let o=0;o{const r=t*a,i=r*e,o=r-n,s=Js(t,a),l=Math.exp(-i);return Qs-o/s*l},o=t=>{const r=t*a*e,o=r*n+n,s=Math.pow(a,2)*Math.pow(t,2)*e,l=Math.exp(-r),c=Js(Math.pow(t,2),a);return(-i(t)+Qs>0?-1:1)*((o-s)*l)/c}):(i=t=>Math.exp(-t*e)*((t-n)*e+1)-.001,o=t=>Math.exp(-t*e)*(e*e*(n-t)));const s=function(e,t,n){let r=n;for(let i=1;ivoid 0!==e[t])}function rl(e=qs,t=zs){const n="object"!=typeof e?{visualDuration:e,keyframes:[0,1],bounce:t}:e;let{restSpeed:r,restDelta:i}=n;const o=n.keyframes[0],a=n.keyframes[n.keyframes.length-1],s={done:!1,value:o},{stiffness:l,damping:c,mass:u,duration:d,velocity:h,isResolvedFromDuration:f}=function(e){let t={velocity:Fs,stiffness:js,damping:Ls,mass:Hs,isResolvedFromDuration:!1,...e};if(!nl(e,tl)&&nl(e,el))if(e.visualDuration){const n=e.visualDuration,r=2*Math.PI/(1.2*n),i=r*r,o=2*Ai(.05,1,1-(e.bounce||0))*Math.sqrt(i);t={...t,mass:Hs,stiffness:i,damping:o}}else{const n=Xs(e);t={...t,...n,mass:Hs},t.isResolvedFromDuration=!0}return t}({...n,velocity:-Pr(n.velocity||0)}),p=h||0,g=c/(2*Math.sqrt(l*u)),m=a-o,v=Pr(Math.sqrt(l/u)),y=Math.abs(m)<5;let b;if(r||(r=y?Vs.granular:Vs.default),i||(i=y?Bs.granular:Bs.default),g<1){const e=Js(v,g);b=t=>{const n=Math.exp(-g*v*t);return a-n*((p+g*v*m)/e*Math.sin(e*t)+m*Math.cos(e*t))}}else if(1===g)b=e=>a-Math.exp(-v*e)*(m+(p+v*m)*e);else{const e=v*Math.sqrt(g*g-1);b=t=>{const n=Math.exp(-g*v*t),r=Math.min(e*t,300);return a-n*((p+g*v*m)*Math.sinh(r)+e*m*Math.cosh(r))/e}}const w={calculatedDuration:f&&d||null,next:e=>{const t=b(e);if(f)s.done=e>=d;else{let n=0;g<1&&(n=0===e?Rr(p):Os(b,e,t));const o=Math.abs(n)<=r,l=Math.abs(a-t)<=i;s.done=o&&l}return s.value=s.done?a:t,s},toString:()=>{const e=Math.min(Ro(w),Co),t=Mo(t=>w.next(e*t).value,e,30);return e+"ms "+t}};return w}function il({keyframes:e,velocity:t=0,power:n=.8,timeConstant:r=325,bounceDamping:i=10,bounceStiffness:o=500,modifyTarget:a,min:s,max:l,restDelta:c=.5,restSpeed:u}){const d=e[0],h={done:!1,value:d},f=e=>void 0===s?l:void 0===l||Math.abs(s-e)-p*Math.exp(-e/r),y=e=>m+v(e),b=e=>{const t=v(e),n=y(e);h.done=Math.abs(t)<=c,h.value=h.done?m:n};let w,x;const k=e=>{var t;(t=h.value,void 0!==s&&tl)&&(w=e,x=rl({keyframes:[h.value,f(h.value)],velocity:Os(y,e,h.value),damping:i,stiffness:o,restDelta:c,restSpeed:u}))};return k(0),{calculatedDuration:null,next:e=>{let t=!1;return x||void 0!==w||(t=!0,b(e),k(e)),void 0!==w&&e>=w?x.next(e-w):(!t&&b(e),h)}}}const ol=ha(.42,0,1,1),al=ha(0,0,.58,1),sl=ha(.42,0,.58,1),ll={linear:kr,easeIn:ol,easeInOut:sl,easeOut:al,circIn:ba,circInOut:xa,circOut:wa,backIn:ma,backInOut:va,backOut:ga,anticipate:ya},cl=e=>{if(Do(e)){Tr(4===e.length,"Cubic bezier arrays must contain four numerical values.");const[t,n,r,i]=e;return ha(t,n,r,i)}return"string"==typeof e?(Tr(void 0!==ll[e],`Invalid easing type '${e}'`),ll[e]):e};function ul(e,t,{clamp:n=!0,ease:r,mixer:i}={}){const o=e.length;if(Tr(o===t.length,"Both input and output ranges must be the same length"),1===o)return()=>t[0];if(2===o&&t[0]===t[1])return()=>t[1];const a=e[0]===e[1];e[0]>e[o-1]&&(e=[...e].reverse(),t=[...t].reverse());const s=function(e,t,n){const r=[],i=n||$s,o=e.length-1;for(let a=0;a{if(a&&n1)for(;rc(Ai(e[0],e[o-1],t)):c}function dl(e){const t=[0];return function(e,t){const n=e[e.length-1];for(let r=1;r<=t;r++){const i=Cr(0,t,r);e.push(ws(n,1,i))}}(t,e.length-1),t}function hl({duration:e=300,keyframes:t,times:n,ease:r="easeInOut"}){const i=(e=>Array.isArray(e)&&"number"!=typeof e[0])(r)?r.map(cl):cl(r),o={done:!1,value:t[0]},a=function(e,t){return e.map(e=>e*t)}(n&&n.length===t.length?n:dl(t),e),s=ul(a,t,{ease:Array.isArray(i)?i:(l=t,c=i,l.map(()=>c||sl).splice(0,l.length-1))});var l,c;return{calculatedDuration:e,next:t=>(o.value=s(t),o.done=t>=e,o)}}const fl=e=>{const t=({timestamp:t})=>e(t);return{start:()=>Ar.update(t,!0),stop:()=>Nr(t),now:()=>Mr.isProcessing?Mr.timestamp:ea.now()}};var pl={};const gl={decay:il,inertia:il,tween:hl,keyframes:hl,spring:rl},ml=e=>e/100;class vl extends bs{constructor(e){super(e),this.holdTime=null,this.cancelTime=null,this.currentTime=0,this.playbackSpeed=1,this.pendingPlayState="running",this.startTime=null,this.state="idle",this.stop=()=>{if(this.resolver.cancel(),this.isStopped=!0,"idle"===this.state)return;this.teardown();const{onStop:e}=this.options;e&&e()};const{name:t,motionValue:n,element:r,keyframes:i}=this.options,o=(null==r?void 0:r.KeyframeResolver)||ls;this.resolver=new o(i,(e,t)=>this.onKeyframesResolved(e,t),t,n,r),this.resolver.scheduleResolve()}flatten(){super.flatten(),this._resolved&&Object.assign(this._resolved,this.initPlayback(this._resolved.keyframes))}initPlayback(e){const{type:t="keyframes",repeat:n=0,repeatDelay:r=0,repeatType:i,velocity:o=0}=this.options,a=Po(t)?t:gl[t]||hl;let s,l;a!==hl&&"number"!=typeof e[0]&&("production"!==pl.NODE_ENV&&Tr(2===e.length,`Only two keyframes currently supported with spring and inertia animations. Trying to animate ${e}`),s=Ps(ml,$s(e[0],e[1])),e=[0,100]);const c=a({...this.options,keyframes:e});"mirror"===i&&(l=a({...this.options,keyframes:[...e].reverse(),velocity:-o})),null===c.calculatedDuration&&(c.calculatedDuration=Ro(c));const{calculatedDuration:u}=c,d=u+r;return{generator:c,mirroredGenerator:l,mapPercentToKeyframes:s,calculatedDuration:u,resolvedDuration:d,totalDuration:d*(n+1)-r}}onPostResolved(){const{autoplay:e=!0}=this.options;this.play(),"paused"!==this.pendingPlayState&&e?this.state=this.pendingPlayState:this.pause()}tick(e,t=!1){const{resolved:n}=this;if(!n){const{keyframes:e}=this.options;return{done:!0,value:e[e.length-1]}}const{finalKeyframe:r,generator:i,mirroredGenerator:o,mapPercentToKeyframes:a,keyframes:s,calculatedDuration:l,totalDuration:c,resolvedDuration:u}=n;if(null===this.startTime)return i.next(0);const{delay:d,repeat:h,repeatType:f,repeatDelay:p,onUpdate:g}=this.options;this.speed>0?this.startTime=Math.min(this.startTime,e):this.speed<0&&(this.startTime=Math.min(e-c/this.speed,this.startTime)),t?this.currentTime=e:null!==this.holdTime?this.currentTime=this.holdTime:this.currentTime=Math.round(e-this.startTime)*this.speed;const m=this.currentTime-d*(this.speed>=0?1:-1),v=this.speed>=0?m<0:m>c;this.currentTime=Math.max(m,0),"finished"===this.state&&null===this.holdTime&&(this.currentTime=c);let y=this.currentTime,b=i;if(h){const e=Math.min(this.currentTime,c)/u;let t=Math.floor(e),n=e%1;!n&&e>=1&&(n=1),1===n&&t--,t=Math.min(t,h+1);Boolean(t%2)&&("reverse"===f?(n=1-n,p&&(n-=p/u)):"mirror"===f&&(b=o)),y=Ai(0,1,n)*u}const w=v?{done:!1,value:s[0]}:b.next(y);a&&(w.value=a(w.value));let{done:x}=w;v||null===l||(x=this.speed>=0?this.currentTime>=c:this.currentTime<=0);const k=null===this.holdTime&&("finished"===this.state||"running"===this.state&&x);return k&&void 0!==r&&(w.value=ys(s,this.options,r)),g&&g(w.value),k&&this.finish(),w}get duration(){const{resolved:e}=this;return e?Pr(e.calculatedDuration):0}get time(){return Pr(this.currentTime)}set time(e){e=Rr(e),this.currentTime=e,null!==this.holdTime||0===this.speed?this.holdTime=e:this.driver&&(this.startTime=this.driver.now()-e/this.speed)}get speed(){return this.playbackSpeed}set speed(e){const t=this.playbackSpeed!==e;this.playbackSpeed=e,t&&(this.time=Pr(this.currentTime))}play(){if(this.resolver.isScheduled||this.resolver.resume(),!this._resolved)return void(this.pendingPlayState="running");if(this.isStopped)return;const{driver:e=fl,onPlay:t,startTime:n}=this.options;this.driver||(this.driver=e(e=>this.tick(e))),t&&t();const r=this.driver.now();null!==this.holdTime?this.startTime=r-this.holdTime:this.startTime?"finished"===this.state&&(this.startTime=r):this.startTime=null!=n?n:this.calcStartTime(),"finished"===this.state&&this.updateFinishedPromise(),this.cancelTime=this.startTime,this.holdTime=null,this.state="running",this.driver.start()}pause(){var e;this._resolved?(this.state="paused",this.holdTime=null!==(e=this.currentTime)&&void 0!==e?e:0):this.pendingPlayState="paused"}complete(){"running"!==this.state&&this.play(),this.pendingPlayState=this.state="finished",this.holdTime=null}finish(){this.teardown(),this.state="finished";const{onComplete:e}=this.options;e&&e()}cancel(){null!==this.cancelTime&&this.tick(this.cancelTime),this.teardown(),this.updateFinishedPromise()}teardown(){this.state="idle",this.stopDriver(),this.resolveFinishedPromise(),this.updateFinishedPromise(),this.startTime=this.cancelTime=null,this.resolver.cancel()}stopDriver(){this.driver&&(this.driver.stop(),this.driver=void 0)}sample(e){return this.startTime=0,this.tick(e,!0)}}const yl=new Set(["opacity","clipPath","filter","transform"]);function bl(e,t,n,{delay:r=0,duration:i=300,repeat:o=0,repeatType:a="loop",ease:s="easeInOut",times:l}={}){const c={[t]:n};l&&(c.offset=l);const u=Lo(s,i);return Array.isArray(u)&&(c.easing=u),e.animate(c,{delay:r,duration:i,easing:Array.isArray(u)?"linear":u,fill:"both",iterations:o+1,direction:"reverse"===a?"alternate":"normal"})}const wl=Er(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));const xl={anticipate:ya,backInOut:va,circInOut:xa};class kl extends bs{constructor(e){super(e);const{name:t,motionValue:n,element:r,keyframes:i}=this.options;this.resolver=new gs(i,(e,t)=>this.onKeyframesResolved(e,t),t,n,r),this.resolver.scheduleResolve()}initPlayback(e,t){let{duration:n=300,times:r,ease:i,type:o,motionValue:a,name:s,startTime:l}=this.options;if(!a.owner||!a.owner.current)return!1;var c;if("string"==typeof i&&No()&&i in xl&&(i=xl[i]),Po((c=this.options).type)||"spring"===c.type||!$o(c.ease)){const{onComplete:t,onUpdate:a,motionValue:s,element:l,...c}=this.options,u=function(e,t){const n=new vl({...t,keyframes:e,repeat:0,delay:0,isGenerator:!0});let r={done:!1,value:e[0]};const i=[];let o=0;for(;!r.done&&o<2e4;)r=n.sample(o),i.push(r.value),o+=10;return{times:void 0,keyframes:i,duration:o-10,ease:"linear"}}(e,c);1===(e=u.keyframes).length&&(e[1]=e[0]),n=u.duration,r=u.times,i=u.ease,o="keyframes"}const u=bl(a.owner.current,s,e,{...this.options,duration:n,times:r,ease:i});return u.startTime=null!=l?l:this.calcStartTime(),this.pendingTimeline?(_o(u,this.pendingTimeline),this.pendingTimeline=void 0):u.onfinish=()=>{const{onComplete:n}=this.options;a.set(ys(e,this.options,t)),n&&n(),this.cancel(),this.resolveFinishedPromise()},{animation:u,duration:n,times:r,type:o,ease:i,keyframes:e}}get duration(){const{resolved:e}=this;if(!e)return 0;const{duration:t}=e;return Pr(t)}get time(){const{resolved:e}=this;if(!e)return 0;const{animation:t}=e;return Pr(t.currentTime||0)}set time(e){const{resolved:t}=this;if(!t)return;const{animation:n}=t;n.currentTime=Rr(e)}get speed(){const{resolved:e}=this;if(!e)return 1;const{animation:t}=e;return t.playbackRate}set speed(e){const{resolved:t}=this;if(!t)return;const{animation:n}=t;n.playbackRate=e}get state(){const{resolved:e}=this;if(!e)return"idle";const{animation:t}=e;return t.playState}get startTime(){const{resolved:e}=this;if(!e)return null;const{animation:t}=e;return t.startTime}attachTimeline(e){if(this._resolved){const{resolved:t}=this;if(!t)return kr;const{animation:n}=t;_o(n,e)}else this.pendingTimeline=e;return kr}play(){if(this.isStopped)return;const{resolved:e}=this;if(!e)return;const{animation:t}=e;"finished"===t.playState&&this.updateFinishedPromise(),t.play()}pause(){const{resolved:e}=this;if(!e)return;const{animation:t}=e;t.pause()}stop(){if(this.resolver.cancel(),this.isStopped=!0,"idle"===this.state)return;this.resolveFinishedPromise(),this.updateFinishedPromise();const{resolved:e}=this;if(!e)return;const{animation:t,keyframes:n,duration:r,type:i,ease:o,times:a}=e;if("idle"===t.playState||"finished"===t.playState)return;if(this.time){const{motionValue:e,onUpdate:t,onComplete:s,element:l,...c}=this.options,u=new vl({...c,keyframes:n,duration:r,type:i,ease:o,times:a,isGenerator:!0}),d=Rr(this.time);e.setWithVelocity(u.sample(d-10).value,u.sample(d).value,10)}const{onStop:s}=this.options;s&&s(),this.cancel()}complete(){const{resolved:e}=this;e&&e.animation.finish()}cancel(){const{resolved:e}=this;e&&e.animation.cancel()}static supports(e){const{motionValue:t,name:n,repeatDelay:r,repeatType:i,damping:o,type:a}=e;if(!(t&&t.owner&&t.owner.current instanceof HTMLElement))return!1;const{onUpdate:s,transformTemplate:l}=t.owner.getProps();return wl()&&n&&yl.has(n)&&!s&&!l&&!r&&"mirror"!==i&&0!==o&&"inertia"!==a}}const Sl={type:"spring",stiffness:500,damping:25,restSpeed:10},Tl={type:"keyframes",duration:.8},El={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},Cl=(e,{keyframes:t})=>t.length>2?Tl:Ei.has(e)?e.startsWith("scale")?{type:"spring",stiffness:550,damping:0===t[1]?2*Math.sqrt(550):30,restSpeed:10}:Sl:El;const Rl=(e,t,n,r={},i,o)=>a=>{const s=Eo(r,e)||{},l=s.delay||r.delay||0;let{elapsed:c=0}=r;c-=Rr(l);let u={keyframes:Array.isArray(n)?n:[null,n],ease:"easeOut",velocity:t.getVelocity(),...s,delay:-c,onUpdate:e=>{t.set(e),s.onUpdate&&s.onUpdate(e)},onComplete:()=>{a(),s.onComplete&&s.onComplete()},name:e,motionValue:t,element:o?void 0:i};(function({when:e,delay:t,delayChildren:n,staggerChildren:r,staggerDirection:i,repeat:o,repeatType:a,repeatDelay:s,from:l,elapsed:c,...u}){return!!Object.keys(u).length})(s)||(u={...u,...Cl(e,u)}),u.duration&&(u.duration=Rr(u.duration)),u.repeatDelay&&(u.repeatDelay=Rr(u.repeatDelay)),void 0!==u.from&&(u.keyframes[0]=u.from);let d=!1;if((!1===u.type||0===u.duration&&!u.repeatDelay)&&(u.duration=0,0===u.delay&&(d=!0)),d&&!o&&void 0!==t.get()){const e=ys(u.keyframes,s);if(void 0!==e)return Ar.update(()=>{u.onUpdate(e),u.onComplete()}),new To([])}return!o&&kl.supports(u)?new kl(u):new vl(u)};function Pl({protectedKeys:e,needsAnimating:t},n){const r=e.hasOwnProperty(n)&&!0!==t[n];return t[n]=!1,r}function _l(e,t,{delay:n=0,transitionOverride:r,type:i}={}){var o;let{transition:a=e.getDefaultTransition(),transitionEnd:s,...l}=t;r&&(a=r);const c=[],u=i&&e.animationState&&e.animationState.getState()[i];for(const d in l){const t=e.getValue(d,null!==(o=e.latestValues[d])&&void 0!==o?o:null),r=l[d];if(void 0===r||u&&Pl(u,d))continue;const i={delay:n,...Eo(a||{},d)};let s=!1;if(window.MotionHandoffAnimation){const t=ua(e);if(t){const e=window.MotionHandoffAnimation(t,d,Ar);null!==e&&(i.startTime=e,s=!0)}}ca(e,d),t.start(Rl(d,t,r,e.shouldReduceMotion&&Xo.has(d)?{type:!1}:i,e,s));const h=t.animation;h&&c.push(h)}return s&&Promise.all(c).then(()=>{Ar.update(()=>{s&&function(e,t){const n=xo(e,t);let{transitionEnd:r={},transition:i={},...o}=n||{};o={...o,...r};for(const a in o)la(e,a,bi(o[a]))}(e,s)})}),c}function Dl(e,t,n={}){var r;const i=xo(e,t,"exit"===n.type?null===(r=e.presenceContext)||void 0===r?void 0:r.custom:void 0);let{transition:o=e.getDefaultTransition()||{}}=i||{};n.transitionOverride&&(o=n.transitionOverride);const a=i?()=>Promise.all(_l(e,i,n)):()=>Promise.resolve(),s=e.variantChildren&&e.variantChildren.size?(r=0)=>{const{delayChildren:i=0,staggerChildren:a,staggerDirection:s}=o;return function(e,t,n=0,r=0,i=1,o){const a=[],s=(e.variantChildren.size-1)*r,l=1===i?(e=0)=>e*r:(e=0)=>s-e*r;return Array.from(e.variantChildren).sort(Il).forEach((e,r)=>{e.notify("AnimationStart",t),a.push(Dl(e,t,{...o,delay:n+l(r)}).then(()=>e.notify("AnimationComplete",t)))}),Promise.all(a)}(e,t,i+r,a,s,n)}:()=>Promise.resolve(),{when:l}=o;if(l){const[e,t]="beforeChildren"===l?[a,s]:[s,a];return e().then(()=>t())}return Promise.all([a(),s(n.delay)])}function Il(e,t){return e.sortNodePosition(t)}const Al=Xr.length;function Nl(e){if(!e)return;if(!e.isControllingVariants){const t=e.parent&&Nl(e.parent)||{};return void 0!==e.props.initial&&(t.initial=e.props.initial),t}const t={};for(let n=0;nPromise.all(t.map(({animation:t,options:n})=>function(e,t,n={}){let r;if(e.notify("AnimationStart",t),Array.isArray(t)){const i=t.map(t=>Dl(e,t,n));r=Promise.all(i)}else if("string"==typeof t)r=Dl(e,t,n);else{const i="function"==typeof t?xo(e,t,n.custom):t;r=Promise.all(_l(e,i,n))}return r.then(()=>{e.notify("AnimationComplete",t)})}(e,t,n)))}function jl(e){let t=Ol(e),n=Fl(),r=!0;const i=t=>(n,r)=>{var i;const o=xo(e,r,"exit"===t?null===(i=e.presenceContext)||void 0===i?void 0:i.custom:void 0);if(o){const{transition:e,transitionEnd:t,...r}=o;n={...n,...r,...t}}return n};function o(o){const{props:a}=e,s=Nl(e.parent)||{},l=[],c=new Set;let u={},d=1/0;for(let t=0;t<$l;t++){const h=Ml[t],f=n[h],p=void 0!==a[h]?a[h]:s[h],g=Gr(p),m=h===o?f.isActive:null;!1===m&&(d=t);let v=p===s[h]&&p!==a[h]&&g;if(v&&r&&e.manuallyAnimateOnMount&&(v=!1),f.protectedKeys={...u},!f.isActive&&null===m||!p&&!f.prevProp||Kr(p)||"boolean"==typeof p)continue;const y=Ll(f.prevProp,p);let b=y||h===o&&f.isActive&&!v&&g||t>d&&g,w=!1;const x=Array.isArray(p)?p:[p];let k=x.reduce(i(h),{});!1===m&&(k={});const{prevResolvedValues:S={}}=f,T={...S,...k},E=t=>{b=!0,c.has(t)&&(w=!0,c.delete(t)),f.needsAnimating[t]=!0;const n=e.getValue(t);n&&(n.liveStyle=!1)};for(const e in T){const t=k[e],n=S[e];if(u.hasOwnProperty(e))continue;let r=!1;r=yi(t)&&yi(n)?!wo(t,n):t!==n,r?null!=t?E(e):c.add(e):void 0!==t&&c.has(e)?E(e):f.protectedKeys[e]=!0}f.prevProp=p,f.prevResolvedValues=k,f.isActive&&(u={...u,...k}),r&&e.blockInitialAnimation&&(b=!1);b&&(!(v&&y)||w)&&l.push(...x.map(e=>({animation:e,options:{type:h}})))}if(c.size){const t={};c.forEach(n=>{const r=e.getBaseTarget(n),i=e.getValue(n);i&&(i.liveStyle=!0),t[n]=null!=r?r:null}),l.push({animation:t})}let h=Boolean(l.length);return!r||!1!==a.initial&&a.initial!==a.animate||e.manuallyAnimateOnMount||(h=!1),r=!1,h?t(l):Promise.resolve()}return{animateChanges:o,setActive:function(t,r){var i;if(n[t].isActive===r)return Promise.resolve();null===(i=e.variantChildren)||void 0===i||i.forEach(e=>{var n;return null===(n=e.animationState)||void 0===n?void 0:n.setActive(t,r)}),n[t].isActive=r;const a=o(t);for(const e in n)n[e].protectedKeys={};return a},setAnimateFunction:function(n){t=n(e)},getState:()=>n,reset:()=>{n=Fl(),r=!0}}}function Ll(e,t){return"string"==typeof t?t!==e:!!Array.isArray(t)&&!wo(t,e)}function Hl(e=!1){return{isActive:e,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function Fl(){return{animate:Hl(!0),whileInView:Hl(),whileHover:Hl(),whileTap:Hl(),whileDrag:Hl(),whileFocus:Hl(),exit:Hl()}}class Ul{constructor(e){this.isMounted=!1,this.node=e}update(){}}let zl=0;const ql={animation:{Feature:class extends Ul{constructor(e){super(e),e.animationState||(e.animationState=jl(e))}updateAnimationControlsSubscription(){const{animate:e}=this.node.getProps();Kr(e)&&(this.unmountControls=e.subscribe(this.node))}mount(){this.updateAnimationControlsSubscription()}update(){const{animate:e}=this.node.getProps(),{animate:t}=this.node.prevProps||{};e!==t&&this.updateAnimationControlsSubscription()}unmount(){var e;this.node.animationState.reset(),null===(e=this.unmountControls)||void 0===e||e.call(this)}}},exit:{Feature:class extends Ul{constructor(){super(...arguments),this.id=zl++}update(){if(!this.node.presenceContext)return;const{isPresent:e,onExitComplete:t}=this.node.presenceContext,{isPresent:n}=this.node.prevPresenceContext||{};if(!this.node.animationState||e===n)return;const r=this.node.animationState.setActive("exit",!e);t&&!e&&r.then(()=>t(this.id))}mount(){const{register:e}=this.node.presenceContext||{};e&&(this.unmount=e(this.id))}unmount(){}}}};function Vl(e,t,n,r={passive:!0}){return e.addEventListener(t,n,r),()=>e.removeEventListener(t,n)}function Bl(e){return{point:{x:e.pageX,y:e.pageY}}}function Wl(e,t,n,r){return Vl(e,t,(e=>t=>Vo(t)&&e(t,Bl(t)))(n),r)}const Yl=(e,t)=>Math.abs(e-t);class Gl{constructor(e,t,{transformPagePoint:n,contextWindow:r,dragSnapToOrigin:i=!1}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.updatePoint=()=>{if(!this.lastMoveEvent||!this.lastMoveEventInfo)return;const e=Xl(this.lastMoveEventInfo,this.history),t=null!==this.startEvent,n=function(e,t){const n=Yl(e.x,t.x),r=Yl(e.y,t.y);return Math.sqrt(n**2+r**2)}(e.offset,{x:0,y:0})>=3;if(!t&&!n)return;const{point:r}=e,{timestamp:i}=Mr;this.history.push({...r,timestamp:i});const{onStart:o,onMove:a}=this.handlers;t||(o&&o(this.lastMoveEvent,e),this.startEvent=this.lastMoveEvent),a&&a(this.lastMoveEvent,e)},this.handlePointerMove=(e,t)=>{this.lastMoveEvent=e,this.lastMoveEventInfo=Kl(t,this.transformPagePoint),Ar.update(this.updatePoint,!0)},this.handlePointerUp=(e,t)=>{this.end();const{onEnd:n,onSessionEnd:r,resumeAnimation:i}=this.handlers;if(this.dragSnapToOrigin&&i&&i(),!this.lastMoveEvent||!this.lastMoveEventInfo)return;const o=Xl("pointercancel"===e.type?this.lastMoveEventInfo:Kl(t,this.transformPagePoint),this.history);this.startEvent&&n&&n(e,o),r&&r(e,o)},!Vo(e))return;this.dragSnapToOrigin=i,this.handlers=t,this.transformPagePoint=n,this.contextWindow=r||window;const o=Kl(Bl(e),this.transformPagePoint),{point:a}=o,{timestamp:s}=Mr;this.history=[{...a,timestamp:s}];const{onSessionStart:l}=t;l&&l(e,Xl(o,this.history)),this.removeListeners=Ps(Wl(this.contextWindow,"pointermove",this.handlePointerMove),Wl(this.contextWindow,"pointerup",this.handlePointerUp),Wl(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(e){this.handlers=e}end(){this.removeListeners&&this.removeListeners(),Nr(this.updatePoint)}}function Kl(e,t){return t?{point:t(e.point)}:e}function Ql(e,t){return{x:e.x-t.x,y:e.y-t.y}}function Xl({point:e},t){return{point:e,delta:Ql(e,Jl(t)),offset:Ql(e,Zl(t)),velocity:ec(t,.1)}}function Zl(e){return e[0]}function Jl(e){return e[e.length-1]}function ec(e,t){if(e.length<2)return{x:0,y:0};let n=e.length-1,r=null;const i=Jl(e);for(;n>=0&&(r=e[n],!(i.timestamp-r.timestamp>Rr(t)));)n--;if(!r)return{x:0,y:0};const o=Pr(i.timestamp-r.timestamp);if(0===o)return{x:0,y:0};const a={x:(i.x-r.x)/o,y:(i.y-r.y)/o};return a.x===1/0&&(a.x=0),a.y===1/0&&(a.y=0),a}function tc(e){return e.max-e.min}function nc(e,t,n,r=.5){e.origin=r,e.originPoint=ws(t.min,t.max,e.origin),e.scale=tc(n)/tc(t),e.translate=ws(n.min,n.max,e.origin)-e.originPoint,(e.scale>=.9999&&e.scale<=1.0001||isNaN(e.scale))&&(e.scale=1),(e.translate>=-.01&&e.translate<=.01||isNaN(e.translate))&&(e.translate=0)}function rc(e,t,n,r){nc(e.x,t.x,n.x,r?r.originX:void 0),nc(e.y,t.y,n.y,r?r.originY:void 0)}function ic(e,t,n){e.min=n.min+t.min,e.max=e.min+tc(t)}function oc(e,t,n){e.min=t.min-n.min,e.max=e.min+tc(t)}function ac(e,t,n){oc(e.x,t.x,n.x),oc(e.y,t.y,n.y)}function sc(e,t,n){return{min:void 0!==t?e.min+t:void 0,max:void 0!==n?e.max+n-(e.max-e.min):void 0}}function lc(e,t){let n=t.min-e.min,r=t.max-e.max;return t.max-t.min({x:{min:0,max:0},y:{min:0,max:0}});function fc(e){return[e("x"),e("y")]}function pc({top:e,left:t,right:n,bottom:r}){return{x:{min:t,max:n},y:{min:e,max:r}}}function gc(e){return void 0===e||1===e}function mc({scale:e,scaleX:t,scaleY:n}){return!gc(e)||!gc(t)||!gc(n)}function vc(e){return mc(e)||yc(e)||e.z||e.rotate||e.rotateX||e.rotateY||e.skewX||e.skewY}function yc(e){return bc(e.x)||bc(e.y)}function bc(e){return e&&"0%"!==e}function wc(e,t,n){return n+t*(e-n)}function xc(e,t,n,r,i){return void 0!==i&&(e=wc(e,i,r)),wc(e,n,r)+t}function kc(e,t=0,n=1,r,i){e.min=xc(e.min,t,n,r,i),e.max=xc(e.max,t,n,r,i)}function Sc(e,{x:t,y:n}){kc(e.x,t.translate,t.scale,t.originPoint),kc(e.y,n.translate,n.scale,n.originPoint)}const Tc=.999999999999,Ec=1.0000000000001;function Cc(e,t){e.min=e.min+t,e.max=e.max+t}function Rc(e,t,n,r,i=.5){kc(e,t,n,ws(e.min,e.max,i),r)}function Pc(e,t){Rc(e.x,t.x,t.scaleX,t.scale,t.originX),Rc(e.y,t.y,t.scaleY,t.scale,t.originY)}function _c(e,t){return pc(function(e,t){if(!t)return e;const n=t({x:e.left,y:e.top}),r=t({x:e.right,y:e.bottom});return{top:n.y,left:n.x,bottom:r.y,right:r.x}}(e.getBoundingClientRect(),t))}const Dc=({current:e})=>e?e.ownerDocument.defaultView:null,Ic=new WeakMap;class Ac{constructor(e){this.openDragLock=null,this.isDragging=!1,this.currentDirection=null,this.originPoint={x:0,y:0},this.constraints=!1,this.hasMutatedConstraints=!1,this.elastic={x:{min:0,max:0},y:{min:0,max:0}},this.visualElement=e}start(e,{snapToCursor:t=!1}={}){const{presenceContext:n}=this.visualElement;if(n&&!1===n.isPresent)return;const{dragSnapToOrigin:r}=this.getProps();this.panSession=new Gl(e,{onSessionStart:e=>{const{dragSnapToOrigin:n}=this.getProps();n?this.pauseAnimation():this.stopAnimation(),t&&this.snapToCursor(Bl(e).point)},onStart:(e,t)=>{const{drag:n,dragPropagation:r,onDragStart:i}=this.getProps();if(n&&!r&&(this.openDragLock&&this.openDragLock(),this.openDragLock="x"===(o=n)||"y"===o?Ho[o]?null:(Ho[o]=!0,()=>{Ho[o]=!1}):Ho.x||Ho.y?null:(Ho.x=Ho.y=!0,()=>{Ho.x=Ho.y=!1}),!this.openDragLock))return;var o;this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),fc(e=>{let t=this.getAxisMotionValue(e).get()||0;if(Li.test(t)){const{projection:n}=this.visualElement;if(n&&n.layout){const r=n.layout.layoutBox[e];if(r){t=tc(r)*(parseFloat(t)/100)}}}this.originPoint[e]=t}),i&&Ar.postRender(()=>i(e,t)),ca(this.visualElement,"transform");const{animationState:a}=this.visualElement;a&&a.setActive("whileDrag",!0)},onMove:(e,t)=>{const{dragPropagation:n,dragDirectionLock:r,onDirectionLock:i,onDrag:o}=this.getProps();if(!n&&!this.openDragLock)return;const{offset:a}=t;if(r&&null===this.currentDirection)return this.currentDirection=function(e,t=10){let n=null;Math.abs(e.y)>t?n="y":Math.abs(e.x)>t&&(n="x");return n}(a),void(null!==this.currentDirection&&i&&i(this.currentDirection));this.updateAxis("x",t.point,a),this.updateAxis("y",t.point,a),this.visualElement.render(),o&&o(e,t)},onSessionEnd:(e,t)=>this.stop(e,t),resumeAnimation:()=>fc(e=>{var t;return"paused"===this.getAnimationState(e)&&(null===(t=this.getAxisMotionValue(e).animation)||void 0===t?void 0:t.play())})},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:r,contextWindow:Dc(this.visualElement)})}stop(e,t){const n=this.isDragging;if(this.cancel(),!n)return;const{velocity:r}=t;this.startAnimation(r);const{onDragEnd:i}=this.getProps();i&&Ar.postRender(()=>i(e,t))}cancel(){this.isDragging=!1;const{projection:e,animationState:t}=this.visualElement;e&&(e.isAnimationBlocked=!1),this.panSession&&this.panSession.end(),this.panSession=void 0;const{dragPropagation:n}=this.getProps();!n&&this.openDragLock&&(this.openDragLock(),this.openDragLock=null),t&&t.setActive("whileDrag",!1)}updateAxis(e,t,n){const{drag:r}=this.getProps();if(!n||!Nc(e,r,this.currentDirection))return;const i=this.getAxisMotionValue(e);let o=this.originPoint[e]+n[e];this.constraints&&this.constraints[e]&&(o=function(e,{min:t,max:n},r){return void 0!==t&&en&&(e=r?ws(n,e,r.max):Math.min(e,n)),e}(o,this.constraints[e],this.elastic[e])),i.set(o)}resolveConstraints(){var e;const{dragConstraints:t,dragElastic:n}=this.getProps(),r=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):null===(e=this.visualElement.projection)||void 0===e?void 0:e.layout,i=this.constraints;t&&ri(t)?this.constraints||(this.constraints=this.resolveRefConstraints()):this.constraints=!(!t||!r)&&function(e,{top:t,left:n,bottom:r,right:i}){return{x:sc(e.x,n,i),y:sc(e.y,t,r)}}(r.layoutBox,t),this.elastic=function(e=cc){return!1===e?e=0:!0===e&&(e=cc),{x:uc(e,"left","right"),y:uc(e,"top","bottom")}}(n),i!==this.constraints&&r&&this.constraints&&!this.hasMutatedConstraints&&fc(e=>{!1!==this.constraints&&this.getAxisMotionValue(e)&&(this.constraints[e]=function(e,t){const n={};return void 0!==t.min&&(n.min=t.min-e.min),void 0!==t.max&&(n.max=t.max-e.min),n}(r.layoutBox[e],this.constraints[e]))})}resolveRefConstraints(){const{dragConstraints:e,onMeasureDragConstraints:t}=this.getProps();if(!e||!ri(e))return!1;const n=e.current;Tr(null!==n,"If `dragConstraints` is set as a React ref, that ref must be passed to another component's `ref` prop.");const{projection:r}=this.visualElement;if(!r||!r.layout)return!1;const i=function(e,t,n){const r=_c(e,n),{scroll:i}=t;return i&&(Cc(r.x,i.offset.x),Cc(r.y,i.offset.y)),r}(n,r.root,this.visualElement.getTransformPagePoint());let o=function(e,t){return{x:lc(e.x,t.x),y:lc(e.y,t.y)}}(r.layout.layoutBox,i);if(t){const e=t(function({x:e,y:t}){return{top:t.min,right:e.max,bottom:t.max,left:e.min}}(o));this.hasMutatedConstraints=!!e,e&&(o=pc(e))}return o}startAnimation(e){const{drag:t,dragMomentum:n,dragElastic:r,dragTransition:i,dragSnapToOrigin:o,onDragTransitionEnd:a}=this.getProps(),s=this.constraints||{},l=fc(a=>{if(!Nc(a,t,this.currentDirection))return;let l=s&&s[a]||{};o&&(l={min:0,max:0});const c=r?200:1e6,u=r?40:1e7,d={type:"inertia",velocity:n?e[a]:0,bounceStiffness:c,bounceDamping:u,timeConstant:750,restDelta:1,restSpeed:10,...i,...l};return this.startAxisValueAnimation(a,d)});return Promise.all(l).then(a)}startAxisValueAnimation(e,t){const n=this.getAxisMotionValue(e);return ca(this.visualElement,e),n.start(Rl(e,n,0,t,this.visualElement,!1))}stopAnimation(){fc(e=>this.getAxisMotionValue(e).stop())}pauseAnimation(){fc(e=>{var t;return null===(t=this.getAxisMotionValue(e).animation)||void 0===t?void 0:t.pause()})}getAnimationState(e){var t;return null===(t=this.getAxisMotionValue(e).animation)||void 0===t?void 0:t.state}getAxisMotionValue(e){const t=`_drag${e.toUpperCase()}`,n=this.visualElement.getProps(),r=n[t];return r||this.visualElement.getValue(e,(n.initial?n.initial[e]:void 0)||0)}snapToCursor(e){fc(t=>{const{drag:n}=this.getProps();if(!Nc(t,n,this.currentDirection))return;const{projection:r}=this.visualElement,i=this.getAxisMotionValue(t);if(r&&r.layout){const{min:n,max:o}=r.layout.layoutBox[t];i.set(e[t]-ws(n,o,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:e,dragConstraints:t}=this.getProps(),{projection:n}=this.visualElement;if(!ri(t)||!n||!this.constraints)return;this.stopAnimation();const r={x:0,y:0};fc(e=>{const t=this.getAxisMotionValue(e);if(t&&!1!==this.constraints){const n=t.get();r[e]=function(e,t){let n=.5;const r=tc(e),i=tc(t);return i>r?n=Cr(t.min,t.max-r,e.min):r>i&&(n=Cr(e.min,e.max-i,t.min)),Ai(0,1,n)}({min:n,max:n},this.constraints[e])}});const{transformTemplate:i}=this.visualElement.getProps();this.visualElement.current.style.transform=i?i({},""):"none",n.root&&n.root.updateScroll(),n.updateLayout(),this.resolveConstraints(),fc(t=>{if(!Nc(t,e,null))return;const n=this.getAxisMotionValue(t),{min:i,max:o}=this.constraints[t];n.set(ws(i,o,r[t]))})}addListeners(){if(!this.visualElement.current)return;Ic.set(this.visualElement,this);const e=Wl(this.visualElement.current,"pointerdown",e=>{const{drag:t,dragListener:n=!0}=this.getProps();t&&n&&this.start(e)}),t=()=>{const{dragConstraints:e}=this.getProps();ri(e)&&e.current&&(this.constraints=this.resolveRefConstraints())},{projection:n}=this.visualElement,r=n.addEventListener("measure",t);n&&!n.layout&&(n.root&&n.root.updateScroll(),n.updateLayout()),Ar.read(t);const i=Vl(window,"resize",()=>this.scalePositionWithinConstraints()),o=n.addEventListener("didUpdate",({delta:e,hasLayoutChanged:t})=>{this.isDragging&&t&&(fc(t=>{const n=this.getAxisMotionValue(t);n&&(this.originPoint[t]+=e[t].translate,n.set(n.get()+e[t].translate))}),this.visualElement.render())});return()=>{i(),e(),r(),o&&o()}}getProps(){const e=this.visualElement.getProps(),{drag:t=!1,dragDirectionLock:n=!1,dragPropagation:r=!1,dragConstraints:i=!1,dragElastic:o=cc,dragMomentum:a=!0}=e;return{...e,drag:t,dragDirectionLock:n,dragPropagation:r,dragConstraints:i,dragElastic:o,dragMomentum:a}}}function Nc(e,t,n){return!(!0!==t&&t!==e||null!==n&&n!==e)}const Mc=e=>(t,n)=>{e&&Ar.postRender(()=>e(t,n))};const $c={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function Oc(e,t){return t.max===t.min?0:e/(t.max-t.min)*100}const jc={correct:(e,t)=>{if(!t.target)return e;if("string"==typeof e){if(!Hi.test(e))return e;e=parseFloat(e)}return`${Oc(e,t.target.x)}% ${Oc(e,t.target.y)}%`}},Lc={correct:(e,{treeScale:t,projectionDelta:n})=>{const r=e,i=za.parse(e);if(i.length>5)return r;const o=za.createTransformer(e),a="number"!=typeof i[0]?1:0,s=n.x.scale*t.x,l=n.y.scale*t.y;i[0+a]/=s,i[1+a]/=l;const c=ws(s,l,.5);return"number"==typeof i[2+a]&&(i[2+a]/=c),"number"==typeof i[3+a]&&(i[3+a]/=c),o(i)}};class Hc extends y.Component{componentDidMount(){const{visualElement:e,layoutGroup:t,switchLayoutGroup:n,layoutId:r}=this.props,{projection:i}=e;var o;o=Uc,Object.assign(ao,o),i&&(t.group&&t.group.add(i),n&&n.register&&r&&n.register(i),i.root.didUpdate(),i.addEventListener("animationComplete",()=>{this.safeToRemove()}),i.setOptions({...i.options,onExitComplete:()=>this.safeToRemove()})),$c.hasEverUpdated=!0}getSnapshotBeforeUpdate(e){const{layoutDependency:t,visualElement:n,drag:r,isPresent:i}=this.props,o=n.projection;return o?(o.isPresent=i,r||e.layoutDependency!==t||void 0===t?o.willUpdate():this.safeToRemove(),e.isPresent!==i&&(i?o.promote():o.relegate()||Ar.postRender(()=>{const e=o.getStack();e&&e.members.length||this.safeToRemove()})),null):null}componentDidUpdate(){const{projection:e}=this.props.visualElement;e&&(e.root.didUpdate(),si.postRender(()=>{!e.currentAnimation&&e.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:e,layoutGroup:t,switchLayoutGroup:n}=this.props,{projection:r}=e;r&&(r.scheduleCheckAfterUnmount(),t&&t.group&&t.group.remove(r),n&&n.deregister&&n.deregister(r))}safeToRemove(){const{safeToRemove:e}=this.props;e&&e()}render(){return null}}function Fc(e){const[t,n]=gr(),r=y.useContext(sr);return v.jsx(Hc,{...e,layoutGroup:r,switchLayoutGroup:y.useContext(li),isPresent:t,safeToRemove:n})}const Uc={borderRadius:{...jc,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:jc,borderTopRightRadius:jc,borderBottomLeftRadius:jc,borderBottomRightRadius:jc,boxShadow:Lc};const zc=(e,t)=>e.depth-t.depth;class qc{constructor(){this.children=[],this.isDirty=!1}add(e){ta(this.children,e),this.isDirty=!0}remove(e){na(this.children,e),this.isDirty=!0}forEach(e){this.isDirty&&this.children.sort(zc),this.isDirty=!1,this.children.forEach(e)}}const Vc=["TopLeft","TopRight","BottomLeft","BottomRight"],Bc=Vc.length,Wc=e=>"string"==typeof e?parseFloat(e):e,Yc=e=>"number"==typeof e||Hi.test(e);function Gc(e,t){return void 0!==e[t]?e[t]:e.borderRadius}const Kc=Xc(0,.5,wa),Qc=Xc(.5,.95,kr);function Xc(e,t,n){return r=>rt?1:n(Cr(e,t,r))}function Zc(e,t){e.min=t.min,e.max=t.max}function Jc(e,t){Zc(e.x,t.x),Zc(e.y,t.y)}function eu(e,t){e.translate=t.translate,e.scale=t.scale,e.originPoint=t.originPoint,e.origin=t.origin}function tu(e,t,n,r,i){return e=wc(e-=t,1/n,r),void 0!==i&&(e=wc(e,1/i,r)),e}function nu(e,t,[n,r,i],o,a){!function(e,t=0,n=1,r=.5,i,o=e,a=e){Li.test(t)&&(t=parseFloat(t),t=ws(a.min,a.max,t/100)-a.min);if("number"!=typeof t)return;let s=ws(o.min,o.max,r);e===o&&(s-=t),e.min=tu(e.min,t,n,s,i),e.max=tu(e.max,t,n,s,i)}(e,t[n],t[r],t[i],t.scale,o,a)}const ru=["x","scaleX","originX"],iu=["y","scaleY","originY"];function ou(e,t,n,r){nu(e.x,t,ru,n?n.x:void 0,r?r.x:void 0),nu(e.y,t,iu,n?n.y:void 0,r?r.y:void 0)}function au(e){return 0===e.translate&&1===e.scale}function su(e){return au(e.x)&&au(e.y)}function lu(e,t){return e.min===t.min&&e.max===t.max}function cu(e,t){return Math.round(e.min)===Math.round(t.min)&&Math.round(e.max)===Math.round(t.max)}function uu(e,t){return cu(e.x,t.x)&&cu(e.y,t.y)}function du(e){return tc(e.x)/tc(e.y)}function hu(e,t){return e.translate===t.translate&&e.scale===t.scale&&e.originPoint===t.originPoint}class fu{constructor(){this.members=[]}add(e){ta(this.members,e),e.scheduleRender()}remove(e){if(na(this.members,e),e===this.prevLead&&(this.prevLead=void 0),e===this.lead){const e=this.members[this.members.length-1];e&&this.promote(e)}}relegate(e){const t=this.members.findIndex(t=>e===t);if(0===t)return!1;let n;for(let r=t;r>=0;r--){const e=this.members[r];if(!1!==e.isPresent){n=e;break}}return!!n&&(this.promote(n),!0)}promote(e,t){const n=this.lead;if(e!==n&&(this.prevLead=n,this.lead=e,e.show(),n)){n.instance&&n.scheduleRender(),e.scheduleRender(),e.resumeFrom=n,t&&(e.resumeFrom.preserveOpacity=!0),n.snapshot&&(e.snapshot=n.snapshot,e.snapshot.latestValues=n.animationValues||n.latestValues),e.root&&e.root.isUpdating&&(e.isLayoutDirty=!0);const{crossfade:r}=e.options;!1===r&&n.hide()}}exitAnimationComplete(){this.members.forEach(e=>{const{options:t,resumingFrom:n}=e;t.onExitComplete&&t.onExitComplete(),n&&n.options.onExitComplete&&n.options.onExitComplete()})}scheduleRender(){this.members.forEach(e=>{e.instance&&e.scheduleRender(!1)})}removeLeadSnapshot(){this.lead&&this.lead.snapshot&&(this.lead.snapshot=void 0)}}const pu={type:"projectionFrame",totalNodes:0,resolvedTargetDeltas:0,recalculatedProjection:0},gu="undefined"!=typeof window&&void 0!==window.MotionDebug,mu=["","X","Y","Z"],vu={visibility:"hidden"};let yu=0;function bu(e,t,n,r){const{latestValues:i}=t;i[e]&&(n[e]=i[e],t.setStaticValue(e,0),r&&(r[e]=0))}function wu(e){if(e.hasCheckedOptimisedAppear=!0,e.root===e)return;const{visualElement:t}=e.options;if(!t)return;const n=ua(t);if(window.MotionHasOptimisedAnimation(n,"transform")){const{layout:t,layoutId:r}=e.options;window.MotionCancelOptimisedAnimation(n,"transform",Ar,!(t||r))}const{parent:r}=e;r&&!r.hasCheckedOptimisedAppear&&wu(r)}function xu({attachResizeListener:e,defaultParent:t,measureScroll:n,checkIsScrollRoot:r,resetTransform:i}){return class{constructor(e={},n=(null==t?void 0:t())){this.id=yu++,this.animationId=0,this.children=new Set,this.options={},this.isTreeAnimating=!1,this.isAnimationBlocked=!1,this.isLayoutDirty=!1,this.isProjectionDirty=!1,this.isSharedProjectionDirty=!1,this.isTransformDirty=!1,this.updateManuallyBlocked=!1,this.updateBlockedByResize=!1,this.isUpdating=!1,this.isSVG=!1,this.needsReset=!1,this.shouldResetTransform=!1,this.hasCheckedOptimisedAppear=!1,this.treeScale={x:1,y:1},this.eventHandlers=new Map,this.hasTreeAnimated=!1,this.updateScheduled=!1,this.scheduleUpdate=()=>this.update(),this.projectionUpdateScheduled=!1,this.checkUpdateFailed=()=>{this.isUpdating&&(this.isUpdating=!1,this.clearAllSnapshots())},this.updateProjection=()=>{this.projectionUpdateScheduled=!1,gu&&(pu.totalNodes=pu.resolvedTargetDeltas=pu.recalculatedProjection=0),this.nodes.forEach(Tu),this.nodes.forEach(Iu),this.nodes.forEach(Au),this.nodes.forEach(Eu),gu&&window.MotionDebug.record(pu)},this.resolvedRelativeTargetAt=0,this.hasProjected=!1,this.isVisible=!0,this.animationProgress=0,this.sharedNodes=new Map,this.latestValues=e,this.root=n?n.root||n:this,this.path=n?[...n.path,n]:[],this.parent=n,this.depth=n?n.depth+1:0;for(let t=0;tthis.root.updateBlockedByResize=!1;e(t,()=>{this.root.updateBlockedByResize=!0,n&&n(),n=function(e,t){const n=ea.now(),r=({timestamp:i})=>{const o=i-n;o>=t&&(Nr(r),e(o-t))};return Ar.read(r,!0),()=>Nr(r)}(r,250),$c.hasAnimatedSinceResize&&($c.hasAnimatedSinceResize=!1,this.nodes.forEach(Du))})}i&&this.root.registerSharedNode(i,this),!1!==this.options.animate&&a&&(i||o)&&this.addEventListener("didUpdate",({delta:e,hasLayoutChanged:t,hasRelativeTargetChanged:n,layout:r})=>{if(this.isTreeAnimationBlocked())return this.target=void 0,void(this.relativeTarget=void 0);const i=this.options.transition||a.getDefaultTransition()||Lu,{onLayoutAnimationStart:o,onLayoutAnimationComplete:s}=a.getProps(),l=!this.targetLayout||!uu(this.targetLayout,r)||n,c=!t&&n;if(this.options.layoutRoot||this.resumeFrom&&this.resumeFrom.instance||c||t&&(l||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0),this.setAnimationOrigin(e,c);const t={...Eo(i,"layout"),onPlay:o,onComplete:s};(a.shouldReduceMotion||this.options.layoutRoot)&&(t.delay=0,t.type=!1),this.startAnimation(t)}else t||Du(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=r})}unmount(){this.options.layoutId&&this.willUpdate(),this.root.nodes.remove(this);const e=this.getStack();e&&e.remove(this),this.parent&&this.parent.children.delete(this),this.instance=void 0,Nr(this.updateProjection)}blockUpdate(){this.updateManuallyBlocked=!0}unblockUpdate(){this.updateManuallyBlocked=!1}isUpdateBlocked(){return this.updateManuallyBlocked||this.updateBlockedByResize}isTreeAnimationBlocked(){return this.isAnimationBlocked||this.parent&&this.parent.isTreeAnimationBlocked()||!1}startUpdate(){this.isUpdateBlocked()||(this.isUpdating=!0,this.nodes&&this.nodes.forEach(Nu),this.animationId++)}getTransformTemplate(){const{visualElement:e}=this.options;return e&&e.getProps().transformTemplate}willUpdate(e=!0){if(this.root.hasTreeAnimated=!0,this.root.isUpdateBlocked())return void(this.options.onExitComplete&&this.options.onExitComplete());if(window.MotionCancelOptimisedAnimation&&!this.hasCheckedOptimisedAppear&&wu(this),!this.root.isUpdating&&this.root.startUpdate(),this.isLayoutDirty)return;this.isLayoutDirty=!0;for(let i=0;i{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){!this.snapshot&&this.instance&&(this.snapshot=this.measure())}updateLayout(){if(!this.instance)return;if(this.updateScroll(),!(this.options.alwaysMeasureLayout&&this.isLead()||this.isLayoutDirty))return;if(this.resumeFrom&&!this.resumeFrom.instance)for(let n=0;nTc&&(t.x=1),t.yTc&&(t.y=1)}(this.layoutCorrected,this.treeScale,this.path,n),!t.layout||t.target||1===this.treeScale.x&&1===this.treeScale.y||(t.target=t.layout.layoutBox,t.targetWithTransforms={x:{min:0,max:0},y:{min:0,max:0}});const{target:l}=t;l?(this.projectionDelta&&this.prevProjectionDelta?(eu(this.prevProjectionDelta.x,this.projectionDelta.x),eu(this.prevProjectionDelta.y,this.projectionDelta.y)):this.createProjectionDeltas(),rc(this.projectionDelta,this.layoutCorrected,l,this.latestValues),this.treeScale.x===a&&this.treeScale.y===s&&hu(this.projectionDelta.x,this.prevProjectionDelta.x)&&hu(this.projectionDelta.y,this.prevProjectionDelta.y)||(this.hasProjected=!0,this.scheduleRender(),this.notifyListeners("projectionUpdate",l)),gu&&pu.recalculatedProjection++):this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender())}hide(){this.isVisible=!1}show(){this.isVisible=!0}scheduleRender(e=!0){var t;if(null===(t=this.options.visualElement)||void 0===t||t.scheduleRender(),e){const e=this.getStack();e&&e.scheduleRender()}this.resumingFrom&&!this.resumingFrom.instance&&(this.resumingFrom=void 0)}createProjectionDeltas(){this.prevProjectionDelta={x:{translate:0,scale:1,origin:0,originPoint:0},y:{translate:0,scale:1,origin:0,originPoint:0}},this.projectionDelta={x:{translate:0,scale:1,origin:0,originPoint:0},y:{translate:0,scale:1,origin:0,originPoint:0}},this.projectionDeltaWithTransform={x:{translate:0,scale:1,origin:0,originPoint:0},y:{translate:0,scale:1,origin:0,originPoint:0}}}setAnimationOrigin(e,t=!1){const n=this.snapshot,r=n?n.latestValues:{},i={...this.latestValues},o={x:{translate:0,scale:1,origin:0,originPoint:0},y:{translate:0,scale:1,origin:0,originPoint:0}};this.relativeParent&&this.relativeParent.options.layoutRoot||(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!t;const a={x:{min:0,max:0},y:{min:0,max:0}},s=(n?n.source:void 0)!==(this.layout?this.layout.source:void 0),l=this.getStack(),c=!l||l.members.length<=1,u=Boolean(s&&!c&&!0===this.options.crossfade&&!this.path.some(ju));let d;this.animationProgress=0,this.mixTargetDelta=t=>{const n=t/1e3;var l,h,f,p,g,m;$u(o.x,e.x,n),$u(o.y,e.y,n),this.setTargetDelta(o),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(ac(a,this.layout.layoutBox,this.relativeParent.layout.layoutBox),f=this.relativeTarget,p=this.relativeTargetOrigin,g=a,m=n,Ou(f.x,p.x,g.x,m),Ou(f.y,p.y,g.y,m),d&&(l=this.relativeTarget,h=d,lu(l.x,h.x)&&lu(l.y,h.y))&&(this.isProjectionDirty=!1),d||(d={x:{min:0,max:0},y:{min:0,max:0}}),Jc(d,this.relativeTarget)),s&&(this.animationValues=i,function(e,t,n,r,i,o){i?(e.opacity=ws(0,void 0!==n.opacity?n.opacity:1,Kc(r)),e.opacityExit=ws(void 0!==t.opacity?t.opacity:1,0,Qc(r))):o&&(e.opacity=ws(void 0!==t.opacity?t.opacity:1,void 0!==n.opacity?n.opacity:1,r));for(let a=0;a{$c.hasAnimatedSinceResize=!0,this.currentAnimation=function(e,t,n){const r=wi(e)?e:sa(e);return r.start(Rl("",r,t,n)),r.animation}(0,1e3,{...e,onUpdate:t=>{this.mixTargetDelta(t),e.onUpdate&&e.onUpdate(t)},onComplete:()=>{e.onComplete&&e.onComplete(),this.completeAnimation()}}),this.resumingFrom&&(this.resumingFrom.currentAnimation=this.currentAnimation),this.pendingAnimation=void 0})}completeAnimation(){this.resumingFrom&&(this.resumingFrom.currentAnimation=void 0,this.resumingFrom.preserveOpacity=void 0);const e=this.getStack();e&&e.exitAnimationComplete(),this.resumingFrom=this.currentAnimation=this.animationValues=void 0,this.notifyListeners("animationComplete")}finishAnimation(){this.currentAnimation&&(this.mixTargetDelta&&this.mixTargetDelta(1e3),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const e=this.getLead();let{targetWithTransforms:t,target:n,layout:r,latestValues:i}=e;if(t&&n&&r){if(this!==e&&this.layout&&r&&zu(this.options.animationType,this.layout.layoutBox,r.layoutBox)){n=this.target||{x:{min:0,max:0},y:{min:0,max:0}};const t=tc(this.layout.layoutBox.x);n.x.min=e.target.x.min,n.x.max=n.x.min+t;const r=tc(this.layout.layoutBox.y);n.y.min=e.target.y.min,n.y.max=n.y.min+r}Jc(t,n),Pc(t,i),rc(this.projectionDeltaWithTransform,this.layoutCorrected,t,i)}}registerSharedNode(e,t){this.sharedNodes.has(e)||this.sharedNodes.set(e,new fu);this.sharedNodes.get(e).add(t);const n=t.options.initialPromotionConfig;t.promote({transition:n?n.transition:void 0,preserveFollowOpacity:n&&n.shouldPreserveFollowOpacity?n.shouldPreserveFollowOpacity(t):void 0})}isLead(){const e=this.getStack();return!e||e.lead===this}getLead(){var e;const{layoutId:t}=this.options;return t&&(null===(e=this.getStack())||void 0===e?void 0:e.lead)||this}getPrevLead(){var e;const{layoutId:t}=this.options;return t?null===(e=this.getStack())||void 0===e?void 0:e.prevLead:void 0}getStack(){const{layoutId:e}=this.options;if(e)return this.root.sharedNodes.get(e)}promote({needsReset:e,transition:t,preserveFollowOpacity:n}={}){const r=this.getStack();r&&r.promote(this,n),e&&(this.projectionDelta=void 0,this.needsReset=!0),t&&this.setOptions({transition:t})}relegate(){const e=this.getStack();return!!e&&e.relegate(this)}resetSkewAndRotation(){const{visualElement:e}=this.options;if(!e)return;let t=!1;const{latestValues:n}=e;if((n.z||n.rotate||n.rotateX||n.rotateY||n.rotateZ||n.skewX||n.skewY)&&(t=!0),!t)return;const r={};n.z&&bu("z",e,r,this.animationValues);for(let i=0;i{var t;return null===(t=e.currentAnimation)||void 0===t?void 0:t.stop()}),this.root.nodes.forEach(Ru),this.root.sharedNodes.clear()}}}function ku(e){e.updateLayout()}function Su(e){var t;const n=(null===(t=e.resumeFrom)||void 0===t?void 0:t.snapshot)||e.snapshot;if(e.isLead()&&e.layout&&n&&e.hasListeners("didUpdate")){const{layoutBox:t,measuredBox:r}=e.layout,{animationType:i}=e.options,o=n.source!==e.layout.source;"size"===i?fc(e=>{const r=o?n.measuredBox[e]:n.layoutBox[e],i=tc(r);r.min=t[e].min,r.max=r.min+i}):zu(i,n.layoutBox,t)&&fc(r=>{const i=o?n.measuredBox[r]:n.layoutBox[r],a=tc(t[r]);i.max=i.min+a,e.relativeTarget&&!e.currentAnimation&&(e.isProjectionDirty=!0,e.relativeTarget[r].max=e.relativeTarget[r].min+a)});const a={x:{translate:0,scale:1,origin:0,originPoint:0},y:{translate:0,scale:1,origin:0,originPoint:0}};rc(a,t,n.layoutBox);const s={x:{translate:0,scale:1,origin:0,originPoint:0},y:{translate:0,scale:1,origin:0,originPoint:0}};o?rc(s,e.applyTransform(r,!0),n.measuredBox):rc(s,t,n.layoutBox);const l=!su(a);let c=!1;if(!e.resumeFrom){const r=e.getClosestProjectingParent();if(r&&!r.resumeFrom){const{snapshot:i,layout:o}=r;if(i&&o){const a={x:{min:0,max:0},y:{min:0,max:0}};ac(a,n.layoutBox,i.layoutBox);const s={x:{min:0,max:0},y:{min:0,max:0}};ac(s,t,o.layoutBox),uu(a,s)||(c=!0),r.options.layoutRoot&&(e.relativeTarget=s,e.relativeTargetOrigin=a,e.relativeParent=r)}}}e.notifyListeners("didUpdate",{layout:t,snapshot:n,delta:s,layoutDelta:a,hasLayoutChanged:l,hasRelativeTargetChanged:c})}else if(e.isLead()){const{onExitComplete:t}=e.options;t&&t()}e.options.transition=void 0}function Tu(e){gu&&pu.totalNodes++,e.parent&&(e.isProjecting()||(e.isProjectionDirty=e.parent.isProjectionDirty),e.isSharedProjectionDirty||(e.isSharedProjectionDirty=Boolean(e.isProjectionDirty||e.parent.isProjectionDirty||e.parent.isSharedProjectionDirty)),e.isTransformDirty||(e.isTransformDirty=e.parent.isTransformDirty))}function Eu(e){e.isProjectionDirty=e.isSharedProjectionDirty=e.isTransformDirty=!1}function Cu(e){e.clearSnapshot()}function Ru(e){e.clearMeasurements()}function Pu(e){e.isLayoutDirty=!1}function _u(e){const{visualElement:t}=e.options;t&&t.getProps().onBeforeLayoutMeasure&&t.notify("BeforeLayoutMeasure"),e.resetTransform()}function Du(e){e.finishAnimation(),e.targetDelta=e.relativeTarget=e.target=void 0,e.isProjectionDirty=!0}function Iu(e){e.resolveTargetDelta()}function Au(e){e.calcProjection()}function Nu(e){e.resetSkewAndRotation()}function Mu(e){e.removeLeadSnapshot()}function $u(e,t,n){e.translate=ws(t.translate,0,n),e.scale=ws(t.scale,1,n),e.origin=t.origin,e.originPoint=t.originPoint}function Ou(e,t,n,r){e.min=ws(t.min,n.min,r),e.max=ws(t.max,n.max,r)}function ju(e){return e.animationValues&&void 0!==e.animationValues.opacityExit}const Lu={duration:.45,ease:[.4,0,.1,1]},Hu=e=>"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(e),Fu=Hu("applewebkit/")&&!Hu("chrome/")?Math.round:kr;function Uu(e){e.min=Fu(e.min),e.max=Fu(e.max)}function zu(e,t,n){return"position"===e||"preserve-aspect"===e&&(r=du(t),i=du(n),o=.2,!(Math.abs(r-i)<=o));var r,i,o}function qu(e){var t;return e!==e.root&&(null===(t=e.scroll)||void 0===t?void 0:t.wasRoot)}const Vu=xu({attachResizeListener:(e,t)=>Vl(e,"resize",t),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),Bu={current:void 0},Wu=xu({measureScroll:e=>({x:e.scrollLeft,y:e.scrollTop}),defaultParent:()=>{if(!Bu.current){const e=new Vu({});e.mount(window),e.setOptions({layoutScroll:!0}),Bu.current=e}return Bu.current},resetTransform:(e,t)=>{e.style.transform=void 0!==t?t:"none"},checkIsScrollRoot:e=>Boolean("fixed"===window.getComputedStyle(e).position)}),Yu={pan:{Feature:class extends Ul{constructor(){super(...arguments),this.removePointerDownListener=kr}onPointerDown(e){this.session=new Gl(e,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:Dc(this.node)})}createPanHandlers(){const{onPanSessionStart:e,onPanStart:t,onPan:n,onPanEnd:r}=this.node.getProps();return{onSessionStart:Mc(e),onStart:Mc(t),onMove:n,onEnd:(e,t)=>{delete this.session,r&&Ar.postRender(()=>r(e,t))}}}mount(){this.removePointerDownListener=Wl(this.node.current,"pointerdown",e=>this.onPointerDown(e))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}}},drag:{Feature:class extends Ul{constructor(e){super(e),this.removeGroupControls=kr,this.removeListeners=kr,this.controls=new Ac(e)}mount(){const{dragControls:e}=this.node.getProps();e&&(this.removeGroupControls=e.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||kr}unmount(){this.removeGroupControls(),this.removeListeners()}},ProjectionNode:Wu,MeasureLayout:Fc}};function Gu(e,t,n){const{props:r}=e;e.animationState&&r.whileHover&&e.animationState.setActive("whileHover","Start"===n);const i=r["onHover"+n];i&&Ar.postRender(()=>i(t,Bl(t)))}function Ku(e,t,n){const{props:r}=e;e.animationState&&r.whileTap&&e.animationState.setActive("whileTap","Start"===n);const i=r["onTap"+("End"===n?"":n)];i&&Ar.postRender(()=>i(t,Bl(t)))}const Qu=new WeakMap,Xu=new WeakMap,Zu=e=>{const t=Qu.get(e.target);t&&t(e)},Ju=e=>{e.forEach(Zu)};function ed(e,t,n){const r=function({root:e,...t}){const n=e||document;Xu.has(n)||Xu.set(n,{});const r=Xu.get(n),i=JSON.stringify(t);return r[i]||(r[i]=new IntersectionObserver(Ju,{root:e,...t})),r[i]}(t);return Qu.set(e,n),r.observe(e),()=>{Qu.delete(e),r.unobserve(e)}}const td={some:0,all:1};const nd={inView:{Feature:class extends Ul{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.unmount();const{viewport:e={}}=this.node.getProps(),{root:t,margin:n,amount:r="some",once:i}=e,o={root:t?t.current:void 0,rootMargin:n,threshold:"number"==typeof r?r:td[r]};return ed(this.node.current,o,e=>{const{isIntersecting:t}=e;if(this.isInView===t)return;if(this.isInView=t,i&&!t&&this.hasEnteredView)return;t&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",t);const{onViewportEnter:n,onViewportLeave:r}=this.node.getProps(),o=t?n:r;o&&o(e)})}mount(){this.startObserver()}update(){if("undefined"==typeof IntersectionObserver)return;const{props:e,prevProps:t}=this.node;["amount","margin","root"].some(function({viewport:e={}},{viewport:t={}}={}){return n=>e[n]!==t[n]}(e,t))&&this.startObserver()}unmount(){}}},tap:{Feature:class extends Ul{mount(){const{current:e}=this.node;e&&(this.unmount=Qo(e,e=>(Ku(this.node,e,"Start"),(e,{success:t})=>Ku(this.node,e,t?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}},focus:{Feature:class extends Ul{constructor(){super(...arguments),this.isActive=!1}onFocus(){let e=!1;try{e=this.node.current.matches(":focus-visible")}catch(t){e=!0}e&&this.node.animationState&&(this.node.animationState.setActive("whileFocus",!0),this.isActive=!0)}onBlur(){this.isActive&&this.node.animationState&&(this.node.animationState.setActive("whileFocus",!1),this.isActive=!1)}mount(){this.unmount=Ps(Vl(this.node.current,"focus",()=>this.onFocus()),Vl(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}},hover:{Feature:class extends Ul{mount(){const{current:e}=this.node;e&&(this.unmount=function(e,t,n={}){const[r,i,o]=Uo(e,n),a=zo(e=>{const{target:n}=e,r=t(e);if("function"!=typeof r||!n)return;const o=zo(e=>{r(e),n.removeEventListener("pointerleave",o)});n.addEventListener("pointerleave",o,i)});return r.forEach(e=>{e.addEventListener("pointerenter",a,i)}),o}(e,e=>(Gu(this.node,e,"Start"),e=>Gu(this.node,e,"End"))))}unmount(){}}}},rd={layout:{ProjectionNode:Wu,MeasureLayout:Fc}},id={current:null},od={current:!1};const ad=[...fs,Na,za],sd=new WeakMap;var ld={};var cd={};const ud=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class dd{scrapeMotionValuesFromProps(e,t,n){return{}}constructor({parent:e,props:t,presenceContext:n,reducedMotionConfig:r,blockInitialAnimation:i,visualState:o},a={}){this.current=null,this.children=new Set,this.isVariantNode=!1,this.isControllingVariants=!1,this.shouldReduceMotion=null,this.values=new Map,this.KeyframeResolver=ls,this.features={},this.valueSubscriptions=new Map,this.prevMotionValues={},this.events={},this.propEventSubscriptions={},this.notifyUpdate=()=>this.notify("Update",this.latestValues),this.render=()=>{this.current&&(this.triggerBuild(),this.renderInstance(this.current,this.renderState,this.props.style,this.projection))},this.renderScheduledAt=0,this.scheduleRender=()=>{const e=ea.now();this.renderScheduledAtthis.bindToMotionValue(t,e)),od.current||function(){if(od.current=!0,yr)if(window.matchMedia){const e=window.matchMedia("(prefers-reduced-motion)"),t=()=>id.current=e.matches;e.addListener(t),t()}else id.current=!1}(),this.shouldReduceMotion="never"!==this.reducedMotionConfig&&("always"===this.reducedMotionConfig||id.current),"production"!==cd.NODE_ENV&&Vr(!0!==this.shouldReduceMotion,"You have Reduced Motion enabled on your device. Animations may not appear as expected."),this.parent&&this.parent.children.add(this),this.update(this.props,this.presenceContext)}unmount(){sd.delete(this.current),this.projection&&this.projection.unmount(),Nr(this.notifyUpdate),Nr(this.render),this.valueSubscriptions.forEach(e=>e()),this.valueSubscriptions.clear(),this.removeFromVariantTree&&this.removeFromVariantTree(),this.parent&&this.parent.children.delete(this);for(const e in this.events)this.events[e].clear();for(const e in this.features){const t=this.features[e];t&&(t.unmount(),t.isMounted=!1)}this.current=null}bindToMotionValue(e,t){this.valueSubscriptions.has(e)&&this.valueSubscriptions.get(e)();const n=Ei.has(e),r=t.on("change",t=>{this.latestValues[e]=t,this.props.onUpdate&&Ar.preRender(this.notifyUpdate),n&&this.projection&&(this.projection.isTransformDirty=!0)}),i=t.on("renderRequest",this.scheduleRender);let o;window.MotionCheckAppearSync&&(o=window.MotionCheckAppearSync(this,e,t)),this.valueSubscriptions.set(e,()=>{r(),i(),o&&o(),t.owner&&t.stop()})}sortNodePosition(e){return this.current&&this.sortInstanceNodePosition&&this.type===e.type?this.sortInstanceNodePosition(this.current,e.current):0}updateFeatures(){let e="animation";for(e in Lr){const t=Lr[e];if(!t)continue;const{isEnabled:n,Feature:r}=t;if(!this.features[e]&&r&&n(this.props)&&(this.features[e]=new r(this)),this.features[e]){const t=this.features[e];t.isMounted?t.update():(t.mount(),t.isMounted=!0)}}}triggerBuild(){this.build(this.renderState,this.latestValues,this.props)}measureViewportBox(){return this.current?this.measureInstanceViewportBox(this.current,this.props):{x:{min:0,max:0},y:{min:0,max:0}}}getStaticValue(e){return this.latestValues[e]}setStaticValue(e,t){this.latestValues[e]=t}update(e,t){(e.transformTemplate||this.props.transformTemplate)&&this.scheduleRender(),this.prevProps=this.props,this.props=e,this.prevPresenceContext=this.presenceContext,this.presenceContext=t;for(let n=0;nt.variantChildren.delete(e)}addValue(e,t){const n=this.values.get(e);t!==n&&(n&&this.removeValue(e),this.bindToMotionValue(e,t),this.values.set(e,t),this.latestValues[e]=t.get())}removeValue(e){this.values.delete(e);const t=this.valueSubscriptions.get(e);t&&(t(),this.valueSubscriptions.delete(e)),delete this.latestValues[e],this.removeValueFromRenderState(e,this.renderState)}hasValue(e){return this.values.has(e)}getValue(e,t){if(this.props.values&&this.props.values[e])return this.props.values[e];let n=this.values.get(e);return void 0===n&&void 0!==t&&(n=sa(null===t?void 0:t,{owner:this}),this.addValue(e,n)),n}readValue(e,t){var n;let r=void 0===this.latestValues[e]&&this.current?null!==(n=this.getBaseTargetFromProps(this.props,e))&&void 0!==n?n:this.readValueFromInstance(this.current,e,this.options):this.latestValues[e];var i;return null!=r&&("string"==typeof r&&(cs(r)||ka(r))?r=parseFloat(r):(i=r,!ad.find(hs(i))&&za.test(t)&&(r=Ka(e,t))),this.setBaseTarget(e,wi(r)?r.get():r)),wi(r)?r.get():r}setBaseTarget(e,t){this.baseTarget[e]=t}getBaseTarget(e){var t;const{initial:n}=this.props;let r;if("string"==typeof n||"object"==typeof n){const i=vi(this.props,n,null===(t=this.presenceContext)||void 0===t?void 0:t.custom);i&&(r=i[e])}if(n&&void 0!==r)return r;const i=this.getBaseTargetFromProps(this.props,e);return void 0===i||wi(i)?void 0!==this.initialValues[e]&&void 0===r?void 0:this.baseTarget[e]:i}on(e,t){return this.events[e]||(this.events[e]=new ra),this.events[e].add(t)}notify(e,...t){this.events[e]&&this.events[e].notify(...t)}}class hd extends dd{constructor(){super(...arguments),this.KeyframeResolver=gs}sortInstanceNodePosition(e,t){return 2&e.compareDocumentPosition(t)?1:-1}getBaseTargetFromProps(e,t){return e.style?e.style[t]:void 0}removeValueFromRenderState(e,{vars:t,style:n}){delete t[e],delete n[e]}handleChildMotionValue(){this.childSubscription&&(this.childSubscription(),delete this.childSubscription);const{children:e}=this.props;wi(e)&&(this.childSubscription=e.on("change",e=>{this.current&&(this.current.textContent=`${e}`)}))}}class fd extends hd{constructor(){super(...arguments),this.type="html",this.renderInstance=ro}readValueFromInstance(e,t){if(Ei.has(t)){const e=Ga(t);return e&&e.default||0}{const r=(n=e,window.getComputedStyle(n)),i=(Ri(t)?r.getPropertyValue(t):r[t])||0;return"string"==typeof i?i.trim():i}var n}measureInstanceViewportBox(e,{transformPagePoint:t}){return _c(e,t)}build(e,t,n){Ki(e,t,n.transformTemplate)}scrapeMotionValuesFromProps(e,t,n){return lo(e,t,n)}}class pd extends hd{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=hc}getBaseTargetFromProps(e,t){return e[t]}readValueFromInstance(e,t){if(Ei.has(t)){const e=Ga(t);return e&&e.default||0}return t=io.has(t)?t:oi(t),e.getAttribute(t)}scrapeMotionValuesFromProps(e,t,n){return co(e,t,n)}build(e,t,n){Ji(e,t,this.isSVGTag,n.transformTemplate)}renderInstance(e,t,n,r){oo(e,t,0,r)}mount(e){this.isSVGTag=no(e.tagName),super.mount(e)}}const gd=Wr(bo({...ql,...nd,...Yu,...rd},(e,t)=>gi(e)?new pd(t):new fd(t,{allowProjection:e!==y.Fragment})));function md({from:e,onAnswer:t,onReject:n}){const r=e;return v.jsxs(gd.div,{initial:{opacity:0,y:-10},animate:{opacity:1,y:0},className:"bg-gradient-to-r from-blue-900 to-blue-800 border-b border-blue-700 px-4 py-4",children:[v.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[v.jsx("div",{className:"w-10 h-10 bg-blue-600 rounded-full flex items-center justify-center",children:v.jsx(ce,{className:"w-5 h-5 text-white"})}),v.jsxs("div",{children:[v.jsx("p",{className:"text-blue-300 text-xs",children:"Chamada recebida"}),v.jsx("p",{className:"text-white font-semibold text-sm truncate max-w-[180px]",children:r})]})]}),v.jsxs("div",{className:"flex gap-3",children:[v.jsxs("button",{onClick:t,className:"flex-1 bg-green-500 hover:bg-green-600 text-white rounded-[15px] py-2.5 flex items-center justify-center gap-2 transition-colors font-medium text-sm",children:[v.jsx(oe,{className:"w-4 h-4"}),"Atender"]}),v.jsxs("button",{onClick:n,className:"flex-1 bg-red-500 hover:bg-red-600 text-white rounded-[15px] py-2.5 flex items-center justify-center gap-2 transition-colors font-medium text-sm",children:[v.jsx(re,{className:"w-4 h-4"}),"Recusar"]})]})]})}function vd({open:e,step:t,consultTarget:n,consultEstablished:r,onDial:i,onTransfer:o,onCancel:a}){const[s,l]=y.useState("");if(!e)return null;const c=()=>{s.trim()&&i(s.trim())};return v.jsx(xr,{children:v.jsx(gd.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:v.jsxs(gd.div,{initial:{scale:.92,opacity:0},animate:{scale:1,opacity:1},exit:{scale:.92,opacity:0},className:"bg-gray-900 border border-gray-700 rounded-[15px] w-full max-w-xs shadow-2xl overflow-hidden",children:[v.jsxs("div",{className:"bg-gradient-to-r from-purple-700 to-purple-600 px-4 py-4 flex items-center gap-3",children:[v.jsx("div",{className:"w-9 h-9 bg-white/20 rounded-full flex items-center justify-center",children:v.jsx(ee,{className:"w-5 h-5 text-white"})}),v.jsxs("div",{className:"flex-1",children:[v.jsx("p",{className:"text-white font-semibold text-sm",children:"Transferência Assistida"}),v.jsxs("p",{className:"text-purple-200 text-xs",children:["dial"===t&&"Informe o destino","connecting"===t&&`Chamando: ${n}...`,"consulting"===t&&`Consultando: ${n}`,"transferring"===t&&"Transferindo..."]})]}),v.jsx("button",{onClick:a,className:"text-purple-200 hover:text-white",children:v.jsx(ue,{className:"w-5 h-5"})})]}),v.jsxs("div",{className:"p-4 space-y-4",children:["dial"===t&&v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"space-y-1",children:[v.jsx("label",{className:"text-gray-400 text-xs uppercase tracking-wider",children:"Destino da transferência"}),v.jsx("input",{type:"text",value:s,onChange:e=>l(e.target.value),onKeyDown:e=>{"Enter"===e.key?c():/^\d$|[\*\#]/.test(e.key)&&jn(e.key,80)},placeholder:"Ramal ou número",autoFocus:!0,className:"w-full bg-gray-800 border border-gray-700 rounded-lg px-3 py-2.5 text-white text-sm placeholder-gray-500 focus:outline-none focus:border-purple-500 transition-colors"})]}),v.jsxs("div",{className:"bg-gray-800 rounded-lg p-3 text-xs text-gray-400 space-y-1",children:[v.jsx("p",{className:"text-gray-300 font-medium text-xs",children:"Como funciona:"}),v.jsx("p",{children:"1. A chamada atual entra em espera"}),v.jsx("p",{children:"2. Você liga para o destino"}),v.jsxs("p",{children:["3. Após consultar, clica em ",v.jsx("span",{className:"text-purple-300",children:"Transferir"})]})]}),v.jsxs("div",{className:"flex gap-2",children:[v.jsx("button",{onClick:a,className:"flex-1 bg-gray-700 hover:bg-gray-600 text-gray-300 rounded-[15px] py-2.5 text-sm font-medium transition-colors",children:"Cancelar"}),v.jsxs("button",{onClick:c,disabled:!s.trim(),className:"flex-1 bg-purple-600 hover:bg-purple-700 disabled:bg-gray-700 disabled:text-gray-500 text-white rounded-[15px] py-2.5 text-sm font-medium transition-colors flex items-center justify-center gap-2",children:[v.jsx(oe,{className:"w-4 h-4"}),"Consultar"]})]})]}),"connecting"===t&&v.jsxs("div",{className:"flex flex-col items-center gap-3 py-4",children:[v.jsx(Q,{className:"w-8 h-8 text-purple-400 animate-spin"}),v.jsxs("p",{className:"text-gray-300 text-sm",children:["Chamando ",n,"..."]}),v.jsx("button",{onClick:a,className:"mt-2 bg-gray-700 hover:bg-gray-600 text-gray-300 rounded-[15px] px-5 py-2 text-sm font-medium transition-colors",children:"Cancelar"})]}),"consulting"===t&&v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"bg-gray-800 rounded-[15px] p-4 space-y-2",children:[v.jsxs("div",{className:"flex items-center gap-2",children:[v.jsx("div",{className:"w-2 h-2 bg-green-400 rounded-full animate-pulse"}),v.jsx("span",{className:"text-gray-400 text-xs",children:"Em consulta com"})]}),v.jsx("p",{className:"text-white font-semibold truncate",children:n}),v.jsx("p",{className:"text-gray-500 text-xs",children:"Chamada original em espera"})]}),v.jsxs("p",{className:"text-gray-400 text-xs text-center",children:["Quando pronto, clique em ",v.jsx("span",{className:"text-purple-300",children:"Transferir"})," para conectar as duas chamadas."]}),v.jsxs("div",{className:"flex gap-2",children:[v.jsx("button",{onClick:a,className:"flex-1 bg-gray-700 hover:bg-gray-600 text-gray-300 rounded-[15px] py-2.5 text-sm font-medium transition-colors",children:"Cancelar"}),v.jsxs("button",{onClick:o,className:"flex-1 bg-green-600 hover:bg-green-700 text-white rounded-[15px] py-2.5 text-sm font-medium transition-colors flex items-center justify-center gap-2",children:[v.jsx(q,{className:"w-4 h-4"}),"Transferir"]})]})]}),"transferring"===t&&v.jsxs("div",{className:"flex flex-col items-center gap-3 py-4",children:[v.jsx(Q,{className:"w-8 h-8 text-purple-400 animate-spin"}),v.jsx("p",{className:"text-gray-300 text-sm",children:"Executando transferência..."})]})]})]})})})}function yd(e){const t=new Date(e),n=new Date,r=new Date(n.getFullYear(),n.getMonth(),n.getDate()),i=new Date(r);i.setDate(i.getDate()-1);const o=new Date(t.getFullYear(),t.getMonth(),t.getDate()),a=o.getTime()===r.getTime(),s=o.getTime()===i.getTime(),l=t.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"});if(a)return`Hoje ${l}`;if(s)return`Ontem ${l}`;return`${t.toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit",year:"2-digit"})} ${l}`}function bd({direction:e,status:t}){const n="w-4 h-4";return"missed"===t||"rejected"===t?v.jsx(ne,{className:`${n} text-red-400`}):"inbound"===e?v.jsx(te,{className:`${n} text-green-400`}):v.jsx(ie,{className:`${n} text-blue-400`})}function wd({onSelect:e,onCallDirect:t,canCall:n}){const r=_n.getCallLogs();return r.length?v.jsx("div",{className:"flex-1 overflow-y-auto divide-y divide-gray-800",children:r.map((r,i)=>{return v.jsxs("div",{className:"flex items-center gap-3 px-4 py-3 hover:bg-white/5 transition-colors cursor-pointer",onClick:()=>null==e?void 0:e(r.number),children:[v.jsx(bd,{direction:r.direction,status:r.status}),v.jsxs("div",{className:"flex-1 min-w-0",children:[v.jsx("p",{className:"text-white text-sm truncate font-medium",children:r.number}),v.jsx("p",{className:"text-slate-500 text-xs",children:yd(r.startedAt)})]}),v.jsx("span",{className:"text-slate-500 text-xs whitespace-nowrap mr-1",children:"answered"===r.status?(o=r.duration,`${Math.floor(o/60).toString().padStart(2,"0")}:${(o%60).toString().padStart(2,"0")}`):"missed"===r.status?"Perdida":"Recusada"}),v.jsx("button",{onClick:e=>{e.stopPropagation(),null==t||t(r.number)},disabled:!n,className:"w-7 h-7 bg-emerald-600 hover:bg-emerald-500 disabled:bg-gray-700 disabled:opacity-50 rounded-full flex items-center justify-center flex-shrink-0 transition-colors",title:"Ligar",children:v.jsx(oe,{className:"w-3.5 h-3.5 text-white"})})]},i);var o})}):v.jsx("div",{className:"flex-1 flex items-center justify-center text-slate-500 text-sm",children:"Sem chamadas recentes"})}function xd({onBack:e}){const[t,n]=y.useState(Xn.getLogs());return v.jsxs("div",{className:"flex flex-col h-full bg-gray-900",children:[v.jsxs("div",{className:"px-4 py-4 border-b border-gray-800 flex items-center justify-between flex-shrink-0",children:[v.jsxs("div",{className:"flex items-center gap-2",children:[e&&v.jsx("button",{onClick:e,className:"text-gray-400 hover:text-white transition-colors p-1",title:"Voltar",children:v.jsx(V,{size:16})}),v.jsxs("h3",{className:"text-white font-semibold text-sm",children:["Logs (",t.length,")"]})]}),v.jsxs("div",{className:"flex gap-2",children:[v.jsx("button",{onClick:()=>{n(Xn.getLogs())},className:"text-gray-400 hover:text-white text-xs px-2 py-1 bg-gray-800 hover:bg-gray-700 rounded transition-colors",children:"Atualizar"}),v.jsxs("button",{onClick:()=>{const e=Xn.exportLogs();navigator.clipboard.writeText(e).then(()=>{alert("Logs copiados para a área de transferência")})},disabled:0===t.length,className:"text-gray-400 hover:text-white disabled:opacity-40 text-xs px-2 py-1 bg-gray-800 hover:bg-gray-700 rounded transition-colors flex items-center gap-1",children:[v.jsx(K,{size:12}),"Copiar"]}),v.jsx("button",{onClick:()=>{confirm("Tem certeza que deseja limpar todos os logs?")&&(Xn.clearLogs(),n([]))},disabled:0===t.length,className:"text-gray-400 hover:text-red-400 disabled:opacity-40 text-xs px-2 py-1 bg-gray-800 hover:bg-gray-700 rounded transition-colors flex items-center gap-1",children:v.jsx(le,{size:12})})]})]}),v.jsx("div",{className:"px-4 py-4",children:0===t.length?v.jsx("p",{className:"text-gray-500 text-xs text-center py-8",children:"Nenhum log registrado"}):v.jsx("div",{className:"space-y-2",children:t.map((e,t)=>v.jsxs("div",{className:"text-xs font-mono text-gray-400 break-words",children:[v.jsxs("span",{className:"text-gray-600",children:["[",e.timestamp,"]"]})," ",v.jsx("span",{className:"ERROR"===e.level?"text-red-400":"text-yellow-400",children:e.level}),": ",v.jsx("span",{className:"text-gray-300",children:e.message})]},t))})})]})}function kd({connectionStatus:e,callStatus:t,isMuted:n,isOnHold:r,incomingCallInfo:i,callDuration:o,dialInput:a,setDialInput:s,dtmfLog:l,transferModal:c,setTransferModal:u,transferStep:d,setTransferStep:h,transferTarget:f,setTransferTarget:p,consultEstablished:g,setConsultEstablished:m,blindTransferModal:b,setBlindTransferModal:w,blindTransferTarget:x,setBlindTransferTarget:k,settings:S,onConnect:T,onDisconnect:E,onCall:C,onHangup:R,onAnswer:P,onReject:_,onToggleMute:D,onToggleHold:I,onDialPadPress:A,onTransfer:N,onBlindTransfer:M,onTransferDial:$,onTransferExecute:O,onTransferCancel:j,onBlindTransferExecute:L,onClose:H,isConnecting:F,onTabChange:U,onCallDirect:z}){const[q,V]=y.useState("dialpad"),B=y.useRef(null);y.useEffect(()=>{"dialpad"===q&&B.current&&B.current.focus()},[q]);const W=e=>{V(e),null==U||U(e)};return v.jsxs("div",{className:"bg-gray-900 flex-1 border-t border-gray-800 relative w-full flex flex-col min-h-0",children:[v.jsx(ar,{connectionStatus:e,callStatus:t,callDuration:o,aor:S.aor,onDisconnect:()=>{_n.setManualDisconnect(!0),E()},onConnect:async()=>{const e=await _n.mergeConfig({});e&&e.server&&e.username&&e.domain&&e.password&&(_n.setManualDisconnect(!1),await T(e),W("dialpad"))}}),v.jsxs("div",{className:"flex gap-0.5 px-3 py-2 bg-gray-900 border-b border-gray-800 flex-shrink-0",children:[v.jsxs("button",{onClick:()=>W("dialpad"),className:"flex-1 flex flex-col items-center gap-0.5 py-1.5 rounded-[15px] text-[10px] font-medium transition-all "+("dialpad"===q?"bg-white/10 text-white":"text-slate-500 hover:text-slate-300 hover:bg-white/5"),children:[v.jsx(oe,{className:"w-3.5 h-3.5"}),"Teclado"]}),v.jsxs("button",{onClick:()=>W("recentes"),className:"flex-1 flex flex-col items-center gap-0.5 py-1.5 rounded-[15px] text-[10px] font-medium transition-all "+("recentes"===q?"bg-white/10 text-white":"text-slate-500 hover:text-slate-300 hover:bg-white/5"),children:[v.jsx(G,{className:"w-3.5 h-3.5"}),"Recentes"]}),v.jsxs("button",{onClick:()=>W("settings"),className:"flex-1 flex flex-col items-center gap-0.5 py-1.5 rounded-[15px] text-[10px] font-medium transition-all "+("settings"===q?"bg-white/10 text-white":"text-slate-500 hover:text-slate-300 hover:bg-white/5"),children:[v.jsx(se,{className:"w-3.5 h-3.5"}),"Config"]})]}),"settings"===q&&v.jsx("div",{className:"flex-1 min-h-0",children:v.jsx(rr,{settings:S,onConnect:e=>{T(e),W("dialpad")},onSave:async e=>{await _n.setSipConfig(e)},isConnecting:F,hideHeader:!0,onShowLogs:()=>W("logs")})}),"recentes"===q&&v.jsx("div",{className:"flex-1 overflow-y-auto min-h-0",children:v.jsx(wd,{onSelect:e=>{s(e??""),W("dialpad")},onCallDirect:e=>{W("dialpad"),null==z||z(e)},canCall:"registered"===e&&"idle"===t})}),"logs"===q&&v.jsx("div",{className:"flex-1 overflow-y-auto min-h-0",children:v.jsx(xd,{onBack:()=>W("settings")})}),"dialpad"===q&&v.jsxs(v.Fragment,{children:[i&&"ringing"===t&&v.jsx(md,{from:i.from,onAnswer:P,onReject:_}),v.jsxs("div",{className:"px-4 pt-4 pb-2 flex-1 relative",children:[v.jsxs("div",{className:"bg-gray-800 rounded-[15px] px-4 py-3 mb-4 flex items-center gap-2",children:[v.jsx("input",{ref:B,type:"tel",value:a,onChange:e=>s(e.target.value.replace(/[^\d\*\#]/g,"")),onKeyDown:n=>{"Enter"===n.key?a.trim()&&"registered"===e&&"idle"===t&&C():/^\d$|[\*\#]/.test(n.key)&&"active"!==t&&jn(n.key,80)},placeholder:"Digite o número",className:"flex-1 bg-transparent text-white text-lg outline-none placeholder-gray-500",disabled:"active"===t||"calling"===t,inputMode:"numeric"}),a&&v.jsxs(v.Fragment,{children:[v.jsx("button",{onClick:()=>s(a.slice(0,-1)),disabled:"active"===t||"calling"===t,className:"text-gray-400 hover:text-white disabled:opacity-40 text-xs px-2 py-1 bg-gray-700 hover:bg-gray-600 rounded transition-colors",title:"Backspace",children:"⌫"}),v.jsx("button",{onClick:()=>s(""),disabled:"active"===t||"calling"===t,className:"text-gray-400 hover:text-white disabled:opacity-40 text-sm transition-colors",children:"✕"})]})]}),l&&"active"===t&&v.jsx("div",{className:"text-center text-gray-400 text-sm mb-3 tracking-widest",children:l}),v.jsx(tr,{onPress:A,disabled:"calling"===t||"ringing"===t}),v.jsx(nr,{callStatus:t,isMuted:n,isOnHold:r,onCall:C,onHangup:R,onToggleMute:D,onToggleHold:I,onTransfer:N,onBlindTransfer:M,canCall:"registered"===e&&!!a.trim()}),b&&v.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:v.jsxs("div",{className:"bg-gray-900 border border-gray-700 rounded-[15px] w-full max-w-xs shadow-2xl overflow-hidden",children:[v.jsxs("div",{className:"bg-gradient-to-r from-blue-700 to-blue-600 px-4 py-4 flex items-center gap-3",children:[v.jsx("div",{className:"w-9 h-9 bg-white/20 rounded-full flex items-center justify-center",children:v.jsx("svg",{className:"w-5 h-5 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:v.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.949V19a2 2 0 01-2 2h-1C9.716 21 3 14.284 3 6V5z"})})}),v.jsx("p",{className:"text-white font-semibold text-sm",children:"Transferência Cega"})]}),v.jsxs("div",{className:"p-4 space-y-4",children:[v.jsxs("div",{className:"space-y-1",children:[v.jsx("label",{className:"text-gray-400 text-xs uppercase tracking-wider",children:"Destino"}),v.jsx("input",{type:"tel",value:x,onChange:e=>k(e.target.value.replace(/[^\d\*\#]/g,"")),onKeyDown:e=>{"Enter"===e.key?L(x):/^\d$|[\*\#]/.test(e.key)&&jn(e.key,80)},placeholder:"Ramal ou número",autoFocus:!0,inputMode:"numeric",className:"w-full bg-gray-800 border border-gray-700 rounded-lg px-3 py-2.5 text-white text-sm placeholder-gray-500 focus:outline-none focus:border-blue-500 transition-colors"})]}),v.jsx("p",{className:"text-gray-400 text-xs",children:"A chamada será transferida imediatamente sem consulta prévia."}),v.jsxs("div",{className:"flex gap-2",children:[v.jsx("button",{onClick:()=>{w(!1),k("")},className:"flex-1 bg-gray-700 hover:bg-gray-600 text-gray-300 rounded-[15px] py-2.5 text-sm font-medium transition-colors",children:"Cancelar"}),v.jsx("button",{onClick:()=>L(x),disabled:!x.trim(),className:"flex-1 bg-blue-600 hover:bg-blue-700 disabled:bg-gray-700 disabled:text-gray-500 text-white rounded-[15px] py-2.5 text-sm font-medium transition-colors",children:"Transferir"})]})]})]})}),v.jsx(vd,{open:c,step:d,consultTarget:f,consultEstablished:g,onDial:$,onTransfer:O,onCancel:j})]})]})]})}const Sd={registered:"bg-emerald-500",connecting:"bg-amber-500",disconnected:"bg-slate-500",failed:"bg-red-500"},Td={"bottom-right":"bottom-6 right-6","bottom-left":"bottom-6 left-6","top-right":"top-6 right-6","top-left":"top-6 left-6"};function Ed({config:e,api:t,embedded:n=!1}){y.useEffect(()=>{const e=console.error,t=console.warn,n=console.log;return console.error=function(...t){Xn.addLog("ERROR",t),Jn(t)||e.apply(console,t)},console.warn=function(...e){Xn.addLog("WARN",e),Jn(e)||t.apply(console,e)},console.log=function(...e){Jn(e)||n.apply(console,e)},()=>{console.error=e,console.warn=t,console.log=n}},[]);const[r,i]=y.useState(!1),[o,a]=y.useState(""),[s,l]=y.useState(""),[c,u]=y.useState(null),[d,h]=y.useState("dialpad"),[f,p]=y.useState({}),g=b.useRef(null),m=b.useRef(!1),w=b.useRef(0),x=b.useRef("idle"),k=b.useRef(null),S=Kn(f,g),{connectionStatus:T,callStatus:E,isMuted:C,isOnHold:R,incomingCallInfo:P,callDuration:_,transferModal:D,setTransferModal:I,transferStep:A,setTransferStep:N,transferTarget:M,setTransferTarget:$,consultEstablished:O,setConsultEstablished:j,blindTransferModal:L,setBlindTransferModal:H,blindTransferTarget:F,setBlindTransferTarget:U,connect:z,disconnect:q,call:V,hangup:B,answer:W,reject:Y,toggleMute:G,toggleHold:K,sendDTMF:Q,openTransfer:X,transferDial:Z,transferExecute:ee,transferCancel:te,blindTransfer:ne}=S;k.current=V,y.useEffect(()=>{_n.mergeConfig(e||{}).then(e=>p(e))},[]),y.useEffect(()=>{r?_n.mergeConfig(e||{}).then(e=>p(e)):h("dialpad")},[r,e]),y.useEffect(()=>{P&&"ringing"===E&&!r&&i(!0)},[P,E,r]),y.useEffect(()=>{(async()=>{if(await new Promise(e=>setTimeout(e,0)),"disconnected"===T){const t=await _n.mergeConfig(e||{});if(t.username&&t.domain&&t.server&&t.password){_n.getManualDisconnect()||(w.current=Date.now(),ie(t))}}})()},[]),y.useEffect(()=>{if("disconnected"===T&&f.username&&f.domain&&f.server&&f.password){!_n.getManualDisconnect()&&Date.now()-w.current>5e3&&(w.current=Date.now(),ie(f))}},[T]),y.useEffect(()=>{t.emit("statusChange",T),t.emit("__connectionStatusChange",T)},[T,t]),y.useEffect(()=>{const e=x.current,n=E;x.current=n,t.emit("callStateChange",n),t.emit("__callStatusChange",n),"active"===n&&t.emit("call:start",{direction:"ringing"===e?"inbound":"outbound"}),"active"===e&&"idle"===n&&t.emit("call:end",{}),"ringing"===e&&"idle"===n&&t.emit("call:missed",{})},[E,t]),y.useEffect(()=>{const e=null!==P;t.emit("incomingChange",e),t.emit("__incomingCallChange",P)},[P,t]),y.useEffect(()=>{var e;if(!c)return;const{number:t,auto:n}=c;if(a(t),u(null),!n)return;if("registered"!==T||"idle"!==E)return;const r=null==(e=f.aor)?void 0:e.split("@")[1];r&&k.current(t,r).catch(e=>console.error("[Widget] Auto call failed:",e))},[c]),t._emitter={open:()=>i(!0),close:()=>i(!1),dial:(e,t={})=>{i(!0),u({number:e,auto:Boolean(t.auto)})},answer:W,hangup:B,reject:Y,toggleHold:K,toggleMute:G,blindTransfer:ne,openTransfer:X,transferDial:Z,transferExecute:ee,transferCancel:te};const ie=async e=>{if(!m.current){m.current=!0;try{const t=await z(e);p(t)}catch(t){console.error("[Widget] Connect failed:",t)}finally{m.current=!1}}},ae=(null==e?void 0:e.position)||"bottom-right",se=(null==e?void 0:e.fabStyle)||"round",le=Td[ae]||Td["bottom-right"],ce="settings"===d||"logs"===d?"360px":"active"===E?"620px":"520px",de="disconnected"===T||"failed"===T,he="connecting"===T,fe=["calling","ringing","ringing_in","connected","active"].includes(E),pe=null!==P,ge=fe?"bg-blue-600":de?"bg-slate-500":he?"bg-amber-500":"bg-emerald-500",me=fe?J:de?re:oe,ve="pill"===se?v.jsxs("button",{onClick:()=>i(!r),className:`inline-flex items-center gap-2 px-3 h-8 rounded-lg text-white text-xs font-semibold transition-colors ${ge} hover:brightness-110 shadow-lg`,children:[v.jsx(me,{size:14}),v.jsx("span",{children:fe?"Em ligação":de?"Ramal Offline":he?"Conectando...":"Ramal Online"}),pe&&!r&&v.jsx("span",{className:"absolute inset-0 rounded-lg bg-green-400/20 animate-ping"})]}):v.jsxs("button",{onClick:()=>i(!r),className:`relative w-14 h-14 rounded-full flex items-center justify-center ${ge} hover:brightness-110 transition-colors shadow-lg`,children:[v.jsx(me,{size:24,className:"text-white"}),v.jsx("div",{className:`absolute top-0.5 right-0.5 w-3.5 h-3.5 rounded-full border-2 border-white ${Sd[T]||"bg-slate-500"}`}),pe&&!r&&v.jsx("span",{className:"absolute inset-0 rounded-full bg-green-400/20 animate-ping"})]});return v.jsxs(v.Fragment,{children:[v.jsx("audio",{ref:g,autoPlay:!0,playsInline:!0,controls:!1,style:{display:"none"}}),!n&&v.jsx("div",{className:`fixed ${le} z-50`,children:ve}),r&&v.jsx("div",{className:"fixed inset-0 z-[9998] bg-black/40 backdrop-blur-sm flex items-center justify-center",onClick:()=>i(!1),children:v.jsxs("div",{className:"relative w-full max-w-sm transition-[height] duration-300 ease-in-out",style:{height:ce,maxHeight:"calc(100vh - 48px)"},onClick:e=>e.stopPropagation(),children:[v.jsx("button",{onClick:()=>i(!1),className:"absolute -top-3 -right-3 w-7 h-7 bg-slate-800 border border-slate-600 rounded-full flex items-center justify-center text-gray-400 hover:text-white transition-colors z-10",children:v.jsx(ue,{size:14})}),v.jsx("div",{className:"rounded-[15px] overflow-hidden flex flex-col h-full",style:{boxShadow:"0 0px 6px 7px rgb(163 161 161 / 15%)"},children:v.jsx(kd,{connectionStatus:T,callStatus:E,isMuted:C,isOnHold:R,incomingCallInfo:P,callDuration:_,dialInput:o,setDialInput:a,dtmfLog:s,transferModal:D,setTransferModal:I,transferStep:A,setTransferStep:N,transferTarget:M,setTransferTarget:$,consultEstablished:O,setConsultEstablished:j,blindTransferModal:L,setBlindTransferModal:H,blindTransferTarget:F,setBlindTransferTarget:U,settings:f,onConnect:ie,onDisconnect:q,onCall:async()=>{try{if(!f.aor)return void console.error("[Widget] Cannot call: not connected (missing aor)");const e=f.aor.split("@")[1];await V(o,e)}catch(e){console.error("[Widget] Call failed:",e)}},onHangup:B,onAnswer:W,onReject:Y,onToggleMute:G,onToggleHold:K,onDialPadPress:e=>{"active"===E?(l(t=>t+e),Q(e)):(a(t=>t+e),jn(e,80))},onTransfer:X,onBlindTransfer:()=>H(!0),onTransferDial:e=>{var t;return Z(e,null==(t=f.aor)?void 0:t.split("@")[1])},onTransferExecute:ee,onTransferCancel:te,onTabChange:h,onBlindTransferExecute:e=>{var t;return ne(e,null==(t=f.aor)?void 0:t.split("@")[1])},onCallDirect:e=>{var t;if(!e)return;a(e);const n=null==(t=f.aor)?void 0:t.split("@")[1];n&&V(e,n).catch(e=>console.error("[Widget] Call failed:",e))},onClose:()=>i(!1),isConnecting:"connecting"===T})})]})})]})}const Cd={registered:"bg-emerald-500",connecting:"bg-amber-500",disconnected:"bg-slate-500",failed:"bg-red-500"};function Rd({status:e,callStatus:t,hasIncomingCall:n,onClick:r,variant:i="round"}){const o="disconnected"===e||"failed"===e,a="connecting"===e,s=["ringing","ringing_in","connected"].includes(t),l=s?"bg-blue-600":o?"bg-slate-500":a?"bg-amber-500":"bg-emerald-500",c=s?J:o?re:oe;return"pill"===i?v.jsxs("button",{onClick:r,className:`inline-flex items-center gap-2 px-3 h-8 rounded-lg text-white text-xs font-semibold transition-colors ${l} hover:brightness-110 shadow-lg`,children:[v.jsx(c,{size:14}),v.jsx("span",{children:s?"Em ligação":o?"Ramal Offline":a?"Conectando...":"Ramal Online"}),n&&v.jsx("span",{className:"absolute inset-0 rounded-lg bg-green-400/20 animate-ping"})]}):v.jsxs("button",{onClick:r,className:`relative w-14 h-14 rounded-full flex items-center justify-center ${l} hover:brightness-110 transition-colors shadow-lg`,children:[v.jsx(c,{size:24,className:"text-white"}),v.jsx("div",{className:`absolute top-0.5 right-0.5 w-3.5 h-3.5 rounded-full border-2 border-white ${Cd[e]||"bg-slate-500"}`}),n&&v.jsx("span",{className:"absolute inset-0 rounded-full bg-green-400/20 animate-ping"})]})}const Pd={};let _d=null,Dd=null,Id=null;const Ad={statusChange:()=>_d,callStateChange:()=>Dd,incomingChange:()=>Id},Nd={open(){var e;null==(e=Nd._emitter)||e.open()},close(){var e;null==(e=Nd._emitter)||e.close()},dial(e,t={}){var n;null==(n=Nd._emitter)||n.dial(e,t)},answer(){var e;null==(e=Nd._emitter)||e.answer()},hangup(){var e;null==(e=Nd._emitter)||e.hangup()},reject(){var e;null==(e=Nd._emitter)||e.reject()},toggleHold(){var e;null==(e=Nd._emitter)||e.toggleHold()},toggleMute(){var e;null==(e=Nd._emitter)||e.toggleMute()},blindTransfer(e){var t;null==(t=Nd._emitter)||t.blindTransfer(e)},openTransfer(){var e;null==(e=Nd._emitter)||e.openTransfer()},transferDial(e){var t;null==(t=Nd._emitter)||t.transferDial(e)},transferExecute(){var e;null==(e=Nd._emitter)||e.transferExecute()},transferCancel(){var e;null==(e=Nd._emitter)||e.transferCancel()},on(e,t){var n;(Pd[e]??(Pd[e]=[])).push(t);const r=null==(n=Ad[e])?void 0:n.call(Ad);if(null!=r)try{t(r)}catch(i){}},off(e,t){Pd[e]&&(Pd[e]=Pd[e].filter(e=>e!==t))},emit(e,t){var n;"statusChange"===e&&(_d=t),"callStateChange"===e&&(Dd=t),"incomingChange"===e&&(Id=t),null==(n=Pd[e])||n.forEach(e=>{try{e(t)}catch(n){}})},get status(){return _d},_emitter:null};function Md(e,t){const n=document.createElement("div");n.style.cssText=e,t.appendChild(n);const r=n.attachShadow({mode:"open"}),i=document.createElement("style");i.textContent='*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:#e5e7eb}:before,:after{--tw-content: ""}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji",Segoe UI Symbol,"Noto Color Emoji";font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]:where(:not([hidden=until-found])){display:none}:host{--background: 0 0% 100%;--foreground: 0 0% 3.9%;--card: 0 0% 100%;--card-foreground: 0 0% 3.9%;--popover: 0 0% 100%;--popover-foreground: 0 0% 3.9%;--primary: 0 0% 9%;--primary-foreground: 0 0% 98%;--secondary: 0 0% 96.1%;--secondary-foreground: 0 0% 9%;--muted: 0 0% 96.1%;--muted-foreground: 0 0% 45.1%;--accent: 0 0% 96.1%;--accent-foreground: 0 0% 9%;--destructive: 0 84.2% 60.2%;--destructive-foreground: 0 0% 98%;--border: 0 0% 89.8%;--input: 0 0% 89.8%;--ring: 0 0% 3.9%;--chart-1: 12 76% 61%;--chart-2: 173 58% 39%;--chart-3: 197 37% 24%;--chart-4: 43 74% 66%;--chart-5: 27 87% 67%;--radius: .5rem;--sidebar-background: 0 0% 98%;--sidebar-foreground: 240 5.3% 26.1%;--sidebar-primary: 240 5.9% 10%;--sidebar-primary-foreground: 0 0% 98%;--sidebar-accent: 240 4.8% 95.9%;--sidebar-accent-foreground: 240 5.9% 10%;--sidebar-border: 220 13% 91%;--sidebar-ring: 217.2 91.2% 59.8%}:host(.dark){--background: 0 0% 3.9%;--foreground: 0 0% 98%;--card: 0 0% 3.9%;--card-foreground: 0 0% 98%;--popover: 0 0% 3.9%;--popover-foreground: 0 0% 98%;--primary: 0 0% 98%;--primary-foreground: 0 0% 9%;--secondary: 0 0% 14.9%;--secondary-foreground: 0 0% 98%;--muted: 0 0% 14.9%;--muted-foreground: 0 0% 63.9%;--accent: 0 0% 14.9%;--accent-foreground: 0 0% 98%;--destructive: 0 62.8% 30.6%;--destructive-foreground: 0 0% 98%;--border: 0 0% 14.9%;--input: 0 0% 14.9%;--ring: 0 0% 83.1%;--chart-1: 220 70% 50%;--chart-2: 160 60% 45%;--chart-3: 30 80% 55%;--chart-4: 280 65% 60%;--chart-5: 340 75% 55%;--sidebar-background: 240 5.9% 10%;--sidebar-foreground: 240 4.8% 95.9%;--sidebar-primary: 224.3 76.3% 48%;--sidebar-primary-foreground: 0 0% 100%;--sidebar-accent: 240 3.7% 15.9%;--sidebar-accent-foreground: 240 4.8% 95.9%;--sidebar-border: 240 3.7% 15.9%;--sidebar-ring: 217.2 91.2% 59.8%}:host *{border-color:hsl(var(--border));outline-color:hsl(var(--ring) / .5)}:host{color:hsl(var(--foreground))}.container{width:100%}@media(min-width:640px){.container{max-width:640px}}@media(min-width:768px){.container{max-width:768px}}@media(min-width:1024px){.container{max-width:1024px}}@media(min-width:1280px){.container{max-width:1280px}}@media(min-width:1536px){.container{max-width:1536px}}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border-width:0}.pointer-events-none{pointer-events:none}.pointer-events-auto{pointer-events:auto}.visible{visibility:visible}.invisible{visibility:hidden}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.inset-0{top:0;right:0;bottom:0;left:0}.inset-x-0{left:0;right:0}.inset-y-0{top:0;bottom:0}.-bottom-12{bottom:-3rem}.-left-12{left:-3rem}.-right-12{right:-3rem}.-right-3{right:-.75rem}.-top-12{top:-3rem}.-top-3{top:-.75rem}.bottom-0{bottom:0}.bottom-6{bottom:1.5rem}.left-0{left:0}.left-1{left:.25rem}.left-1\\/2{left:50%}.left-2{left:.5rem}.left-6{left:1.5rem}.left-\\[50\\%\\]{left:50%}.right-0{right:0}.right-0\\.5{right:.125rem}.right-1{right:.25rem}.right-2{right:.5rem}.right-3{right:.75rem}.right-4{right:1rem}.right-6{right:1.5rem}.top-0{top:0}.top-0\\.5{top:.125rem}.top-1\\.5{top:.375rem}.top-1\\/2{top:50%}.top-2{top:.5rem}.top-3\\.5{top:.875rem}.top-4{top:1rem}.top-6{top:1.5rem}.top-\\[1px\\]{top:1px}.top-\\[50\\%\\]{top:50%}.top-\\[60\\%\\]{top:60%}.top-full{top:100%}.z-10{z-index:10}.z-20{z-index:20}.z-50{z-index:50}.z-\\[100\\]{z-index:100}.z-\\[1\\]{z-index:1}.z-\\[9998\\]{z-index:9998}.-mx-1{margin-left:-.25rem;margin-right:-.25rem}.mx-2{margin-left:.5rem;margin-right:.5rem}.mx-3\\.5{margin-left:.875rem;margin-right:.875rem}.mx-auto{margin-left:auto;margin-right:auto}.my-0\\.5{margin-top:.125rem;margin-bottom:.125rem}.my-1{margin-top:.25rem;margin-bottom:.25rem}.-ml-4{margin-left:-1rem}.-mt-4{margin-top:-1rem}.mb-1{margin-bottom:.25rem}.mb-2{margin-bottom:.5rem}.mb-3{margin-bottom:.75rem}.mb-4{margin-bottom:1rem}.ml-1{margin-left:.25rem}.ml-auto{margin-left:auto}.mr-1{margin-right:.25rem}.mr-2{margin-right:.5rem}.mt-0\\.5{margin-top:.125rem}.mt-1{margin-top:.25rem}.mt-1\\.5{margin-top:.375rem}.mt-2{margin-top:.5rem}.mt-24{margin-top:6rem}.mt-3{margin-top:.75rem}.mt-4{margin-top:1rem}.mt-auto{margin-top:auto}.block{display:block}.inline{display:inline}.flex{display:flex}.inline-flex{display:inline-flex}.table{display:table}.grid{display:grid}.hidden{display:none}.aspect-square{aspect-ratio:1 / 1}.aspect-video{aspect-ratio:16 / 9}.size-4{width:1rem;height:1rem}.h-1\\.5{height:.375rem}.h-10{height:2.5rem}.h-12{height:3rem}.h-14{height:3.5rem}.h-16{height:4rem}.h-2{height:.5rem}.h-2\\.5{height:.625rem}.h-3{height:.75rem}.h-3\\.5{height:.875rem}.h-4{height:1rem}.h-5{height:1.25rem}.h-7{height:1.75rem}.h-8{height:2rem}.h-9{height:2.25rem}.h-\\[1px\\]{height:1px}.h-\\[var\\(--radix-navigation-menu-viewport-height\\)\\]{height:var(--radix-navigation-menu-viewport-height)}.h-\\[var\\(--radix-select-trigger-height\\)\\]{height:var(--radix-select-trigger-height)}.h-auto{height:auto}.h-full{height:100%}.h-px{height:1px}.h-svh{height:100svh}.max-h-96{max-height:24rem}.max-h-\\[300px\\]{max-height:300px}.max-h-screen{max-height:100vh}.min-h-0{min-height:0px}.min-h-\\[60px\\]{min-height:60px}.min-h-svh{min-height:100svh}.w-0{width:0px}.w-1{width:.25rem}.w-10{width:2.5rem}.w-12{width:3rem}.w-14{width:3.5rem}.w-16{width:4rem}.w-2{width:.5rem}.w-2\\.5{width:.625rem}.w-3{width:.75rem}.w-3\\.5{width:.875rem}.w-3\\/4{width:75%}.w-4{width:1rem}.w-5{width:1.25rem}.w-64{width:16rem}.w-7{width:1.75rem}.w-72{width:18rem}.w-8{width:2rem}.w-9{width:2.25rem}.w-\\[--sidebar-width\\]{width:var(--sidebar-width)}.w-\\[100px\\]{width:100px}.w-\\[1px\\]{width:1px}.w-auto{width:auto}.w-full{width:100%}.w-max{width:-moz-max-content;width:max-content}.w-px{width:1px}.min-w-0{min-width:0px}.min-w-10{min-width:2.5rem}.min-w-5{min-width:1.25rem}.min-w-8{min-width:2rem}.min-w-9{min-width:2.25rem}.min-w-\\[12rem\\]{min-width:12rem}.min-w-\\[8rem\\]{min-width:8rem}.min-w-\\[var\\(--radix-select-trigger-width\\)\\]{min-width:var(--radix-select-trigger-width)}.max-w-\\[--skeleton-width\\]{max-width:var(--skeleton-width)}.max-w-\\[180px\\]{max-width:180px}.max-w-lg{max-width:32rem}.max-w-max{max-width:-moz-max-content;max-width:max-content}.max-w-sm{max-width:24rem}.max-w-xs{max-width:20rem}.flex-1{flex:1 1 0%}.flex-\\[2\\]{flex:2}.flex-shrink-0,.shrink-0{flex-shrink:0}.grow{flex-grow:1}.grow-0{flex-grow:0}.basis-full{flex-basis:100%}.caption-bottom{caption-side:bottom}.border-collapse{border-collapse:collapse}.-translate-x-1\\/2{--tw-translate-x: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.-translate-x-px{--tw-translate-x: -1px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.-translate-y-1\\/2{--tw-translate-y: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-x-\\[-50\\%\\]{--tw-translate-x: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-x-px{--tw-translate-x: 1px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-y-\\[-50\\%\\]{--tw-translate-y: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.rotate-45{--tw-rotate: 45deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.rotate-90{--tw-rotate: 90deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.transform{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}@keyframes ping{75%,to{transform:scale(2);opacity:0}}.animate-ping{animation:ping 1s cubic-bezier(0,0,.2,1) infinite}@keyframes pulse{50%{opacity:.5}}.animate-pulse{animation:pulse 2s cubic-bezier(.4,0,.6,1) infinite}@keyframes spin{to{transform:rotate(360deg)}}.animate-spin{animation:spin 1s linear infinite}.cursor-default{cursor:default}.cursor-pointer{cursor:pointer}.touch-none{touch-action:none}.select-none{-webkit-user-select:none;-moz-user-select:none;user-select:none}.list-none{list-style-type:none}.grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.flex-row{flex-direction:row}.flex-col{flex-direction:column}.flex-col-reverse{flex-direction:column-reverse}.flex-wrap{flex-wrap:wrap}.items-start{align-items:flex-start}.items-end{align-items:flex-end}.items-center{align-items:center}.items-stretch{align-items:stretch}.justify-center{justify-content:center}.justify-between{justify-content:space-between}.gap-0\\.5{gap:.125rem}.gap-1{gap:.25rem}.gap-1\\.5{gap:.375rem}.gap-2{gap:.5rem}.gap-3{gap:.75rem}.gap-4{gap:1rem}.space-x-1>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(.25rem * var(--tw-space-x-reverse));margin-left:calc(.25rem * calc(1 - var(--tw-space-x-reverse)))}.space-x-4>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(1rem * var(--tw-space-x-reverse));margin-left:calc(1rem * calc(1 - var(--tw-space-x-reverse)))}.space-y-1>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.25rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.25rem * var(--tw-space-y-reverse))}.space-y-1\\.5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.375rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.375rem * var(--tw-space-y-reverse))}.space-y-2>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.5rem * var(--tw-space-y-reverse))}.space-y-3>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.75rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.75rem * var(--tw-space-y-reverse))}.space-y-4>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1rem * var(--tw-space-y-reverse))}.space-y-5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1.25rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1.25rem * var(--tw-space-y-reverse))}.divide-y>:not([hidden])~:not([hidden]){--tw-divide-y-reverse: 0;border-top-width:calc(1px * calc(1 - var(--tw-divide-y-reverse)));border-bottom-width:calc(1px * var(--tw-divide-y-reverse))}.divide-gray-800>:not([hidden])~:not([hidden]){--tw-divide-opacity: 1;border-color:rgb(31 41 55 / var(--tw-divide-opacity, 1))}.overflow-auto{overflow:auto}.overflow-hidden{overflow:hidden}.overflow-y-auto{overflow-y:auto}.overflow-x-hidden{overflow-x:hidden}.truncate{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.whitespace-nowrap{white-space:nowrap}.break-words{overflow-wrap:break-word}.rounded{border-radius:.25rem}.rounded-2xl{border-radius:1rem}.rounded-\\[15px\\]{border-radius:15px}.rounded-\\[2px\\]{border-radius:2px}.rounded-\\[inherit\\]{border-radius:inherit}.rounded-full{border-radius:9999px}.rounded-lg{border-radius:var(--radius)}.rounded-md{border-radius:calc(var(--radius) - 2px)}.rounded-sm{border-radius:calc(var(--radius) - 4px)}.rounded-xl{border-radius:.75rem}.rounded-t-\\[10px\\]{border-top-left-radius:10px;border-top-right-radius:10px}.rounded-tl-sm{border-top-left-radius:calc(var(--radius) - 4px)}.border{border-width:1px}.border-2{border-width:2px}.border-\\[1\\.5px\\]{border-width:1.5px}.border-y{border-top-width:1px;border-bottom-width:1px}.border-b{border-bottom-width:1px}.border-l{border-left-width:1px}.border-r{border-right-width:1px}.border-t{border-top-width:1px}.border-dashed{border-style:dashed}.border-\\[--color-border\\]{border-color:var(--color-border)}.border-blue-700{--tw-border-opacity: 1;border-color:rgb(29 78 216 / var(--tw-border-opacity, 1))}.border-border\\/50{border-color:hsl(var(--border) / .5)}.border-destructive{border-color:hsl(var(--destructive))}.border-destructive\\/50{border-color:hsl(var(--destructive) / .5)}.border-gray-700{--tw-border-opacity: 1;border-color:rgb(55 65 81 / var(--tw-border-opacity, 1))}.border-gray-800{--tw-border-opacity: 1;border-color:rgb(31 41 55 / var(--tw-border-opacity, 1))}.border-input{border-color:hsl(var(--input))}.border-primary{border-color:hsl(var(--primary))}.border-primary\\/50{border-color:hsl(var(--primary) / .5)}.border-sidebar-border{border-color:hsl(var(--sidebar-border))}.border-slate-600{--tw-border-opacity: 1;border-color:rgb(71 85 105 / var(--tw-border-opacity, 1))}.border-transparent{border-color:transparent}.border-white{--tw-border-opacity: 1;border-color:rgb(255 255 255 / var(--tw-border-opacity, 1))}.border-white\\/30{border-color:#ffffff4d}.border-l-transparent{border-left-color:transparent}.border-t-transparent{border-top-color:transparent}.border-t-white{--tw-border-opacity: 1;border-top-color:rgb(255 255 255 / var(--tw-border-opacity, 1))}.bg-\\[--color-bg\\]{background-color:var(--color-bg)}.bg-accent{background-color:hsl(var(--accent))}.bg-amber-500{--tw-bg-opacity: 1;background-color:rgb(245 158 11 / var(--tw-bg-opacity, 1))}.bg-background{background-color:hsl(var(--background))}.bg-black\\/40{background-color:#0006}.bg-black\\/70{background-color:#000000b3}.bg-black\\/80{background-color:#000c}.bg-blue-500{--tw-bg-opacity: 1;background-color:rgb(59 130 246 / var(--tw-bg-opacity, 1))}.bg-blue-600{--tw-bg-opacity: 1;background-color:rgb(37 99 235 / var(--tw-bg-opacity, 1))}.bg-blue-700{--tw-bg-opacity: 1;background-color:rgb(29 78 216 / var(--tw-bg-opacity, 1))}.bg-border{background-color:hsl(var(--border))}.bg-card{background-color:hsl(var(--card))}.bg-destructive{background-color:hsl(var(--destructive))}.bg-emerald-500{--tw-bg-opacity: 1;background-color:rgb(16 185 129 / var(--tw-bg-opacity, 1))}.bg-emerald-600{--tw-bg-opacity: 1;background-color:rgb(5 150 105 / var(--tw-bg-opacity, 1))}.bg-foreground{background-color:hsl(var(--foreground))}.bg-gray-700{--tw-bg-opacity: 1;background-color:rgb(55 65 81 / var(--tw-bg-opacity, 1))}.bg-gray-800{--tw-bg-opacity: 1;background-color:rgb(31 41 55 / var(--tw-bg-opacity, 1))}.bg-gray-900{--tw-bg-opacity: 1;background-color:rgb(17 24 39 / var(--tw-bg-opacity, 1))}.bg-green-400{--tw-bg-opacity: 1;background-color:rgb(74 222 128 / var(--tw-bg-opacity, 1))}.bg-green-400\\/20{background-color:#4ade8033}.bg-green-500{--tw-bg-opacity: 1;background-color:rgb(34 197 94 / var(--tw-bg-opacity, 1))}.bg-green-600{--tw-bg-opacity: 1;background-color:rgb(22 163 74 / var(--tw-bg-opacity, 1))}.bg-muted{background-color:hsl(var(--muted))}.bg-muted\\/50{background-color:hsl(var(--muted) / .5)}.bg-orange-500{--tw-bg-opacity: 1;background-color:rgb(249 115 22 / var(--tw-bg-opacity, 1))}.bg-popover{background-color:hsl(var(--popover))}.bg-primary{background-color:hsl(var(--primary))}.bg-primary\\/10{background-color:hsl(var(--primary) / .1)}.bg-primary\\/20{background-color:hsl(var(--primary) / .2)}.bg-purple-600{--tw-bg-opacity: 1;background-color:rgb(147 51 234 / var(--tw-bg-opacity, 1))}.bg-purple-700{--tw-bg-opacity: 1;background-color:rgb(126 34 206 / var(--tw-bg-opacity, 1))}.bg-red-500{--tw-bg-opacity: 1;background-color:rgb(239 68 68 / var(--tw-bg-opacity, 1))}.bg-secondary{background-color:hsl(var(--secondary))}.bg-sidebar{background-color:hsl(var(--sidebar-background))}.bg-sidebar-border{background-color:hsl(var(--sidebar-border))}.bg-slate-500{--tw-bg-opacity: 1;background-color:rgb(100 116 139 / var(--tw-bg-opacity, 1))}.bg-slate-800{--tw-bg-opacity: 1;background-color:rgb(30 41 59 / var(--tw-bg-opacity, 1))}.bg-transparent{background-color:transparent}.bg-white\\/10{background-color:#ffffff1a}.bg-white\\/20{background-color:#fff3}.bg-gradient-to-r{background-image:linear-gradient(to right,var(--tw-gradient-stops))}.from-blue-600{--tw-gradient-from: #2563eb var(--tw-gradient-from-position);--tw-gradient-to: rgb(37 99 235 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-blue-700{--tw-gradient-from: #1d4ed8 var(--tw-gradient-from-position);--tw-gradient-to: rgb(29 78 216 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-blue-900{--tw-gradient-from: #1e3a8a var(--tw-gradient-from-position);--tw-gradient-to: rgb(30 58 138 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-purple-700{--tw-gradient-from: #7e22ce var(--tw-gradient-from-position);--tw-gradient-to: rgb(126 34 206 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.to-blue-600{--tw-gradient-to: #2563eb var(--tw-gradient-to-position)}.to-blue-700{--tw-gradient-to: #1d4ed8 var(--tw-gradient-to-position)}.to-blue-800{--tw-gradient-to: #1e40af var(--tw-gradient-to-position)}.to-purple-600{--tw-gradient-to: #9333ea var(--tw-gradient-to-position)}.fill-current{fill:currentColor}.fill-primary{fill:hsl(var(--primary))}.p-0{padding:0}.p-1{padding:.25rem}.p-2{padding:.5rem}.p-3{padding:.75rem}.p-4{padding:1rem}.p-6{padding:1.5rem}.p-\\[1px\\]{padding:1px}.px-1{padding-left:.25rem;padding-right:.25rem}.px-1\\.5{padding-left:.375rem;padding-right:.375rem}.px-2{padding-left:.5rem;padding-right:.5rem}.px-2\\.5{padding-left:.625rem;padding-right:.625rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-4{padding-left:1rem;padding-right:1rem}.px-5{padding-left:1.25rem;padding-right:1.25rem}.px-8{padding-left:2rem;padding-right:2rem}.py-0\\.5{padding-top:.125rem;padding-bottom:.125rem}.py-1{padding-top:.25rem;padding-bottom:.25rem}.py-1\\.5{padding-top:.375rem;padding-bottom:.375rem}.py-2{padding-top:.5rem;padding-bottom:.5rem}.py-2\\.5{padding-top:.625rem;padding-bottom:.625rem}.py-3{padding-top:.75rem;padding-bottom:.75rem}.py-4{padding-top:1rem;padding-bottom:1rem}.py-6{padding-top:1.5rem;padding-bottom:1.5rem}.py-8{padding-top:2rem;padding-bottom:2rem}.pb-2{padding-bottom:.5rem}.pb-3{padding-bottom:.75rem}.pb-4{padding-bottom:1rem}.pl-2{padding-left:.5rem}.pl-2\\.5{padding-left:.625rem}.pl-4{padding-left:1rem}.pl-8{padding-left:2rem}.pr-2{padding-right:.5rem}.pr-2\\.5{padding-right:.625rem}.pr-8{padding-right:2rem}.pt-0{padding-top:0}.pt-1{padding-top:.25rem}.pt-3{padding-top:.75rem}.pt-4{padding-top:1rem}.text-left{text-align:left}.text-center{text-align:center}.align-middle{vertical-align:middle}.font-mono{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace}.text-\\[0\\.8rem\\]{font-size:.8rem}.text-\\[10px\\]{font-size:10px}.text-\\[9px\\]{font-size:9px}.text-base{font-size:1rem;line-height:1.5rem}.text-lg{font-size:1.125rem;line-height:1.75rem}.text-sm{font-size:.875rem;line-height:1.25rem}.text-xl{font-size:1.25rem;line-height:1.75rem}.text-xs{font-size:.75rem;line-height:1rem}.font-bold{font-weight:700}.font-light{font-weight:300}.font-medium{font-weight:500}.font-normal{font-weight:400}.font-semibold{font-weight:600}.uppercase{text-transform:uppercase}.tabular-nums{--tw-numeric-spacing: tabular-nums;font-variant-numeric:var(--tw-ordinal) var(--tw-slashed-zero) var(--tw-numeric-figure) var(--tw-numeric-spacing) var(--tw-numeric-fraction)}.leading-none{line-height:1}.tracking-tight{letter-spacing:-.025em}.tracking-wider{letter-spacing:.05em}.tracking-widest{letter-spacing:.1em}.text-accent-foreground{color:hsl(var(--accent-foreground))}.text-amber-400{--tw-text-opacity: 1;color:rgb(251 191 36 / var(--tw-text-opacity, 1))}.text-blue-200{--tw-text-opacity: 1;color:rgb(191 219 254 / var(--tw-text-opacity, 1))}.text-blue-300{--tw-text-opacity: 1;color:rgb(147 197 253 / var(--tw-text-opacity, 1))}.text-blue-400{--tw-text-opacity: 1;color:rgb(96 165 250 / var(--tw-text-opacity, 1))}.text-card-foreground{color:hsl(var(--card-foreground))}.text-current{color:currentColor}.text-destructive{color:hsl(var(--destructive))}.text-destructive-foreground{color:hsl(var(--destructive-foreground))}.text-emerald-400{--tw-text-opacity: 1;color:rgb(52 211 153 / var(--tw-text-opacity, 1))}.text-foreground{color:hsl(var(--foreground))}.text-foreground\\/50{color:hsl(var(--foreground) / .5)}.text-gray-300{--tw-text-opacity: 1;color:rgb(209 213 219 / var(--tw-text-opacity, 1))}.text-gray-400{--tw-text-opacity: 1;color:rgb(156 163 175 / var(--tw-text-opacity, 1))}.text-gray-500{--tw-text-opacity: 1;color:rgb(107 114 128 / var(--tw-text-opacity, 1))}.text-gray-600{--tw-text-opacity: 1;color:rgb(75 85 99 / var(--tw-text-opacity, 1))}.text-green-400{--tw-text-opacity: 1;color:rgb(74 222 128 / var(--tw-text-opacity, 1))}.text-muted-foreground{color:hsl(var(--muted-foreground))}.text-popover-foreground{color:hsl(var(--popover-foreground))}.text-primary{color:hsl(var(--primary))}.text-primary-foreground{color:hsl(var(--primary-foreground))}.text-purple-200{--tw-text-opacity: 1;color:rgb(233 213 255 / var(--tw-text-opacity, 1))}.text-purple-300{--tw-text-opacity: 1;color:rgb(216 180 254 / var(--tw-text-opacity, 1))}.text-purple-400{--tw-text-opacity: 1;color:rgb(192 132 252 / var(--tw-text-opacity, 1))}.text-red-400{--tw-text-opacity: 1;color:rgb(248 113 113 / var(--tw-text-opacity, 1))}.text-secondary-foreground{color:hsl(var(--secondary-foreground))}.text-sidebar-foreground{color:hsl(var(--sidebar-foreground))}.text-sidebar-foreground\\/70{color:hsl(var(--sidebar-foreground) / .7)}.text-slate-300{--tw-text-opacity: 1;color:rgb(203 213 225 / var(--tw-text-opacity, 1))}.text-slate-400{--tw-text-opacity: 1;color:rgb(148 163 184 / var(--tw-text-opacity, 1))}.text-slate-500{--tw-text-opacity: 1;color:rgb(100 116 139 / var(--tw-text-opacity, 1))}.text-white{--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1))}.text-yellow-400{--tw-text-opacity: 1;color:rgb(250 204 21 / var(--tw-text-opacity, 1))}.underline-offset-4{text-underline-offset:4px}.placeholder-gray-500::-moz-placeholder{--tw-placeholder-opacity: 1;color:rgb(107 114 128 / var(--tw-placeholder-opacity, 1))}.placeholder-gray-500::placeholder{--tw-placeholder-opacity: 1;color:rgb(107 114 128 / var(--tw-placeholder-opacity, 1))}.opacity-0{opacity:0}.opacity-50{opacity:.5}.opacity-60{opacity:.6}.opacity-70{opacity:.7}.opacity-90{opacity:.9}.shadow{--tw-shadow: 0 1px 3px 0 rgb(0 0 0 / .1), 0 1px 2px -1px rgb(0 0 0 / .1);--tw-shadow-colored: 0 1px 3px 0 var(--tw-shadow-color), 0 1px 2px -1px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-2xl{--tw-shadow: 0 25px 50px -12px rgb(0 0 0 / .25);--tw-shadow-colored: 0 25px 50px -12px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-\\[0_0_0_1px_hsl\\(var\\(--sidebar-border\\)\\)\\]{--tw-shadow: 0 0 0 1px hsl(var(--sidebar-border));--tw-shadow-colored: 0 0 0 1px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-lg{--tw-shadow: 0 10px 15px -3px rgb(0 0 0 / .1), 0 4px 6px -4px rgb(0 0 0 / .1);--tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-md{--tw-shadow: 0 4px 6px -1px rgb(0 0 0 / .1), 0 2px 4px -2px rgb(0 0 0 / .1);--tw-shadow-colored: 0 4px 6px -1px var(--tw-shadow-color), 0 2px 4px -2px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-none{--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-sm{--tw-shadow: 0 1px 2px 0 rgb(0 0 0 / .05);--tw-shadow-colored: 0 1px 2px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-xl{--tw-shadow: 0 20px 25px -5px rgb(0 0 0 / .1), 0 8px 10px -6px rgb(0 0 0 / .1);--tw-shadow-colored: 0 20px 25px -5px var(--tw-shadow-color), 0 8px 10px -6px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-green-500\\/30{--tw-shadow-color: rgb(34 197 94 / .3);--tw-shadow: var(--tw-shadow-colored)}.shadow-red-500\\/30{--tw-shadow-color: rgb(239 68 68 / .3);--tw-shadow: var(--tw-shadow-colored)}.outline-none{outline:2px solid transparent;outline-offset:2px}.outline{outline-style:solid}.ring{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(3px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.ring-0{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(0px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.ring-1{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.ring-ring{--tw-ring-color: hsl(var(--ring))}.ring-sidebar-ring{--tw-ring-color: hsl(var(--sidebar-ring))}.ring-offset-background{--tw-ring-offset-color: hsl(var(--background))}.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.backdrop-blur-sm{--tw-backdrop-blur: blur(4px);-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.transition{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-\\[height\\]{transition-property:height;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-\\[left\\,right\\,width\\]{transition-property:left,right,width;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-\\[margin\\,opacity\\]{transition-property:margin,opacity;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-\\[width\\,height\\,padding\\]{transition-property:width,height,padding;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-\\[width\\]{transition-property:width;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-all{transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-colors{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-opacity{transition-property:opacity;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-transform{transition-property:transform;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.duration-1000{transition-duration:1s}.duration-200{transition-duration:.2s}.duration-300{transition-duration:.3s}.ease-in-out{transition-timing-function:cubic-bezier(.4,0,.2,1)}.ease-linear{transition-timing-function:linear}@keyframes enter{0%{opacity:var(--tw-enter-opacity, 1);transform:translate3d(var(--tw-enter-translate-x, 0),var(--tw-enter-translate-y, 0),0) scale3d(var(--tw-enter-scale, 1),var(--tw-enter-scale, 1),var(--tw-enter-scale, 1)) rotate(var(--tw-enter-rotate, 0))}}@keyframes exit{to{opacity:var(--tw-exit-opacity, 1);transform:translate3d(var(--tw-exit-translate-x, 0),var(--tw-exit-translate-y, 0),0) scale3d(var(--tw-exit-scale, 1),var(--tw-exit-scale, 1),var(--tw-exit-scale, 1)) rotate(var(--tw-exit-rotate, 0))}}.animate-in{animation-name:enter;animation-duration:.15s;--tw-enter-opacity: initial;--tw-enter-scale: initial;--tw-enter-rotate: initial;--tw-enter-translate-x: initial;--tw-enter-translate-y: initial}.fade-in-0{--tw-enter-opacity: 0}.zoom-in-95{--tw-enter-scale: .95}.duration-1000{animation-duration:1s}.duration-200{animation-duration:.2s}.duration-300{animation-duration:.3s}.ease-in-out{animation-timing-function:cubic-bezier(.4,0,.2,1)}.ease-linear{animation-timing-function:linear}.file\\:border-0::file-selector-button{border-width:0px}.file\\:bg-transparent::file-selector-button{background-color:transparent}.file\\:text-sm::file-selector-button{font-size:.875rem;line-height:1.25rem}.file\\:font-medium::file-selector-button{font-weight:500}.file\\:text-foreground::file-selector-button{color:hsl(var(--foreground))}.placeholder\\:text-muted-foreground::-moz-placeholder{color:hsl(var(--muted-foreground))}.placeholder\\:text-muted-foreground::placeholder{color:hsl(var(--muted-foreground))}.after\\:absolute:after{content:var(--tw-content);position:absolute}.after\\:-inset-2:after{content:var(--tw-content);top:-.5rem;right:-.5rem;bottom:-.5rem;left:-.5rem}.after\\:inset-y-0:after{content:var(--tw-content);top:0;bottom:0}.after\\:left-1\\/2:after{content:var(--tw-content);left:50%}.after\\:w-1:after{content:var(--tw-content);width:.25rem}.after\\:w-\\[2px\\]:after{content:var(--tw-content);width:2px}.after\\:-translate-x-1\\/2:after{content:var(--tw-content);--tw-translate-x: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.first\\:rounded-l-md:first-child{border-top-left-radius:calc(var(--radius) - 2px);border-bottom-left-radius:calc(var(--radius) - 2px)}.first\\:border-l:first-child{border-left-width:1px}.last\\:rounded-r-md:last-child{border-top-right-radius:calc(var(--radius) - 2px);border-bottom-right-radius:calc(var(--radius) - 2px)}.focus-within\\:relative:focus-within{position:relative}.focus-within\\:z-20:focus-within{z-index:20}.hover\\:bg-accent:hover{background-color:hsl(var(--accent))}.hover\\:bg-blue-600:hover{--tw-bg-opacity: 1;background-color:rgb(37 99 235 / var(--tw-bg-opacity, 1))}.hover\\:bg-blue-700:hover{--tw-bg-opacity: 1;background-color:rgb(29 78 216 / var(--tw-bg-opacity, 1))}.hover\\:bg-destructive\\/80:hover{background-color:hsl(var(--destructive) / .8)}.hover\\:bg-destructive\\/90:hover{background-color:hsl(var(--destructive) / .9)}.hover\\:bg-emerald-500:hover{--tw-bg-opacity: 1;background-color:rgb(16 185 129 / var(--tw-bg-opacity, 1))}.hover\\:bg-gray-600:hover{--tw-bg-opacity: 1;background-color:rgb(75 85 99 / var(--tw-bg-opacity, 1))}.hover\\:bg-gray-700:hover{--tw-bg-opacity: 1;background-color:rgb(55 65 81 / var(--tw-bg-opacity, 1))}.hover\\:bg-green-600:hover{--tw-bg-opacity: 1;background-color:rgb(22 163 74 / var(--tw-bg-opacity, 1))}.hover\\:bg-green-700:hover{--tw-bg-opacity: 1;background-color:rgb(21 128 61 / var(--tw-bg-opacity, 1))}.hover\\:bg-muted:hover{background-color:hsl(var(--muted))}.hover\\:bg-muted\\/50:hover{background-color:hsl(var(--muted) / .5)}.hover\\:bg-orange-600:hover{--tw-bg-opacity: 1;background-color:rgb(234 88 12 / var(--tw-bg-opacity, 1))}.hover\\:bg-primary:hover{background-color:hsl(var(--primary))}.hover\\:bg-primary\\/80:hover{background-color:hsl(var(--primary) / .8)}.hover\\:bg-primary\\/90:hover{background-color:hsl(var(--primary) / .9)}.hover\\:bg-purple-600:hover{--tw-bg-opacity: 1;background-color:rgb(147 51 234 / var(--tw-bg-opacity, 1))}.hover\\:bg-purple-700:hover{--tw-bg-opacity: 1;background-color:rgb(126 34 206 / var(--tw-bg-opacity, 1))}.hover\\:bg-red-600:hover{--tw-bg-opacity: 1;background-color:rgb(220 38 38 / var(--tw-bg-opacity, 1))}.hover\\:bg-secondary:hover{background-color:hsl(var(--secondary))}.hover\\:bg-secondary\\/80:hover{background-color:hsl(var(--secondary) / .8)}.hover\\:bg-sidebar-accent:hover{background-color:hsl(var(--sidebar-accent))}.hover\\:bg-white\\/5:hover{background-color:#ffffff0d}.hover\\:text-accent-foreground:hover{color:hsl(var(--accent-foreground))}.hover\\:text-foreground:hover{color:hsl(var(--foreground))}.hover\\:text-gray-300:hover{--tw-text-opacity: 1;color:rgb(209 213 219 / var(--tw-text-opacity, 1))}.hover\\:text-muted-foreground:hover{color:hsl(var(--muted-foreground))}.hover\\:text-primary-foreground:hover{color:hsl(var(--primary-foreground))}.hover\\:text-red-400:hover{--tw-text-opacity: 1;color:rgb(248 113 113 / var(--tw-text-opacity, 1))}.hover\\:text-sidebar-accent-foreground:hover{color:hsl(var(--sidebar-accent-foreground))}.hover\\:text-slate-300:hover{--tw-text-opacity: 1;color:rgb(203 213 225 / var(--tw-text-opacity, 1))}.hover\\:text-white:hover{--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1))}.hover\\:underline:hover{text-decoration-line:underline}.hover\\:opacity-100:hover{opacity:1}.hover\\:shadow-\\[0_0_0_1px_hsl\\(var\\(--sidebar-accent\\)\\)\\]:hover{--tw-shadow: 0 0 0 1px hsl(var(--sidebar-accent));--tw-shadow-colored: 0 0 0 1px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.hover\\:brightness-110:hover{--tw-brightness: brightness(1.1);filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.hover\\:after\\:bg-sidebar-border:hover:after{content:var(--tw-content);background-color:hsl(var(--sidebar-border))}.focus\\:border-blue-500:focus{--tw-border-opacity: 1;border-color:rgb(59 130 246 / var(--tw-border-opacity, 1))}.focus\\:border-purple-500:focus{--tw-border-opacity: 1;border-color:rgb(168 85 247 / var(--tw-border-opacity, 1))}.focus\\:bg-accent:focus{background-color:hsl(var(--accent))}.focus\\:bg-primary:focus{background-color:hsl(var(--primary))}.focus\\:text-accent-foreground:focus{color:hsl(var(--accent-foreground))}.focus\\:text-primary-foreground:focus{color:hsl(var(--primary-foreground))}.focus\\:opacity-100:focus{opacity:1}.focus\\:outline-none:focus{outline:2px solid transparent;outline-offset:2px}.focus\\:ring-1:focus{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus\\:ring-2:focus{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus\\:ring-ring:focus{--tw-ring-color: hsl(var(--ring))}.focus\\:ring-offset-2:focus{--tw-ring-offset-width: 2px}.focus-visible\\:outline-none:focus-visible{outline:2px solid transparent;outline-offset:2px}.focus-visible\\:ring-1:focus-visible{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus-visible\\:ring-2:focus-visible{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus-visible\\:ring-ring:focus-visible{--tw-ring-color: hsl(var(--ring))}.focus-visible\\:ring-sidebar-ring:focus-visible{--tw-ring-color: hsl(var(--sidebar-ring))}.focus-visible\\:ring-offset-1:focus-visible{--tw-ring-offset-width: 1px}.focus-visible\\:ring-offset-2:focus-visible{--tw-ring-offset-width: 2px}.focus-visible\\:ring-offset-background:focus-visible{--tw-ring-offset-color: hsl(var(--background))}.active\\:bg-gray-600:active{--tw-bg-opacity: 1;background-color:rgb(75 85 99 / var(--tw-bg-opacity, 1))}.active\\:bg-sidebar-accent:active{background-color:hsl(var(--sidebar-accent))}.active\\:text-sidebar-accent-foreground:active{color:hsl(var(--sidebar-accent-foreground))}.disabled\\:pointer-events-none:disabled{pointer-events:none}.disabled\\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\\:bg-gray-700:disabled{--tw-bg-opacity: 1;background-color:rgb(55 65 81 / var(--tw-bg-opacity, 1))}.disabled\\:text-gray-500:disabled{--tw-text-opacity: 1;color:rgb(107 114 128 / var(--tw-text-opacity, 1))}.disabled\\:opacity-30:disabled{opacity:.3}.disabled\\:opacity-40:disabled{opacity:.4}.disabled\\:opacity-50:disabled{opacity:.5}.disabled\\:shadow-none:disabled{--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.group\\/menu-item:focus-within .group-focus-within\\/menu-item\\:opacity-100{opacity:1}.group\\/menu-item:hover .group-hover\\/menu-item\\:opacity-100,.group:hover .group-hover\\:opacity-100{opacity:1}.group.destructive .group-\\[\\.destructive\\]\\:border-muted\\/40{border-color:hsl(var(--muted) / .4)}.group.toaster .group-\\[\\.toaster\\]\\:border-border{border-color:hsl(var(--border))}.group.toast .group-\\[\\.toast\\]\\:bg-muted{background-color:hsl(var(--muted))}.group.toast .group-\\[\\.toast\\]\\:bg-primary{background-color:hsl(var(--primary))}.group.toaster .group-\\[\\.toaster\\]\\:bg-background{background-color:hsl(var(--background))}.group.destructive .group-\\[\\.destructive\\]\\:text-red-300{--tw-text-opacity: 1;color:rgb(252 165 165 / var(--tw-text-opacity, 1))}.group.toast .group-\\[\\.toast\\]\\:text-muted-foreground{color:hsl(var(--muted-foreground))}.group.toast .group-\\[\\.toast\\]\\:text-primary-foreground{color:hsl(var(--primary-foreground))}.group.toaster .group-\\[\\.toaster\\]\\:text-foreground{color:hsl(var(--foreground))}.group.toaster .group-\\[\\.toaster\\]\\:shadow-lg{--tw-shadow: 0 10px 15px -3px rgb(0 0 0 / .1), 0 4px 6px -4px rgb(0 0 0 / .1);--tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.group.destructive .group-\\[\\.destructive\\]\\:hover\\:border-destructive\\/30:hover{border-color:hsl(var(--destructive) / .3)}.group.destructive .group-\\[\\.destructive\\]\\:hover\\:bg-destructive:hover{background-color:hsl(var(--destructive))}.group.destructive .group-\\[\\.destructive\\]\\:hover\\:text-destructive-foreground:hover{color:hsl(var(--destructive-foreground))}.group.destructive .group-\\[\\.destructive\\]\\:hover\\:text-red-50:hover{--tw-text-opacity: 1;color:rgb(254 242 242 / var(--tw-text-opacity, 1))}.group.destructive .group-\\[\\.destructive\\]\\:focus\\:ring-destructive:focus{--tw-ring-color: hsl(var(--destructive))}.group.destructive .group-\\[\\.destructive\\]\\:focus\\:ring-red-400:focus{--tw-ring-opacity: 1;--tw-ring-color: rgb(248 113 113 / var(--tw-ring-opacity, 1))}.group.destructive .group-\\[\\.destructive\\]\\:focus\\:ring-offset-red-600:focus{--tw-ring-offset-color: #dc2626}.peer\\/menu-button:hover~.peer-hover\\/menu-button\\:text-sidebar-accent-foreground{color:hsl(var(--sidebar-accent-foreground))}.peer:disabled~.peer-disabled\\:cursor-not-allowed{cursor:not-allowed}.peer:disabled~.peer-disabled\\:opacity-70{opacity:.7}.has-\\[\\[data-variant\\=inset\\]\\]\\:bg-sidebar:has([data-variant=inset]){background-color:hsl(var(--sidebar-background))}.has-\\[\\:disabled\\]\\:opacity-50:has(:disabled){opacity:.5}.group\\/menu-item:has([data-sidebar=menu-action]) .group-has-\\[\\[data-sidebar\\=menu-action\\]\\]\\/menu-item\\:pr-8{padding-right:2rem}.aria-disabled\\:pointer-events-none[aria-disabled=true]{pointer-events:none}.aria-disabled\\:opacity-50[aria-disabled=true]{opacity:.5}.aria-selected\\:bg-accent[aria-selected=true]{background-color:hsl(var(--accent))}.aria-selected\\:bg-accent\\/50[aria-selected=true]{background-color:hsl(var(--accent) / .5)}.aria-selected\\:text-accent-foreground[aria-selected=true]{color:hsl(var(--accent-foreground))}.aria-selected\\:text-muted-foreground[aria-selected=true]{color:hsl(var(--muted-foreground))}.aria-selected\\:opacity-100[aria-selected=true]{opacity:1}.data-\\[disabled\\=true\\]\\:pointer-events-none[data-disabled=true],.data-\\[disabled\\]\\:pointer-events-none[data-disabled]{pointer-events:none}.data-\\[panel-group-direction\\=vertical\\]\\:h-px[data-panel-group-direction=vertical]{height:1px}.data-\\[panel-group-direction\\=vertical\\]\\:w-full[data-panel-group-direction=vertical]{width:100%}.data-\\[side\\=bottom\\]\\:translate-y-1[data-side=bottom]{--tw-translate-y: .25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\\[side\\=left\\]\\:-translate-x-1[data-side=left]{--tw-translate-x: -.25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\\[side\\=right\\]\\:translate-x-1[data-side=right]{--tw-translate-x: .25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\\[side\\=top\\]\\:-translate-y-1[data-side=top]{--tw-translate-y: -.25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\\[state\\=checked\\]\\:translate-x-4[data-state=checked]{--tw-translate-x: 1rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\\[state\\=unchecked\\]\\:translate-x-0[data-state=unchecked],.data-\\[swipe\\=cancel\\]\\:translate-x-0[data-swipe=cancel]{--tw-translate-x: 0px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\\[swipe\\=end\\]\\:translate-x-\\[var\\(--radix-toast-swipe-end-x\\)\\][data-swipe=end]{--tw-translate-x: var(--radix-toast-swipe-end-x);transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\\[swipe\\=move\\]\\:translate-x-\\[var\\(--radix-toast-swipe-move-x\\)\\][data-swipe=move]{--tw-translate-x: var(--radix-toast-swipe-move-x);transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}@keyframes accordion-up{0%{height:var(--radix-accordion-content-height)}to{height:0}}.data-\\[state\\=closed\\]\\:animate-accordion-up[data-state=closed]{animation:accordion-up .2s ease-out}@keyframes accordion-down{0%{height:0}to{height:var(--radix-accordion-content-height)}}.data-\\[state\\=open\\]\\:animate-accordion-down[data-state=open]{animation:accordion-down .2s ease-out}.data-\\[panel-group-direction\\=vertical\\]\\:flex-col[data-panel-group-direction=vertical]{flex-direction:column}.data-\\[active\\=true\\]\\:bg-sidebar-accent[data-active=true]{background-color:hsl(var(--sidebar-accent))}.data-\\[active\\]\\:bg-accent\\/50[data-active]{background-color:hsl(var(--accent) / .5)}.data-\\[selected\\=true\\]\\:bg-accent[data-selected=true]{background-color:hsl(var(--accent))}.data-\\[state\\=active\\]\\:bg-background[data-state=active]{background-color:hsl(var(--background))}.data-\\[state\\=checked\\]\\:bg-primary[data-state=checked]{background-color:hsl(var(--primary))}.data-\\[state\\=on\\]\\:bg-accent[data-state=on],.data-\\[state\\=open\\]\\:bg-accent[data-state=open]{background-color:hsl(var(--accent))}.data-\\[state\\=open\\]\\:bg-accent\\/50[data-state=open]{background-color:hsl(var(--accent) / .5)}.data-\\[state\\=open\\]\\:bg-secondary[data-state=open]{background-color:hsl(var(--secondary))}.data-\\[state\\=selected\\]\\:bg-muted[data-state=selected]{background-color:hsl(var(--muted))}.data-\\[state\\=unchecked\\]\\:bg-input[data-state=unchecked]{background-color:hsl(var(--input))}.data-\\[active\\=true\\]\\:font-medium[data-active=true]{font-weight:500}.data-\\[active\\=true\\]\\:text-sidebar-accent-foreground[data-active=true]{color:hsl(var(--sidebar-accent-foreground))}.data-\\[placeholder\\]\\:text-muted-foreground[data-placeholder]{color:hsl(var(--muted-foreground))}.data-\\[selected\\=true\\]\\:text-accent-foreground[data-selected=true]{color:hsl(var(--accent-foreground))}.data-\\[state\\=active\\]\\:text-foreground[data-state=active]{color:hsl(var(--foreground))}.data-\\[state\\=checked\\]\\:text-primary-foreground[data-state=checked]{color:hsl(var(--primary-foreground))}.data-\\[state\\=on\\]\\:text-accent-foreground[data-state=on],.data-\\[state\\=open\\]\\:text-accent-foreground[data-state=open]{color:hsl(var(--accent-foreground))}.data-\\[state\\=open\\]\\:text-muted-foreground[data-state=open]{color:hsl(var(--muted-foreground))}.data-\\[disabled\\=true\\]\\:opacity-50[data-disabled=true],.data-\\[disabled\\]\\:opacity-50[data-disabled]{opacity:.5}.data-\\[state\\=open\\]\\:opacity-100[data-state=open]{opacity:1}.data-\\[state\\=active\\]\\:shadow[data-state=active]{--tw-shadow: 0 1px 3px 0 rgb(0 0 0 / .1), 0 1px 2px -1px rgb(0 0 0 / .1);--tw-shadow-colored: 0 1px 3px 0 var(--tw-shadow-color), 0 1px 2px -1px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.data-\\[swipe\\=move\\]\\:transition-none[data-swipe=move]{transition-property:none}.data-\\[state\\=closed\\]\\:duration-300[data-state=closed]{transition-duration:.3s}.data-\\[state\\=open\\]\\:duration-500[data-state=open]{transition-duration:.5s}.data-\\[motion\\^\\=from-\\]\\:animate-in[data-motion^=from-],.data-\\[state\\=open\\]\\:animate-in[data-state=open],.data-\\[state\\=visible\\]\\:animate-in[data-state=visible]{animation-name:enter;animation-duration:.15s;--tw-enter-opacity: initial;--tw-enter-scale: initial;--tw-enter-rotate: initial;--tw-enter-translate-x: initial;--tw-enter-translate-y: initial}.data-\\[motion\\^\\=to-\\]\\:animate-out[data-motion^=to-],.data-\\[state\\=closed\\]\\:animate-out[data-state=closed],.data-\\[state\\=hidden\\]\\:animate-out[data-state=hidden],.data-\\[swipe\\=end\\]\\:animate-out[data-swipe=end]{animation-name:exit;animation-duration:.15s;--tw-exit-opacity: initial;--tw-exit-scale: initial;--tw-exit-rotate: initial;--tw-exit-translate-x: initial;--tw-exit-translate-y: initial}.data-\\[motion\\^\\=from-\\]\\:fade-in[data-motion^=from-]{--tw-enter-opacity: 0}.data-\\[motion\\^\\=to-\\]\\:fade-out[data-motion^=to-],.data-\\[state\\=closed\\]\\:fade-out-0[data-state=closed]{--tw-exit-opacity: 0}.data-\\[state\\=closed\\]\\:fade-out-80[data-state=closed]{--tw-exit-opacity: .8}.data-\\[state\\=hidden\\]\\:fade-out[data-state=hidden]{--tw-exit-opacity: 0}.data-\\[state\\=open\\]\\:fade-in-0[data-state=open],.data-\\[state\\=visible\\]\\:fade-in[data-state=visible]{--tw-enter-opacity: 0}.data-\\[state\\=closed\\]\\:zoom-out-95[data-state=closed]{--tw-exit-scale: .95}.data-\\[state\\=open\\]\\:zoom-in-90[data-state=open]{--tw-enter-scale: .9}.data-\\[state\\=open\\]\\:zoom-in-95[data-state=open]{--tw-enter-scale: .95}.data-\\[motion\\=from-end\\]\\:slide-in-from-right-52[data-motion=from-end]{--tw-enter-translate-x: 13rem}.data-\\[motion\\=from-start\\]\\:slide-in-from-left-52[data-motion=from-start]{--tw-enter-translate-x: -13rem}.data-\\[motion\\=to-end\\]\\:slide-out-to-right-52[data-motion=to-end]{--tw-exit-translate-x: 13rem}.data-\\[motion\\=to-start\\]\\:slide-out-to-left-52[data-motion=to-start]{--tw-exit-translate-x: -13rem}.data-\\[side\\=bottom\\]\\:slide-in-from-top-2[data-side=bottom]{--tw-enter-translate-y: -.5rem}.data-\\[side\\=left\\]\\:slide-in-from-right-2[data-side=left]{--tw-enter-translate-x: .5rem}.data-\\[side\\=right\\]\\:slide-in-from-left-2[data-side=right]{--tw-enter-translate-x: -.5rem}.data-\\[side\\=top\\]\\:slide-in-from-bottom-2[data-side=top]{--tw-enter-translate-y: .5rem}.data-\\[state\\=closed\\]\\:slide-out-to-bottom[data-state=closed]{--tw-exit-translate-y: 100%}.data-\\[state\\=closed\\]\\:slide-out-to-left[data-state=closed]{--tw-exit-translate-x: -100%}.data-\\[state\\=closed\\]\\:slide-out-to-left-1\\/2[data-state=closed]{--tw-exit-translate-x: -50%}.data-\\[state\\=closed\\]\\:slide-out-to-right[data-state=closed],.data-\\[state\\=closed\\]\\:slide-out-to-right-full[data-state=closed]{--tw-exit-translate-x: 100%}.data-\\[state\\=closed\\]\\:slide-out-to-top[data-state=closed]{--tw-exit-translate-y: -100%}.data-\\[state\\=closed\\]\\:slide-out-to-top-\\[48\\%\\][data-state=closed]{--tw-exit-translate-y: -48%}.data-\\[state\\=open\\]\\:slide-in-from-bottom[data-state=open]{--tw-enter-translate-y: 100%}.data-\\[state\\=open\\]\\:slide-in-from-left[data-state=open]{--tw-enter-translate-x: -100%}.data-\\[state\\=open\\]\\:slide-in-from-left-1\\/2[data-state=open]{--tw-enter-translate-x: -50%}.data-\\[state\\=open\\]\\:slide-in-from-right[data-state=open]{--tw-enter-translate-x: 100%}.data-\\[state\\=open\\]\\:slide-in-from-top[data-state=open]{--tw-enter-translate-y: -100%}.data-\\[state\\=open\\]\\:slide-in-from-top-\\[48\\%\\][data-state=open]{--tw-enter-translate-y: -48%}.data-\\[state\\=open\\]\\:slide-in-from-top-full[data-state=open]{--tw-enter-translate-y: -100%}.data-\\[state\\=closed\\]\\:duration-300[data-state=closed]{animation-duration:.3s}.data-\\[state\\=open\\]\\:duration-500[data-state=open]{animation-duration:.5s}.data-\\[panel-group-direction\\=vertical\\]\\:after\\:left-0[data-panel-group-direction=vertical]:after{content:var(--tw-content);left:0}.data-\\[panel-group-direction\\=vertical\\]\\:after\\:h-1[data-panel-group-direction=vertical]:after{content:var(--tw-content);height:.25rem}.data-\\[panel-group-direction\\=vertical\\]\\:after\\:w-full[data-panel-group-direction=vertical]:after{content:var(--tw-content);width:100%}.data-\\[panel-group-direction\\=vertical\\]\\:after\\:-translate-y-1\\/2[data-panel-group-direction=vertical]:after{content:var(--tw-content);--tw-translate-y: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\\[panel-group-direction\\=vertical\\]\\:after\\:translate-x-0[data-panel-group-direction=vertical]:after{content:var(--tw-content);--tw-translate-x: 0px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\\[state\\=open\\]\\:hover\\:bg-sidebar-accent:hover[data-state=open]{background-color:hsl(var(--sidebar-accent))}.data-\\[state\\=open\\]\\:hover\\:text-sidebar-accent-foreground:hover[data-state=open]{color:hsl(var(--sidebar-accent-foreground))}.group[data-collapsible=offcanvas] .group-data-\\[collapsible\\=offcanvas\\]\\:left-\\[calc\\(var\\(--sidebar-width\\)\\*-1\\)\\]{left:calc(var(--sidebar-width) * -1)}.group[data-collapsible=offcanvas] .group-data-\\[collapsible\\=offcanvas\\]\\:right-\\[calc\\(var\\(--sidebar-width\\)\\*-1\\)\\]{right:calc(var(--sidebar-width) * -1)}.group[data-side=left] .group-data-\\[side\\=left\\]\\:-right-4{right:-1rem}.group[data-side=right] .group-data-\\[side\\=right\\]\\:left-0{left:0}.group[data-collapsible=icon] .group-data-\\[collapsible\\=icon\\]\\:-mt-8{margin-top:-2rem}.group[data-collapsible=icon] .group-data-\\[collapsible\\=icon\\]\\:hidden{display:none}.group[data-collapsible=icon] .group-data-\\[collapsible\\=icon\\]\\:\\!size-8{width:2rem!important;height:2rem!important}.group[data-collapsible=icon] .group-data-\\[collapsible\\=icon\\]\\:w-\\[--sidebar-width-icon\\]{width:var(--sidebar-width-icon)}.group[data-collapsible=icon] .group-data-\\[collapsible\\=icon\\]\\:w-\\[calc\\(var\\(--sidebar-width-icon\\)_\\+_theme\\(spacing\\.4\\)\\)\\]{width:calc(var(--sidebar-width-icon) + 1rem)}.group[data-collapsible=icon] .group-data-\\[collapsible\\=icon\\]\\:w-\\[calc\\(var\\(--sidebar-width-icon\\)_\\+_theme\\(spacing\\.4\\)_\\+2px\\)\\]{width:calc(var(--sidebar-width-icon) + 1rem + 2px)}.group[data-collapsible=offcanvas] .group-data-\\[collapsible\\=offcanvas\\]\\:w-0{width:0px}.group[data-collapsible=offcanvas] .group-data-\\[collapsible\\=offcanvas\\]\\:translate-x-0{--tw-translate-x: 0px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.group[data-side=right] .group-data-\\[side\\=right\\]\\:rotate-180,.group[data-state=open] .group-data-\\[state\\=open\\]\\:rotate-180{--tw-rotate: 180deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.group[data-collapsible=icon] .group-data-\\[collapsible\\=icon\\]\\:overflow-hidden{overflow:hidden}.group[data-variant=floating] .group-data-\\[variant\\=floating\\]\\:rounded-lg{border-radius:var(--radius)}.group[data-variant=floating] .group-data-\\[variant\\=floating\\]\\:border{border-width:1px}.group[data-side=left] .group-data-\\[side\\=left\\]\\:border-r{border-right-width:1px}.group[data-side=right] .group-data-\\[side\\=right\\]\\:border-l{border-left-width:1px}.group[data-variant=floating] .group-data-\\[variant\\=floating\\]\\:border-sidebar-border{border-color:hsl(var(--sidebar-border))}.group[data-collapsible=icon] .group-data-\\[collapsible\\=icon\\]\\:\\!p-0{padding:0!important}.group[data-collapsible=icon] .group-data-\\[collapsible\\=icon\\]\\:\\!p-2{padding:.5rem!important}.group[data-collapsible=icon] .group-data-\\[collapsible\\=icon\\]\\:opacity-0{opacity:0}.group[data-variant=floating] .group-data-\\[variant\\=floating\\]\\:shadow{--tw-shadow: 0 1px 3px 0 rgb(0 0 0 / .1), 0 1px 2px -1px rgb(0 0 0 / .1);--tw-shadow-colored: 0 1px 3px 0 var(--tw-shadow-color), 0 1px 2px -1px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.group[data-collapsible=offcanvas] .group-data-\\[collapsible\\=offcanvas\\]\\:after\\:left-full:after{content:var(--tw-content);left:100%}.group[data-collapsible=offcanvas] .group-data-\\[collapsible\\=offcanvas\\]\\:hover\\:bg-sidebar:hover{background-color:hsl(var(--sidebar-background))}.peer\\/menu-button[data-size=default]~.peer-data-\\[size\\=default\\]\\/menu-button\\:top-1\\.5{top:.375rem}.peer\\/menu-button[data-size=lg]~.peer-data-\\[size\\=lg\\]\\/menu-button\\:top-2\\.5{top:.625rem}.peer\\/menu-button[data-size=sm]~.peer-data-\\[size\\=sm\\]\\/menu-button\\:top-1{top:.25rem}.peer[data-variant=inset]~.peer-data-\\[variant\\=inset\\]\\:min-h-\\[calc\\(100svh-theme\\(spacing\\.4\\)\\)\\]{min-height:calc(100svh - 1rem)}.peer\\/menu-button[data-active=true]~.peer-data-\\[active\\=true\\]\\/menu-button\\:text-sidebar-accent-foreground{color:hsl(var(--sidebar-accent-foreground))}.dark\\:border-destructive:is(.dark *){border-color:hsl(var(--destructive))}@media(min-width:640px){.sm\\:bottom-0{bottom:0}.sm\\:right-0{right:0}.sm\\:top-auto{top:auto}.sm\\:mt-0{margin-top:0}.sm\\:flex{display:flex}.sm\\:max-w-sm{max-width:24rem}.sm\\:flex-row{flex-direction:row}.sm\\:flex-col{flex-direction:column}.sm\\:justify-end{justify-content:flex-end}.sm\\:gap-2\\.5{gap:.625rem}.sm\\:space-x-2>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(.5rem * var(--tw-space-x-reverse));margin-left:calc(.5rem * calc(1 - var(--tw-space-x-reverse)))}.sm\\:space-x-4>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(1rem * var(--tw-space-x-reverse));margin-left:calc(1rem * calc(1 - var(--tw-space-x-reverse)))}.sm\\:space-y-0>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(0px * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(0px * var(--tw-space-y-reverse))}.sm\\:rounded-lg{border-radius:var(--radius)}.sm\\:text-left{text-align:left}.data-\\[state\\=open\\]\\:sm\\:slide-in-from-bottom-full[data-state=open]{--tw-enter-translate-y: 100%}}@media(min-width:768px){.md\\:absolute{position:absolute}.md\\:block{display:block}.md\\:flex{display:flex}.md\\:w-\\[var\\(--radix-navigation-menu-viewport-width\\)\\]{width:var(--radix-navigation-menu-viewport-width)}.md\\:w-auto{width:auto}.md\\:max-w-\\[420px\\]{max-width:420px}.md\\:text-sm{font-size:.875rem;line-height:1.25rem}.md\\:opacity-0{opacity:0}.after\\:md\\:hidden:after{content:var(--tw-content);display:none}.peer[data-variant=inset]~.md\\:peer-data-\\[variant\\=inset\\]\\:m-2{margin:.5rem}.peer[data-state=collapsed][data-variant=inset]~.md\\:peer-data-\\[state\\=collapsed\\]\\:peer-data-\\[variant\\=inset\\]\\:ml-2{margin-left:.5rem}.peer[data-variant=inset]~.md\\:peer-data-\\[variant\\=inset\\]\\:ml-0{margin-left:0}.peer[data-variant=inset]~.md\\:peer-data-\\[variant\\=inset\\]\\:rounded-xl{border-radius:.75rem}.peer[data-variant=inset]~.md\\:peer-data-\\[variant\\=inset\\]\\:shadow{--tw-shadow: 0 1px 3px 0 rgb(0 0 0 / .1), 0 1px 2px -1px rgb(0 0 0 / .1);--tw-shadow-colored: 0 1px 3px 0 var(--tw-shadow-color), 0 1px 2px -1px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}}.\\[\\&\\:has\\(\\>\\.day-range-end\\)\\]\\:rounded-r-md:has(>.day-range-end){border-top-right-radius:calc(var(--radius) - 2px);border-bottom-right-radius:calc(var(--radius) - 2px)}.\\[\\&\\:has\\(\\>\\.day-range-start\\)\\]\\:rounded-l-md:has(>.day-range-start){border-top-left-radius:calc(var(--radius) - 2px);border-bottom-left-radius:calc(var(--radius) - 2px)}.\\[\\&\\:has\\(\\[aria-selected\\]\\)\\]\\:rounded-md:has([aria-selected]){border-radius:calc(var(--radius) - 2px)}.\\[\\&\\:has\\(\\[aria-selected\\]\\)\\]\\:bg-accent:has([aria-selected]){background-color:hsl(var(--accent))}.first\\:\\[\\&\\:has\\(\\[aria-selected\\]\\)\\]\\:rounded-l-md:has([aria-selected]):first-child{border-top-left-radius:calc(var(--radius) - 2px);border-bottom-left-radius:calc(var(--radius) - 2px)}.last\\:\\[\\&\\:has\\(\\[aria-selected\\]\\)\\]\\:rounded-r-md:has([aria-selected]):last-child{border-top-right-radius:calc(var(--radius) - 2px);border-bottom-right-radius:calc(var(--radius) - 2px)}.\\[\\&\\:has\\(\\[aria-selected\\]\\.day-outside\\)\\]\\:bg-accent\\/50:has([aria-selected].day-outside){background-color:hsl(var(--accent) / .5)}.\\[\\&\\:has\\(\\[aria-selected\\]\\.day-range-end\\)\\]\\:rounded-r-md:has([aria-selected].day-range-end){border-top-right-radius:calc(var(--radius) - 2px);border-bottom-right-radius:calc(var(--radius) - 2px)}.\\[\\&\\:has\\(\\[role\\=checkbox\\]\\)\\]\\:pr-0:has([role=checkbox]){padding-right:0}.\\[\\&\\>\\[role\\=checkbox\\]\\]\\:translate-y-\\[2px\\]>[role=checkbox]{--tw-translate-y: 2px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.\\[\\&\\>button\\]\\:hidden>button{display:none}.\\[\\&\\>span\\:last-child\\]\\:truncate>span:last-child{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.\\[\\&\\>span\\]\\:line-clamp-1>span{overflow:hidden;display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:1}.\\[\\&\\>svg\\+div\\]\\:translate-y-\\[-3px\\]>svg+div{--tw-translate-y: -3px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.\\[\\&\\>svg\\]\\:absolute>svg{position:absolute}.\\[\\&\\>svg\\]\\:left-4>svg{left:1rem}.\\[\\&\\>svg\\]\\:top-4>svg{top:1rem}.\\[\\&\\>svg\\]\\:size-4>svg{width:1rem;height:1rem}.\\[\\&\\>svg\\]\\:h-2\\.5>svg{height:.625rem}.\\[\\&\\>svg\\]\\:h-3>svg{height:.75rem}.\\[\\&\\>svg\\]\\:h-3\\.5>svg{height:.875rem}.\\[\\&\\>svg\\]\\:w-2\\.5>svg{width:.625rem}.\\[\\&\\>svg\\]\\:w-3>svg{width:.75rem}.\\[\\&\\>svg\\]\\:w-3\\.5>svg{width:.875rem}.\\[\\&\\>svg\\]\\:shrink-0>svg{flex-shrink:0}.\\[\\&\\>svg\\]\\:text-destructive>svg{color:hsl(var(--destructive))}.\\[\\&\\>svg\\]\\:text-foreground>svg{color:hsl(var(--foreground))}.\\[\\&\\>svg\\]\\:text-muted-foreground>svg{color:hsl(var(--muted-foreground))}.\\[\\&\\>svg\\]\\:text-sidebar-accent-foreground>svg{color:hsl(var(--sidebar-accent-foreground))}.\\[\\&\\>svg\\~\\*\\]\\:pl-7>svg~*{padding-left:1.75rem}.\\[\\&\\>tr\\]\\:last\\:border-b-0:last-child>tr{border-bottom-width:0px}.\\[\\&\\[data-panel-group-direction\\=vertical\\]\\>div\\]\\:rotate-90[data-panel-group-direction=vertical]>div{--tw-rotate: 90deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.\\[\\&\\[data-state\\=open\\]\\>svg\\]\\:rotate-180[data-state=open]>svg{--tw-rotate: 180deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.\\[\\&_\\.recharts-cartesian-axis-tick_text\\]\\:fill-muted-foreground .recharts-cartesian-axis-tick text{fill:hsl(var(--muted-foreground))}.\\[\\&_\\.recharts-cartesian-grid_line\\[stroke\\=\\\'\\#ccc\\\'\\]\\]\\:stroke-border\\/50 .recharts-cartesian-grid line[stroke="#ccc"]{stroke:hsl(var(--border) / .5)}.\\[\\&_\\.recharts-curve\\.recharts-tooltip-cursor\\]\\:stroke-border .recharts-curve.recharts-tooltip-cursor{stroke:hsl(var(--border))}.\\[\\&_\\.recharts-dot\\[stroke\\=\\\'\\#fff\\\'\\]\\]\\:stroke-transparent .recharts-dot[stroke="#fff"]{stroke:transparent}.\\[\\&_\\.recharts-layer\\]\\:outline-none .recharts-layer{outline:2px solid transparent;outline-offset:2px}.\\[\\&_\\.recharts-polar-grid_\\[stroke\\=\\\'\\#ccc\\\'\\]\\]\\:stroke-border .recharts-polar-grid [stroke="#ccc"]{stroke:hsl(var(--border))}.\\[\\&_\\.recharts-radial-bar-background-sector\\]\\:fill-muted .recharts-radial-bar-background-sector,.\\[\\&_\\.recharts-rectangle\\.recharts-tooltip-cursor\\]\\:fill-muted .recharts-rectangle.recharts-tooltip-cursor{fill:hsl(var(--muted))}.\\[\\&_\\.recharts-reference-line_\\[stroke\\=\\\'\\#ccc\\\'\\]\\]\\:stroke-border .recharts-reference-line [stroke="#ccc"]{stroke:hsl(var(--border))}.\\[\\&_\\.recharts-sector\\[stroke\\=\\\'\\#fff\\\'\\]\\]\\:stroke-transparent .recharts-sector[stroke="#fff"]{stroke:transparent}.\\[\\&_\\.recharts-sector\\]\\:outline-none .recharts-sector,.\\[\\&_\\.recharts-surface\\]\\:outline-none .recharts-surface{outline:2px solid transparent;outline-offset:2px}.\\[\\&_\\[cmdk-group-heading\\]\\]\\:px-2 [cmdk-group-heading]{padding-left:.5rem;padding-right:.5rem}.\\[\\&_\\[cmdk-group-heading\\]\\]\\:py-1\\.5 [cmdk-group-heading]{padding-top:.375rem;padding-bottom:.375rem}.\\[\\&_\\[cmdk-group-heading\\]\\]\\:text-xs [cmdk-group-heading]{font-size:.75rem;line-height:1rem}.\\[\\&_\\[cmdk-group-heading\\]\\]\\:font-medium [cmdk-group-heading]{font-weight:500}.\\[\\&_\\[cmdk-group-heading\\]\\]\\:text-muted-foreground [cmdk-group-heading]{color:hsl(var(--muted-foreground))}.\\[\\&_\\[cmdk-group\\]\\:not\\(\\[hidden\\]\\)_\\~\\[cmdk-group\\]\\]\\:pt-0 [cmdk-group]:not([hidden])~[cmdk-group]{padding-top:0}.\\[\\&_\\[cmdk-group\\]\\]\\:px-2 [cmdk-group]{padding-left:.5rem;padding-right:.5rem}.\\[\\&_\\[cmdk-input-wrapper\\]_svg\\]\\:h-5 [cmdk-input-wrapper] svg{height:1.25rem}.\\[\\&_\\[cmdk-input-wrapper\\]_svg\\]\\:w-5 [cmdk-input-wrapper] svg{width:1.25rem}.\\[\\&_\\[cmdk-input\\]\\]\\:h-12 [cmdk-input]{height:3rem}.\\[\\&_\\[cmdk-item\\]\\]\\:px-2 [cmdk-item]{padding-left:.5rem;padding-right:.5rem}.\\[\\&_\\[cmdk-item\\]\\]\\:py-3 [cmdk-item]{padding-top:.75rem;padding-bottom:.75rem}.\\[\\&_\\[cmdk-item\\]_svg\\]\\:h-5 [cmdk-item] svg{height:1.25rem}.\\[\\&_\\[cmdk-item\\]_svg\\]\\:w-5 [cmdk-item] svg{width:1.25rem}.\\[\\&_p\\]\\:leading-relaxed p{line-height:1.625}.\\[\\&_svg\\]\\:pointer-events-none svg{pointer-events:none}.\\[\\&_svg\\]\\:size-4 svg{width:1rem;height:1rem}.\\[\\&_svg\\]\\:shrink-0 svg{flex-shrink:0}.\\[\\&_tr\\:last-child\\]\\:border-0 tr:last-child{border-width:0px}.\\[\\&_tr\\]\\:border-b tr{border-bottom-width:1px}[data-side=left][data-collapsible=offcanvas] .\\[\\[data-side\\=left\\]\\[data-collapsible\\=offcanvas\\]_\\&\\]\\:-right-2{right:-.5rem}[data-side=left][data-state=collapsed] .\\[\\[data-side\\=left\\]\\[data-state\\=collapsed\\]_\\&\\]\\:cursor-e-resize{cursor:e-resize}[data-side=left] .\\[\\[data-side\\=left\\]_\\&\\]\\:cursor-w-resize{cursor:w-resize}[data-side=right][data-collapsible=offcanvas] .\\[\\[data-side\\=right\\]\\[data-collapsible\\=offcanvas\\]_\\&\\]\\:-left-2{left:-.5rem}[data-side=right][data-state=collapsed] .\\[\\[data-side\\=right\\]\\[data-state\\=collapsed\\]_\\&\\]\\:cursor-w-resize{cursor:w-resize}[data-side=right] .\\[\\[data-side\\=right\\]_\\&\\]\\:cursor-e-resize{cursor:e-resize}',r.appendChild(i);const o=document.createElement("div");return o.style.cssText="pointer-events:auto;",r.appendChild(o),{container:o,shadow:r,host:n}}function $d(e,t){if(Boolean(t)&&t){const{container:n}=Md("display:inline-flex;align-items:center;height:100%;pointer-events:auto;",t),{container:r}=Md("position:fixed;z-index:2147483647;bottom:0;right:0;pointer-events:auto;width:0;height:0;",document.body),i=L.createRoot(n),o=L.createRoot(r);let a={status:"disconnected",callStatus:"idle",incomingCallInfo:null};const s=()=>{i.render(v.jsx(Rd,{status:a.status,callStatus:a.callStatus,hasIncomingCall:null!==a.incomingCallInfo,onClick:()=>Nd.open(),variant:e.fabStyle||"round"}))};Nd.on("__connectionStatusChange",e=>{a.status!==e&&(a.status=e,s())}),Nd.on("__callStatusChange",e=>{a.callStatus!==e&&(a.callStatus=e,s())}),Nd.on("__incomingCallChange",e=>{a.incomingCallInfo!==e&&(a.incomingCallInfo=e,s())}),o.render(v.jsx(Ed,{config:e,api:Nd,embedded:!0})),s()}else{const{container:t}=Md("position:fixed;z-index:2147483647;bottom:0;right:0;pointer-events:auto;width:0;height:0;",document.body);L.createRoot(t).render(v.jsx(Ed,{config:e,api:Nd,embedded:!1}))}}function Od(){const e=function(){const e={},t=document.currentScript||Array.from(document.scripts).find(e=>{var t;return null==(t=e.src)?void 0:t.includes("handphone.js")});if(t){const n=t.dataset.sipUser,r=t.dataset.sipPassword,i=t.dataset.sipDomain,o=t.dataset.sipServer,a=t.dataset.position,s=t.dataset.element,l=t.dataset.fabStyle,c="true"===t.dataset.autoConnect,u=t.dataset.dial;if(n&&(e.username=n),r&&(e.password=r),i&&(e.domain=i),o&&(e.server=o),a&&(e.position=a),s&&(e.element=s),l&&(e.fabStyle=l),c&&(e.autoConnect=!0),u)try{e.dial=JSON.parse(u)}catch{e.dial={number:u,auto:!1}}}return window.HandphoneConfig?{...e,...window.HandphoneConfig}:e}();if(!e.element)return void $d(e,null);const t=document.querySelector(e.element);if(t)return void $d(e,t);const n=new MutationObserver(()=>{const t=document.querySelector(e.element);t&&(n.disconnect(),$d(e,t))});n.observe(document.body,{childList:!0,subtree:!0})}window.Handphone=Nd,window.addEventListener("message",e=>{const t=e.data;if(!t||"handphone:dial"!==t.type)return;const n=String(t.number??"").trim();n&&Nd.dial(n,{auto:Boolean(t.auto)})}),"loading"===document.readyState?document.addEventListener("DOMContentLoaded",Od):Od()}(); + */class de extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}}class he extends de{constructor(e){super(e||"Unsupported content type.")}}class fe extends de{constructor(e){super(e||"Request pending.")}}class pe extends de{constructor(e){super(e||"Unspecified session description handler error.")}}class ge extends de{constructor(){super("The session has terminated.")}}class me extends de{constructor(e){super(e||"An error occurred during state transition.")}}class ve{constructor(e){this.incomingAckRequest=e}get request(){return this.incomingAckRequest.message}}class ye{constructor(e){this.incomingByeRequest=e}get request(){return this.incomingByeRequest.message}accept(e){return this.incomingByeRequest.accept(e),Promise.resolve()}reject(e){return this.incomingByeRequest.reject(e),Promise.resolve()}}class be{constructor(e){this.incomingCancelRequest=e}get request(){return this.incomingCancelRequest}}class we{constructor(){this.listeners=new Array}addListener(e,t){const n=t=>{this.removeListener(n),e(t)};!0===(null==t?void 0:t.once)?this.listeners.push(n):this.listeners.push(e)}emit(e){this.listeners.slice().forEach(t=>t(e))}removeAllListeners(){this.listeners=[]}removeListener(e){this.listeners=this.listeners.filter(t=>t!==e)}on(e){return this.addListener(e)}off(e){return this.removeListener(e)}once(e){return this.addListener(e,{once:!0})}}class xe{constructor(e){this.incomingInfoRequest=e}get request(){return this.incomingInfoRequest.message}accept(e){return this.incomingInfoRequest.accept(e),Promise.resolve()}reject(e){return this.incomingInfoRequest.reject(e),Promise.resolve()}}class ke{constructor(e){this.parameters={};for(const t in e)e.hasOwnProperty(t)&&this.setParam(t,e[t])}setParam(e,t){e&&(this.parameters[e.toLowerCase()]=null==t?null:t.toString())}getParam(e){if(e)return this.parameters[e.toLowerCase()]}hasParam(e){return!(!e||void 0===this.parameters[e.toLowerCase()])}deleteParam(e){if(e=e.toLowerCase(),this.hasParam(e)){const t=this.parameters[e];return delete this.parameters[e],t}}clearParams(){this.parameters={}}}class Se extends ke{constructor(e,t,n){super(n),this.uri=e,this._displayName=t}get friendlyName(){return this.displayName||this.uri.aor}get displayName(){return this._displayName}set displayName(e){this._displayName=e}clone(){return new Se(this.uri.clone(),this._displayName,JSON.parse(JSON.stringify(this.parameters)))}toString(){let e=this.displayName||"0"===this.displayName?'"'+this.displayName+'" ':"";e+="<"+this.uri.toString()+">";for(const t in this.parameters)this.parameters.hasOwnProperty(t)&&(e+=";"+t,null!==this.parameters[t]&&(e+="="+this.parameters[t]));return e}}class Te extends ke{constructor(e="sip",t,n,r,i,o){if(super(i||{}),this.headers={},!n)throw new TypeError('missing or invalid "host" parameter');for(const a in o)o.hasOwnProperty(a)&&this.setHeader(a,o[a]);this.raw={scheme:e,user:t,host:n,port:r},this.normal={scheme:e.toLowerCase(),user:t,host:n.toLowerCase(),port:r}}get scheme(){return this.normal.scheme}set scheme(e){this.raw.scheme=e,this.normal.scheme=e.toLowerCase()}get user(){return this.normal.user}set user(e){this.normal.user=this.raw.user=e}get host(){return this.normal.host}set host(e){this.raw.host=e,this.normal.host=e.toLowerCase()}get aor(){return this.normal.user+"@"+this.normal.host}get port(){return this.normal.port}set port(e){this.normal.port=this.raw.port=e}setHeader(e,t){this.headers[this.headerize(e)]=t instanceof Array?t:[t]}getHeader(e){if(e)return this.headers[this.headerize(e)]}hasHeader(e){return!!e&&!!this.headers.hasOwnProperty(this.headerize(e))}deleteHeader(e){if(e=this.headerize(e),this.headers.hasOwnProperty(e)){const t=this.headers[e];return delete this.headers[e],t}}clearHeaders(){this.headers={}}clone(){return new Te(this._raw.scheme,this._raw.user||"",this._raw.host,this._raw.port,JSON.parse(JSON.stringify(this.parameters)),JSON.parse(JSON.stringify(this.headers)))}toRaw(){return this._toString(this._raw)}toString(){return this._toString(this._normal)}get _normal(){return this.normal}get _raw(){return this.raw}_toString(e){let t=e.scheme+":";e.scheme.toLowerCase().match("^sips?$")||(t+="//"),e.user&&(t+=this.escapeUser(e.user)+"@"),t+=e.host,(e.port||0===e.port)&&(t+=":"+e.port);for(const r in this.parameters)this.parameters.hasOwnProperty(r)&&(t+=";"+r,null!==this.parameters[r]&&(t+="="+this.parameters[r]));const n=[];for(const r in this.headers)if(this.headers.hasOwnProperty(r))for(const e in this.headers[r])this.headers[r].hasOwnProperty(e)&&n.push(r+"="+this.headers[r][e]);return n.length>0&&(t+="?"+n.join("&")),t}escapeUser(e){let t;try{t=decodeURIComponent(e)}catch(n){throw n}return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%2B/gi,"+").replace(/%3F/gi,"?").replace(/%2F/gi,"/")}headerize(e){const t={"Call-Id":"Call-ID",Cseq:"CSeq","Min-Se":"Min-SE",Rack:"RAck",Rseq:"RSeq","Www-Authenticate":"WWW-Authenticate"},n=e.toLowerCase().replace(/_/g,"-").split("-"),r=n.length;let i="";for(let o=0;or.includes(e)).every(n=>e.parameters[n]===t.parameters[n])&&(!!["user","ttl","method","transport"].every(n=>e.hasParam(n)&&t.hasParam(n)||!e.hasParam(n)&&!t.hasParam(n))&&!!["maddr"].every(n=>e.hasParam(n)&&t.hasParam(n)||!e.hasParam(n)&&!t.hasParam(n)))}(e,t))return!1;const n=Object.keys(e.headers),r=Object.keys(t.headers);if(0!==n.length||0!==r.length){if(n.length!==r.length)return!1;const i=n.filter(e=>r.includes(e));if(i.length!==r.length)return!1;if(!i.every(n=>e.headers[n].length&&t.headers[n].length&&e.headers[n][0]===t.headers[n][0]))return!1}return!0}function Ce(e,t,n){return n=n||" ",e.length>t?e:(t-=e.length,e+(n+=n.repeat(t)).slice(0,t))}class Re extends Error{constructor(e,t,n,r){super(),this.message=e,this.expected=t,this.found=n,this.location=r,this.name="SyntaxError","function"==typeof Object.setPrototypeOf?Object.setPrototypeOf(this,Re.prototype):this.__proto__=Re.prototype,"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,Re)}static buildMessage(e,t){function n(e){return e.charCodeAt(0).toString(16).toUpperCase()}function r(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\0/g,"\\0").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/[\x00-\x0F]/g,e=>"\\x0"+n(e)).replace(/[\x10-\x1F\x7F-\x9F]/g,e=>"\\x"+n(e))}function i(e){return e.replace(/\\/g,"\\\\").replace(/\]/g,"\\]").replace(/\^/g,"\\^").replace(/-/g,"\\-").replace(/\0/g,"\\0").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/[\x00-\x0F]/g,e=>"\\x0"+n(e)).replace(/[\x10-\x1F\x7F-\x9F]/g,e=>"\\x"+n(e))}function o(e){switch(e.type){case"literal":return'"'+r(e.text)+'"';case"class":const t=e.parts.map(e=>Array.isArray(e)?i(e[0])+"-"+i(e[1]):i(e));return"["+(e.inverted?"^":"")+t+"]";case"any":return"any character";case"end":return"end of input";case"other":return e.description}}return"Expected "+function(e){const t=e.map(o);let n,r;if(t.sort(),t.length>0){for(n=1,r=1;n",v(">",!1),"\\",v("\\",!1),"[",v("[",!1),"]",v("]",!1),"{",v("{",!1),"}",v("}",!1),function(){return"*"},function(){return"/"},function(){return"="},function(){return"("},function(){return")"},function(){return">"},function(){return"<"},function(){return","},function(){return";"},function(){return":"},function(){return'"'},/^[!-']/,y([["!","'"]],!1,!1),/^[*-[]/,y([["*","["]],!1,!1),/^[\]-~]/,y([["]","~"]],!1,!1),function(e){return e},/^[#-[]/,y([["#","["]],!1,!1),/^[\0-\t]/,y([["\0","\t"]],!1,!1),/^[\v-\f]/,y([["\v","\f"]],!1,!1),/^[\x0E-\x7F]/,y([["",""]],!1,!1),function(){(t=t||{data:{}}).data.uri=new Te(t.data.scheme,t.data.user,t.data.host,t.data.port),delete t.data.scheme,delete t.data.user,delete t.data.host,delete t.data.host_type,delete t.data.port},function(){(t=t||{data:{}}).data.uri=new Te(t.data.scheme,t.data.user,t.data.host,t.data.port,t.data.uri_params,t.data.uri_headers),delete t.data.scheme,delete t.data.user,delete t.data.host,delete t.data.host_type,delete t.data.port,delete t.data.uri_params,"SIP_URI"===t.startRule&&(t.data=t.data.uri)},"sips",v("sips",!0),"sip",v("sip",!0),function(e){(t=t||{data:{}}).data.scheme=e},function(){(t=t||{data:{}}).data.user=decodeURIComponent(g().slice(0,-1))},function(){(t=t||{data:{}}).data.password=g()},function(){return(t=t||{data:{}}).data.host=g(),t.data.host},function(){return(t=t||{data:{}}).data.host_type="domain",g()},/^[a-zA-Z0-9_\-]/,y([["a","z"],["A","Z"],["0","9"],"_","-"],!1,!1),/^[a-zA-Z0-9\-]/,y([["a","z"],["A","Z"],["0","9"],"-"],!1,!1),function(){return(t=t||{data:{}}).data.host_type="IPv6",g()},"::",v("::",!1),function(){return(t=t||{data:{}}).data.host_type="IPv6",g()},function(){return(t=t||{data:{}}).data.host_type="IPv4",g()},"25",v("25",!1),/^[0-5]/,y([["0","5"]],!1,!1),"2",v("2",!1),/^[0-4]/,y([["0","4"]],!1,!1),"1",v("1",!1),/^[1-9]/,y([["1","9"]],!1,!1),function(e){return t=t||{data:{}},e=parseInt(e.join("")),t.data.port=e,e},"transport=",v("transport=",!0),"udp",v("udp",!0),"tcp",v("tcp",!0),"sctp",v("sctp",!0),"tls",v("tls",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.transport=e.toLowerCase()},"user=",v("user=",!0),"phone",v("phone",!0),"ip",v("ip",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.user=e.toLowerCase()},"method=",v("method=",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.method=e},"ttl=",v("ttl=",!0),function(e){(t=t||{data:{}}).data.params||(t.data.params={}),t.data.params.ttl=e},"maddr=",v("maddr=",!0),function(e){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.maddr=e},"lr",v("lr",!0),function(){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),t.data.uri_params.lr=void 0},function(e,n){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),n=null===n?void 0:n[1],t.data.uri_params[e.toLowerCase()]=n},function(e,n){e=e.join("").toLowerCase(),n=n.join(""),(t=t||{data:{}}).data.uri_headers||(t.data.uri_headers={}),t.data.uri_headers[e]?t.data.uri_headers[e].push(n):t.data.uri_headers[e]=[n]},function(){"Refer_To"===(t=t||{data:{}}).startRule&&(t.data.uri=new Te(t.data.scheme,t.data.user,t.data.host,t.data.port,t.data.uri_params,t.data.uri_headers),delete t.data.scheme,delete t.data.user,delete t.data.host,delete t.data.host_type,delete t.data.port,delete t.data.uri_params)},"//",v("//",!1),function(){(t=t||{data:{}}).data.scheme=g()},v("SIP",!0),function(){(t=t||{data:{}}).data.sip_version=g()},"INVITE",v("INVITE",!1),"ACK",v("ACK",!1),"VXACH",v("VXACH",!1),"OPTIONS",v("OPTIONS",!1),"BYE",v("BYE",!1),"CANCEL",v("CANCEL",!1),"REGISTER",v("REGISTER",!1),"SUBSCRIBE",v("SUBSCRIBE",!1),"NOTIFY",v("NOTIFY",!1),"REFER",v("REFER",!1),"PUBLISH",v("PUBLISH",!1),function(){return(t=t||{data:{}}).data.method=g(),t.data.method},function(e){(t=t||{data:{}}).data.status_code=parseInt(e.join(""))},function(){(t=t||{data:{}}).data.reason_phrase=g()},function(){(t=t||{data:{}}).data=g()},function(){var e,n;for(n=(t=t||{data:{}}).data.multi_header.length,e=0;e""6>7?.A &2@""6@7A.5 &2B""6B7C.) &2D""6D7E'),k(";).# &;,"),k('2F""6F7G.} &2H""6H7I.q &2J""6J7K.e &2L""6L7M.Y &2N""6N7O.M &2P""6P7Q.A &2R""6R7S.5 &2T""6T7U.) &2V""6V7W'),k('%%2X""6X7Y/5#;#/,$;#/#$+#)(#\'#("\'#&\'#/"!&,)'),k('%%$;$0#*;$&/,#; /#$+")("\'#&\'#." &"/=#$;$/�#*;$&&&#/\'$8":Z" )("\'#&\'#'),k(';.." &"'),k("%$;'.# &;(0)*;'.# &;(&/?#28\"\"6879/0$;//'$8#:[# )(#'#(\"'#&'#"),k('%%$;2/�#*;2&&&#/g#$%$;.0#*;.&/,#;2/#$+")("\'#&\'#0=*%$;.0#*;.&/,#;2/#$+")("\'#&\'#&/#$+")("\'#&\'#/"!&,)'),k('4\\""5!7].# &;3'),k('4^""5!7_'),k('4`""5!7a'),k(';!.) &4b""5!7c'),k('%$;).• &2F""6F7G.‰ &2J""6J7K.} &2L""6L7M.q &2X""6X7Y.e &2P""6P7Q.Y &2H""6H7I.M &2@""6@7A.A &2d""6d7e.5 &2R""6R7S.) &2N""6N7O/ž#0›*;).• &2F""6F7G.‰ &2J""6J7K.} &2L""6L7M.q &2X""6X7Y.e &2P""6P7Q.Y &2H""6H7I.M &2@""6@7A.A &2d""6d7e.5 &2R""6R7S.) &2N""6N7O&&&#/"!&,)'),k('%$;).‰ &2F""6F7G.} &2L""6L7M.q &2X""6X7Y.e &2P""6P7Q.Y &2H""6H7I.M &2@""6@7A.A &2d""6d7e.5 &2R""6R7S.) &2N""6N7O/’#0*;).‰ &2F""6F7G.} &2L""6L7M.q &2X""6X7Y.e &2P""6P7Q.Y &2H""6H7I.M &2@""6@7A.A &2d""6d7e.5 &2R""6R7S.) &2N""6N7O&&&#/"!&,)'),k('2T""6T7U.ã &2V""6V7W.× &2f""6f7g.Ë &2h""6h7i.¿ &2:""6:7;.³ &2D""6D7E.§ &22""6273.› &28""6879. &2j""6j7k.ƒ &;&.} &24""6475.q &2l""6l7m.e &2n""6n7o.Y &26""6677.M &2>""6>7?.A &2p""6p7q.5 &2r""6r7s.) &;\'.# &;('),k('%$;).ī &2F""6F7G.ğ &2J""6J7K.ē &2L""6L7M.ć &2X""6X7Y.û &2P""6P7Q.ï &2H""6H7I.ã &2@""6@7A.× &2d""6d7e.Ë &2R""6R7S.¿ &2N""6N7O.³ &2T""6T7U.§ &2V""6V7W.› &2f""6f7g. &2h""6h7i.ƒ &28""6879.w &2j""6j7k.k &;&.e &24""6475.Y &2l""6l7m.M &2n""6n7o.A &26""6677.5 &2p""6p7q.) &2r""6r7s/Ĵ#0ı*;).ī &2F""6F7G.ğ &2J""6J7K.ē &2L""6L7M.ć &2X""6X7Y.û &2P""6P7Q.ï &2H""6H7I.ã &2@""6@7A.× &2d""6d7e.Ë &2R""6R7S.¿ &2N""6N7O.³ &2T""6T7U.§ &2V""6V7W.› &2f""6f7g. &2h""6h7i.ƒ &28""6879.w &2j""6j7k.k &;&.e &24""6475.Y &2l""6l7m.M &2n""6n7o.A &26""6677.5 &2p""6p7q.) &2r""6r7s&&&#/"!&,)'),k("%;//?#2P\"\"6P7Q/0$;//'$8#:t# )(#'#(\"'#&'#"),k("%;//?#24\"\"6475/0$;//'$8#:u# )(#'#(\"'#&'#"),k("%;//?#2>\"\"6>7?/0$;//'$8#:v# )(#'#(\"'#&'#"),k("%;//?#2T\"\"6T7U/0$;//'$8#:w# )(#'#(\"'#&'#"),k("%;//?#2V\"\"6V7W/0$;//'$8#:x# )(#'#(\"'#&'#"),k('%2h""6h7i/0#;//\'$8":y" )("\'#&\'#'),k('%;//6#2f""6f7g/\'$8":z" )("\'#&\'#'),k("%;//?#2D\"\"6D7E/0$;//'$8#:{# )(#'#(\"'#&'#"),k("%;//?#22\"\"6273/0$;//'$8#:|# )(#'#(\"'#&'#"),k("%;//?#28\"\"6879/0$;//'$8#:}# )(#'#(\"'#&'#"),k("%;//0#;&/'$8\":~\" )(\"'#&'#"),k("%;&/0#;//'$8\":~\" )(\"'#&'#"),k("%;=/T#$;G.) &;K.# &;F0/*;G.) &;K.# &;F&/,$;>/#$+#)(#'#(\"'#&'#"),k('4""5!7€.A &4""5!7‚.5 &4ƒ""5!7„.) &;3.# &;.'),k("%%;//Q#;&/H$$;J.# &;K0)*;J.# &;K&/,$;&/#$+$)($'#(#'#(\"'#&'#/\"!&,)"),k("%;//]#;&/T$%$;J.# &;K0)*;J.# &;K&/\"!&,)/1$;&/($8$:…$!!)($'#(#'#(\"'#&'#"),k(';..G &2L""6L7M.; &4†""5!7‡./ &4ƒ""5!7„.# &;3'),k('%2j""6j7k/J#4ˆ""5!7‰.5 &4Š""5!7‹.) &4Œ""5!7/#$+")("\'#&\'#'),k("%;N/M#28\"\"6879/>$;O.\" &\"/0$;S/'$8$:Ž$ )($'#(#'#(\"'#&'#"),k("%;N/d#28\"\"6879/U$;O.\" &\"/G$;S/>$;_/5$;l.\" &\"/'$8&:& )(&'#(%'#($'#(#'#(\"'#&'#"),k('%3""5$7‘.) &3’""5#7“/\' 8!:”!! )'),k('%;P/]#%28""6879/,#;R/#$+")("\'#&\'#." &"/6$2:""6:7;/\'$8#:•# )(#\'#("\'#&\'#'),k("$;+.) &;-.# &;Q/2#0/*;+.) &;-.# &;Q&&&#"),k('2<""6<7=.q &2>""6>7?.e &2@""6@7A.Y &2B""6B7C.M &2D""6D7E.A &22""6273.5 &26""6677.) &24""6475'),k('%$;+._ &;-.Y &2<""6<7=.M &2>""6>7?.A &2@""6@7A.5 &2B""6B7C.) &2D""6D7E0e*;+._ &;-.Y &2<""6<7=.M &2>""6>7?.A &2@""6@7A.5 &2B""6B7C.) &2D""6D7E&/& 8!:–! )'),k('%;T/J#%28""6879/,#;^/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),k("%;U.) &;\\.# &;X/& 8!:—! )"),k('%$%;V/2#2J""6J7K/#$+")("\'#&\'#0<*%;V/2#2J""6J7K/#$+")("\'#&\'#&/D#;W/;$2J""6J7K." &"/\'$8#:˜# )(#\'#("\'#&\'#'),k('$4™""5!7š/,#0)*4™""5!7š&&&#'),k('%4$""5!7%/?#$4›""5!7œ0)*4›""5!7œ&/#$+")("\'#&\'#'),k('%2l""6l7m/?#;Y/6$2n""6n7o/\'$8#:# )(#\'#("\'#&\'#'),k('%%;Z/³#28""6879/¤$;Z/›$28""6879/Œ$;Z/ƒ$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+-)(-\'#(,\'#(+\'#(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.ސ &%2ž""6ž7Ÿ/¤#;Z/›$28""6879/Œ$;Z/ƒ$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+,)(,\'#(+\'#(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.۹ &%2ž""6ž7Ÿ/Œ#;Z/ƒ$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+*)(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.ٺ &%2ž""6ž7Ÿ/t#;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.ؓ &%2ž""6ž7Ÿ/\\#;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+&)(&\'#(%\'#($\'#(#\'#("\'#&\'#.ׄ &%2ž""6ž7Ÿ/D#;Z/;$28""6879/,$;[/#$+$)($\'#(#\'#("\'#&\'#.֍ &%2ž""6ž7Ÿ/,#;[/#$+")("\'#&\'#.ծ &%2ž""6ž7Ÿ/,#;Z/#$+")("\'#&\'#.Տ &%;Z/›#2ž""6ž7Ÿ/Œ$;Z/ƒ$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$++)(+\'#(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.Ӈ &%;Z/ª#%28""6879/,#;Z/#$+")("\'#&\'#." &"/ƒ$2ž""6ž7Ÿ/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+*)(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.а &%;Z/¹#%28""6879/,#;Z/#$+")("\'#&\'#." &"/’$%28""6879/,#;Z/#$+")("\'#&\'#." &"/k$2ž""6ž7Ÿ/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+))()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.Ί &%;Z/È#%28""6879/,#;Z/#$+")("\'#&\'#." &"/¡$%28""6879/,#;Z/#$+")("\'#&\'#." &"/z$%28""6879/,#;Z/#$+")("\'#&\'#." &"/S$2ž""6ž7Ÿ/D$;Z/;$28""6879/,$;[/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.˕ &%;Z/×#%28""6879/,#;Z/#$+")("\'#&\'#." &"/°$%28""6879/,#;Z/#$+")("\'#&\'#." &"/‰$%28""6879/,#;Z/#$+")("\'#&\'#." &"/b$%28""6879/,#;Z/#$+")("\'#&\'#." &"/;$2ž""6ž7Ÿ/,$;[/#$+\')(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.ȑ &%;Z/þ#%28""6879/,#;Z/#$+")("\'#&\'#." &"/×$%28""6879/,#;Z/#$+")("\'#&\'#." &"/°$%28""6879/,#;Z/#$+")("\'#&\'#." &"/‰$%28""6879/,#;Z/#$+")("\'#&\'#." &"/b$%28""6879/,#;Z/#$+")("\'#&\'#." &"/;$2ž""6ž7Ÿ/,$;Z/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.Ħ &%;Z/Ĝ#%28""6879/,#;Z/#$+")("\'#&\'#." &"/õ$%28""6879/,#;Z/#$+")("\'#&\'#." &"/Î$%28""6879/,#;Z/#$+")("\'#&\'#." &"/§$%28""6879/,#;Z/#$+")("\'#&\'#." &"/€$%28""6879/,#;Z/#$+")("\'#&\'#." &"/Y$%28""6879/,#;Z/#$+")("\'#&\'#." &"/2$2ž""6ž7Ÿ/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#/& 8!: ! )'),k('%;#/M#;#." &"/?$;#." &"/1$;#." &"/#$+$)($\'#(#\'#("\'#&\'#'),k("%;Z/;#28\"\"6879/,$;Z/#$+#)(#'#(\"'#&'#.# &;\\"),k("%;]/o#2J\"\"6J7K/`$;]/W$2J\"\"6J7K/H$;]/?$2J\"\"6J7K/0$;]/'$8':¡' )(''#(&'#(%'#($'#(#'#(\"'#&'#"),k('%2¢""6¢7£/2#4¤""5!7¥/#$+")("\'#&\'#.˜ &%2¦""6¦7§/;#4¨""5!7©/,$;!/#$+#)(#\'#("\'#&\'#.j &%2ª""6ª7«/5#;!/,$;!/#$+#)(#\'#("\'#&\'#.B &%4¬""5!7­/,#;!/#$+")("\'#&\'#.# &;!'),k('%%;!." &"/[#;!." &"/M$;!." &"/?$;!." &"/1$;!." &"/#$+%)(%\'#($\'#(#\'#("\'#&\'#/\' 8!:®!! )'),k('$%22""6273/,#;`/#$+")("\'#&\'#0<*%22""6273/,#;`/#$+")("\'#&\'#&'),k(";a.A &;b.; &;c.5 &;d./ &;e.) &;f.# &;g"),k('%3¯""5*7°/a#3±""5#7².G &3³""5#7´.; &3µ""5$7¶./ &3·""5#7¸.# &;6/($8":¹"! )("\'#&\'#'),k('%3º""5%7»/I#3¼""5%7½./ &3¾""5"7¿.# &;6/($8":À"! )("\'#&\'#'),k('%3Á""5\'7Â/1#;/($8":Ã"! )("\'#&\'#'),k('%3Ä""5$7Å/1#;ð/($8":Æ"! )("\'#&\'#'),k('%3Ç""5&7È/1#;T/($8":É"! )("\'#&\'#'),k('%3Ê""5"7Ë/N#%2>""6>7?/,#;6/#$+")("\'#&\'#." &"/\'$8":Ì" )("\'#&\'#'),k('%;h/P#%2>""6>7?/,#;i/#$+")("\'#&\'#." &"/)$8":Í""! )("\'#&\'#'),k('%$;j/�#*;j&&&#/"!&,)'),k('%$;j/�#*;j&&&#/"!&,)'),k(";k.) &;+.# &;-"),k('2l""6l7m.e &2n""6n7o.Y &24""6475.M &28""6879.A &2<""6<7=.5 &2@""6@7A.) &2B""6B7C'),k('%26""6677/n#;m/e$$%2<""6<7=/,#;m/#$+")("\'#&\'#0<*%2<""6<7=/,#;m/#$+")("\'#&\'#&/#$+#)(#\'#("\'#&\'#'),k('%;n/A#2>""6>7?/2$;o/)$8#:Î#"" )(#\'#("\'#&\'#'),k("$;p.) &;+.# &;-/2#0/*;p.) &;+.# &;-&&&#"),k("$;p.) &;+.# &;-0/*;p.) &;+.# &;-&"),k('2l""6l7m.e &2n""6n7o.Y &24""6475.M &26""6677.A &28""6879.5 &2@""6@7A.) &2B""6B7C'),k(";‘.# &;r"),k("%;/G#;'/>$;s/5$;'/,$;„/#$+%)(%'#($'#(#'#(\"'#&'#"),k(";M.# &;t"),k("%;/E#28\"\"6879/6$;u.# &;x/'$8#:Ï# )(#'#(\"'#&'#"),k('%;v.# &;w/J#%26""6677/,#;ƒ/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),k('%2Ð""6Ð7Ñ/:#;€/1$;w." &"/#$+#)(#\'#("\'#&\'#'),k('%24""6475/,#;{/#$+")("\'#&\'#'),k("%;z/3#$;y0#*;y&/#$+\")(\"'#&'#"),k(";*.) &;+.# &;-"),k(';+. &;-.‰ &22""6273.} &26""6677.q &28""6879.e &2:""6:7;.Y &2<""6<7=.M &2>""6>7?.A &2@""6@7A.5 &2B""6B7C.) &2D""6D7E'),k('%;|/e#$%24""6475/,#;|/#$+")("\'#&\'#0<*%24""6475/,#;|/#$+")("\'#&\'#&/#$+")("\'#&\'#'),k('%$;~0#*;~&/e#$%22""6273/,#;}/#$+")("\'#&\'#0<*%22""6273/,#;}/#$+")("\'#&\'#&/#$+")("\'#&\'#'),k("$;~0#*;~&"),k(';+.w &;-.q &28""6879.e &2:""6:7;.Y &2<""6<7=.M &2>""6>7?.A &2@""6@7A.5 &2B""6B7C.) &2D""6D7E'),k('%%;"/‡#$;".G &;!.A &2@""6@7A.5 &2F""6F7G.) &2J""6J7K0M*;".G &;!.A &2@""6@7A.5 &2F""6F7G.) &2J""6J7K&/#$+")("\'#&\'#/& 8!:Ò! )'),k(";.# &;‚"),k('%%;O/2#2:""6:7;/#$+")("\'#&\'#." &"/,#;S/#$+")("\'#&\'#." &"'),k('$;+.ƒ &;-.} &2B""6B7C.q &2D""6D7E.e &22""6273.Y &28""6879.M &2:""6:7;.A &2<""6<7=.5 &2>""6>7?.) &2@""6@7A/Œ#0‰*;+.ƒ &;-.} &2B""6B7C.q &2D""6D7E.e &22""6273.Y &28""6879.M &2:""6:7;.A &2<""6<7=.5 &2>""6>7?.) &2@""6@7A&&&#'),k("$;y0#*;y&"),k('%3’""5#7Ó/q#24""6475/b$$;!/�#*;!&&&#/L$2J""6J7K/=$$;!/�#*;!&&&#/\'$8%:Ô% )(%\'#($\'#(#\'#("\'#&\'#'),k('2Õ""6Õ7Ö'),k('2×""6×7Ø'),k('2Ù""6Ù7Ú'),k('2Û""6Û7Ü'),k('2Ý""6Ý7Þ'),k('2ß""6ß7à'),k('2á""6á7â'),k('2ã""6ã7ä'),k('2å""6å7æ'),k('2ç""6ç7è'),k('2é""6é7ê'),k("%;….Y &;†.S &;ˆ.M &;‰.G &;Š.A &;‹.; &;Œ.5 &;./ &;.) &;Ž.# &;6/& 8!:ë! )"),k("%;„/G#;'/>$;’/5$;'/,$;”/#$+%)(%'#($'#(#'#(\"'#&'#"),k("%;“/' 8!:ì!! )"),k("%;!/5#;!/,$;!/#$+#)(#'#(\"'#&'#"),k("%$;*.A &;+.; &;-.5 &;3./ &;4.) &;'.# &;(0G*;*.A &;+.; &;-.5 &;3./ &;4.) &;'.# &;(&/& 8!:í! )"),k("%;¶/Y#$%;A/,#;¶/#$+\")(\"'#&'#06*%;A/,#;¶/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),k('%;9/N#%2:""6:7;/,#;9/#$+")("\'#&\'#." &"/\'$8":î" )("\'#&\'#'),k("%;:.c &%;˜/Y#$%;A/,#;˜/#$+\")(\"'#&'#06*%;A/,#;˜/#$+\")(\"'#&'#&/#$+\")(\"'#&'#/& 8!:ï! )"),k("%;L.# &;™/]#$%;B/,#;›/#$+\")(\"'#&'#06*%;B/,#;›/#$+\")(\"'#&'#&/'$8\":ð\" )(\"'#&'#"),k("%;š.\" &\"/>#;@/5$;M/,$;?/#$+$)($'#(#'#(\"'#&'#"),k("%%;6/Y#$%;./,#;6/#$+\")(\"'#&'#06*%;./,#;6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#.# &;H/' 8!:ñ!! )"),k(";œ.) &;.# &; "),k("%3ò\"\"5!7ó/:#;$;Ï/5$;./,$;/#$+%)(%'#($'#(#'#(\"'#&'#"),k("%$;!/�#*;!&&&#/' 8!:ŋ!! )"),k("%;Ñ/]#$%;A/,#;Ñ/#$+\")(\"'#&'#06*%;A/,#;Ñ/#$+\")(\"'#&'#&/'$8\":Ō\" )(\"'#&'#"),k("%;™/]#$%;B/,#; /#$+\")(\"'#&'#06*%;B/,#; /#$+\")(\"'#&'#&/'$8\":ō\" )(\"'#&'#"),k('%;L.O &;™.I &%;@." &"/:#;t/1$;?." &"/#$+#)(#\'#("\'#&\'#/]#$%;B/,#; /#$+")("\'#&\'#06*%;B/,#; /#$+")("\'#&\'#&/\'$8":Ŏ" )("\'#&\'#'),k("%;Ô/]#$%;B/,#;Õ/#$+\")(\"'#&'#06*%;B/,#;Õ/#$+\")(\"'#&'#&/'$8\":ŏ\" )(\"'#&'#"),k("%;–/& 8!:Ő! )"),k('%3ő""5(7Œ/:#;$;6/5$;;/,$;ì/#$+%)(%'#($'#(#'#(\"'#&'#"),k('%3’""5#7Ó.# &;6/\' 8!:Ƌ!! )'),k('%3±""5#7ƌ.G &3³""5#7ƍ.; &3·""5#7Ǝ./ &3µ""5$7Ə.# &;6/\' 8!:Ɛ!! )'),k('%;î/D#%;C/,#;ï/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),k("%;U.) &;\\.# &;X/& 8!:Ƒ! )"),k('%%;!." &"/[#;!." &"/M$;!." &"/?$;!." &"/1$;!." &"/#$+%)(%\'#($\'#(#\'#("\'#&\'#/\' 8!:ƒ!! )'),k('%%;!/?#;!." &"/1$;!." &"/#$+#)(#\'#("\'#&\'#/\' 8!:Ɠ!! )'),k(";¾"),k('%;ž/^#$%;B/,#;ó/#$+")("\'#&\'#06*%;B/,#;ó/#$+")("\'#&\'#&/($8":Ɣ"!!)("\'#&\'#'),k(";ô.# &; "),k('%2ƕ""6ƕ7Ɩ/L#;""6>7?'),k('%;Ā/b#28""6879/S$;û/J$%2ƣ""6ƣ7Ƥ/,#;ì/#$+")("\'#&\'#." &"/#$+$)($\'#(#\'#("\'#&\'#'),k('%3ƥ""5%7Ʀ.) &3Ƨ""5$7ƨ/\' 8!:ơ!! )'),k('%3±""5#7².6 &3³""5#7´.* &$;+0#*;+&/\' 8!:Ʃ!! )'),k("%;Ą/‡#2F\"\"6F7G/x$;ă/o$2F\"\"6F7G/`$;ă/W$2F\"\"6F7G/H$;ă/?$2F\"\"6F7G/0$;ą/'$8):ƪ) )()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#"),k("%;#/>#;#/5$;#/,$;#/#$+$)($'#(#'#(\"'#&'#"),k("%;ă/,#;ă/#$+\")(\"'#&'#"),k("%;ă/5#;ă/,$;ă/#$+#)(#'#(\"'#&'#"),k("%;q/T#$;m0#*;m&/D$%; /,#;ø/#$+\")(\"'#&'#.\" &\"/#$+#)(#'#(\"'#&'#"),k('%2ƫ""6ƫ7Ƭ.) &2ƭ""6ƭ7Ʈ/w#;0/n$;Ĉ/e$$%;B/2#;ĉ.# &; /#$+")("\'#&\'#0<*%;B/2#;ĉ.# &; /#$+")("\'#&\'#&/#$+$)($\'#(#\'#("\'#&\'#'),k(";™.# &;L"),k("%2Ư\"\"6Ư7ư/5#;h&&(h=l,f=[]),f.push(e))}function k(e){return e.split("").map(e=>e.charCodeAt(0)-32)}if(t.data={},d=function t(r){const i=s[r];let o=0;const u=[];let d=i.length;const h=[],f=[];let g;for(;;){for(;ol?(d=o+3+i[o+1],o+=3):(d=o+3+i[o+1]+i[o+2],o+=3+i[o+1]);break;case 18:h.push(d),u.push(o+4+i[o+2]+i[o+3]),e.substr(l,a[i[o+1]].length)===a[i[o+1]]?(d=o+4+i[o+2],o+=4):(d=o+4+i[o+2]+i[o+3],o+=4+i[o+2]);break;case 19:h.push(d),u.push(o+4+i[o+2]+i[o+3]),e.substr(l,a[i[o+1]].length).toLowerCase()===a[i[o+1]]?(d=o+4+i[o+2],o+=4):(d=o+4+i[o+2]+i[o+3],o+=4+i[o+2]);break;case 20:h.push(d),u.push(o+4+i[o+2]+i[o+3]),a[i[o+1]].test(e.charAt(l))?(d=o+4+i[o+2],o+=4):(d=o+4+i[o+2]+i[o+3],o+=4+i[o+2]);break;case 21:f.push(e.substr(l,i[o+1])),l+=i[o+1],o+=2;break;case 22:f.push(a[i[o+1]]),l+=a[i[o+1]].length,o+=2;break;case 23:f.push(n),0===p&&x(a[i[o+1]]),o+=2;break;case 24:c=f[f.length-1-i[o+1]],o+=2;break;case 25:c=l,o++;break;case 26:g=i.slice(o+4,o+4+i[o+3]).map(function(e){return f[f.length-1-e]}),f.splice(f.length-i[o+2],i[o+2],a[i[o+1]].apply(null,g)),o+=4+i[o+3];break;case 27:f.push(t(i[o+1])),o+=2;break;case 28:p++,o++;break;case 29:p--,o++;break;default:throw new Error("Invalid opcode: "+i[o]+".")}if(!(h.length>0))break;d=h.pop(),o=u.pop()}return f[0]}(o),d!==n&&l===e.length)return d;throw d!==n&&l=this.headers[e].length)return;const n=this.headers[e][t],r=n.raw;if(n.parsed)return n.parsed;const i=_e.parse(r,e.replace(/-/g,"_"));return-1===i?void this.headers[e].splice(t,1):(n.parsed=i,i)}s(e,t=0){return this.parseHeader(e,t)}setHeader(e,t){this.headers[$e(e)]=[{raw:t}]}toString(){return this.data}}class Le extends je{constructor(){super()}}class He extends je{constructor(){super()}}class Fe{constructor(e,t,n,r,i,o,a){this.headers={},this.extraHeaders=[],this.options=Fe.getDefaultOptions(),i&&(this.options=Object.assign(Object.assign({},this.options),i),this.options.optionTags&&this.options.optionTags.length&&(this.options.optionTags=this.options.optionTags.slice()),this.options.routeSet&&this.options.routeSet.length&&(this.options.routeSet=this.options.routeSet.slice())),o&&o.length&&(this.extraHeaders=o.slice()),a&&(this.body={body:a.content,contentType:a.contentType}),this.method=e,this.ruri=t.clone(),this.fromURI=n.clone(),this.fromTag=this.options.fromTag?this.options.fromTag:Me(),this.from=Fe.makeNameAddrHeader(this.fromURI,this.options.fromDisplayName,this.fromTag),this.toURI=r.clone(),this.toTag=this.options.toTag,this.to=Fe.makeNameAddrHeader(this.toURI,this.options.toDisplayName,this.toTag),this.callId=this.options.callId?this.options.callId:this.options.callIdPrefix+Ae(15),this.cseq=this.options.cseq,this.setHeader("route",this.options.routeSet),this.setHeader("via",""),this.setHeader("to",this.to.toString()),this.setHeader("from",this.from.toString()),this.setHeader("cseq",this.cseq+" "+this.method),this.setHeader("call-id",this.callId),this.setHeader("max-forwards","70")}static getDefaultOptions(){return{callId:"",callIdPrefix:"",cseq:1,toDisplayName:"",toTag:"",fromDisplayName:"",fromTag:"",forceRport:!1,hackViaTcp:!1,optionTags:["outbound"],routeSet:[],userAgentString:"sip.js",viaHost:""}}static makeNameAddrHeader(e,t,n){const r={};return n&&(r.tag=n),new Se(e,t,r)}getHeader(e){const t=this.headers[$e(e)];if(t){if(t[0])return t[0]}else{const t=new RegExp("^\\s*"+e+"\\s*:","i");for(const e of this.extraHeaders)if(t.test(e))return e.substring(e.indexOf(":")+1).trim()}}getHeaders(e){const t=[],n=this.headers[$e(e)];if(n)for(const r of n)t.push(r);else{const n=new RegExp("^\\s*"+e+"\\s*:","i");for(const e of this.extraHeaders)n.test(e)&&t.push(e.substring(e.indexOf(":")+1).trim())}return t}hasHeader(e){if(this.headers[$e(e)])return!0;{const t=new RegExp("^\\s*"+e+"\\s*:","i");for(const e of this.extraHeaders)if(t.test(e))return!0}return!1}setHeader(e,t){this.headers[$e(e)]=t instanceof Array?t:[t]}setViaHeader(e,t){this.options.hackViaTcp&&(t="TCP");let n="SIP/2.0/"+t;n+=" "+this.options.viaHost+";branch="+e,this.options.forceRport&&(n+=";rport"),this.setHeader("via",n),this.branch=e}toString(){let e="";e+=this.method+" "+this.ruri.toRaw()+" SIP/2.0\r\n";for(const t in this.headers)if(this.headers[t])for(const n of this.headers[t])e+=t+": "+n+"\r\n";for(const t of this.extraHeaders)e+=t.trim()+"\r\n";return e+="Supported: "+this.options.optionTags.join(", ")+"\r\n",e+="User-Agent: "+this.options.userAgentString+"\r\n",this.body?"string"==typeof this.body?(e+="Content-Length: "+Oe(this.body)+"\r\n\r\n",e+=this.body):this.body.body&&this.body.contentType?(e+="Content-Type: "+this.body.contentType+"\r\n",e+="Content-Length: "+Oe(this.body.body)+"\r\n\r\n",e+=this.body.body):e+="Content-Length: 0\r\n\r\n":e+="Content-Length: 0\r\n\r\n",e}}function Ue(e){return"application/sdp"===e?"session":"render"}function ze(e){const t="string"==typeof e?e:e.body,n="string"==typeof e?"application/sdp":e.contentType;return{contentDisposition:Ue(n),contentType:n,content:t}}function qe(e){return!(!e||"string"!=typeof e.content||"string"!=typeof e.contentType||void 0!==e.contentDisposition)||"string"==typeof e.contentDisposition}function Ve(e){let t,n,r;if(e instanceof Le&&e.body){const i=e.parseHeader("Content-Disposition");t=i?i.type:void 0,n=e.parseHeader("Content-Type"),r=e.body}if(e instanceof He&&e.body){const i=e.parseHeader("Content-Disposition");t=i?i.type:void 0,n=e.parseHeader("Content-Type"),r=e.body}if(e instanceof Fe&&e.body)if(t=e.getHeader("Content-Disposition"),n=e.getHeader("Content-Type"),"string"==typeof e.body){if(!n)throw new Error("Header content type header does not equal body content type.");r=e.body}else{if(n&&n!==e.body.contentType)throw new Error("Header content type header does not equal body content type.");n=e.body.contentType,r=e.body.body}if(qe(e)&&(t=e.contentDisposition,n=e.contentType,r=e.content),r){if(n&&!t&&(t=Ue(n)),!t)throw new Error("Content disposition undefined.");if(!n)throw new Error("Content type undefined.");return{contentDisposition:t,contentType:n,content:r}}}var Be,We,Ye,Ge;(We=Be=Be||(Be={})).Initial="Initial",We.Early="Early",We.AckWait="AckWait",We.Confirmed="Confirmed",We.Terminated="Terminated",(Ge=Ye=Ye||(Ye={})).Initial="Initial",Ge.HaveLocalOffer="HaveLocalOffer",Ge.HaveRemoteOffer="HaveRemoteOffer",Ge.Stable="Stable",Ge.Closed="Closed";const Ke=500,Qe={T1:Ke,T2:4e3,TIMER_B:32e3,TIMER_D:0,TIMER_F:32e3,TIMER_H:32e3,TIMER_I:0,TIMER_J:0,TIMER_K:0,TIMER_L:32e3,TIMER_M:32e3,TIMER_N:32e3,PROVISIONAL_RESPONSE_INTERVAL:6e4};class Xe extends de{constructor(e){super(e||"Transaction state error.")}}var Ze,Je;(Je=Ze=Ze||(Ze={})).ACK="ACK",Je.BYE="BYE",Je.CANCEL="CANCEL",Je.INFO="INFO",Je.INVITE="INVITE",Je.MESSAGE="MESSAGE",Je.NOTIFY="NOTIFY",Je.OPTIONS="OPTIONS",Je.REGISTER="REGISTER",Je.UPDATE="UPDATE",Je.SUBSCRIBE="SUBSCRIBE",Je.PUBLISH="PUBLISH",Je.REFER="REFER",Je.PRACK="PRACK";const et=[Ze.ACK,Ze.BYE,Ze.CANCEL,Ze.INFO,Ze.INVITE,Ze.MESSAGE,Ze.NOTIFY,Ze.OPTIONS,Ze.PRACK,Ze.REFER,Ze.REGISTER,Ze.SUBSCRIBE];class tt{constructor(e){this.incomingMessageRequest=e}get request(){return this.incomingMessageRequest.message}accept(e){return this.incomingMessageRequest.accept(e),Promise.resolve()}reject(e){return this.incomingMessageRequest.reject(e),Promise.resolve()}}class nt{constructor(e){this.incomingNotifyRequest=e}get request(){return this.incomingNotifyRequest.message}accept(e){return this.incomingNotifyRequest.accept(e),Promise.resolve()}reject(e){return this.incomingNotifyRequest.reject(e),Promise.resolve()}}class rt{constructor(e,t){this.incomingReferRequest=e,this.session=t}get referTo(){const e=this.incomingReferRequest.message.parseHeader("refer-to");if(!(e instanceof Se))throw new Error("Failed to parse Refer-To header.");return e}get referredBy(){return this.incomingReferRequest.message.getHeader("referred-by")}get replaces(){const e=this.referTo.uri.getHeader("replaces");return e instanceof Array?e[0]:e}get request(){return this.incomingReferRequest.message}accept(e={statusCode:202}){return this.incomingReferRequest.accept(e),Promise.resolve()}reject(e){return this.incomingReferRequest.reject(e),Promise.resolve()}makeInviter(e){if(this.inviter)return this.inviter;const t=this.referTo.uri.clone();t.clearHeaders();const n=((e=e||{}).extraHeaders||[]).slice(),r=this.replaces;r&&n.push("Replaces: "+decodeURIComponent(r));const i=this.referredBy;return i&&n.push("Referred-By: "+i),e.extraHeaders=n,this.inviter=this.session.userAgent._makeInviter(t,e),this.inviter._referred=this.session,this.session._referral=this.inviter,this.inviter}}var it,ot,at;!function(e){e.Initial="Initial",e.Establishing="Establishing",e.Established="Established",e.Terminating="Terminating",e.Terminated="Terminated"}(it=it||(it={}));class st{constructor(e,t={}){this.pendingReinvite=!1,this.pendingReinviteAck=!1,this._state=it.Initial,this.delegate=t.delegate,this._stateEventEmitter=new we,this._userAgent=e}dispose(){switch(this.logger.log(`Session ${this.id} in state ${this._state} is being disposed`),delete this.userAgent._sessions[this.id],this._sessionDescriptionHandler&&this._sessionDescriptionHandler.close(),this.state){case it.Initial:case it.Establishing:break;case it.Established:return new Promise(e=>{this._bye({onAccept:()=>e(),onRedirect:()=>e(),onReject:()=>e()})});case it.Terminating:case it.Terminated:break;default:throw new Error("Unknown state.")}return Promise.resolve()}get assertedIdentity(){return this._assertedIdentity}get dialog(){return this._dialog}get id(){return this._id}get replacee(){return this._replacee}get sessionDescriptionHandler(){return this._sessionDescriptionHandler}get sessionDescriptionHandlerFactory(){return this.userAgent.configuration.sessionDescriptionHandlerFactory}get sessionDescriptionHandlerModifiers(){return this._sessionDescriptionHandlerModifiers||[]}set sessionDescriptionHandlerModifiers(e){this._sessionDescriptionHandlerModifiers=e.slice()}get sessionDescriptionHandlerOptions(){return this._sessionDescriptionHandlerOptions||{}}set sessionDescriptionHandlerOptions(e){this._sessionDescriptionHandlerOptions=Object.assign({},e)}get sessionDescriptionHandlerModifiersReInvite(){return this._sessionDescriptionHandlerModifiersReInvite||[]}set sessionDescriptionHandlerModifiersReInvite(e){this._sessionDescriptionHandlerModifiersReInvite=e.slice()}get sessionDescriptionHandlerOptionsReInvite(){return this._sessionDescriptionHandlerOptionsReInvite||{}}set sessionDescriptionHandlerOptionsReInvite(e){this._sessionDescriptionHandlerOptionsReInvite=Object.assign({},e)}get state(){return this._state}get stateChange(){return this._stateEventEmitter}get userAgent(){return this._userAgent}bye(e={}){let t="Session.bye() may only be called if established session.";switch(this.state){case it.Initial:"function"==typeof this.cancel?(t+=" However Inviter.invite() has not yet been called.",t+=" Perhaps you should have called Inviter.cancel()?"):"function"==typeof this.reject&&(t+=" However Invitation.accept() has not yet been called.",t+=" Perhaps you should have called Invitation.reject()?");break;case it.Establishing:"function"==typeof this.cancel?(t+=" However a dialog does not yet exist.",t+=" Perhaps you should have called Inviter.cancel()?"):"function"==typeof this.reject&&(t+=" However Invitation.accept() has not yet been called (or not yet resolved).",t+=" Perhaps you should have called Invitation.reject()?");break;case it.Established:{const t=e.requestDelegate,n=this.copyRequestOptions(e.requestOptions);return this._bye(t,n)}case it.Terminating:t+=" However this session is already terminating.","function"==typeof this.cancel?t+=" Perhaps you have already called Inviter.cancel()?":"function"==typeof this.reject&&(t+=" Perhaps you have already called Session.bye()?");break;case it.Terminated:t+=" However this session is already terminated.";break;default:throw new Error("Unknown state")}return this.logger.error(t),Promise.reject(new Error(`Invalid session state ${this.state}`))}info(e={}){if(this.state!==it.Established){const e="Session.info() may only be called if established session.";return this.logger.error(e),Promise.reject(new Error(`Invalid session state ${this.state}`))}const t=e.requestDelegate,n=this.copyRequestOptions(e.requestOptions);return this._info(t,n)}invite(e={}){if(this.logger.log("Session.invite"),this.state!==it.Established)return Promise.reject(new Error(`Invalid session state ${this.state}`));if(this.pendingReinvite)return Promise.reject(new fe("Reinvite in progress. Please wait until complete, then try again."));this.pendingReinvite=!0,e.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiersReInvite=e.sessionDescriptionHandlerModifiers),e.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptionsReInvite=e.sessionDescriptionHandlerOptions);const t={onAccept:t=>{const n=Ve(t.message);if(!n)return this.logger.error("Received 2xx response to re-INVITE without a session description"),this.ackAndBye(t,400,"Missing session description"),this.stateTransition(it.Terminated),void(this.pendingReinvite=!1);if(e.withoutSdp){const r={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};this.setOfferAndGetAnswer(n,r).then(e=>{t.ack({body:e})}).catch(e=>{this.logger.error("Failed to handle offer in 2xx response to re-INVITE"),this.logger.error(e.message),this.state===it.Terminated?t.ack():(this.ackAndBye(t,488,"Bad Media Description"),this.stateTransition(it.Terminated))}).then(()=>{this.pendingReinvite=!1,e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(t)})}else{const r={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};this.setAnswer(n,r).then(()=>{t.ack()}).catch(e=>{this.logger.error("Failed to handle answer in 2xx response to re-INVITE"),this.logger.error(e.message),this.state!==it.Terminated?(this.ackAndBye(t,488,"Bad Media Description"),this.stateTransition(it.Terminated)):t.ack()}).then(()=>{this.pendingReinvite=!1,e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(t)})}},onProgress:e=>{},onRedirect:e=>{},onReject:t=>{this.logger.warn("Received a non-2xx response to re-INVITE"),this.pendingReinvite=!1,e.withoutSdp?e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(t):this.rollbackOffer().catch(e=>{if(this.logger.error("Failed to rollback offer on non-2xx response to re-INVITE"),this.logger.error(e.message),this.state!==it.Terminated){if(!this.dialog)throw new Error("Dialog undefined.");const e=[];e.push("Reason: "+this.getReasonHeaderValue(500,"Internal Server Error")),this.dialog.bye(void 0,{extraHeaders:e}),this.stateTransition(it.Terminated)}}).then(()=>{e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(t)})},onTrying:e=>{}},n=e.requestOptions||{};if(n.extraHeaders=(n.extraHeaders||[]).slice(),n.extraHeaders.push("Allow: "+et.toString()),n.extraHeaders.push("Contact: "+this._contact),e.withoutSdp){if(!this.dialog)throw this.pendingReinvite=!1,new Error("Dialog undefined.");return Promise.resolve(this.dialog.invite(t,n))}const r={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};return this.getOffer(r).then(e=>{if(!this.dialog)throw this.pendingReinvite=!1,new Error("Dialog undefined.");return n.body=e,this.dialog.invite(t,n)}).catch(e=>{throw this.logger.error(e.message),this.logger.error("Failed to send re-INVITE"),this.pendingReinvite=!1,e})}message(e={}){if(this.state!==it.Established){const e="Session.message() may only be called if established session.";return this.logger.error(e),Promise.reject(new Error(`Invalid session state ${this.state}`))}const t=e.requestDelegate,n=this.copyRequestOptions(e.requestOptions);return this._message(t,n)}refer(e,t={}){if(this.state!==it.Established){const e="Session.refer() may only be called if established session.";return this.logger.error(e),Promise.reject(new Error(`Invalid session state ${this.state}`))}if(e instanceof st&&!e.dialog){const e="Session.refer() may only be called with session which is established. You are perhaps attempting to attended transfer to a target for which there is not dialog yet established. Perhaps you are attempting a 'semi-attended' tansfer? Regardless, this is not supported. The recommended approached is to check to see if the target Session is in the Established state before calling refer(); if the state is not Established you may proceed by falling back using a URI as the target (blind transfer).";return this.logger.error(e),Promise.reject(new Error(`Invalid session state ${this.state}`))}const n=t.requestDelegate,r=this.copyRequestOptions(t.requestOptions);return r.extraHeaders=r.extraHeaders?r.extraHeaders.concat(this.referExtraHeaders(this.referToString(e))):this.referExtraHeaders(this.referToString(e)),this._refer(t.onNotify,n,r)}_bye(e,t){if(!this.dialog)return Promise.reject(new Error("Session dialog undefined."));const n=this.dialog;switch(n.sessionState){case Be.Initial:case Be.Early:throw new Error(`Invalid dialog state ${n.sessionState}`);case Be.AckWait:return this.stateTransition(it.Terminating),new Promise(r=>{n.delegate={onAck:()=>{const i=n.bye(e,t);return this.stateTransition(it.Terminated),r(i),Promise.resolve()},onAckTimeout:()=>{const i=n.bye(e,t);this.stateTransition(it.Terminated),r(i)}}});case Be.Confirmed:{const r=n.bye(e,t);return this.stateTransition(it.Terminated),Promise.resolve(r)}case Be.Terminated:throw new Error(`Invalid dialog state ${n.sessionState}`);default:throw new Error("Unrecognized state.")}}_info(e,t){return this.dialog?Promise.resolve(this.dialog.info(e,t)):Promise.reject(new Error("Session dialog undefined."))}_message(e,t){return this.dialog?Promise.resolve(this.dialog.message(e,t)):Promise.reject(new Error("Session dialog undefined."))}_refer(e,t,n){return this.dialog?(this.onNotify=e,Promise.resolve(this.dialog.refer(t,n))):Promise.reject(new Error("Session dialog undefined."))}ackAndBye(e,t,n){e.ack();const r=[];t&&r.push("Reason: "+this.getReasonHeaderValue(t,n)),e.session.bye(void 0,{extraHeaders:r})}onAckRequest(e){if(this.logger.log("Session.onAckRequest"),this.state!==it.Established&&this.state!==it.Terminating)return this.logger.error(`ACK received while in state ${this.state}, dropping request`),Promise.resolve();const t=this.dialog;if(!t)throw new Error("Dialog undefined.");const n={sessionDescriptionHandlerOptions:this.pendingReinviteAck?this.sessionDescriptionHandlerOptionsReInvite:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.pendingReinviteAck?this._sessionDescriptionHandlerModifiersReInvite:this._sessionDescriptionHandlerModifiers};if(this.delegate&&this.delegate.onAck){const t=new ve(e);this.delegate.onAck(t)}switch(this.pendingReinviteAck=!1,t.signalingState){case Ye.Initial:{this.logger.error(`Invalid signaling state ${t.signalingState}.`);const e=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];return t.bye(void 0,{extraHeaders:e}),this.stateTransition(it.Terminated),Promise.resolve()}case Ye.Stable:{const r=Ve(e.message);return r?"render"===r.contentDisposition?(this._renderbody=r.content,this._rendertype=r.contentType,Promise.resolve()):"session"!==r.contentDisposition?Promise.resolve():this.setAnswer(r,n).catch(e=>{this.logger.error(e.message);const n=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];t.bye(void 0,{extraHeaders:n}),this.stateTransition(it.Terminated)}):Promise.resolve()}case Ye.HaveLocalOffer:{this.logger.error(`Invalid signaling state ${t.signalingState}.`);const e=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];return t.bye(void 0,{extraHeaders:e}),this.stateTransition(it.Terminated),Promise.resolve()}case Ye.HaveRemoteOffer:{this.logger.error(`Invalid signaling state ${t.signalingState}.`);const e=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];return t.bye(void 0,{extraHeaders:e}),this.stateTransition(it.Terminated),Promise.resolve()}case Ye.Closed:default:throw new Error(`Invalid signaling state ${t.signalingState}.`)}}onByeRequest(e){if(this.logger.log("Session.onByeRequest"),this.state===it.Established){if(this.delegate&&this.delegate.onBye){const t=new ye(e);this.delegate.onBye(t)}else e.accept();this.stateTransition(it.Terminated)}else this.logger.error(`BYE received while in state ${this.state}, dropping request`)}onInfoRequest(e){if(this.logger.log("Session.onInfoRequest"),this.state===it.Established)if(this.delegate&&this.delegate.onInfo){const t=new xe(e);this.delegate.onInfo(t)}else e.accept();else this.logger.error(`INFO received while in state ${this.state}, dropping request`)}onInviteRequest(e){if(this.logger.log("Session.onInviteRequest"),this.state!==it.Established)return void this.logger.error(`INVITE received while in state ${this.state}, dropping request`);this.pendingReinviteAck=!0;const t=["Contact: "+this._contact];if(e.message.hasHeader("P-Asserted-Identity")){const t=e.message.getHeader("P-Asserted-Identity");if(!t)throw new Error("Header undefined.");this._assertedIdentity=_e.nameAddrHeaderParse(t)}const n={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};this.generateResponseOfferAnswerInDialog(n).then(n=>{const r=e.accept({statusCode:200,extraHeaders:t,body:n});this.delegate&&this.delegate.onInvite&&this.delegate.onInvite(e.message,r.message,200)}).catch(t=>{if(this.logger.error(t.message),this.logger.error("Failed to handle to re-INVITE request"),!this.dialog)throw new Error("Dialog undefined.");if(this.logger.error(this.dialog.signalingState),this.dialog.signalingState===Ye.Stable){const t=e.reject({statusCode:488});return void(this.delegate&&this.delegate.onInvite&&this.delegate.onInvite(e.message,t.message,488))}this.rollbackOffer().then(()=>{const t=e.reject({statusCode:488});this.delegate&&this.delegate.onInvite&&this.delegate.onInvite(e.message,t.message,488)}).catch(t=>{this.logger.error(t.message),this.logger.error("Failed to rollback offer on re-INVITE request");const n=e.reject({statusCode:488});if(this.state!==it.Terminated){if(!this.dialog)throw new Error("Dialog undefined.");const e=[];e.push("Reason: "+this.getReasonHeaderValue(500,"Internal Server Error")),this.dialog.bye(void 0,{extraHeaders:e}),this.stateTransition(it.Terminated)}this.delegate&&this.delegate.onInvite&&this.delegate.onInvite(e.message,n.message,488)})})}onMessageRequest(e){if(this.logger.log("Session.onMessageRequest"),this.state===it.Established)if(this.delegate&&this.delegate.onMessage){const t=new tt(e);this.delegate.onMessage(t)}else e.accept();else this.logger.error(`MESSAGE received while in state ${this.state}, dropping request`)}onNotifyRequest(e){if(this.logger.log("Session.onNotifyRequest"),this.state===it.Established){if(this.onNotify){const t=new nt(e);return void this.onNotify(t)}if(this.delegate&&this.delegate.onNotify){const t=new nt(e);this.delegate.onNotify(t)}else e.accept()}else this.logger.error(`NOTIFY received while in state ${this.state}, dropping request`)}onPrackRequest(e){if(this.logger.log("Session.onPrackRequest"),this.state===it.Established)throw new Error("Unimplemented.");this.logger.error(`PRACK received while in state ${this.state}, dropping request`)}onReferRequest(e){if(this.logger.log("Session.onReferRequest"),this.state!==it.Established)return void this.logger.error(`REFER received while in state ${this.state}, dropping request`);if(!e.message.hasHeader("refer-to"))return this.logger.warn("Invalid REFER packet. A refer-to header is required. Rejecting."),void e.reject();const t=new rt(e,this);this.delegate&&this.delegate.onRefer?this.delegate.onRefer(t):(this.logger.log("No delegate available to handle REFER, automatically accepting and following."),t.accept().then(()=>t.makeInviter(this._referralInviterOptions).invite()).catch(e=>{this.logger.error(e.message)}))}generateResponseOfferAnswer(e,t){if(this.dialog)return this.generateResponseOfferAnswerInDialog(t);const n=Ve(e.message);return n&&"session"===n.contentDisposition?this.setOfferAndGetAnswer(n,t):this.getOffer(t)}generateResponseOfferAnswerInDialog(e){if(!this.dialog)throw new Error("Dialog undefined.");switch(this.dialog.signalingState){case Ye.Initial:return this.getOffer(e);case Ye.HaveLocalOffer:return Promise.resolve(void 0);case Ye.HaveRemoteOffer:if(!this.dialog.offer)throw new Error(`Session offer undefined in signaling state ${this.dialog.signalingState}.`);return this.setOfferAndGetAnswer(this.dialog.offer,e);case Ye.Stable:return this.state!==it.Established?Promise.resolve(void 0):this.getOffer(e);case Ye.Closed:default:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`)}}getOffer(e){const t=this.setupSessionDescriptionHandler(),n=e.sessionDescriptionHandlerOptions,r=e.sessionDescriptionHandlerModifiers;try{return t.getDescription(n,r).then(e=>ze(e)).catch(e=>{this.logger.error("Session.getOffer: SDH getDescription rejected...");const t=e instanceof Error?e:new Error("Session.getOffer unknown error.");throw this.logger.error(t.message),t})}catch(i){this.logger.error("Session.getOffer: SDH getDescription threw...");const e=i instanceof Error?i:new Error(i);return this.logger.error(e.message),Promise.reject(e)}}rollbackOffer(){const e=this.setupSessionDescriptionHandler();if(void 0===e.rollbackDescription)return Promise.resolve();try{return e.rollbackDescription().catch(e=>{this.logger.error("Session.rollbackOffer: SDH rollbackDescription rejected...");const t=e instanceof Error?e:new Error("Session.rollbackOffer unknown error.");throw this.logger.error(t.message),t})}catch(t){this.logger.error("Session.rollbackOffer: SDH rollbackDescription threw...");const e=t instanceof Error?t:new Error(t);return this.logger.error(e.message),Promise.reject(e)}}setAnswer(e,t){const n=this.setupSessionDescriptionHandler(),r=t.sessionDescriptionHandlerOptions,i=t.sessionDescriptionHandlerModifiers;try{if(!n.hasDescription(e.contentType))return Promise.reject(new he)}catch(o){this.logger.error("Session.setAnswer: SDH hasDescription threw...");const e=o instanceof Error?o:new Error(o);return this.logger.error(e.message),Promise.reject(e)}try{return n.setDescription(e.content,r,i).catch(e=>{this.logger.error("Session.setAnswer: SDH setDescription rejected...");const t=e instanceof Error?e:new Error("Session.setAnswer unknown error.");throw this.logger.error(t.message),t})}catch(o){this.logger.error("Session.setAnswer: SDH setDescription threw...");const e=o instanceof Error?o:new Error(o);return this.logger.error(e.message),Promise.reject(e)}}setOfferAndGetAnswer(e,t){const n=this.setupSessionDescriptionHandler(),r=t.sessionDescriptionHandlerOptions,i=t.sessionDescriptionHandlerModifiers;try{if(!n.hasDescription(e.contentType))return Promise.reject(new he)}catch(o){this.logger.error("Session.setOfferAndGetAnswer: SDH hasDescription threw...");const e=o instanceof Error?o:new Error(o);return this.logger.error(e.message),Promise.reject(e)}try{return n.setDescription(e.content,r,i).then(()=>n.getDescription(r,i)).then(e=>ze(e)).catch(e=>{this.logger.error("Session.setOfferAndGetAnswer: SDH setDescription or getDescription rejected...");const t=e instanceof Error?e:new Error("Session.setOfferAndGetAnswer unknown error.");throw this.logger.error(t.message),t})}catch(o){this.logger.error("Session.setOfferAndGetAnswer: SDH setDescription or getDescription threw...");const e=o instanceof Error?o:new Error(o);return this.logger.error(e.message),Promise.reject(e)}}setSessionDescriptionHandler(e){if(this._sessionDescriptionHandler)throw new Error("Session description handler defined.");this._sessionDescriptionHandler=e}setupSessionDescriptionHandler(){var e;return this._sessionDescriptionHandler||(this._sessionDescriptionHandler=this.sessionDescriptionHandlerFactory(this,this.userAgent.configuration.sessionDescriptionHandlerFactoryOptions),(null===(e=this.delegate)||void 0===e?void 0:e.onSessionDescriptionHandler)&&this.delegate.onSessionDescriptionHandler(this._sessionDescriptionHandler,!1)),this._sessionDescriptionHandler}stateTransition(e){const t=()=>{throw new Error(`Invalid state transition from ${this._state} to ${e}`)};switch(this._state){case it.Initial:e!==it.Establishing&&e!==it.Established&&e!==it.Terminating&&e!==it.Terminated&&t();break;case it.Establishing:e!==it.Established&&e!==it.Terminating&&e!==it.Terminated&&t();break;case it.Established:e!==it.Terminating&&e!==it.Terminated&&t();break;case it.Terminating:e!==it.Terminated&&t();break;case it.Terminated:t();break;default:throw new Error("Unrecognized state.")}this._state=e,this.logger.log(`Session ${this.id} transitioned to state ${this._state}`),this._stateEventEmitter.emit(this._state),e===it.Terminated&&this.dispose()}copyRequestOptions(e={}){return{extraHeaders:e.extraHeaders?e.extraHeaders.slice():void 0,body:e.body?{contentDisposition:e.body.contentDisposition||"render",contentType:e.body.contentType||"text/plain",content:e.body.content||""}:void 0}}getReasonHeaderValue(e,t){const n=e;let r=Ne(e);return!r&&t&&(r=t),"SIP;cause="+n+';text="'+r+'"'}referExtraHeaders(e){const t=[];return t.push("Referred-By: <"+this.userAgent.configuration.uri+">"),t.push("Contact: "+this._contact),t.push("Allow: "+["ACK","CANCEL","INVITE","MESSAGE","BYE","OPTIONS","INFO","NOTIFY","REFER"].toString()),t.push("Refer-To: "+e),t}referToString(e){let t;if(e instanceof Te)t=e.toString();else{if(!e.dialog)throw new Error("Dialog undefined.");const n=e.remoteIdentity.friendlyName,r=e.dialog.remoteTarget.toString(),i=e.dialog.callId,o=e.dialog.remoteTag,a=e.dialog.localTag;t=`"${n}" <${r}?Replaces=${encodeURIComponent(`${i};to-tag=${o};from-tag=${a}`)}>`}return t}}(at=ot=ot||(ot={})).Required="Required",at.Supported="Supported",at.Unsupported="Unsupported";const lt={"100rel":!0,199:!0,answermode:!0,"early-session":!0,eventlist:!0,explicitsub:!0,"from-change":!0,"geolocation-http":!0,"geolocation-sip":!0,gin:!0,gruu:!0,histinfo:!0,ice:!0,join:!0,"multiple-refer":!0,norefersub:!0,nosub:!0,outbound:!0,path:!0,policy:!0,precondition:!0,pref:!0,privacy:!0,"recipient-list-invite":!0,"recipient-list-message":!0,"recipient-list-subscribe":!0,replaces:!0,"resource-priority":!0,"sdp-anat":!0,"sec-agree":!0,tdialog:!0,timer:!0,uui:!0};class ct extends st{constructor(e,t){super(e),this.incomingInviteRequest=t,this.disposed=!1,this.expiresTimer=void 0,this.isCanceled=!1,this.rel100="none",this.rseq=Math.floor(1e4*Math.random()),this.userNoAnswerTimer=void 0,this.waitingForPrack=!1,this.logger=e.getLogger("sip.Invitation");const n=this.incomingInviteRequest.message,r=n.getHeader("require");r&&r.toLowerCase().includes("100rel")&&(this.rel100="required");const i=n.getHeader("supported");if(i&&i.toLowerCase().includes("100rel")&&(this.rel100="supported"),n.toTag=t.toTag,"string"!=typeof n.toTag)throw new TypeError("toTag should have been a string.");if(this.userNoAnswerTimer=setTimeout(()=>{t.reject({statusCode:480}),this.stateTransition(it.Terminated)},this.userAgent.configuration.noAnswerTimeout?1e3*this.userAgent.configuration.noAnswerTimeout:6e4),n.hasHeader("expires")){const e=1e3*Number(n.getHeader("expires")||0);this.expiresTimer=setTimeout(()=>{this.state===it.Initial&&(t.reject({statusCode:487}),this.stateTransition(it.Terminated))},e)}const o=this.request.getHeader("P-Asserted-Identity");o&&(this._assertedIdentity=_e.nameAddrHeaderParse(o)),this._contact=this.userAgent.contact.toString();const a=n.parseHeader("Content-Disposition");a&&"render"===a.type&&(this._renderbody=n.body,this._rendertype=n.getHeader("Content-Type")),this._id=n.callId+n.fromTag,this.userAgent._sessions[this._id]=this}dispose(){if(this.disposed)return Promise.resolve();switch(this.disposed=!0,this.expiresTimer&&(clearTimeout(this.expiresTimer),this.expiresTimer=void 0),this.userNoAnswerTimer&&(clearTimeout(this.userNoAnswerTimer),this.userNoAnswerTimer=void 0),this.prackNeverArrived(),this.state){case it.Initial:case it.Establishing:return this.reject().then(()=>super.dispose());case it.Established:case it.Terminating:case it.Terminated:return super.dispose();default:throw new Error("Unknown state.")}}get autoSendAnInitialProvisionalResponse(){return"required"!==this.rel100&&this.userAgent.configuration.sendInitialProvisionalResponse}get body(){return this.incomingInviteRequest.message.body}get localIdentity(){return this.request.to}get remoteIdentity(){return this.request.from}get request(){return this.incomingInviteRequest.message}accept(e={}){if(this.logger.log("Invitation.accept"),this.state!==it.Initial){const e=new Error(`Invalid session state ${this.state}`);return this.logger.error(e.message),Promise.reject(e)}return e.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiers=e.sessionDescriptionHandlerModifiers),e.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptions=e.sessionDescriptionHandlerOptions),this.stateTransition(it.Establishing),this.sendAccept(e).then(({message:e,session:t})=>{t.delegate={onAck:e=>this.onAckRequest(e),onAckTimeout:()=>this.onAckTimeout(),onBye:e=>this.onByeRequest(e),onInfo:e=>this.onInfoRequest(e),onInvite:e=>this.onInviteRequest(e),onMessage:e=>this.onMessageRequest(e),onNotify:e=>this.onNotifyRequest(e),onPrack:e=>this.onPrackRequest(e),onRefer:e=>this.onReferRequest(e)},this._dialog=t,this.stateTransition(it.Established),this._replacee&&this._replacee._bye()}).catch(e=>this.handleResponseError(e))}progress(e={}){if(this.logger.log("Invitation.progress"),this.state!==it.Initial){const e=new Error(`Invalid session state ${this.state}`);return this.logger.error(e.message),Promise.reject(e)}const t=e.statusCode||180;if(t<100||t>199)throw new TypeError("Invalid statusCode: "+t);return e.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiers=e.sessionDescriptionHandlerModifiers),e.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptions=e.sessionDescriptionHandlerOptions),this.waitingForPrack?(this.logger.warn("Unexpected call for progress while waiting for prack, ignoring"),Promise.resolve()):100===e.statusCode?this.sendProgressTrying().then(()=>{}).catch(e=>this.handleResponseError(e)):"required"===this.rel100||"supported"===this.rel100&&e.rel100||"supported"===this.rel100&&this.userAgent.configuration.sipExtension100rel===ot.Required?this.sendProgressReliableWaitForPrack(e).then(()=>{}).catch(e=>this.handleResponseError(e)):this.sendProgress(e).then(()=>{}).catch(e=>this.handleResponseError(e))}reject(e={}){if(this.logger.log("Invitation.reject"),this.state!==it.Initial&&this.state!==it.Establishing){const e=new Error(`Invalid session state ${this.state}`);return this.logger.error(e.message),Promise.reject(e)}const t=e.statusCode||480,n=e.reasonPhrase?e.reasonPhrase:Ne(t),r=e.extraHeaders||[];if(t<300||t>699)throw new TypeError("Invalid statusCode: "+t);const i=e.body?ze(e.body):void 0;return t<400?this.incomingInviteRequest.redirect([],{statusCode:t,reasonPhrase:n,extraHeaders:r,body:i}):this.incomingInviteRequest.reject({statusCode:t,reasonPhrase:n,extraHeaders:r,body:i}),this.stateTransition(it.Terminated),Promise.resolve()}_onCancel(e){if(this.logger.log("Invitation._onCancel"),this.state===it.Initial||this.state===it.Establishing){if(this.delegate&&this.delegate.onCancel){const t=new be(e);this.delegate.onCancel(t)}this.isCanceled=!0,this.incomingInviteRequest.reject({statusCode:487}),this.stateTransition(it.Terminated)}else this.logger.error(`CANCEL received while in state ${this.state}, dropping request`)}handlePrackOfferAnswer(e){if(!this.dialog)throw new Error("Dialog undefined.");const t=Ve(e.message);if(!t||"session"!==t.contentDisposition)return Promise.resolve(void 0);const n={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers};switch(this.dialog.signalingState){case Ye.Initial:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`);case Ye.Stable:return this.setAnswer(t,n).then(()=>{});case Ye.HaveLocalOffer:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`);case Ye.HaveRemoteOffer:return this.setOfferAndGetAnswer(t,n);case Ye.Closed:default:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`)}}handleResponseError(e){let t=480;if(e instanceof Error?this.logger.error(e.message):this.logger.error(e),e instanceof he?(this.logger.error("A session description handler occurred while sending response (content type unsupported"),t=415):e instanceof pe?this.logger.error("A session description handler occurred while sending response"):e instanceof ge?this.logger.error("Session ended before response could be formulated and sent (while waiting for PRACK)"):e instanceof Xe&&this.logger.error("Session changed state before response could be formulated and sent"),this.state===it.Initial||this.state===it.Establishing)try{this.incomingInviteRequest.reject({statusCode:t}),this.stateTransition(it.Terminated)}catch(n){throw this.logger.error("An error occurred attempting to reject the request while handling another error"),n}if(!this.isCanceled)throw e;this.logger.warn("An error occurred while attempting to formulate and send a response to an incoming INVITE. However a CANCEL was received and processed while doing so which can (and often does) result in errors occurring as the session terminates in the meantime. Said error is being ignored.")}onAckTimeout(){if(this.logger.log("Invitation.onAckTimeout"),!this.dialog)throw new Error("Dialog undefined.");this.logger.log("No ACK received for an extended period of time, terminating session"),this.dialog.bye(),this.stateTransition(it.Terminated)}sendAccept(e={}){const t={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers},n=e.extraHeaders||[];return this.waitingForPrack?this.waitForArrivalOfPrack().then(()=>clearTimeout(this.userNoAnswerTimer)).then(()=>this.generateResponseOfferAnswer(this.incomingInviteRequest,t)).then(e=>this.incomingInviteRequest.accept({statusCode:200,body:e,extraHeaders:n})):(clearTimeout(this.userNoAnswerTimer),this.generateResponseOfferAnswer(this.incomingInviteRequest,t).then(e=>this.incomingInviteRequest.accept({statusCode:200,body:e,extraHeaders:n})))}sendProgress(e={}){const t=e.statusCode||180,n=e.reasonPhrase,r=(e.extraHeaders||[]).slice(),i=e.body?ze(e.body):void 0;if(183===t&&!i)return this.sendProgressWithSDP(e);try{const e=this.incomingInviteRequest.progress({statusCode:t,reasonPhrase:n,extraHeaders:r,body:i});return this._dialog=e.session,Promise.resolve(e)}catch(o){return Promise.reject(o)}}sendProgressWithSDP(e={}){const t={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers},n=e.statusCode||183,r=e.reasonPhrase,i=(e.extraHeaders||[]).slice();return this.generateResponseOfferAnswer(this.incomingInviteRequest,t).then(e=>this.incomingInviteRequest.progress({statusCode:n,reasonPhrase:r,extraHeaders:i,body:e})).then(e=>(this._dialog=e.session,e))}sendProgressReliable(e={}){return e.extraHeaders=(e.extraHeaders||[]).slice(),e.extraHeaders.push("Require: 100rel"),e.extraHeaders.push("RSeq: "+Math.floor(1e4*Math.random())),this.sendProgressWithSDP(e)}sendProgressReliableWaitForPrack(e={}){const t={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers},n=e.statusCode||183,r=e.reasonPhrase,i=(e.extraHeaders||[]).slice();let o;return i.push("Require: 100rel"),i.push("RSeq: "+this.rseq++),new Promise((e,a)=>{this.waitingForPrack=!0,this.generateResponseOfferAnswer(this.incomingInviteRequest,t).then(e=>(o=e,this.incomingInviteRequest.progress({statusCode:n,reasonPhrase:r,extraHeaders:i,body:o}))).then(t=>{let s,l;this._dialog=t.session,t.session.delegate={onPrack:n=>{s=n,clearTimeout(c),clearTimeout(h),this.waitingForPrack&&(this.waitingForPrack=!1,this.handlePrackOfferAnswer(s).then(n=>{try{l=s.accept({statusCode:200,body:n}),this.prackArrived(),e({prackRequest:s,prackResponse:l,progressResponse:t})}catch(r){a(r)}}).catch(e=>a(e)))}};const c=setTimeout(()=>{this.waitingForPrack&&(this.waitingForPrack=!1,this.logger.warn("No PRACK received, rejecting INVITE."),clearTimeout(h),this.reject({statusCode:504}).then(()=>a(new ge)).catch(e=>a(e)))},64*Qe.T1),u=()=>{try{this.incomingInviteRequest.progress({statusCode:n,reasonPhrase:r,extraHeaders:i,body:o})}catch(e){return this.waitingForPrack=!1,void a(e)}h=setTimeout(u,d*=2)};let d=Qe.T1,h=setTimeout(u,d)}).catch(e=>{this.waitingForPrack=!1,a(e)})})}sendProgressTrying(){try{const e=this.incomingInviteRequest.trying();return Promise.resolve(e)}catch(e){return Promise.reject(e)}}waitForArrivalOfPrack(){if(this.waitingForPrackPromise)throw new Error("Already waiting for PRACK");return this.waitingForPrackPromise=new Promise((e,t)=>{this.waitingForPrackResolve=e,this.waitingForPrackReject=t}),this.waitingForPrackPromise}prackArrived(){this.waitingForPrackResolve&&this.waitingForPrackResolve(),this.waitingForPrackPromise=void 0,this.waitingForPrackResolve=void 0,this.waitingForPrackReject=void 0}prackNeverArrived(){this.waitingForPrackReject&&this.waitingForPrackReject(new ge),this.waitingForPrackPromise=void 0,this.waitingForPrackResolve=void 0,this.waitingForPrackReject=void 0}}class ut extends st{constructor(e,t,n={}){super(e,n),this.disposed=!1,this.earlyMedia=!1,this.earlyMediaSessionDescriptionHandlers=new Map,this.isCanceled=!1,this.inviteWithoutSdp=!1,this.logger=e.getLogger("sip.Inviter"),this.earlyMedia=void 0!==n.earlyMedia?n.earlyMedia:this.earlyMedia,this.fromTag=Me(),this.inviteWithoutSdp=void 0!==n.inviteWithoutSdp?n.inviteWithoutSdp:this.inviteWithoutSdp;const r=Object.assign({},n);r.params=Object.assign({},n.params);const i=n.anonymous||!1,o=e.contact.toString({anonymous:i,outbound:i?!e.contact.tempGruu:!e.contact.pubGruu});i&&e.configuration.uri&&(r.params.fromDisplayName="Anonymous",r.params.fromUri="sip:anonymous@anonymous.invalid");let a=e.userAgentCore.configuration.aor;if(r.params.fromUri&&(a="string"==typeof r.params.fromUri?_e.URIParse(r.params.fromUri):r.params.fromUri),!a)throw new TypeError("Invalid from URI: "+r.params.fromUri);let s=t;if(r.params.toUri&&(s="string"==typeof r.params.toUri?_e.URIParse(r.params.toUri):r.params.toUri),!s)throw new TypeError("Invalid to URI: "+r.params.toUri);const l=Object.assign({},r.params);l.fromTag=this.fromTag;const c=(r.extraHeaders||[]).slice();i&&e.configuration.uri&&(c.push("P-Preferred-Identity: "+e.configuration.uri.toString()),c.push("Privacy: id")),c.push("Contact: "+o),c.push("Allow: "+["ACK","CANCEL","INVITE","MESSAGE","BYE","OPTIONS","INFO","NOTIFY","REFER"].toString()),e.configuration.sipExtension100rel===ot.Required&&c.push("Require: 100rel"),e.configuration.sipExtensionReplaces===ot.Required&&c.push("Require: replaces"),r.extraHeaders=c;this.outgoingRequestMessage=e.userAgentCore.makeOutgoingRequestMessage(Ze.INVITE,t,a,s,l,c,void 0),this._contact=o,this._referralInviterOptions=r,this._renderbody=n.renderbody,this._rendertype=n.rendertype,n.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiers=n.sessionDescriptionHandlerModifiers),n.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptions=n.sessionDescriptionHandlerOptions),n.sessionDescriptionHandlerModifiersReInvite&&(this.sessionDescriptionHandlerModifiersReInvite=n.sessionDescriptionHandlerModifiersReInvite),n.sessionDescriptionHandlerOptionsReInvite&&(this.sessionDescriptionHandlerOptionsReInvite=n.sessionDescriptionHandlerOptionsReInvite),this._id=this.outgoingRequestMessage.callId+this.fromTag,this.userAgent._sessions[this._id]=this}dispose(){if(this.disposed)return Promise.resolve();switch(this.disposed=!0,this.disposeEarlyMedia(),this.state){case it.Initial:case it.Establishing:return this.cancel().then(()=>super.dispose());case it.Established:case it.Terminating:case it.Terminated:return super.dispose();default:throw new Error("Unknown state.")}}get body(){return this.outgoingRequestMessage.body}get localIdentity(){return this.outgoingRequestMessage.from}get remoteIdentity(){return this.outgoingRequestMessage.to}get request(){return this.outgoingRequestMessage}cancel(e={}){if(this.logger.log("Inviter.cancel"),this.state!==it.Initial&&this.state!==it.Establishing){const e=new Error(`Invalid session state ${this.state}`);return this.logger.error(e.message),Promise.reject(e)}if(this.isCanceled=!0,this.stateTransition(it.Terminating),this.outgoingInviteRequest){let t;e.statusCode&&e.reasonPhrase&&(t=function(e,t){if(e&&e<200||e>699)throw new TypeError("Invalid statusCode: "+e);if(e)return"SIP;cause="+e+';text="'+(Ne(e)||t)+'"'}(e.statusCode,e.reasonPhrase)),this.outgoingInviteRequest.cancel(t,e)}else this.logger.warn("Canceled session before INVITE was sent"),this.stateTransition(it.Terminated);return Promise.resolve()}invite(e={}){if(this.logger.log("Inviter.invite"),this.state!==it.Initial)return super.invite(e);if(e.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiers=e.sessionDescriptionHandlerModifiers),e.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptions=e.sessionDescriptionHandlerOptions),e.withoutSdp||this.inviteWithoutSdp)return this._renderbody&&this._rendertype&&(this.outgoingRequestMessage.body={contentType:this._rendertype,body:this._renderbody}),this.stateTransition(it.Establishing),Promise.resolve(this.sendInvite(e));const t={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.getOffer(t).then(t=>(this.outgoingRequestMessage.body={body:t.content,contentType:t.contentType},this.stateTransition(it.Establishing),this.sendInvite(e))).catch(e=>{throw this.logger.log(e.message),this.state!==it.Terminated&&this.stateTransition(it.Terminated),e})}sendInvite(e={}){return this.outgoingInviteRequest=this.userAgent.userAgentCore.invite(this.outgoingRequestMessage,{onAccept:t=>this.dialog?(this.logger.log("Additional confirmed dialog, sending ACK and BYE"),void this.ackAndBye(t)):this.isCanceled?(this.logger.log("Canceled session accepted, sending ACK and BYE"),this.ackAndBye(t),void this.stateTransition(it.Terminated)):(this.notifyReferer(t),void this.onAccept(t).then(()=>{this.disposeEarlyMedia()}).catch(()=>{this.disposeEarlyMedia()}).then(()=>{e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(t)})),onProgress:t=>{this.isCanceled||(this.notifyReferer(t),this.onProgress(t).catch(()=>{this.disposeEarlyMedia()}).then(()=>{e.requestDelegate&&e.requestDelegate.onProgress&&e.requestDelegate.onProgress(t)}))},onRedirect:t=>{this.notifyReferer(t),this.onRedirect(t),e.requestDelegate&&e.requestDelegate.onRedirect&&e.requestDelegate.onRedirect(t)},onReject:t=>{this.notifyReferer(t),this.onReject(t),e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(t)},onTrying:t=>{this.notifyReferer(t),this.onTrying(t),e.requestDelegate&&e.requestDelegate.onTrying&&e.requestDelegate.onTrying(t)}}),this.outgoingInviteRequest}disposeEarlyMedia(){this.earlyMediaSessionDescriptionHandlers.forEach(e=>{e.close()}),this.earlyMediaSessionDescriptionHandlers.clear()}notifyReferer(e){if(!this._referred)return;if(!(this._referred instanceof st))throw new Error("Referred session not instance of session");if(!this._referred.dialog)return;if(!e.message.statusCode)throw new Error("Status code undefined.");if(!e.message.reasonPhrase)throw new Error("Reason phrase undefined.");const t=`SIP/2.0 ${e.message.statusCode} ${e.message.reasonPhrase}`.trim();this._referred.dialog.notify(void 0,{extraHeaders:["Event: refer","Subscription-State: terminated"],body:{contentDisposition:"render",contentType:"message/sipfrag",content:t}}).delegate={onReject:()=>{this._referred=void 0}}}onAccept(e){if(this.logger.log("Inviter.onAccept"),this.state!==it.Establishing)return this.logger.error(`Accept received while in state ${this.state}, dropping response`),Promise.reject(new Error(`Invalid session state ${this.state}`));const t=e.message,n=e.session;switch(t.hasHeader("P-Asserted-Identity")&&(this._assertedIdentity=_e.nameAddrHeaderParse(t.getHeader("P-Asserted-Identity"))),n.delegate={onAck:e=>this.onAckRequest(e),onBye:e=>this.onByeRequest(e),onInfo:e=>this.onInfoRequest(e),onInvite:e=>this.onInviteRequest(e),onMessage:e=>this.onMessageRequest(e),onNotify:e=>this.onNotifyRequest(e),onPrack:e=>this.onPrackRequest(e),onRefer:e=>this.onReferRequest(e)},this._dialog=n,n.signalingState){case Ye.Initial:case Ye.HaveLocalOffer:return this.logger.error("Received 2xx response to INVITE without a session description"),this.ackAndBye(e,400,"Missing session description"),this.stateTransition(it.Terminated),Promise.reject(new Error("Bad Media Description"));case Ye.HaveRemoteOffer:{if(!this._dialog.offer)throw new Error(`Session offer undefined in signaling state ${this._dialog.signalingState}.`);const t={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.setOfferAndGetAnswer(this._dialog.offer,t).then(t=>{e.ack({body:t}),this.stateTransition(it.Established)}).catch(t=>{throw this.ackAndBye(e,488,"Invalid session description"),this.stateTransition(it.Terminated),t})}case Ye.Stable:{if(this.earlyMediaSessionDescriptionHandlers.size>0){const t=this.earlyMediaSessionDescriptionHandlers.get(n.id);if(!t)throw new Error("Session description handler undefined.");return this.setSessionDescriptionHandler(t),this.earlyMediaSessionDescriptionHandlers.delete(n.id),e.ack(),this.stateTransition(it.Established),Promise.resolve()}if(this.earlyMediaDialog){if(this.earlyMediaDialog!==n){if(this.earlyMedia){const e="You have set the 'earlyMedia' option to 'true' which requires that your INVITE requests do not fork and yet this INVITE request did in fact fork. Consequentially and not surprisingly the end point which accepted the INVITE (confirmed dialog) does not match the end point with which early media has been setup (early dialog) and thus this session is unable to proceed. In accordance with the SIP specifications, the SIP servers your end point is connected to determine if an INVITE forks and the forking behavior of those servers cannot be controlled by this library. If you wish to use early media with this library you must configure those servers accordingly. Alternatively you may set the 'earlyMedia' to 'false' which will allow this library to function with any INVITE requests which do fork.";this.logger.error(e)}const t=new Error("Early media dialog does not equal confirmed dialog, terminating session");return this.logger.error(t.message),this.ackAndBye(e,488,"Not Acceptable Here"),this.stateTransition(it.Terminated),Promise.reject(t)}return e.ack(),this.stateTransition(it.Established),Promise.resolve()}const t=n.answer;if(!t)throw new Error("Answer is undefined.");const r={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.setAnswer(t,r).then(()=>{let t;this._renderbody&&this._rendertype&&(t={body:{contentDisposition:"render",contentType:this._rendertype,content:this._renderbody}}),e.ack(t),this.stateTransition(it.Established)}).catch(t=>{throw this.logger.error(t.message),this.ackAndBye(e,488,"Not Acceptable Here"),this.stateTransition(it.Terminated),t})}case Ye.Closed:return Promise.reject(new Error("Terminated."));default:throw new Error("Unknown session signaling state.")}}onProgress(e){var t;if(this.logger.log("Inviter.onProgress"),this.state!==it.Establishing)return this.logger.error(`Progress received while in state ${this.state}, dropping response`),Promise.reject(new Error(`Invalid session state ${this.state}`));if(!this.outgoingInviteRequest)throw new Error("Outgoing INVITE request undefined.");const n=e.message,r=e.session;n.hasHeader("P-Asserted-Identity")&&(this._assertedIdentity=_e.nameAddrHeaderParse(n.getHeader("P-Asserted-Identity")));const i=n.getHeader("require"),o=n.getHeader("rseq"),a=!!(i&&i.includes("100rel")&&o?Number(o):void 0),s=[];switch(a&&s.push("RAck: "+n.getHeader("rseq")+" "+n.getHeader("cseq")),r.signalingState){case Ye.Initial:return a&&(this.logger.warn("First reliable provisional response received MUST contain an offer when INVITE does not contain an offer."),e.prack({extraHeaders:s})),Promise.resolve();case Ye.HaveLocalOffer:return a&&e.prack({extraHeaders:s}),Promise.resolve();case Ye.HaveRemoteOffer:if(!a)return this.logger.warn("Non-reliable provisional response MUST NOT contain an initial offer, discarding response."),Promise.resolve();{const i=this.sessionDescriptionHandlerFactory(this,this.userAgent.configuration.sessionDescriptionHandlerFactoryOptions||{});return(null===(t=this.delegate)||void 0===t?void 0:t.onSessionDescriptionHandler)&&this.delegate.onSessionDescriptionHandler(i,!0),this.earlyMediaSessionDescriptionHandlers.set(r.id,i),i.setDescription(n.body,this.sessionDescriptionHandlerOptions,this.sessionDescriptionHandlerModifiers).then(()=>i.getDescription(this.sessionDescriptionHandlerOptions,this.sessionDescriptionHandlerModifiers)).then(t=>{const n={contentDisposition:"session",contentType:t.contentType,content:t.body};e.prack({extraHeaders:s,body:n})}).catch(e=>{throw this.stateTransition(it.Terminated),e})}case Ye.Stable:if(a&&e.prack({extraHeaders:s}),this.earlyMedia&&!this.earlyMediaDialog){this.earlyMediaDialog=r;const e=r.answer;if(!e)throw new Error("Answer is undefined.");const t={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.setAnswer(e,t).catch(e=>{throw this.stateTransition(it.Terminated),e})}return Promise.resolve();case Ye.Closed:return Promise.reject(new Error("Terminated."));default:throw new Error("Unknown session signaling state.")}}onRedirect(e){this.logger.log("Inviter.onRedirect"),this.state===it.Establishing||this.state===it.Terminating?this.stateTransition(it.Terminated):this.logger.error(`Redirect received while in state ${this.state}, dropping response`)}onReject(e){this.logger.log("Inviter.onReject"),this.state===it.Establishing||this.state===it.Terminating?this.stateTransition(it.Terminated):this.logger.error(`Reject received while in state ${this.state}, dropping response`)}onTrying(e){this.logger.log("Inviter.onTrying"),this.state===it.Establishing||this.logger.error(`Trying received while in state ${this.state}, dropping response`)}}class dt{constructor(e,t,n,r="text/plain",i={}){this.logger=e.getLogger("sip.Messager"),i.params=i.params||{};let o=e.userAgentCore.configuration.aor;if(i.params.fromUri&&(o="string"==typeof i.params.fromUri?_e.URIParse(i.params.fromUri):i.params.fromUri),!o)throw new TypeError("Invalid from URI: "+i.params.fromUri);let a=t;if(i.params.toUri&&(a="string"==typeof i.params.toUri?_e.URIParse(i.params.toUri):i.params.toUri),!a)throw new TypeError("Invalid to URI: "+i.params.toUri);const s=i.params?Object.assign({},i.params):{},l=(i.extraHeaders||[]).slice(),c={contentDisposition:"render",contentType:r,content:n};this.request=e.userAgentCore.makeOutgoingRequestMessage(Ze.MESSAGE,t,o,a,s,l,c),this.userAgent=e}message(e={}){return this.userAgent.userAgentCore.request(this.request,e.requestDelegate),Promise.resolve()}}var ht,ft,pt,gt,mt,vt,yt,bt,wt,xt,kt,St,Tt;(ft=ht=ht||(ht={})).Initial="Initial",ft.Registered="Registered",ft.Unregistered="Unregistered",ft.Terminated="Terminated";class Et{constructor(e,t={}){this.disposed=!1,this._contacts=[],this._retryAfter=void 0,this._state=ht.Initial,this._waiting=!1,this._stateEventEmitter=new we,this._waitingEventEmitter=new we,this.userAgent=e;const n=e.configuration.uri.clone();if(n.user=void 0,this.options=Object.assign(Object.assign(Object.assign({},Et.defaultOptions()),{registrar:n}),Et.stripUndefinedProperties(t)),this.options.extraContactHeaderParams=(this.options.extraContactHeaderParams||[]).slice(),this.options.extraHeaders=(this.options.extraHeaders||[]).slice(),!this.options.registrar)throw new Error("Registrar undefined.");if(this.options.registrar=this.options.registrar.clone(),this.options.regId&&!this.options.instanceId?this.options.instanceId=this.userAgent.instanceId:!this.options.regId&&this.options.instanceId&&(this.options.regId=1),this.options.instanceId&&-1===_e.parse(this.options.instanceId,"uuid"))throw new Error("Invalid instanceId.");if(this.options.regId&&this.options.regId<0)throw new Error("Invalid regId.");const r=this.options.registrar,i=this.options.params&&this.options.params.fromUri||e.userAgentCore.configuration.aor,o=this.options.params&&this.options.params.toUri||e.configuration.uri,a=this.options.params||{},s=(t.extraHeaders||[]).slice();if(this.request=e.userAgentCore.makeOutgoingRequestMessage(Ze.REGISTER,r,i,o,a,s,void 0),this.expires=this.options.expires||Et.defaultExpires,this.expires<0)throw new Error("Invalid expires.");if(this.refreshFrequency=this.options.refreshFrequency||Et.defaultRefreshFrequency,this.refreshFrequency<50||this.refreshFrequency>99)throw new Error("Invalid refresh frequency. The value represents a percentage of the expiration time and should be between 50 and 99.");this.logger=e.getLogger("sip.Registerer"),this.options.logConfiguration&&(this.logger.log("Configuration:"),Object.keys(this.options).forEach(e=>{const t=this.options[e];if("registrar"===e)this.logger.log("· "+e+": "+t);else this.logger.log("· "+e+": "+JSON.stringify(t))})),this.id=this.request.callId+this.request.from.parameters.tag,this.userAgent._registerers[this.id]=this}static defaultOptions(){return{expires:Et.defaultExpires,extraContactHeaderParams:[],extraHeaders:[],logConfiguration:!0,instanceId:"",params:{},regId:0,registrar:new Te("sip","anonymous","anonymous.invalid"),refreshFrequency:Et.defaultRefreshFrequency}}static stripUndefinedProperties(e){return Object.keys(e).reduce((t,n)=>(void 0!==e[n]&&(t[n]=e[n]),t),{})}get contacts(){return this._contacts.slice()}get retryAfter(){return this._retryAfter}get state(){return this._state}get stateChange(){return this._stateEventEmitter}dispose(){return this.disposed?Promise.resolve():(this.disposed=!0,this.logger.log(`Registerer ${this.id} in state ${this.state} is being disposed`),delete this.userAgent._registerers[this.id],new Promise(e=>{const t=()=>{if(!this.waiting&&this._state===ht.Registered)return this.stateChange.addListener(()=>{this.terminated(),e()},{once:!0}),void this.unregister();this.terminated(),e()};this.waiting?this.waitingChange.addListener(()=>{t()},{once:!0}):t()}))}register(e={}){if(this.state===ht.Terminated)throw this.stateError(),new Error("Registerer terminated. Unable to register.");if(this.disposed)throw this.stateError(),new Error("Registerer disposed. Unable to register.");if(this.waiting){this.waitingWarning();const e=new fe("REGISTER request already in progress, waiting for final response");return Promise.reject(e)}e.requestOptions&&(this.options=Object.assign(Object.assign({},this.options),e.requestOptions));const t=(this.options.extraHeaders||[]).slice();t.push("Contact: "+this.generateContactHeader(this.expires)),t.push("Allow: "+["ACK","CANCEL","INVITE","MESSAGE","BYE","OPTIONS","INFO","NOTIFY","REFER"].toString()),this.request.cseq++,this.request.setHeader("cseq",this.request.cseq+" REGISTER"),this.request.extraHeaders=t,this.waitingToggle(!0);const n=this.userAgent.userAgentCore.register(this.request,{onAccept:t=>{let n;t.message.hasHeader("expires")&&(n=Number(t.message.getHeader("expires"))),this._contacts=t.message.getHeaders("contact");let r,i=this._contacts.length;if(!i)return this.logger.error("No Contact header in response to REGISTER, dropping response."),void this.unregistered();for(;i--;){if(r=t.message.parseHeader("contact",i),!r)throw new Error("Contact undefined");if(this.userAgent.contact.pubGruu&&Ee(r.uri,this.userAgent.contact.pubGruu)){n=Number(r.getParam("expires"));break}if(""===this.userAgent.configuration.contactName){if(r.uri.user===this.userAgent.contact.uri.user){n=Number(r.getParam("expires"));break}}else if(Ee(r.uri,this.userAgent.contact.uri)){n=Number(r.getParam("expires"));break}r=void 0}if(void 0===r)return this.logger.error("No Contact header pointing to us, dropping response"),this.unregistered(),void this.waitingToggle(!1);if(void 0===n)return this.logger.error("Contact pointing to us is missing expires parameter, dropping response"),this.unregistered(),void this.waitingToggle(!1);if(r.hasParam("temp-gruu")){const e=r.getParam("temp-gruu");e&&(this.userAgent.contact.tempGruu=_e.URIParse(e.replace(/"/g,"")))}if(r.hasParam("pub-gruu")){const e=r.getParam("pub-gruu");e&&(this.userAgent.contact.pubGruu=_e.URIParse(e.replace(/"/g,"")))}this.registered(n),e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(t),this.waitingToggle(!1)},onProgress:t=>{e.requestDelegate&&e.requestDelegate.onProgress&&e.requestDelegate.onProgress(t)},onRedirect:t=>{this.logger.error("Redirect received. Not supported."),this.unregistered(),e.requestDelegate&&e.requestDelegate.onRedirect&&e.requestDelegate.onRedirect(t),this.waitingToggle(!1)},onReject:t=>{if(423===t.message.statusCode)return t.message.hasHeader("min-expires")?(this.expires=Number(t.message.getHeader("min-expires")),this.waitingToggle(!1),void this.register()):(this.logger.error("423 response received for REGISTER without Min-Expires, dropping response"),this.unregistered(),void this.waitingToggle(!1));this.logger.warn(`Failed to register, status code ${t.message.statusCode}`);let n=NaN;if(500===t.message.statusCode||503===t.message.statusCode){const e=t.message.getHeader("retry-after");e&&(n=Number.parseInt(e,void 0))}this._retryAfter=isNaN(n)?void 0:n,this.unregistered(),e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(t),this._retryAfter=void 0,this.waitingToggle(!1)},onTrying:t=>{e.requestDelegate&&e.requestDelegate.onTrying&&e.requestDelegate.onTrying(t)}});return Promise.resolve(n)}unregister(e={}){if(this.state===ht.Terminated)throw this.stateError(),new Error("Registerer terminated. Unable to register.");if(this.disposed&&this.state!==ht.Registered)throw this.stateError(),new Error("Registerer disposed. Unable to register.");if(this.waiting){this.waitingWarning();const e=new fe("REGISTER request already in progress, waiting for final response");return Promise.reject(e)}this._state===ht.Registered||e.all||this.logger.warn("Not currently registered, but sending an unregister anyway.");const t=(e.requestOptions&&e.requestOptions.extraHeaders||[]).slice();this.request.extraHeaders=t,e.all?(t.push("Contact: *"),t.push("Expires: 0")):t.push("Contact: "+this.generateContactHeader(0)),this.request.cseq++,this.request.setHeader("cseq",this.request.cseq+" REGISTER"),void 0!==this.registrationTimer&&(clearTimeout(this.registrationTimer),this.registrationTimer=void 0),this.waitingToggle(!0);const n=this.userAgent.userAgentCore.register(this.request,{onAccept:t=>{this._contacts=t.message.getHeaders("contact"),this.unregistered(),e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(t),this.waitingToggle(!1)},onProgress:t=>{e.requestDelegate&&e.requestDelegate.onProgress&&e.requestDelegate.onProgress(t)},onRedirect:t=>{this.logger.error("Unregister redirected. Not currently supported."),this.unregistered(),e.requestDelegate&&e.requestDelegate.onRedirect&&e.requestDelegate.onRedirect(t),this.waitingToggle(!1)},onReject:t=>{this.logger.error(`Unregister rejected with status code ${t.message.statusCode}`),this.unregistered(),e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(t),this.waitingToggle(!1)},onTrying:t=>{e.requestDelegate&&e.requestDelegate.onTrying&&e.requestDelegate.onTrying(t)}});return Promise.resolve(n)}clearTimers(){void 0!==this.registrationTimer&&(clearTimeout(this.registrationTimer),this.registrationTimer=void 0),void 0!==this.registrationExpiredTimer&&(clearTimeout(this.registrationExpiredTimer),this.registrationExpiredTimer=void 0)}generateContactHeader(e){let t=this.userAgent.contact.toString({register:!0});return this.options.regId&&this.options.instanceId&&(t+=";reg-id="+this.options.regId,t+=';+sip.instance=""'),this.options.extraContactHeaderParams&&this.options.extraContactHeaderParams.forEach(e=>{t+=";"+e}),t+=";expires="+e,t}registered(e){this.clearTimers(),this.registrationTimer=setTimeout(()=>{this.registrationTimer=void 0,this.register()},this.refreshFrequency/100*e*1e3),this.registrationExpiredTimer=setTimeout(()=>{this.logger.warn("Registration expired"),this.unregistered()},1e3*e),this._state!==ht.Registered&&this.stateTransition(ht.Registered)}unregistered(){this.clearTimers(),this._state!==ht.Unregistered&&this.stateTransition(ht.Unregistered)}terminated(){this.clearTimers(),this._state!==ht.Terminated&&this.stateTransition(ht.Terminated)}stateTransition(e){const t=()=>{throw new Error(`Invalid state transition from ${this._state} to ${e}`)};switch(this._state){case ht.Initial:e!==ht.Registered&&e!==ht.Unregistered&&e!==ht.Terminated&&t();break;case ht.Registered:e!==ht.Unregistered&&e!==ht.Terminated&&t();break;case ht.Unregistered:e!==ht.Registered&&e!==ht.Terminated&&t();break;case ht.Terminated:t();break;default:throw new Error("Unrecognized state.")}this._state=e,this.logger.log(`Registration transitioned to state ${this._state}`),this._stateEventEmitter.emit(this._state),e===ht.Terminated&&this.dispose()}get waiting(){return this._waiting}get waitingChange(){return this._waitingEventEmitter}waitingToggle(e){if(this._waiting===e)throw new Error(`Invalid waiting transition from ${this._waiting} to ${e}`);this._waiting=e,this.logger.log(`Waiting toggled to ${this._waiting}`),this._waitingEventEmitter.emit(this._waiting)}waitingWarning(){let e="An attempt was made to send a REGISTER request while a prior one was still in progress.";e+=" RFC 3261 requires UAs MUST NOT send a new registration until they have received a final response",e+=" from the registrar for the previous one or the previous REGISTER request has timed out.",e+=" Note that if the transport disconnects, you still must wait for the prior request to time out before",e+=" sending a new REGISTER request or alternatively dispose of the current Registerer and create a new Registerer.",this.logger.warn("An attempt was made to send a REGISTER request while a prior one was still in progress. RFC 3261 requires UAs MUST NOT send a new registration until they have received a final response from the registrar for the previous one or the previous REGISTER request has timed out. Note that if the transport disconnects, you still must wait for the prior request to time out before sending a new REGISTER request or alternatively dispose of the current Registerer and create a new Registerer.")}stateError(){let e=`An attempt was made to send a REGISTER request when the Registerer ${this.state===ht.Terminated?"is in 'Terminated' state":"has been disposed"}.`;e+=" The Registerer transitions to 'Terminated' when Registerer.dispose() is called.",e+=" Perhaps you called UserAgent.stop() which dipsoses of all Registerers?",this.logger.error(e)}}Et.defaultExpires=600,Et.defaultRefreshFrequency=99,(gt=pt=pt||(pt={})).Initial="Initial",gt.NotifyWait="NotifyWait",gt.Pending="Pending",gt.Active="Active",gt.Terminated="Terminated",(vt=mt=mt||(mt={})).Connecting="Connecting",vt.Connected="Connected",vt.Disconnecting="Disconnecting",vt.Disconnected="Disconnected",(bt=yt=yt||(yt={})).Started="Started",bt.Stopped="Stopped";class Ct{constructor(){this._dataLength=0,this._bufferLength=0,this._state=new Int32Array(4),this._buffer=new ArrayBuffer(68),this._buffer8=new Uint8Array(this._buffer,0,68),this._buffer32=new Uint32Array(this._buffer,0,17),this.start()}static hashStr(e,t=!1){return this.onePassHasher.start().appendStr(e).end(t)}static hashAsciiStr(e,t=!1){return this.onePassHasher.start().appendAsciiStr(e).end(t)}static _hex(e){const t=Ct.hexChars,n=Ct.hexOut;let r,i,o,a;for(a=0;a<4;a+=1)for(i=8*a,r=e[a],o=0;o<8;o+=2)n[i+1+o]=t.charAt(15&r),r>>>=4,n[i+0+o]=t.charAt(15&r),r>>>=4;return n.join("")}static _md5cycle(e,t){let n=e[0],r=e[1],i=e[2],o=e[3];n+=(r&i|~r&o)+t[0]-680876936|0,n=(n<<7|n>>>25)+r|0,o+=(n&r|~n&i)+t[1]-389564586|0,o=(o<<12|o>>>20)+n|0,i+=(o&n|~o&r)+t[2]+606105819|0,i=(i<<17|i>>>15)+o|0,r+=(i&o|~i&n)+t[3]-1044525330|0,r=(r<<22|r>>>10)+i|0,n+=(r&i|~r&o)+t[4]-176418897|0,n=(n<<7|n>>>25)+r|0,o+=(n&r|~n&i)+t[5]+1200080426|0,o=(o<<12|o>>>20)+n|0,i+=(o&n|~o&r)+t[6]-1473231341|0,i=(i<<17|i>>>15)+o|0,r+=(i&o|~i&n)+t[7]-45705983|0,r=(r<<22|r>>>10)+i|0,n+=(r&i|~r&o)+t[8]+1770035416|0,n=(n<<7|n>>>25)+r|0,o+=(n&r|~n&i)+t[9]-1958414417|0,o=(o<<12|o>>>20)+n|0,i+=(o&n|~o&r)+t[10]-42063|0,i=(i<<17|i>>>15)+o|0,r+=(i&o|~i&n)+t[11]-1990404162|0,r=(r<<22|r>>>10)+i|0,n+=(r&i|~r&o)+t[12]+1804603682|0,n=(n<<7|n>>>25)+r|0,o+=(n&r|~n&i)+t[13]-40341101|0,o=(o<<12|o>>>20)+n|0,i+=(o&n|~o&r)+t[14]-1502002290|0,i=(i<<17|i>>>15)+o|0,r+=(i&o|~i&n)+t[15]+1236535329|0,r=(r<<22|r>>>10)+i|0,n+=(r&o|i&~o)+t[1]-165796510|0,n=(n<<5|n>>>27)+r|0,o+=(n&i|r&~i)+t[6]-1069501632|0,o=(o<<9|o>>>23)+n|0,i+=(o&r|n&~r)+t[11]+643717713|0,i=(i<<14|i>>>18)+o|0,r+=(i&n|o&~n)+t[0]-373897302|0,r=(r<<20|r>>>12)+i|0,n+=(r&o|i&~o)+t[5]-701558691|0,n=(n<<5|n>>>27)+r|0,o+=(n&i|r&~i)+t[10]+38016083|0,o=(o<<9|o>>>23)+n|0,i+=(o&r|n&~r)+t[15]-660478335|0,i=(i<<14|i>>>18)+o|0,r+=(i&n|o&~n)+t[4]-405537848|0,r=(r<<20|r>>>12)+i|0,n+=(r&o|i&~o)+t[9]+568446438|0,n=(n<<5|n>>>27)+r|0,o+=(n&i|r&~i)+t[14]-1019803690|0,o=(o<<9|o>>>23)+n|0,i+=(o&r|n&~r)+t[3]-187363961|0,i=(i<<14|i>>>18)+o|0,r+=(i&n|o&~n)+t[8]+1163531501|0,r=(r<<20|r>>>12)+i|0,n+=(r&o|i&~o)+t[13]-1444681467|0,n=(n<<5|n>>>27)+r|0,o+=(n&i|r&~i)+t[2]-51403784|0,o=(o<<9|o>>>23)+n|0,i+=(o&r|n&~r)+t[7]+1735328473|0,i=(i<<14|i>>>18)+o|0,r+=(i&n|o&~n)+t[12]-1926607734|0,r=(r<<20|r>>>12)+i|0,n+=(r^i^o)+t[5]-378558|0,n=(n<<4|n>>>28)+r|0,o+=(n^r^i)+t[8]-2022574463|0,o=(o<<11|o>>>21)+n|0,i+=(o^n^r)+t[11]+1839030562|0,i=(i<<16|i>>>16)+o|0,r+=(i^o^n)+t[14]-35309556|0,r=(r<<23|r>>>9)+i|0,n+=(r^i^o)+t[1]-1530992060|0,n=(n<<4|n>>>28)+r|0,o+=(n^r^i)+t[4]+1272893353|0,o=(o<<11|o>>>21)+n|0,i+=(o^n^r)+t[7]-155497632|0,i=(i<<16|i>>>16)+o|0,r+=(i^o^n)+t[10]-1094730640|0,r=(r<<23|r>>>9)+i|0,n+=(r^i^o)+t[13]+681279174|0,n=(n<<4|n>>>28)+r|0,o+=(n^r^i)+t[0]-358537222|0,o=(o<<11|o>>>21)+n|0,i+=(o^n^r)+t[3]-722521979|0,i=(i<<16|i>>>16)+o|0,r+=(i^o^n)+t[6]+76029189|0,r=(r<<23|r>>>9)+i|0,n+=(r^i^o)+t[9]-640364487|0,n=(n<<4|n>>>28)+r|0,o+=(n^r^i)+t[12]-421815835|0,o=(o<<11|o>>>21)+n|0,i+=(o^n^r)+t[15]+530742520|0,i=(i<<16|i>>>16)+o|0,r+=(i^o^n)+t[2]-995338651|0,r=(r<<23|r>>>9)+i|0,n+=(i^(r|~o))+t[0]-198630844|0,n=(n<<6|n>>>26)+r|0,o+=(r^(n|~i))+t[7]+1126891415|0,o=(o<<10|o>>>22)+n|0,i+=(n^(o|~r))+t[14]-1416354905|0,i=(i<<15|i>>>17)+o|0,r+=(o^(i|~n))+t[5]-57434055|0,r=(r<<21|r>>>11)+i|0,n+=(i^(r|~o))+t[12]+1700485571|0,n=(n<<6|n>>>26)+r|0,o+=(r^(n|~i))+t[3]-1894986606|0,o=(o<<10|o>>>22)+n|0,i+=(n^(o|~r))+t[10]-1051523|0,i=(i<<15|i>>>17)+o|0,r+=(o^(i|~n))+t[1]-2054922799|0,r=(r<<21|r>>>11)+i|0,n+=(i^(r|~o))+t[8]+1873313359|0,n=(n<<6|n>>>26)+r|0,o+=(r^(n|~i))+t[15]-30611744|0,o=(o<<10|o>>>22)+n|0,i+=(n^(o|~r))+t[6]-1560198380|0,i=(i<<15|i>>>17)+o|0,r+=(o^(i|~n))+t[13]+1309151649|0,r=(r<<21|r>>>11)+i|0,n+=(i^(r|~o))+t[4]-145523070|0,n=(n<<6|n>>>26)+r|0,o+=(r^(n|~i))+t[11]-1120210379|0,o=(o<<10|o>>>22)+n|0,i+=(n^(o|~r))+t[2]+718787259|0,i=(i<<15|i>>>17)+o|0,r+=(o^(i|~n))+t[9]-343485551|0,r=(r<<21|r>>>11)+i|0,e[0]=n+e[0]|0,e[1]=r+e[1]|0,e[2]=i+e[2]|0,e[3]=o+e[3]|0}start(){return this._dataLength=0,this._bufferLength=0,this._state.set(Ct.stateIdentity),this}appendStr(e){const t=this._buffer8,n=this._buffer32;let r,i,o=this._bufferLength;for(i=0;i>>6)+192,t[o++]=63&r|128;else if(r<55296||r>56319)t[o++]=(r>>>12)+224,t[o++]=r>>>6&63|128,t[o++]=63&r|128;else{if(r=1024*(r-55296)+(e.charCodeAt(++i)-56320)+65536,r>1114111)throw new Error("Unicode standard supports code points up to U+10FFFF");t[o++]=(r>>>18)+240,t[o++]=r>>>12&63|128,t[o++]=r>>>6&63|128,t[o++]=63&r|128}o>=64&&(this._dataLength+=64,Ct._md5cycle(this._state,n),o-=64,n[0]=n[16])}return this._bufferLength=o,this}appendAsciiStr(e){const t=this._buffer8,n=this._buffer32;let r,i=this._bufferLength,o=0;for(;;){for(r=Math.min(e.length-o,64-i);r--;)t[i++]=e.charCodeAt(o++);if(i<64)break;this._dataLength+=64,Ct._md5cycle(this._state,n),i=0}return this._bufferLength=i,this}appendByteArray(e){const t=this._buffer8,n=this._buffer32;let r,i=this._bufferLength,o=0;for(;;){for(r=Math.min(e.length-o,64-i);r--;)t[i++]=e[o++];if(i<64)break;this._dataLength+=64,Ct._md5cycle(this._state,n),i=0}return this._bufferLength=i,this}getState(){const e=this,t=e._state;return{buffer:String.fromCharCode.apply(null,e._buffer8),buflen:e._bufferLength,length:e._dataLength,state:[t[0],t[1],t[2],t[3]]}}setState(e){const t=e.buffer,n=e.state,r=this._state;let i;for(this._dataLength=e.length,this._bufferLength=e.buflen,r[0]=n[0],r[1]=n[1],r[2]=n[2],r[3]=n[3],i=0;i>2);let o;if(this._dataLength+=t,n[t]=128,n[t+1]=n[t+2]=n[t+3]=0,r.set(Ct.buffer32Identity.subarray(i),i),t>55&&(Ct._md5cycle(this._state,r),r.set(Ct.buffer32Identity)),o=8*this._dataLength,o<=4294967295)r[14]=o;else{const e=o.toString(16).match(/(.*?)(.{0,8})$/);if(null===e)return;const t=parseInt(e[2],16),n=parseInt(e[1],16)||0;r[14]=t,r[15]=n}return Ct._md5cycle(this._state,r),e?this._state:Ct._hex(this._state)}}function Rt(e){return Ct.hashStr(e)}Ct.stateIdentity=new Int32Array([1732584193,-271733879,-1732584194,271733878]),Ct.buffer32Identity=new Int32Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]),Ct.hexChars="0123456789abcdef",Ct.hexOut=[],Ct.onePassHasher=new Ct,"5d41402abc4b2a76b9719d911017c592"!==Ct.hashStr("hello")&&console.error("Md5 self test failed.");class Pt{constructor(e,t,n,r){this.logger=e.getLogger("sipjs.digestauthentication"),this.username=n,this.password=r,this.ha1=t,this.nc=0,this.ncHex="00000000"}authenticate(e,t,n){if(this.algorithm=t.algorithm,this.realm=t.realm,this.nonce=t.nonce,this.opaque=t.opaque,this.stale=t.stale,this.algorithm){if("MD5"!==this.algorithm)return this.logger.warn("challenge with Digest algorithm different than 'MD5', authentication aborted"),!1}else this.algorithm="MD5";if(!this.realm)return this.logger.warn("challenge without Digest realm, authentication aborted"),!1;if(!this.nonce)return this.logger.warn("challenge without Digest nonce, authentication aborted"),!1;if(t.qop)if(t.qop.indexOf("auth")>-1)this.qop="auth";else{if(!(t.qop.indexOf("auth-int")>-1))return this.logger.warn("challenge without Digest qop different than 'auth' or 'auth-int', authentication aborted"),!1;this.qop="auth-int"}else this.qop=void 0;return this.method=e.method,this.uri=e.ruri,this.cnonce=Ae(12),this.nc+=1,this.updateNcHex(),4294967296===this.nc&&(this.nc=1,this.ncHex="00000001"),this.calculateResponse(n),!0}toString(){const e=[];if(!this.response)throw new Error("response field does not exist, cannot generate Authorization header");return e.push("algorithm="+this.algorithm),e.push('username="'+this.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(", ")}updateNcHex(){const e=Number(this.nc).toString(16);this.ncHex="00000000".substr(0,8-e.length)+e}calculateResponse(e){let t,n;t=this.ha1,""!==t&&void 0!==t||(t=Rt(this.username+":"+this.realm+":"+this.password)),"auth"===this.qop?(n=Rt(this.method+":"+this.uri),this.response=Rt(t+":"+this.nonce+":"+this.ncHex+":"+this.cnonce+":auth:"+n)):"auth-int"===this.qop?(n=Rt(this.method+":"+this.uri+":"+Rt(e||"")),this.response=Rt(t+":"+this.nonce+":"+this.ncHex+":"+this.cnonce+":auth-int:"+n)):void 0===this.qop&&(n=Rt(this.method+":"+this.uri),this.response=Rt(t+":"+this.nonce+":"+n))}}(xt=wt=wt||(wt={}))[xt.error=0]="error",xt[xt.warn=1]="warn",xt[xt.log=2]="log",xt[xt.debug=3]="debug";class _t{constructor(e,t,n){this.logger=e,this.category=t,this.label=n}error(e){this.genericLog(wt.error,e)}warn(e){this.genericLog(wt.warn,e)}log(e){this.genericLog(wt.log,e)}debug(e){this.genericLog(wt.debug,e)}genericLog(e,t){this.logger.genericLog(e,this.category,this.label,t)}get level(){return this.logger.level}set level(e){this.logger.level=e}}class Dt{constructor(){this.builtinEnabled=!0,this._level=wt.log,this.loggers={},this.logger=this.getLogger("sip:loggerfactory")}get level(){return this._level}set level(e){e>=0&&e<=3?this._level=e:e>3?this._level=3:wt.hasOwnProperty(e)?this._level=e:this.logger.error("invalid 'level' parameter value: "+JSON.stringify(e))}get connector(){return this._connector}set connector(e){e?"function"==typeof e?this._connector=e:this.logger.error("invalid 'connector' parameter value: "+JSON.stringify(e)):this._connector=void 0}getLogger(e,t){if(t&&3===this.level)return new _t(this,e,t);if(this.loggers[e])return this.loggers[e];{const t=new _t(this,e);return this.loggers[e]=t,t}}genericLog(e,t,n,r){this.level>=e&&this.builtinEnabled&&this.print(e,t,n,r),this.connector&&this.connector(wt[e],t,n,r)}print(e,t,n,r){if("string"==typeof r){const e=[new Date,t];n&&e.push(n),r=e.concat(r).join(" | ")}switch(e){case wt.error:console.error(r);break;case wt.warn:console.warn(r);break;case wt.log:console.log(r);break;case wt.debug:console.debug(r)}}}function It(e,t){const n="\r\n";if(t.statusCode<100||t.statusCode>699)throw new TypeError("Invalid statusCode: "+t.statusCode);const r=t.reasonPhrase?t.reasonPhrase:Ne(t.statusCode);let i="SIP/2.0 "+t.statusCode+" "+r+n;t.statusCode>=100&&t.statusCode,t.statusCode;const o="From: "+e.getHeader("From")+n,a="Call-ID: "+e.callId+n,s="CSeq: "+e.cseq+" "+e.method+n,l=e.getHeaders("via").reduce((e,t)=>e+"Via: "+t+n,"");let c="To: "+e.getHeader("to");if(t.statusCode>100&&!e.parseHeader("to").hasParam("tag")){let e=t.toTag;e||(e=Me()),c+=";tag="+e}c+=n;let u="";t.supported&&(u="Supported: "+t.supported.join(", ")+n);let d="";t.userAgent&&(d="User-Agent: "+t.userAgent+n);let h="";return t.extraHeaders&&(h=t.extraHeaders.reduce((e,t)=>e+t.trim()+n,"")),i+=l,i+=o,i+=c,i+=s,i+=a,i+=u,i+=d,i+=h,t.body?(i+="Content-Type: "+t.body.contentType+n,i+="Content-Length: "+Oe(t.body.content)+n+n,i+=t.body.content):i+="Content-Length: 0\r\n\r\n",{message:i}}!function(e){function t(e,t){let n=t,r=0,i=0;if(e.substring(n,n+2).match(/(^\r\n)/))return-2;for(;0===r;){if(i=e.indexOf("\r\n",n),-1===i)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 n(e,t,n,r){const i=t.indexOf(":",n),o=t.substring(n,i).trim(),a=t.substring(i+1,r).trim();let s;switch(o.toLowerCase()){case"via":case"v":e.addHeader("via",a),1===e.getHeaders("via").length?(s=e.parseHeader("Via"),s&&(e.via=s,e.viaBranch=s.branch)):s=0;break;case"from":case"f":e.setHeader("from",a),s=e.parseHeader("from"),s&&(e.from=s,e.fromTag=s.getParam("tag"));break;case"to":case"t":e.setHeader("to",a),s=e.parseHeader("to"),s&&(e.to=s,e.toTag=s.getParam("tag"));break;case"record-route":if(s=_e.parse(a,"Record_Route"),-1===s){s=void 0;break}if(!(s instanceof Array)){s=void 0;break}s.forEach(t=>{e.addHeader("record-route",a.substring(t.position,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",a),s=e.parseHeader("call-id"),s&&(e.callId=a);break;case"contact":case"m":if(s=_e.parse(a,"Contact"),-1===s){s=void 0;break}if(!(s instanceof Array)){s=void 0;break}s.forEach(t=>{e.addHeader("contact",a.substring(t.position,t.offset)),e.headers.Contact[e.getHeaders("contact").length-1].parsed=t.parsed});break;case"content-length":case"l":e.setHeader("content-length",a),s=e.parseHeader("content-length");break;case"content-type":case"c":e.setHeader("content-type",a),s=e.parseHeader("content-type");break;case"cseq":e.setHeader("cseq",a),s=e.parseHeader("cseq"),s&&(e.cseq=s.value),e instanceof He&&(e.method=s.method);break;case"max-forwards":e.setHeader("max-forwards",a),s=e.parseHeader("max-forwards");break;case"www-authenticate":e.setHeader("www-authenticate",a),s=e.parseHeader("www-authenticate");break;case"proxy-authenticate":e.setHeader("proxy-authenticate",a),s=e.parseHeader("proxy-authenticate");break;case"refer-to":case"r":e.setHeader("refer-to",a),s=e.parseHeader("refer-to"),s&&(e.referTo=s);break;default:e.addHeader(o.toLowerCase(),a),s=0}return void 0!==s||{error:"error parsing header '"+o+"'"}}e.getHeader=t,e.parseHeader=n,e.parseMessage=function(e,r){let i=0,o=e.indexOf("\r\n");if(-1===o)return void r.warn("no CRLF found, not a SIP message, discarded");const a=e.substring(0,o),s=_e.parse(a,"Request_Response");let l,c;if(-1!==s){for(s.status_code?(l=new He,l.statusCode=s.status_code,l.reasonPhrase=s.reason_phrase):(l=new Le,l.method=s.method,l.ruri=s.uri),l.data=e,i=o+2;;){if(o=t(e,i),-2===o){c=i+2;break}if(-1===o)return void r.error("malformed message");const a=n(l,e,i,o);if(a&&!0!==a)return void r.error(a.error);i=o+2}return l.hasHeader("content-length")?l.body=e.substr(c,Number(l.getHeader("content-length"))):l.body=e.substring(c),l}r.warn('error parsing first line of SIP message: "'+a+'"')}}(kt=kt||(kt={}));class At extends de{constructor(e){super(e||"Unspecified transport error.")}}class Nt{constructor(e,t,n,r,i){this._transport=e,this._user=t,this._id=n,this._state=r,this.listeners=new Array,this.logger=t.loggerFactory.getLogger(i,n),this.logger.debug(`Constructing ${this.typeToString()} with id ${this.id}.`)}dispose(){this.logger.debug(`Destroyed ${this.typeToString()} with id ${this.id}.`)}get id(){return this._id}get kind(){throw new Error("Invalid kind.")}get state(){return this._state}get transport(){return this._transport}addStateChangeListener(e,t){const n=()=>{this.removeStateChangeListener(n),e()};!0===(null==t?void 0:t.once)?this.listeners.push(n):this.listeners.push(e)}notifyStateChangeListeners(){this.listeners.slice().forEach(e=>e())}removeStateChangeListener(e){this.listeners=this.listeners.filter(t=>t!==e)}logTransportError(e,t){this.logger.error(e.message),this.logger.error(`Transport error occurred in ${this.typeToString()} with id ${this.id}.`),this.logger.error(t)}send(e){return this.transport.send(e).catch(e=>{if(e instanceof At)throw this.onTransportError(e),e;let t;throw t=e&&"string"==typeof e.message?new At(e.message):new At,this.onTransportError(t),t})}setState(e){this.logger.debug(`State change to "${e}" on ${this.typeToString()} with id ${this.id}.`),this._state=e,this._user.onStateChange&&this._user.onStateChange(e),this.notifyStateChangeListeners()}typeToString(){return"UnknownType"}}class Mt extends Nt{constructor(e,t,n,r,i){super(t,n,e.viaBranch,r,i),this._request=e,this.user=n}get request(){return this._request}}(Tt=St=St||(St={})).Accepted="Accepted",Tt.Calling="Calling",Tt.Completed="Completed",Tt.Confirmed="Confirmed",Tt.Proceeding="Proceeding",Tt.Terminated="Terminated",Tt.Trying="Trying";class $t extends Mt{constructor(e,t,n){super(e,t,n,St.Proceeding,"sip.transaction.ist")}dispose(){this.stopProgressExtensionTimer(),this.H&&(clearTimeout(this.H),this.H=void 0),this.I&&(clearTimeout(this.I),this.I=void 0),this.L&&(clearTimeout(this.L),this.L=void 0),super.dispose()}get kind(){return"ist"}receiveRequest(e){switch(this.state){case St.Proceeding:if(e.method===Ze.INVITE)return void(this.lastProvisionalResponse&&this.send(this.lastProvisionalResponse).catch(e=>{this.logTransportError(e,"Failed to send retransmission of provisional response.")}));break;case St.Accepted:if(e.method===Ze.INVITE)return;break;case St.Completed:if(e.method===Ze.INVITE){if(!this.lastFinalResponse)throw new Error("Last final response undefined.");return void this.send(this.lastFinalResponse).catch(e=>{this.logTransportError(e,"Failed to send retransmission of final response.")})}if(e.method===Ze.ACK)return void this.stateTransition(St.Confirmed);break;case St.Confirmed:case St.Terminated:if(e.method===Ze.INVITE||e.method===Ze.ACK)return;break;default:throw new Error(`Invalid state ${this.state}`)}const t=`INVITE server transaction received unexpected ${e.method} request while in state ${this.state}.`;this.logger.warn(t)}receiveResponse(e,t){if(e<100||e>699)throw new Error(`Invalid status code ${e}`);switch(this.state){case St.Proceeding:if(e>=100&&e<=199)return this.lastProvisionalResponse=t,e>100&&this.startProgressExtensionTimer(),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send 1xx response.")});if(e>=200&&e<=299)return this.lastFinalResponse=t,this.stateTransition(St.Accepted),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send 2xx response.")});if(e>=300&&e<=699)return this.lastFinalResponse=t,this.stateTransition(St.Completed),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send non-2xx final response.")});break;case St.Accepted:if(e>=200&&e<=299)return void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send 2xx response.")});break;case St.Completed:case St.Confirmed:case St.Terminated:break;default:throw new Error(`Invalid state ${this.state}`)}const n=`INVITE server transaction received unexpected ${e} response from TU while in state ${this.state}.`;throw this.logger.error(n),new Error(n)}retransmitAcceptedResponse(){this.state===St.Accepted&&this.lastFinalResponse&&this.send(this.lastFinalResponse).catch(e=>{this.logTransportError(e,"Failed to send 2xx response.")})}onTransportError(e){this.user.onTransportError&&this.user.onTransportError(e)}typeToString(){return"INVITE server transaction"}stateTransition(e){const t=()=>{throw new Error(`Invalid state transition from ${this.state} to ${e}`)};switch(e){case St.Proceeding:t();break;case St.Accepted:case St.Completed:this.state!==St.Proceeding&&t();break;case St.Confirmed:this.state!==St.Completed&&t();break;case St.Terminated:this.state!==St.Accepted&&this.state!==St.Completed&&this.state!==St.Confirmed&&t();break;default:t()}this.stopProgressExtensionTimer(),e===St.Accepted&&(this.L=setTimeout(()=>this.timerL(),Qe.TIMER_L)),e===St.Completed&&(this.H=setTimeout(()=>this.timerH(),Qe.TIMER_H)),e===St.Confirmed&&(this.I=setTimeout(()=>this.timerI(),Qe.TIMER_I)),e===St.Terminated&&this.dispose(),this.setState(e)}startProgressExtensionTimer(){void 0===this.progressExtensionTimer&&(this.progressExtensionTimer=setInterval(()=>{if(this.logger.debug(`Progress extension timer expired for INVITE server transaction ${this.id}.`),!this.lastProvisionalResponse)throw new Error("Last provisional response undefined.");this.send(this.lastProvisionalResponse).catch(e=>{this.logTransportError(e,"Failed to send retransmission of provisional response.")})},Qe.PROVISIONAL_RESPONSE_INTERVAL))}stopProgressExtensionTimer(){void 0!==this.progressExtensionTimer&&(clearInterval(this.progressExtensionTimer),this.progressExtensionTimer=void 0)}timerG(){}timerH(){this.logger.debug(`Timer H expired for INVITE server transaction ${this.id}.`),this.state===St.Completed&&(this.logger.warn("ACK to negative final response was never received, terminating transaction."),this.stateTransition(St.Terminated))}timerI(){this.logger.debug(`Timer I expired for INVITE server transaction ${this.id}.`),this.stateTransition(St.Terminated)}timerL(){this.logger.debug(`Timer L expired for INVITE server transaction ${this.id}.`),this.state===St.Accepted&&this.stateTransition(St.Terminated)}}class Ot extends Nt{constructor(e,t,n,r,i){super(t,n,Ot.makeId(e),r,i),this._request=e,this.user=n,e.setViaHeader(this.id,t.protocol)}static makeId(e){if("CANCEL"===e.method){if(!e.branch)throw new Error("Outgoing CANCEL request without a branch.");return e.branch}return"z9hG4bK"+Math.floor(1e7*Math.random())}get request(){return this._request}onRequestTimeout(){this.user.onRequestTimeout&&this.user.onRequestTimeout()}}class jt extends Ot{constructor(e,t,n){super(e,t,n,St.Trying,"sip.transaction.nict"),this.F=setTimeout(()=>this.timerF(),Qe.TIMER_F),this.send(e.toString()).catch(e=>{this.logTransportError(e,"Failed to send initial outgoing request.")})}dispose(){this.F&&(clearTimeout(this.F),this.F=void 0),this.K&&(clearTimeout(this.K),this.K=void 0),super.dispose()}get kind(){return"nict"}receiveResponse(e){const t=e.statusCode;if(!t||t<100||t>699)throw new Error(`Invalid status code ${t}`);switch(this.state){case St.Trying:if(t>=100&&t<=199)return this.stateTransition(St.Proceeding),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=200&&t<=699)return this.stateTransition(St.Completed),408===t?void this.onRequestTimeout():void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case St.Proceeding:if(t>=100&&t<=199&&this.user.receiveResponse)return this.user.receiveResponse(e);if(t>=200&&t<=699)return this.stateTransition(St.Completed),408===t?void this.onRequestTimeout():void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case St.Completed:case St.Terminated:return;default:throw new Error(`Invalid state ${this.state}`)}const n=`Non-INVITE client transaction received unexpected ${t} response while in state ${this.state}.`;this.logger.warn(n)}onTransportError(e){this.user.onTransportError&&this.user.onTransportError(e),this.stateTransition(St.Terminated,!0)}typeToString(){return"non-INVITE client transaction"}stateTransition(e,t=!1){const n=()=>{throw new Error(`Invalid state transition from ${this.state} to ${e}`)};switch(e){case St.Trying:n();break;case St.Proceeding:this.state!==St.Trying&&n();break;case St.Completed:this.state!==St.Trying&&this.state!==St.Proceeding&&n();break;case St.Terminated:this.state!==St.Trying&&this.state!==St.Proceeding&&this.state!==St.Completed&&(t||n());break;default:n()}e===St.Completed&&(this.F&&(clearTimeout(this.F),this.F=void 0),this.K=setTimeout(()=>this.timerK(),Qe.TIMER_K)),e===St.Terminated&&this.dispose(),this.setState(e)}timerF(){this.logger.debug(`Timer F expired for non-INVITE client transaction ${this.id}.`),this.state!==St.Trying&&this.state!==St.Proceeding||(this.onRequestTimeout(),this.stateTransition(St.Terminated))}timerK(){this.state===St.Completed&&this.stateTransition(St.Terminated)}}class Lt{constructor(e,t){this.core=e,this.dialogState=t,this.core.dialogs.set(this.id,this)}static initialDialogStateForUserAgentClient(e,t){const n=t.getHeaders("record-route").reverse(),r=t.parseHeader("contact");if(!r)throw new Error("Contact undefined.");if(!(r instanceof Se))throw new Error("Contact not instance of NameAddrHeader.");const i=r.uri,o=e.cseq,a=e.callId,s=e.fromTag,l=t.toTag;if(!a)throw new Error("Call id undefined.");if(!s)throw new Error("From tag undefined.");if(!l)throw new Error("To tag undefined.");if(!e.from)throw new Error("From undefined.");if(!e.to)throw new Error("To undefined.");const c=e.from.uri,u=e.to.uri;if(!t.statusCode)throw new Error("Incoming response status code undefined.");return{id:a+s+l,early:t.statusCode<200,callId:a,localTag:s,remoteTag:l,localSequenceNumber:o,remoteSequenceNumber:void 0,localURI:c,remoteURI:u,remoteTarget:i,routeSet:n,secure:!1}}static initialDialogStateForUserAgentServer(e,t,n=!1){const r=e.getHeaders("record-route"),i=e.parseHeader("contact");if(!i)throw new Error("Contact undefined.");if(!(i instanceof Se))throw new Error("Contact not instance of NameAddrHeader.");const o=i.uri,a=e.cseq,s=e.callId,l=t,c=e.fromTag,u=e.from.uri;return{id:s+l+c,early:n,callId:s,localTag:l,remoteTag:c,localSequenceNumber:void 0,remoteSequenceNumber:a,localURI:e.to.uri,remoteURI:u,remoteTarget:o,routeSet:r,secure:!1}}dispose(){this.core.dialogs.delete(this.id)}get id(){return this.dialogState.id}get early(){return this.dialogState.early}get callId(){return this.dialogState.callId}get localTag(){return this.dialogState.localTag}get remoteTag(){return this.dialogState.remoteTag}get localSequenceNumber(){return this.dialogState.localSequenceNumber}get remoteSequenceNumber(){return this.dialogState.remoteSequenceNumber}get localURI(){return this.dialogState.localURI}get remoteURI(){return this.dialogState.remoteURI}get remoteTarget(){return this.dialogState.remoteTarget}get routeSet(){return this.dialogState.routeSet}get secure(){return this.dialogState.secure}get userAgentCore(){return this.core}confirm(){this.dialogState.early=!1}receiveRequest(e){if(e.method!==Ze.ACK){if(this.remoteSequenceNumber){if(e.cseq<=this.remoteSequenceNumber)throw new Error("Out of sequence in dialog request. Did you forget to call sequenceGuard()?");this.dialogState.remoteSequenceNumber=e.cseq}this.remoteSequenceNumber||(this.dialogState.remoteSequenceNumber=e.cseq)}}recomputeRouteSet(e){this.dialogState.routeSet=e.getHeaders("record-route").reverse()}createOutgoingRequestMessage(e,t){const n=this.remoteURI,r=this.remoteTag,i=this.localURI,o=this.localTag,a=this.callId;let s;s=t&&t.cseq?t.cseq:this.dialogState.localSequenceNumber?this.dialogState.localSequenceNumber+=1:this.dialogState.localSequenceNumber=1;const l=this.remoteTarget,c=this.routeSet,u=t&&t.extraHeaders,d=t&&t.body;return this.userAgentCore.makeOutgoingRequestMessage(e,l,i,n,{callId:a,cseq:s,fromTag:o,toTag:r,routeSet:c},u,d)}incrementLocalSequenceNumber(){if(!this.dialogState.localSequenceNumber)throw new Error("Local sequence number undefined.");this.dialogState.localSequenceNumber+=1}sequenceGuard(e){return e.method===Ze.ACK||(!(this.remoteSequenceNumber&&e.cseq<=this.remoteSequenceNumber)||(this.core.replyStateless(e,{statusCode:500}),!1))}}class Ht extends Ot{constructor(e,t,n){super(e,t,n,St.Calling,"sip.transaction.ict"),this.ackRetransmissionCache=new Map,this.B=setTimeout(()=>this.timerB(),Qe.TIMER_B),this.send(e.toString()).catch(e=>{this.logTransportError(e,"Failed to send initial outgoing request.")})}dispose(){this.B&&(clearTimeout(this.B),this.B=void 0),this.D&&(clearTimeout(this.D),this.D=void 0),this.M&&(clearTimeout(this.M),this.M=void 0),super.dispose()}get kind(){return"ict"}ackResponse(e){const t=e.toTag;if(!t)throw new Error("To tag undefined.");const n="z9hG4bK"+Math.floor(1e7*Math.random());e.setViaHeader(n,this.transport.protocol),this.ackRetransmissionCache.set(t,e),this.send(e.toString()).catch(e=>{this.logTransportError(e,"Failed to send ACK to 2xx response.")})}receiveResponse(e){const t=e.statusCode;if(!t||t<100||t>699)throw new Error(`Invalid status code ${t}`);switch(this.state){case St.Calling:if(t>=100&&t<=199)return this.stateTransition(St.Proceeding),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=200&&t<=299)return this.ackRetransmissionCache.set(e.toTag,void 0),this.stateTransition(St.Accepted),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=300&&t<=699)return this.stateTransition(St.Completed),this.ack(e),void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case St.Proceeding:if(t>=100&&t<=199)return void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=200&&t<=299)return this.ackRetransmissionCache.set(e.toTag,void 0),this.stateTransition(St.Accepted),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=300&&t<=699)return this.stateTransition(St.Completed),this.ack(e),void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case St.Accepted:if(t>=200&&t<=299){if(!this.ackRetransmissionCache.has(e.toTag))return this.ackRetransmissionCache.set(e.toTag,void 0),void(this.user.receiveResponse&&this.user.receiveResponse(e));const t=this.ackRetransmissionCache.get(e.toTag);return t?void this.send(t.toString()).catch(e=>{this.logTransportError(e,"Failed to send retransmission of ACK to 2xx response.")}):void 0}break;case St.Completed:if(t>=300&&t<=699)return void this.ack(e);break;case St.Terminated:break;default:throw new Error(`Invalid state ${this.state}`)}const n=`Received unexpected ${t} response while in state ${this.state}.`;this.logger.warn(n)}onTransportError(e){this.user.onTransportError&&this.user.onTransportError(e),this.stateTransition(St.Terminated,!0)}typeToString(){return"INVITE client transaction"}ack(e){const t=this.request.ruri,n=this.request.callId,r=this.request.cseq,i=this.request.getHeader("from"),o=e.getHeader("to"),a=this.request.getHeader("via"),s=this.request.getHeader("route");if(!i)throw new Error("From undefined.");if(!o)throw new Error("To undefined.");if(!a)throw new Error("Via undefined.");let l=`ACK ${t} SIP/2.0\r\n`;s&&(l+=`Route: ${s}\r\n`),l+=`Via: ${a}\r\n`,l+=`To: ${o}\r\n`,l+=`From: ${i}\r\n`,l+=`Call-ID: ${n}\r\n`,l+=`CSeq: ${r} ACK\r\n`,l+="Max-Forwards: 70\r\n",l+="Content-Length: 0\r\n\r\n",this.send(l).catch(e=>{this.logTransportError(e,"Failed to send ACK to non-2xx response.")})}stateTransition(e,t=!1){const n=()=>{throw new Error(`Invalid state transition from ${this.state} to ${e}`)};switch(e){case St.Calling:n();break;case St.Proceeding:this.state!==St.Calling&&n();break;case St.Accepted:case St.Completed:this.state!==St.Calling&&this.state!==St.Proceeding&&n();break;case St.Terminated:this.state!==St.Calling&&this.state!==St.Accepted&&this.state!==St.Completed&&(t||n());break;default:n()}this.B&&(clearTimeout(this.B),this.B=void 0),St.Proceeding,e===St.Completed&&(this.D=setTimeout(()=>this.timerD(),Qe.TIMER_D)),e===St.Accepted&&(this.M=setTimeout(()=>this.timerM(),Qe.TIMER_M)),e===St.Terminated&&this.dispose(),this.setState(e)}timerA(){}timerB(){this.logger.debug(`Timer B expired for INVITE client transaction ${this.id}.`),this.state===St.Calling&&(this.onRequestTimeout(),this.stateTransition(St.Terminated))}timerD(){this.logger.debug(`Timer D expired for INVITE client transaction ${this.id}.`),this.state===St.Completed&&this.stateTransition(St.Terminated)}timerM(){this.logger.debug(`Timer M expired for INVITE client transaction ${this.id}.`),this.state===St.Accepted&&this.stateTransition(St.Terminated)}}class Ft{constructor(e,t,n,r){this.transactionConstructor=e,this.core=t,this.message=n,this.delegate=r,this.challenged=!1,this.stale=!1,this.logger=this.loggerFactory.getLogger("sip.user-agent-client"),this.init()}dispose(){this.transaction.dispose()}get loggerFactory(){return this.core.loggerFactory}get transaction(){if(!this._transaction)throw new Error("Transaction undefined.");return this._transaction}cancel(e,t={}){if(!this.transaction)throw new Error("Transaction undefined.");if(!this.message.to)throw new Error("To undefined.");if(!this.message.from)throw new Error("From undefined.");const n=this.core.makeOutgoingRequestMessage(Ze.CANCEL,this.message.ruri,this.message.from.uri,this.message.to.uri,{toTag:this.message.toTag,fromTag:this.message.fromTag,callId:this.message.callId,cseq:this.message.cseq},t.extraHeaders);return n.branch=this.message.branch,this.message.headers.Route&&(n.headers.Route=this.message.headers.Route),e&&n.setHeader("Reason",e),this.transaction.state===St.Proceeding?new Ft(jt,this.core,n):this.transaction.addStateChangeListener(()=>{this.transaction&&this.transaction.state===St.Proceeding&&new Ft(jt,this.core,n)},{once:!0}),n}authenticationGuard(e,t){const n=e.statusCode;if(!n)throw new Error("Response status code undefined.");if(401!==n&&407!==n)return!0;let r,i;if(401===n?(r=e.parseHeader("www-authenticate"),i="authorization"):(r=e.parseHeader("proxy-authenticate"),i="proxy-authorization"),!r)return this.logger.warn(n+" with wrong or missing challenge, cannot authenticate"),!0;if(this.challenged&&(this.stale||!0!==r.stale))return this.logger.warn(n+" apparently in authentication loop, cannot authenticate"),!0;if(!this.credentials&&(this.credentials=this.core.configuration.authenticationFactory(),!this.credentials))return this.logger.warn("Unable to obtain credentials, cannot authenticate"),!0;if(!this.credentials.authenticate(this.message,r))return!0;this.challenged=!0,r.stale&&(this.stale=!0);let o=this.message.cseq+=1;return t&&t.localSequenceNumber&&(t.incrementLocalSequenceNumber(),o=this.message.cseq=t.localSequenceNumber),this.message.setHeader("cseq",o+" "+this.message.method),this.message.setHeader(i,this.credentials.toString()),this.init(),!1}onRequestTimeout(){this.logger.warn("User agent client request timed out. Generating internal 408 Request Timeout.");const e=new He;e.statusCode=408,e.reasonPhrase="Request Timeout",this.receiveResponse(e)}onTransportError(e){this.logger.error(e.message),this.logger.error("User agent client request transport error. Generating internal 503 Service Unavailable.");const t=new He;t.statusCode=503,t.reasonPhrase="Service Unavailable",this.receiveResponse(t)}receiveResponse(e){if(!this.authenticationGuard(e))return;const t=e.statusCode?e.statusCode.toString():"";if(!t)throw new Error("Response status code undefined.");switch(!0){case/^100$/.test(t):this.delegate&&this.delegate.onTrying&&this.delegate.onTrying({message:e});break;case/^1[0-9]{2}$/.test(t):this.delegate&&this.delegate.onProgress&&this.delegate.onProgress({message:e});break;case/^2[0-9]{2}$/.test(t):this.delegate&&this.delegate.onAccept&&this.delegate.onAccept({message:e});break;case/^3[0-9]{2}$/.test(t):this.delegate&&this.delegate.onRedirect&&this.delegate.onRedirect({message:e});break;case/^[4-6][0-9]{2}$/.test(t):this.delegate&&this.delegate.onReject&&this.delegate.onReject({message:e});break;default:throw new Error(`Invalid status code ${t}`)}}init(){const e={loggerFactory:this.loggerFactory,onRequestTimeout:()=>this.onRequestTimeout(),onStateChange:e=>{e===St.Terminated&&(this.core.userAgentClients.delete(n),t===this._transaction&&this.dispose())},onTransportError:e=>this.onTransportError(e),receiveResponse:e=>this.receiveResponse(e)},t=new this.transactionConstructor(this.message,this.core.transport,e);this._transaction=t;const n=t.id+t.request.method;this.core.userAgentClients.set(n,this)}}class Ut extends Ft{constructor(e,t,n){const r=e.createOutgoingRequestMessage(Ze.BYE,n);super(jt,e.userAgentCore,r,t),e.dispose()}}class zt extends Mt{constructor(e,t,n){super(e,t,n,St.Trying,"sip.transaction.nist")}dispose(){this.J&&(clearTimeout(this.J),this.J=void 0),super.dispose()}get kind(){return"nist"}receiveRequest(e){switch(this.state){case St.Trying:break;case St.Proceeding:if(!this.lastResponse)throw new Error("Last response undefined.");this.send(this.lastResponse).catch(e=>{this.logTransportError(e,"Failed to send retransmission of provisional response.")});break;case St.Completed:if(!this.lastResponse)throw new Error("Last response undefined.");this.send(this.lastResponse).catch(e=>{this.logTransportError(e,"Failed to send retransmission of final response.")});break;case St.Terminated:break;default:throw new Error(`Invalid state ${this.state}`)}}receiveResponse(e,t){if(e<100||e>699)throw new Error(`Invalid status code ${e}`);if(e>100&&e<=199)throw new Error("Provisional response other than 100 not allowed.");switch(this.state){case St.Trying:if(this.lastResponse=t,e>=100&&e<200)return this.stateTransition(St.Proceeding),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send provisional response.")});if(e>=200&&e<=699)return this.stateTransition(St.Completed),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send final response.")});break;case St.Proceeding:if(this.lastResponse=t,e>=200&&e<=699)return this.stateTransition(St.Completed),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send final response.")});break;case St.Completed:return;case St.Terminated:break;default:throw new Error(`Invalid state ${this.state}`)}const n=`Non-INVITE server transaction received unexpected ${e} response from TU while in state ${this.state}.`;throw this.logger.error(n),new Error(n)}onTransportError(e){this.user.onTransportError&&this.user.onTransportError(e),this.stateTransition(St.Terminated,!0)}typeToString(){return"non-INVITE server transaction"}stateTransition(e,t=!1){const n=()=>{throw new Error(`Invalid state transition from ${this.state} to ${e}`)};switch(e){case St.Trying:n();break;case St.Proceeding:this.state!==St.Trying&&n();break;case St.Completed:this.state!==St.Trying&&this.state!==St.Proceeding&&n();break;case St.Terminated:this.state!==St.Proceeding&&this.state!==St.Completed&&(t||n());break;default:n()}e===St.Completed&&(this.J=setTimeout(()=>this.timerJ(),Qe.TIMER_J)),e===St.Terminated&&this.dispose(),this.setState(e)}timerJ(){this.logger.debug(`Timer J expired for NON-INVITE server transaction ${this.id}.`),this.state===St.Completed&&this.stateTransition(St.Terminated)}}class qt{constructor(e,t,n,r){this.transactionConstructor=e,this.core=t,this.message=n,this.delegate=r,this.logger=this.loggerFactory.getLogger("sip.user-agent-server"),this.toTag=n.toTag?n.toTag:Me(),this.init()}dispose(){this.transaction.dispose()}get loggerFactory(){return this.core.loggerFactory}get transaction(){if(!this._transaction)throw new Error("Transaction undefined.");return this._transaction}accept(e={statusCode:200}){if(!this.acceptable)throw new Xe(`${this.message.method} not acceptable in state ${this.transaction.state}.`);const t=e.statusCode;if(t<200||t>299)throw new TypeError(`Invalid statusCode: ${t}`);return this.reply(e)}progress(e={statusCode:180}){if(!this.progressable)throw new Xe(`${this.message.method} not progressable in state ${this.transaction.state}.`);const t=e.statusCode;if(t<101||t>199)throw new TypeError(`Invalid statusCode: ${t}`);return this.reply(e)}redirect(e,t={statusCode:302}){if(!this.redirectable)throw new Xe(`${this.message.method} not redirectable in state ${this.transaction.state}.`);const n=t.statusCode;if(n<300||n>399)throw new TypeError(`Invalid statusCode: ${n}`);const r=new Array;e.forEach(e=>r.push(`Contact: ${e.toString()}`)),t.extraHeaders=(t.extraHeaders||[]).concat(r);return this.reply(t)}reject(e={statusCode:480}){if(!this.rejectable)throw new Xe(`${this.message.method} not rejectable in state ${this.transaction.state}.`);const t=e.statusCode;if(t<400||t>699)throw new TypeError(`Invalid statusCode: ${t}`);return this.reply(e)}trying(e){if(!this.tryingable)throw new Xe(`${this.message.method} not tryingable in state ${this.transaction.state}.`);return this.reply({statusCode:100})}receiveCancel(e){this.delegate&&this.delegate.onCancel&&this.delegate.onCancel(e)}get acceptable(){if(this.transaction instanceof $t)return this.transaction.state===St.Proceeding||this.transaction.state===St.Accepted;if(this.transaction instanceof zt)return this.transaction.state===St.Trying||this.transaction.state===St.Proceeding;throw new Error("Unknown transaction type.")}get progressable(){if(this.transaction instanceof $t)return this.transaction.state===St.Proceeding;if(this.transaction instanceof zt)return!1;throw new Error("Unknown transaction type.")}get redirectable(){if(this.transaction instanceof $t)return this.transaction.state===St.Proceeding;if(this.transaction instanceof zt)return this.transaction.state===St.Trying||this.transaction.state===St.Proceeding;throw new Error("Unknown transaction type.")}get rejectable(){if(this.transaction instanceof $t)return this.transaction.state===St.Proceeding;if(this.transaction instanceof zt)return this.transaction.state===St.Trying||this.transaction.state===St.Proceeding;throw new Error("Unknown transaction type.")}get tryingable(){if(this.transaction instanceof $t)return this.transaction.state===St.Proceeding;if(this.transaction instanceof zt)return this.transaction.state===St.Trying;throw new Error("Unknown transaction type.")}reply(e){e.toTag||100===e.statusCode||(e.toTag=this.toTag),e.userAgent=e.userAgent||this.core.configuration.userAgentHeaderFieldValue,e.supported=e.supported||this.core.configuration.supportedOptionTagsResponse;const t=It(this.message,e);return this.transaction.receiveResponse(e.statusCode,t.message),t}init(){const e={loggerFactory:this.loggerFactory,onStateChange:e=>{e===St.Terminated&&(this.core.userAgentServers.delete(n),this.dispose())},onTransportError:e=>{this.logger.error(e.message),this.delegate&&this.delegate.onTransportError?this.delegate.onTransportError(e):this.logger.error("User agent server response transport error.")}},t=new this.transactionConstructor(this.message,this.core.transport,e);this._transaction=t;const n=t.id;this.core.userAgentServers.set(t.id,this)}}class Vt extends qt{constructor(e,t,n){super(zt,e.userAgentCore,t,n)}}class Bt extends Ft{constructor(e,t,n){const r=e.createOutgoingRequestMessage(Ze.INFO,n);super(jt,e.userAgentCore,r,t)}}class Wt extends qt{constructor(e,t,n){super(zt,e.userAgentCore,t,n)}}class Yt extends Ft{constructor(e,t,n){super(jt,e,t,n)}}class Gt extends qt{constructor(e,t,n){super(zt,e,t,n)}}class Kt extends Ft{constructor(e,t,n){const r=e.createOutgoingRequestMessage(Ze.NOTIFY,n);super(jt,e.userAgentCore,r,t)}}class Qt extends qt{constructor(e,t,n){const r=void 0!==e.userAgentCore?e.userAgentCore:e;super(zt,r,t,n)}}class Xt extends Ft{constructor(e,t,n){const r=e.createOutgoingRequestMessage(Ze.PRACK,n);super(jt,e.userAgentCore,r,t),e.signalingStateTransition(r)}}class Zt extends qt{constructor(e,t,n){super(zt,e.userAgentCore,t,n),e.signalingStateTransition(t),this.dialog=e}accept(e={statusCode:200}){return e.body&&this.dialog.signalingStateTransition(e.body),super.accept(e)}}class Jt extends Ft{constructor(e,t,n){const r=e.createOutgoingRequestMessage(Ze.INVITE,n);super(Ht,e.userAgentCore,r,t),this.delegate=t,e.signalingStateTransition(r),e.reinviteUserAgentClient=this,this.dialog=e}receiveResponse(e){if(!this.authenticationGuard(e,this.dialog))return;const t=e.statusCode?e.statusCode.toString():"";if(!t)throw new Error("Response status code undefined.");switch(!0){case/^100$/.test(t):this.delegate&&this.delegate.onTrying&&this.delegate.onTrying({message:e});break;case/^1[0-9]{2}$/.test(t):this.delegate&&this.delegate.onProgress&&this.delegate.onProgress({message:e,session:this.dialog,prack:e=>{throw new Error("Unimplemented.")}});break;case/^2[0-9]{2}$/.test(t):this.dialog.signalingStateTransition(e),this.delegate&&this.delegate.onAccept&&this.delegate.onAccept({message:e,session:this.dialog,ack:e=>this.dialog.ack(e)});break;case/^3[0-9]{2}$/.test(t):this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentClient=void 0,this.delegate&&this.delegate.onRedirect&&this.delegate.onRedirect({message:e});break;case/^[4-6][0-9]{2}$/.test(t):this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentClient=void 0,this.delegate&&this.delegate.onReject&&this.delegate.onReject({message:e});break;default:throw new Error(`Invalid status code ${t}`)}}}class en extends qt{constructor(e,t,n){super($t,e.userAgentCore,t,n),e.reinviteUserAgentServer=this,this.dialog=e}accept(e={statusCode:200}){e.extraHeaders=e.extraHeaders||[],e.extraHeaders=e.extraHeaders.concat(this.dialog.routeSet.map(e=>`Record-Route: ${e}`));const t=super.accept(e),n=this.dialog,r=Object.assign(Object.assign({},t),{session:n});return e.body&&this.dialog.signalingStateTransition(e.body),this.dialog.reConfirm(),r}progress(e={statusCode:180}){const t=super.progress(e),n=this.dialog,r=Object.assign(Object.assign({},t),{session:n});return e.body&&this.dialog.signalingStateTransition(e.body),r}redirect(e,t={statusCode:302}){throw this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentServer=void 0,new Error("Unimplemented.")}reject(e={statusCode:488}){return this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentServer=void 0,super.reject(e)}}class tn extends Ft{constructor(e,t,n){const r=e.createOutgoingRequestMessage(Ze.REFER,n);super(jt,e.userAgentCore,r,t)}}class nn extends qt{constructor(e,t,n){const r=void 0!==e.userAgentCore?e.userAgentCore:e;super(zt,r,t,n)}}class rn extends Lt{constructor(e,t,n,r){super(t,n),this.initialTransaction=e,this._signalingState=Ye.Initial,this.ackWait=!1,this.ackProcessing=!1,this.delegate=r,e instanceof $t&&(this.ackWait=!0),this.early||this.start2xxRetransmissionTimer(),this.signalingStateTransition(e.request),this.logger=t.loggerFactory.getLogger("sip.invite-dialog"),this.logger.log(`INVITE dialog ${this.id} constructed`)}dispose(){super.dispose(),this._signalingState=Ye.Closed,this._offer=void 0,this._answer=void 0,this.invite2xxTimer&&(clearTimeout(this.invite2xxTimer),this.invite2xxTimer=void 0),this.logger.log(`INVITE dialog ${this.id} destroyed`)}get sessionState(){return this.early?Be.Early:this.ackWait?Be.AckWait:this._signalingState===Ye.Closed?Be.Terminated:Be.Confirmed}get signalingState(){return this._signalingState}get offer(){return this._offer}get answer(){return this._answer}confirm(){this.early&&this.start2xxRetransmissionTimer(),super.confirm()}reConfirm(){this.reinviteUserAgentServer&&this.startReInvite2xxRetransmissionTimer()}ack(e={}){let t;if(this.logger.log(`INVITE dialog ${this.id} sending ACK request`),this.reinviteUserAgentClient){if(!(this.reinviteUserAgentClient.transaction instanceof Ht))throw new Error("Transaction not instance of InviteClientTransaction.");t=this.reinviteUserAgentClient.transaction,this.reinviteUserAgentClient=void 0}else{if(!(this.initialTransaction instanceof Ht))throw new Error("Initial transaction not instance of InviteClientTransaction.");t=this.initialTransaction}const n=this.createOutgoingRequestMessage(Ze.ACK,{cseq:t.request.cseq,extraHeaders:e.extraHeaders,body:e.body});return t.ackResponse(n),this.signalingStateTransition(n),{message:n}}bye(e,t){if(this.logger.log(`INVITE dialog ${this.id} sending BYE request`),this.initialTransaction instanceof $t){if(this.early)throw new Error("UAS MUST NOT send a BYE on early dialogs.");if(this.ackWait&&this.initialTransaction.state!==St.Terminated)throw new Error("UAS MUST NOT send a BYE on a confirmed dialog until it has received an ACK for its 2xx response or until the server transaction times out.")}return new Ut(this,e,t)}info(e,t){if(this.logger.log(`INVITE dialog ${this.id} sending INFO request`),this.early)throw new Error("Dialog not confirmed.");return new Bt(this,e,t)}invite(e,t){if(this.logger.log(`INVITE dialog ${this.id} sending INVITE request`),this.early)throw new Error("Dialog not confirmed.");if(this.reinviteUserAgentClient)throw new Error("There is an ongoing re-INVITE client transaction.");if(this.reinviteUserAgentServer)throw new Error("There is an ongoing re-INVITE server transaction.");return new Jt(this,e,t)}message(e,t){if(this.logger.log(`INVITE dialog ${this.id} sending MESSAGE request`),this.early)throw new Error("Dialog not confirmed.");const n=this.createOutgoingRequestMessage(Ze.MESSAGE,t);return new Yt(this.core,n,e)}notify(e,t){if(this.logger.log(`INVITE dialog ${this.id} sending NOTIFY request`),this.early)throw new Error("Dialog not confirmed.");return new Kt(this,e,t)}prack(e,t){return this.logger.log(`INVITE dialog ${this.id} sending PRACK request`),new Xt(this,e,t)}refer(e,t){if(this.logger.log(`INVITE dialog ${this.id} sending REFER request`),this.early)throw new Error("Dialog not confirmed.");return new tn(this,e,t)}receiveRequest(e){if(this.logger.log(`INVITE dialog ${this.id} received ${e.method} request`),e.method!==Ze.ACK)if(this.sequenceGuard(e)){if(super.receiveRequest(e),e.method===Ze.INVITE){const t=()=>{const e=this.ackWait?"waiting for initial ACK":"processing initial ACK";this.logger.warn(`INVITE dialog ${this.id} received re-INVITE while ${e}`);let t="RFC 5407 suggests the following to avoid this race condition... ";t+=" Note: Implementation issues are outside the scope of this document,",t+=" but the following tip is provided for avoiding race conditions of",t+=" this type. The caller can delay sending re-INVITE F6 for some period",t+=" of time (2 seconds, perhaps), after which the caller can reasonably",t+=" assume that its ACK has been received. Implementors can decouple the",t+=" actions of the user (e.g., pressing the hold button) from the actions",t+=" of the protocol (the sending of re-INVITE F6), so that the UA can",t+=" behave like this. In this case, it is the implementor's choice as to",t+=" how long to wait. In most cases, such an implementation may be",t+=" useful to prevent the type of race condition shown in this section.",t+=" This document expresses no preference about whether or not they",t+=" should wait for an ACK to be delivered. After considering the impact",t+=" on user experience, implementors should decide whether or not to wait",t+=" for a while, because the user experience depends on the",t+=" implementation and has no direct bearing on protocol behavior.",this.logger.warn("RFC 5407 suggests the following to avoid this race condition... Note: Implementation issues are outside the scope of this document, but the following tip is provided for avoiding race conditions of this type. The caller can delay sending re-INVITE F6 for some period of time (2 seconds, perhaps), after which the caller can reasonably assume that its ACK has been received. Implementors can decouple the actions of the user (e.g., pressing the hold button) from the actions of the protocol (the sending of re-INVITE F6), so that the UA can behave like this. In this case, it is the implementor's choice as to how long to wait. In most cases, such an implementation may be useful to prevent the type of race condition shown in this section. This document expresses no preference about whether or not they should wait for an ACK to be delivered. After considering the impact on user experience, implementors should decide whether or not to wait for a while, because the user experience depends on the implementation and has no direct bearing on protocol behavior.")},n=[`Retry-After: ${Math.floor(10*Math.random())+1}`];if(this.ackProcessing)return this.core.replyStateless(e,{statusCode:500,extraHeaders:n}),void t();if(this.ackWait&&this.signalingState!==Ye.Stable)return this.core.replyStateless(e,{statusCode:500,extraHeaders:n}),void t();if(this.reinviteUserAgentServer)return void this.core.replyStateless(e,{statusCode:500,extraHeaders:n});if(this.reinviteUserAgentClient)return void this.core.replyStateless(e,{statusCode:491})}if(e.method===Ze.INVITE){const t=e.parseHeader("contact");if(!t)throw new Error("Contact undefined.");if(!(t instanceof Se))throw new Error("Contact not instance of NameAddrHeader.");this.dialogState.remoteTarget=t.uri}switch(e.method){case Ze.BYE:{const t=new Vt(this,e);this.delegate&&this.delegate.onBye?this.delegate.onBye(t):t.accept(),this.dispose()}break;case Ze.INFO:{const t=new Wt(this,e);this.delegate&&this.delegate.onInfo?this.delegate.onInfo(t):t.reject({statusCode:469,extraHeaders:["Recv-Info:"]})}break;case Ze.INVITE:{const t=new en(this,e);this.signalingStateTransition(e),this.delegate&&this.delegate.onInvite?this.delegate.onInvite(t):t.reject({statusCode:488})}break;case Ze.MESSAGE:{const t=new Gt(this.core,e);this.delegate&&this.delegate.onMessage?this.delegate.onMessage(t):t.accept()}break;case Ze.NOTIFY:{const t=new Qt(this,e);this.delegate&&this.delegate.onNotify?this.delegate.onNotify(t):t.accept()}break;case Ze.PRACK:{const t=new Zt(this,e);this.delegate&&this.delegate.onPrack?this.delegate.onPrack(t):t.accept()}break;case Ze.REFER:{const t=new nn(this,e);this.delegate&&this.delegate.onRefer?this.delegate.onRefer(t):t.reject()}break;default:this.logger.log(`INVITE dialog ${this.id} received unimplemented ${e.method} request`),this.core.replyStateless(e,{statusCode:501})}}else this.logger.log(`INVITE dialog ${this.id} rejected out of order ${e.method} request.`);else{if(this.ackWait){if(this.initialTransaction instanceof Ht)return void this.logger.warn(`INVITE dialog ${this.id} received unexpected ${e.method} request, dropping.`);if(this.initialTransaction.request.cseq!==e.cseq)return void this.logger.warn(`INVITE dialog ${this.id} received unexpected ${e.method} request, dropping.`);this.ackWait=!1}else{if(!this.reinviteUserAgentServer)return void this.logger.warn(`INVITE dialog ${this.id} received unexpected ${e.method} request, dropping.`);if(this.reinviteUserAgentServer.transaction.request.cseq!==e.cseq)return void this.logger.warn(`INVITE dialog ${this.id} received unexpected ${e.method} request, dropping.`);this.reinviteUserAgentServer=void 0}if(this.signalingStateTransition(e),this.delegate&&this.delegate.onAck){const t=this.delegate.onAck({message:e});t instanceof Promise&&(this.ackProcessing=!0,t.then(()=>this.ackProcessing=!1).catch(()=>this.ackProcessing=!1))}}}reliableSequenceGuard(e){const t=e.statusCode;if(!t)throw new Error("Status code undefined");if(t>100&&t<200){const t=e.getHeader("require"),n=e.getHeader("rseq"),r=t&&t.includes("100rel")&&n?Number(n):void 0;if(r){if(this.rseq&&this.rseq+1!==r)return!1;this.rseq=this.rseq?this.rseq+1:r}}return!0}signalingStateRollback(){this._signalingState!==Ye.HaveLocalOffer&&this.signalingState!==Ye.HaveRemoteOffer||this._rollbackOffer&&this._rollbackAnswer&&(this._signalingState=Ye.Stable,this._offer=this._rollbackOffer,this._answer=this._rollbackAnswer)}signalingStateTransition(e){const t=Ve(e);if(t&&"session"===t.contentDisposition){if(this._signalingState===Ye.Stable&&(this._rollbackOffer=this._offer,this._rollbackAnswer=this._answer),e instanceof Le)switch(this._signalingState){case Ye.Initial:case Ye.Stable:this._signalingState=Ye.HaveRemoteOffer,this._offer=t,this._answer=void 0;break;case Ye.HaveLocalOffer:this._signalingState=Ye.Stable,this._answer=t;break;case Ye.HaveRemoteOffer:case Ye.Closed:break;default:throw new Error("Unexpected signaling state.")}if(e instanceof He)switch(this._signalingState){case Ye.Initial:case Ye.Stable:this._signalingState=Ye.HaveRemoteOffer,this._offer=t,this._answer=void 0;break;case Ye.HaveLocalOffer:this._signalingState=Ye.Stable,this._answer=t;break;case Ye.HaveRemoteOffer:case Ye.Closed:break;default:throw new Error("Unexpected signaling state.")}if(e instanceof Fe)switch(this._signalingState){case Ye.Initial:case Ye.Stable:this._signalingState=Ye.HaveLocalOffer,this._offer=t,this._answer=void 0;break;case Ye.HaveLocalOffer:break;case Ye.HaveRemoteOffer:this._signalingState=Ye.Stable,this._answer=t;break;case Ye.Closed:break;default:throw new Error("Unexpected signaling state.")}if(qe(e))switch(this._signalingState){case Ye.Initial:case Ye.Stable:this._signalingState=Ye.HaveLocalOffer,this._offer=t,this._answer=void 0;break;case Ye.HaveLocalOffer:break;case Ye.HaveRemoteOffer:this._signalingState=Ye.Stable,this._answer=t;break;case Ye.Closed:break;default:throw new Error("Unexpected signaling state.")}}}start2xxRetransmissionTimer(){if(this.initialTransaction instanceof $t){const e=this.initialTransaction;let t=Qe.T1;const n=()=>{this.ackWait?(this.logger.log("No ACK for 2xx response received, attempting retransmission"),e.retransmitAcceptedResponse(),t=Math.min(2*t,Qe.T2),this.invite2xxTimer=setTimeout(n,t)):this.invite2xxTimer=void 0};this.invite2xxTimer=setTimeout(n,t);const r=()=>{e.state===St.Terminated&&(e.removeStateChangeListener(r),this.invite2xxTimer&&(clearTimeout(this.invite2xxTimer),this.invite2xxTimer=void 0),this.ackWait&&(this.delegate&&this.delegate.onAckTimeout?this.delegate.onAckTimeout():this.bye()))};e.addStateChangeListener(r)}}startReInvite2xxRetransmissionTimer(){if(this.reinviteUserAgentServer&&this.reinviteUserAgentServer.transaction instanceof $t){const e=this.reinviteUserAgentServer.transaction;let t=Qe.T1;const n=()=>{this.reinviteUserAgentServer?(this.logger.log("No ACK for 2xx response received, attempting retransmission"),e.retransmitAcceptedResponse(),t=Math.min(2*t,Qe.T2),this.invite2xxTimer=setTimeout(n,t)):this.invite2xxTimer=void 0};this.invite2xxTimer=setTimeout(n,t);const r=()=>{e.state===St.Terminated&&(e.removeStateChangeListener(r),this.invite2xxTimer&&(clearTimeout(this.invite2xxTimer),this.invite2xxTimer=void 0),this.reinviteUserAgentServer)};e.addStateChangeListener(r)}}}class on extends Ft{constructor(e,t,n){super(Ht,e,t,n),this.confirmedDialogAcks=new Map,this.confirmedDialogs=new Map,this.earlyDialogs=new Map,this.delegate=n}dispose(){this.earlyDialogs.forEach(e=>e.dispose()),this.earlyDialogs.clear(),super.dispose()}onTransportError(e){if(this.transaction.state===St.Calling)return super.onTransportError(e);this.logger.error(e.message),this.logger.error("User agent client request transport error while sending ACK.")}receiveResponse(e){if(!this.authenticationGuard(e))return;const t=e.statusCode?e.statusCode.toString():"";if(!t)throw new Error("Response status code undefined.");switch(!0){case/^100$/.test(t):return void(this.delegate&&this.delegate.onTrying&&this.delegate.onTrying({message:e}));case/^1[0-9]{2}$/.test(t):{if(!e.toTag)return void this.logger.warn("Non-100 1xx INVITE response received without a to tag, dropping.");if(!e.parseHeader("contact"))return void this.logger.error("Non-100 1xx INVITE response received without a Contact header field, dropping.");const t=Lt.initialDialogStateForUserAgentClient(this.message,e);let n=this.earlyDialogs.get(t.id);if(!n){const e=this.transaction;if(!(e instanceof Ht))throw new Error("Transaction not instance of InviteClientTransaction.");n=new rn(e,this.core,t),this.earlyDialogs.set(n.id,n)}if(!n.reliableSequenceGuard(e))return void this.logger.warn("1xx INVITE reliable response received out of order or is a retransmission, dropping.");n.signalingState!==Ye.Initial&&n.signalingState!==Ye.HaveLocalOffer||n.signalingStateTransition(e);const r=n;this.delegate&&this.delegate.onProgress&&this.delegate.onProgress({message:e,session:r,prack:e=>r.prack(void 0,e)})}return;case/^2[0-9]{2}$/.test(t):{if(!e.toTag)return void this.logger.error("2xx INVITE response received without a to tag, dropping.");if(!e.parseHeader("contact"))return void this.logger.error("2xx INVITE response received without a Contact header field, dropping.");const t=Lt.initialDialogStateForUserAgentClient(this.message,e);let n=this.confirmedDialogs.get(t.id);if(n){const e=this.confirmedDialogAcks.get(t.id);if(e){const t=this.transaction;if(!(t instanceof Ht))throw new Error("Client transaction not instance of InviteClientTransaction.");t.ackResponse(e.message)}return}if(n=this.earlyDialogs.get(t.id),n)n.confirm(),n.recomputeRouteSet(e),this.earlyDialogs.delete(n.id),this.confirmedDialogs.set(n.id,n);else{const e=this.transaction;if(!(e instanceof Ht))throw new Error("Transaction not instance of InviteClientTransaction.");n=new rn(e,this.core,t),this.confirmedDialogs.set(n.id,n)}n.signalingState!==Ye.Initial&&n.signalingState!==Ye.HaveLocalOffer||n.signalingStateTransition(e);const r=n;if(this.delegate&&this.delegate.onAccept)this.delegate.onAccept({message:e,session:r,ack:e=>{const t=r.ack(e);return this.confirmedDialogAcks.set(r.id,t),t}});else{const e=r.ack();this.confirmedDialogAcks.set(r.id,e)}}return;case/^3[0-9]{2}$/.test(t):return this.earlyDialogs.forEach(e=>e.dispose()),this.earlyDialogs.clear(),void(this.delegate&&this.delegate.onRedirect&&this.delegate.onRedirect({message:e}));case/^[4-6][0-9]{2}$/.test(t):return this.earlyDialogs.forEach(e=>e.dispose()),this.earlyDialogs.clear(),void(this.delegate&&this.delegate.onReject&&this.delegate.onReject({message:e}));default:throw new Error(`Invalid status code ${t}`)}}}class an extends qt{constructor(e,t,n){super($t,e,t,n),this.core=e}dispose(){this.earlyDialog&&this.earlyDialog.dispose(),super.dispose()}accept(e={statusCode:200}){if(!this.acceptable)throw new Xe(`${this.message.method} not acceptable in state ${this.transaction.state}.`);if(!this.confirmedDialog)if(this.earlyDialog)this.earlyDialog.confirm(),this.confirmedDialog=this.earlyDialog,this.earlyDialog=void 0;else{const e=this.transaction;if(!(e instanceof $t))throw new Error("Transaction not instance of InviteClientTransaction.");const t=Lt.initialDialogStateForUserAgentServer(this.message,this.toTag);this.confirmedDialog=new rn(e,this.core,t)}const t=this.message.getHeaders("record-route").map(e=>`Record-Route: ${e}`),n=`Contact: ${this.core.configuration.contact.toString()}`,r="Allow: "+et.toString();if(!e.body)if(this.confirmedDialog.signalingState===Ye.Stable)e.body=this.confirmedDialog.answer;else if(this.confirmedDialog.signalingState===Ye.Initial||this.confirmedDialog.signalingState===Ye.HaveRemoteOffer)throw new Error("Response must have a body.");e.statusCode=e.statusCode||200,e.extraHeaders=e.extraHeaders||[],e.extraHeaders=e.extraHeaders.concat(t),e.extraHeaders.push(r),e.extraHeaders.push(n);const i=super.accept(e),o=this.confirmedDialog,a=Object.assign(Object.assign({},i),{session:o});return e.body&&this.confirmedDialog.signalingState!==Ye.Stable&&this.confirmedDialog.signalingStateTransition(e.body),a}progress(e={statusCode:180}){if(!this.progressable)throw new Xe(`${this.message.method} not progressable in state ${this.transaction.state}.`);if(!this.earlyDialog){const e=this.transaction;if(!(e instanceof $t))throw new Error("Transaction not instance of InviteClientTransaction.");const t=Lt.initialDialogStateForUserAgentServer(this.message,this.toTag,!0);this.earlyDialog=new rn(e,this.core,t)}const t=this.message.getHeaders("record-route").map(e=>`Record-Route: ${e}`),n=`Contact: ${this.core.configuration.contact}`;e.extraHeaders=e.extraHeaders||[],e.extraHeaders=e.extraHeaders.concat(t),e.extraHeaders.push(n);const r=super.progress(e),i=this.earlyDialog,o=Object.assign(Object.assign({},r),{session:i});return e.body&&this.earlyDialog.signalingState!==Ye.Stable&&this.earlyDialog.signalingStateTransition(e.body),o}redirect(e,t={statusCode:302}){return super.redirect(e,t)}reject(e={statusCode:486}){return super.reject(e)}}class sn extends Ft{constructor(e,t,n){super(jt,e,t,n)}}class ln extends Ft{constructor(e,t,n){super(jt,e,t,n)}}class cn extends qt{constructor(e,t,n){super(zt,e,t,n),this.core=e}}class un extends Ft{constructor(e,t,n){const r=e.createOutgoingRequestMessage(Ze.SUBSCRIBE,n);super(jt,e.userAgentCore,r,t),this.dialog=e}waitNotifyStop(){}receiveResponse(e){if(e.statusCode&&e.statusCode>=200&&e.statusCode<300){const t=e.getHeader("Expires");if(t){const e=Number(t);this.dialog.subscriptionExpires>e&&(this.dialog.subscriptionExpires=e)}else this.logger.warn("Expires header missing in a 200-class response to SUBSCRIBE")}if(e.statusCode&&e.statusCode>=400&&e.statusCode<700){[404,405,410,416,480,481,482,483,484,485,489,501,604].includes(e.statusCode)&&this.dialog.terminate()}super.receiveResponse(e)}}class dn extends Lt{constructor(e,t,n,r,i,o){super(r,i),this.delegate=o,this._autoRefresh=!1,this._subscriptionEvent=e,this._subscriptionExpires=t,this._subscriptionExpiresInitial=t,this._subscriptionExpiresLastSet=Math.floor(Date.now()/1e3),this._subscriptionRefresh=void 0,this._subscriptionRefreshLastSet=void 0,this._subscriptionState=n,this.logger=r.loggerFactory.getLogger("sip.subscribe-dialog"),this.logger.log(`SUBSCRIBE dialog ${this.id} constructed`)}static initialDialogStateForSubscription(e,t){const n=t.getHeaders("record-route"),r=t.parseHeader("contact");if(!r)throw new Error("Contact undefined.");if(!(r instanceof Se))throw new Error("Contact not instance of NameAddrHeader.");const i=r.uri,o=e.cseq,a=e.callId,s=e.fromTag,l=t.fromTag;if(!a)throw new Error("Call id undefined.");if(!s)throw new Error("From tag undefined.");if(!l)throw new Error("To tag undefined.");if(!e.from)throw new Error("From undefined.");if(!e.to)throw new Error("To undefined.");return{id:a+s+l,early:!1,callId:a,localTag:s,remoteTag:l,localSequenceNumber:o,remoteSequenceNumber:void 0,localURI:e.from.uri,remoteURI:e.to.uri,remoteTarget:i,routeSet:n,secure:!1}}dispose(){super.dispose(),this.N&&(clearTimeout(this.N),this.N=void 0),this.refreshTimerClear(),this.logger.log(`SUBSCRIBE dialog ${this.id} destroyed`)}get autoRefresh(){return this._autoRefresh}set autoRefresh(e){this._autoRefresh=!0,this.refreshTimerSet()}get subscriptionEvent(){return this._subscriptionEvent}get subscriptionExpires(){const e=Math.floor(Date.now()/1e3)-this._subscriptionExpiresLastSet,t=this._subscriptionExpires-e;return Math.max(t,0)}set subscriptionExpires(e){if(e<0)throw new Error("Expires must be greater than or equal to zero.");if(this._subscriptionExpires=e,this._subscriptionExpiresLastSet=Math.floor(Date.now()/1e3),this.autoRefresh){const t=this.subscriptionRefresh;(void 0===t||t>=e)&&this.refreshTimerSet()}}get subscriptionExpiresInitial(){return this._subscriptionExpiresInitial}get subscriptionRefresh(){if(void 0===this._subscriptionRefresh||void 0===this._subscriptionRefreshLastSet)return;const e=Math.floor(Date.now()/1e3)-this._subscriptionRefreshLastSet,t=this._subscriptionRefresh-e;return Math.max(t,0)}get subscriptionState(){return this._subscriptionState}receiveRequest(e){if(this.logger.log(`SUBSCRIBE dialog ${this.id} received ${e.method} request`),this.sequenceGuard(e))if(super.receiveRequest(e),e.method===Ze.NOTIFY)this.onNotify(e);else this.logger.log(`SUBSCRIBE dialog ${this.id} received unimplemented ${e.method} request`),this.core.replyStateless(e,{statusCode:501});else this.logger.log(`SUBSCRIBE dialog ${this.id} rejected out of order ${e.method} request.`)}refresh(){const e="Allow: "+et.toString(),t={};return t.extraHeaders=(t.extraHeaders||[]).slice(),t.extraHeaders.push(e),t.extraHeaders.push("Event: "+this.subscriptionEvent),t.extraHeaders.push("Expires: "+this.subscriptionExpiresInitial),t.extraHeaders.push("Contact: "+this.core.configuration.contact.toString()),this.subscribe(void 0,t)}subscribe(e,t={}){var n;if(this.subscriptionState!==pt.Pending&&this.subscriptionState!==pt.Active)throw new Error(`Invalid state ${this.subscriptionState}. May only re-subscribe while in state "pending" or "active".`);this.logger.log(`SUBSCRIBE dialog ${this.id} sending SUBSCRIBE request`);const r=new un(this,e,t);return this.N&&(clearTimeout(this.N),this.N=void 0),(null===(n=t.extraHeaders)||void 0===n?void 0:n.includes("Expires: 0"))||(this.N=setTimeout(()=>this.timerN(),Qe.TIMER_N)),r}terminate(){this.stateTransition(pt.Terminated),this.onTerminated()}unsubscribe(){const e="Allow: "+et.toString(),t={};return t.extraHeaders=(t.extraHeaders||[]).slice(),t.extraHeaders.push(e),t.extraHeaders.push("Event: "+this.subscriptionEvent),t.extraHeaders.push("Expires: 0"),t.extraHeaders.push("Contact: "+this.core.configuration.contact.toString()),this.subscribe(void 0,t)}onNotify(e){const t=e.parseHeader("Event").event;if(!t||t!==this.subscriptionEvent)return void this.core.replyStateless(e,{statusCode:489});this.N&&(clearTimeout(this.N),this.N=void 0);const n=e.parseHeader("Subscription-State");if(!n||!n.state)return void this.core.replyStateless(e,{statusCode:489});const r=n.state,i=n.expires?Math.max(n.expires,0):void 0;switch(r){case"pending":this.stateTransition(pt.Pending,i);break;case"active":this.stateTransition(pt.Active,i);break;case"terminated":this.stateTransition(pt.Terminated,i);break;default:this.logger.warn("Unrecognized subscription state.")}const o=new Qt(this,e);this.delegate&&this.delegate.onNotify?this.delegate.onNotify(o):o.accept()}onRefresh(e){this.delegate&&this.delegate.onRefresh&&this.delegate.onRefresh(e)}onTerminated(){this.delegate&&this.delegate.onTerminated&&this.delegate.onTerminated()}refreshTimerClear(){this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=void 0)}refreshTimerSet(){if(this.refreshTimerClear(),this.autoRefresh&&this.subscriptionExpires>0){const e=900*this.subscriptionExpires;this._subscriptionRefresh=Math.floor(e/1e3),this._subscriptionRefreshLastSet=Math.floor(Date.now()/1e3),this.refreshTimer=setTimeout(()=>{this.refreshTimer=void 0,this._subscriptionRefresh=void 0,this._subscriptionRefreshLastSet=void 0,this.onRefresh(this.refresh())},e)}}stateTransition(e,t){const n=()=>{this.logger.warn(`Invalid subscription state transition from ${this.subscriptionState} to ${e}`)};switch(e){case pt.Initial:case pt.NotifyWait:return void n();case pt.Pending:if(this.subscriptionState!==pt.NotifyWait&&this.subscriptionState!==pt.Pending)return void n();break;case pt.Active:case pt.Terminated:if(this.subscriptionState!==pt.NotifyWait&&this.subscriptionState!==pt.Pending&&this.subscriptionState!==pt.Active)return void n();break;default:return void n()}e===pt.Pending&&t&&(this.subscriptionExpires=t),e===pt.Active&&t&&(this.subscriptionExpires=t),e===pt.Terminated&&this.dispose(),this._subscriptionState=e}timerN(){this.logger.warn("Timer N expired for SUBSCRIBE dialog. Timed out waiting for NOTIFY."),this.subscriptionState!==pt.Terminated&&(this.stateTransition(pt.Terminated),this.onTerminated())}}class hn extends Ft{constructor(e,t,n){const r=t.getHeader("Event");if(!r)throw new Error("Event undefined");const i=t.getHeader("Expires");if(!i)throw new Error("Expires undefined");super(jt,e,t,n),this.delegate=n,this.subscriberId=t.callId+t.fromTag+r,this.subscriptionExpiresRequested=this.subscriptionExpires=Number(i),this.subscriptionEvent=r,this.subscriptionState=pt.NotifyWait,this.waitNotifyStart()}dispose(){super.dispose()}onNotify(e){const t=e.message.parseHeader("Event").event;if(!t||t!==this.subscriptionEvent)return this.logger.warn("Failed to parse event."),void e.reject({statusCode:489});const n=e.message.parseHeader("Subscription-State");if(!n||!n.state)return this.logger.warn("Failed to parse subscription state."),void e.reject({statusCode:489});const r=n.state;switch(r){case"pending":case"active":case"terminated":break;default:return this.logger.warn(`Invalid subscription state ${r}`),void e.reject({statusCode:489})}if("terminated"!==r){if(!e.message.parseHeader("contact"))return this.logger.warn("Failed to parse contact."),void e.reject({statusCode:489})}if(this.dialog)throw new Error("Dialog already created. This implementation only supports install of single subscriptions.");switch(this.waitNotifyStop(),this.subscriptionExpires=n.expires?Math.min(this.subscriptionExpires,Math.max(n.expires,0)):this.subscriptionExpires,r){case"pending":this.subscriptionState=pt.Pending;break;case"active":this.subscriptionState=pt.Active;break;case"terminated":this.subscriptionState=pt.Terminated;break;default:throw new Error(`Unrecognized state ${r}.`)}if(this.subscriptionState!==pt.Terminated){const t=dn.initialDialogStateForSubscription(this.message,e.message);this.dialog=new dn(this.subscriptionEvent,this.subscriptionExpires,this.subscriptionState,this.core,t)}if(this.delegate&&this.delegate.onNotify){const t=e,n=this.dialog;this.delegate.onNotify({request:t,subscription:n})}else e.accept()}waitNotifyStart(){this.N||(this.core.subscribers.set(this.subscriberId,this),this.N=setTimeout(()=>this.timerN(),Qe.TIMER_N))}waitNotifyStop(){this.N&&(this.core.subscribers.delete(this.subscriberId),clearTimeout(this.N),this.N=void 0)}receiveResponse(e){if(this.authenticationGuard(e)){if(e.statusCode&&e.statusCode>=200&&e.statusCode<300){const t=e.getHeader("Expires");if(t){const e=Number(t);e>this.subscriptionExpiresRequested&&this.logger.warn("Expires header in a 200-class response to SUBSCRIBE with a higher value than the one in the request"),ethis.subscriptionExpires&&(this.dialog.subscriptionExpires=this.subscriptionExpires)}e.statusCode&&e.statusCode>=300&&e.statusCode<700&&this.waitNotifyStop(),super.receiveResponse(e)}}timerN(){this.logger.warn("Timer N expired for SUBSCRIBE user agent client. Timed out waiting for NOTIFY."),this.waitNotifyStop(),this.delegate&&this.delegate.onNotifyTimeout&&this.delegate.onNotifyTimeout()}}class fn extends qt{constructor(e,t,n){super(zt,e,t,n),this.core=e}}const pn=["application/sdp","application/dtmf-relay"];class gn{constructor(e,t={}){this.userAgentClients=new Map,this.userAgentServers=new Map,this.configuration=e,this.delegate=t,this.dialogs=new Map,this.subscribers=new Map,this.logger=e.loggerFactory.getLogger("sip.user-agent-core")}dispose(){this.reset()}reset(){this.dialogs.forEach(e=>e.dispose()),this.dialogs.clear(),this.subscribers.forEach(e=>e.dispose()),this.subscribers.clear(),this.userAgentClients.forEach(e=>e.dispose()),this.userAgentClients.clear(),this.userAgentServers.forEach(e=>e.dispose()),this.userAgentServers.clear()}get loggerFactory(){return this.configuration.loggerFactory}get transport(){const e=this.configuration.transportAccessor();if(!e)throw new Error("Transport undefined.");return e}invite(e,t){return new on(this,e,t)}message(e,t){return new Yt(this,e,t)}publish(e,t){return new sn(this,e,t)}register(e,t){return new ln(this,e,t)}subscribe(e,t){return new hn(this,e,t)}request(e,t){return new Ft(jt,this,e,t)}makeOutgoingRequestMessage(e,t,n,r,i,o,a){const s=this.configuration.sipjsId,l=this.configuration.displayName,c=this.configuration.viaForceRport,u=this.configuration.hackViaTcp,d=this.configuration.supportedOptionTags.slice();e===Ze.REGISTER&&d.push("path","gruu"),e===Ze.INVITE&&(this.configuration.contact.pubGruu||this.configuration.contact.tempGruu)&&d.push("gruu");const h={callIdPrefix:s,forceRport:c,fromDisplayName:l,hackViaTcp:u,optionTags:d,routeSet:this.configuration.routeSet,userAgentString:this.configuration.userAgentHeaderFieldValue,viaHost:this.configuration.viaHost},f=Object.assign(Object.assign({},h),i);return new Fe(e,t,n,r,f,o,a)}receiveIncomingRequestFromTransport(e){this.receiveRequestFromTransport(e)}receiveIncomingResponseFromTransport(e){this.receiveResponseFromTransport(e)}replyStateless(e,t){const n=this.configuration.userAgentHeaderFieldValue,r=this.configuration.supportedOptionTagsResponse;t=Object.assign(Object.assign({},t),{userAgent:n,supported:r});const i=It(e,t);return this.transport.send(i.message).catch(t=>{t instanceof Error&&this.logger.error(t.message),this.logger.error(`Transport error occurred sending stateless reply to ${e.method} request.`)}),i}receiveRequestFromTransport(e){const t=e.viaBranch,n=this.userAgentServers.get(t);e.method===Ze.ACK&&n&&n.transaction.state===St.Accepted&&n instanceof an?this.logger.warn(`Discarding out of dialog ACK after 2xx response sent on transaction ${t}.`):e.method!==Ze.CANCEL?n?n.transaction.receiveRequest(e):this.receiveRequest(e):n?(this.replyStateless(e,{statusCode:200}),n.transaction instanceof $t&&n.transaction.state===St.Proceeding&&n instanceof an&&n.receiveCancel(e)):this.replyStateless(e,{statusCode:481})}receiveRequest(e){if(!et.includes(e.method)){const t="Allow: "+et.toString();return void this.replyStateless(e,{statusCode:405,extraHeaders:[t]})}if(!e.ruri)throw new Error("Request-URI undefined.");if("sip"!==e.ruri.scheme)return void this.replyStateless(e,{statusCode:416});const t=e.ruri,n=e=>!!e&&e.user===t.user;if(!n(this.configuration.aor)&&!(n(this.configuration.contact.uri)||n(this.configuration.contact.pubGruu)||n(this.configuration.contact.tempGruu)))return this.logger.warn("Request-URI does not point to us."),void(e.method!==Ze.ACK&&this.replyStateless(e,{statusCode:404}));if(e.method!==Ze.INVITE||e.hasHeader("Contact")){if(!e.toTag){const t=e.viaBranch;if(!this.userAgentServers.has(t)){if(Array.from(this.userAgentServers.values()).some(t=>t.transaction.request.fromTag===e.fromTag&&t.transaction.request.callId===e.callId&&t.transaction.request.cseq===e.cseq))return void this.replyStateless(e,{statusCode:482})}}e.toTag?this.receiveInsideDialogRequest(e):this.receiveOutsideDialogRequest(e)}else this.replyStateless(e,{statusCode:400,reasonPhrase:"Missing Contact Header"})}receiveInsideDialogRequest(e){if(e.method===Ze.NOTIFY){const t=e.parseHeader("Event");if(!t||!t.event)return void this.replyStateless(e,{statusCode:489});const n=e.callId+e.toTag+t.event,r=this.subscribers.get(n);if(r){const t=new Qt(this,e);return void r.onNotify(t)}}const t=e.callId+e.toTag+e.fromTag,n=this.dialogs.get(t);if(n){if(e.method===Ze.OPTIONS){const t="Allow: "+et.toString(),n="Accept: "+pn.toString();return void this.replyStateless(e,{statusCode:200,extraHeaders:[t,n]})}n.receiveRequest(e)}else e.method!==Ze.ACK&&this.replyStateless(e,{statusCode:481})}receiveOutsideDialogRequest(e){switch(e.method){case Ze.ACK:break;case Ze.BYE:this.replyStateless(e,{statusCode:481});break;case Ze.CANCEL:throw new Error(`Unexpected out of dialog request method ${e.method}.`);case Ze.INFO:this.replyStateless(e,{statusCode:405});break;case Ze.INVITE:{const t=new an(this,e);this.delegate.onInvite?this.delegate.onInvite(t):t.reject()}break;case Ze.MESSAGE:{const t=new Gt(this,e);this.delegate.onMessage?this.delegate.onMessage(t):t.accept()}break;case Ze.NOTIFY:{const t=new Qt(this,e);this.delegate.onNotify?this.delegate.onNotify(t):t.reject({statusCode:405})}break;case Ze.OPTIONS:{const t="Allow: "+et.toString(),n="Accept: "+pn.toString();this.replyStateless(e,{statusCode:200,extraHeaders:[t,n]})}break;case Ze.REFER:{const t=new nn(this,e);this.delegate.onRefer?this.delegate.onRefer(t):t.reject({statusCode:405})}break;case Ze.REGISTER:{const t=new cn(this,e);this.delegate.onRegister?this.delegate.onRegister(t):t.reject({statusCode:405})}break;case Ze.SUBSCRIBE:{const t=new fn(this,e);this.delegate.onSubscribe?this.delegate.onSubscribe(t):t.reject({statusCode:480})}break;default:throw new Error(`Unexpected out of dialog request method ${e.method}.`)}}receiveResponseFromTransport(e){if(e.getHeaders("via").length>1)return void this.logger.warn("More than one Via header field present in the response, dropping");const t=e.viaBranch+e.method,n=this.userAgentClients.get(t);n?n.transaction.receiveResponse(e):this.logger.warn(`Discarding unmatched ${e.statusCode} response to ${e.method} ${t}.`)}}class mn{constructor(e,t,n){e.debug("SessionDescriptionHandler.constructor"),this.logger=e,this.mediaStreamFactory=t,this.sessionDescriptionHandlerConfiguration=n,this._localMediaStream=new MediaStream,this._remoteMediaStream=new MediaStream,this._peerConnection=new RTCPeerConnection(null==n?void 0:n.peerConnectionConfiguration),this.initPeerConnectionEventHandlers()}get localMediaStream(){return this._localMediaStream}get remoteMediaStream(){return this._remoteMediaStream}get dataChannel(){return this._dataChannel}get peerConnection(){return this._peerConnection}get peerConnectionDelegate(){return this._peerConnectionDelegate}set peerConnectionDelegate(e){this._peerConnectionDelegate=e}static dispatchAddTrackEvent(e,t){e.dispatchEvent(new MediaStreamTrackEvent("addtrack",{track:t}))}static dispatchRemoveTrackEvent(e,t){e.dispatchEvent(new MediaStreamTrackEvent("removetrack",{track:t}))}close(){this.logger.debug("SessionDescriptionHandler.close"),void 0!==this._peerConnection&&(this._peerConnection.getReceivers().forEach(e=>{e.track&&e.track.stop()}),this._peerConnection.getSenders().forEach(e=>{e.track&&e.track.stop()}),this._dataChannel&&this._dataChannel.close(),this._peerConnection.close(),this._peerConnection=void 0)}enableReceiverTracks(e){const t=this.peerConnection;if(!t)throw new Error("Peer connection closed.");t.getReceivers().forEach(t=>{t.track&&(t.track.enabled=e)})}enableSenderTracks(e){const t=this.peerConnection;if(!t)throw new Error("Peer connection closed.");t.getSenders().forEach(t=>{t.track&&(t.track.enabled=e)})}getDescription(e,t){var n,r;if(this.logger.debug("SessionDescriptionHandler.getDescription"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));this.onDataChannel=null==e?void 0:e.onDataChannel;const i=null===(n=null==e?void 0:e.offerOptions)||void 0===n?void 0:n.iceRestart,o=void 0===(null==e?void 0:e.iceGatheringTimeout)?null===(r=this.sessionDescriptionHandlerConfiguration)||void 0===r?void 0:r.iceGatheringTimeout:null==e?void 0:e.iceGatheringTimeout;return this.getLocalMediaStream(e).then(()=>this.updateDirection(e)).then(()=>this.createDataChannel(e)).then(()=>this.createLocalOfferOrAnswer(e)).then(e=>this.applyModifiers(e,t)).then(e=>this.setLocalSessionDescription(e)).then(()=>this.waitForIceGatheringComplete(i,o)).then(()=>this.getLocalSessionDescription()).then(e=>({body:e.sdp,contentType:"application/sdp"})).catch(e=>{throw this.logger.error("SessionDescriptionHandler.getDescription failed - "+e),e})}hasDescription(e){return this.logger.debug("SessionDescriptionHandler.hasDescription"),"application/sdp"===e}iceGatheringComplete(){this.logger.debug("SessionDescriptionHandler.iceGatheringComplete"),void 0!==this.iceGatheringCompleteTimeoutId&&(this.logger.debug("SessionDescriptionHandler.iceGatheringComplete - clearing timeout"),clearTimeout(this.iceGatheringCompleteTimeoutId),this.iceGatheringCompleteTimeoutId=void 0),void 0!==this.iceGatheringCompletePromise&&(this.logger.debug("SessionDescriptionHandler.iceGatheringComplete - resolving promise"),this.iceGatheringCompleteResolve&&this.iceGatheringCompleteResolve(),this.iceGatheringCompletePromise=void 0,this.iceGatheringCompleteResolve=void 0,this.iceGatheringCompleteReject=void 0)}sendDtmf(e,t){if(this.logger.debug("SessionDescriptionHandler.sendDtmf"),void 0===this._peerConnection)return this.logger.error("SessionDescriptionHandler.sendDtmf failed - peer connection closed"),!1;const n=this._peerConnection.getSenders();if(0===n.length)return this.logger.error("SessionDescriptionHandler.sendDtmf failed - no senders"),!1;const r=n[0].dtmf;if(!r)return this.logger.error("SessionDescriptionHandler.sendDtmf failed - no DTMF sender"),!1;const i=null==t?void 0:t.duration,o=null==t?void 0:t.interToneGap;try{r.insertDTMF(e,i,o)}catch(a){return this.logger.error(a.toString()),!1}return this.logger.log("SessionDescriptionHandler.sendDtmf sent via RTP: "+e.toString()),!0}setDescription(e,t,n){if(this.logger.debug("SessionDescriptionHandler.setDescription"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));this.onDataChannel=null==t?void 0:t.onDataChannel;const r="have-local-offer"===this._peerConnection.signalingState?"answer":"offer";return this.getLocalMediaStream(t).then(()=>this.applyModifiers({sdp:e,type:r},n)).then(e=>this.setRemoteSessionDescription(e)).catch(e=>{throw this.logger.error("SessionDescriptionHandler.setDescription failed - "+e),e})}applyModifiers(e,t){return this.logger.debug("SessionDescriptionHandler.applyModifiers"),t&&0!==t.length?t.reduce((e,t)=>e.then(t),Promise.resolve(e)).then(e=>{if(this.logger.debug("SessionDescriptionHandler.applyModifiers - modified sdp"),!e.sdp||!e.type)throw new Error("Invalid SDP.");return{sdp:e.sdp,type:e.type}}):Promise.resolve(e)}createDataChannel(e){if(void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));if(!0!==(null==e?void 0:e.dataChannel))return Promise.resolve();if(this._dataChannel)return Promise.resolve();switch(this._peerConnection.signalingState){case"stable":this.logger.debug("SessionDescriptionHandler.createDataChannel - creating data channel");try{return this._dataChannel=this._peerConnection.createDataChannel((null==e?void 0:e.dataChannelLabel)||"",null==e?void 0:e.dataChannelOptions),this.onDataChannel&&this.onDataChannel(this._dataChannel),Promise.resolve()}catch(t){return Promise.reject(t)}case"have-remote-offer":return Promise.resolve();default:return Promise.reject(new Error("Invalid signaling state "+this._peerConnection.signalingState))}}createLocalOfferOrAnswer(e){if(void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));switch(this._peerConnection.signalingState){case"stable":return this.logger.debug("SessionDescriptionHandler.createLocalOfferOrAnswer - creating SDP offer"),this._peerConnection.createOffer(null==e?void 0:e.offerOptions);case"have-remote-offer":return this.logger.debug("SessionDescriptionHandler.createLocalOfferOrAnswer - creating SDP answer"),this._peerConnection.createAnswer(null==e?void 0:e.answerOptions);default:return Promise.reject(new Error("Invalid signaling state "+this._peerConnection.signalingState))}}getLocalMediaStream(e){if(this.logger.debug("SessionDescriptionHandler.getLocalMediaStream"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));let t=Object.assign({},null==e?void 0:e.constraints);if(this.localMediaStreamConstraints){if(t.audio=t.audio||this.localMediaStreamConstraints.audio,t.video=t.video||this.localMediaStreamConstraints.video,JSON.stringify(this.localMediaStreamConstraints.audio)===JSON.stringify(t.audio)&&JSON.stringify(this.localMediaStreamConstraints.video)===JSON.stringify(t.video))return Promise.resolve()}else void 0===t.audio&&void 0===t.video&&(t={audio:!0});return this.localMediaStreamConstraints=t,this.mediaStreamFactory(t,this,e).then(e=>this.setLocalMediaStream(e))}setLocalMediaStream(e){if(this.logger.debug("SessionDescriptionHandler.setLocalMediaStream"),!this._peerConnection)throw new Error("Peer connection undefined.");const t=this._peerConnection,n=this._localMediaStream,r=[],i=e=>{const i=e.kind;if("audio"!==i&&"video"!==i)throw new Error(`Unknown new track kind ${i}.`);const o=t.getSenders().find(e=>e.track&&e.track.kind===i);o?r.push(new Promise(e=>{this.logger.debug(`SessionDescriptionHandler.setLocalMediaStream - replacing sender ${i} track`),e()}).then(()=>o.replaceTrack(e).then(()=>{const t=n.getTracks().find(e=>e.kind===i);t&&(t.stop(),n.removeTrack(t),mn.dispatchRemoveTrackEvent(n,t)),n.addTrack(e),mn.dispatchAddTrackEvent(n,e)}).catch(e=>{throw this.logger.error(`SessionDescriptionHandler.setLocalMediaStream - failed to replace sender ${i} track`),e}))):r.push(new Promise(e=>{this.logger.debug(`SessionDescriptionHandler.setLocalMediaStream - adding sender ${i} track`),e()}).then(()=>{try{t.addTrack(e,n)}catch(r){throw this.logger.error(`SessionDescriptionHandler.setLocalMediaStream - failed to add sender ${i} track`),r}n.addTrack(e),mn.dispatchAddTrackEvent(n,e)}))},o=e.getAudioTracks();o.length&&i(o[0]);const a=e.getVideoTracks();return a.length&&i(a[0]),r.reduce((e,t)=>e.then(()=>t),Promise.resolve())}getLocalSessionDescription(){if(this.logger.debug("SessionDescriptionHandler.getLocalSessionDescription"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));const e=this._peerConnection.localDescription;return e?Promise.resolve(e):Promise.reject(new Error("Failed to get local session description"))}setLocalSessionDescription(e){return this.logger.debug("SessionDescriptionHandler.setLocalSessionDescription"),void 0===this._peerConnection?Promise.reject(new Error("Peer connection closed.")):this._peerConnection.setLocalDescription(e)}setRemoteSessionDescription(e){if(this.logger.debug("SessionDescriptionHandler.setRemoteSessionDescription"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));const t=e.sdp;let n;switch(this._peerConnection.signalingState){case"stable":n="offer";break;case"have-local-offer":n="answer";break;default:return Promise.reject(new Error("Invalid signaling state "+this._peerConnection.signalingState))}return t?this._peerConnection.setRemoteDescription({sdp:t,type:n}):(this.logger.error("SessionDescriptionHandler.setRemoteSessionDescription failed - cannot set null sdp"),Promise.reject(new Error("SDP is undefined")))}setRemoteTrack(e){this.logger.debug("SessionDescriptionHandler.setRemoteTrack");const t=this._remoteMediaStream;t.getTrackById(e.id)?this.logger.debug(`SessionDescriptionHandler.setRemoteTrack - have remote ${e.kind} track`):"audio"===e.kind?(this.logger.debug(`SessionDescriptionHandler.setRemoteTrack - adding remote ${e.kind} track`),t.getAudioTracks().forEach(e=>{e.stop(),t.removeTrack(e),mn.dispatchRemoveTrackEvent(t,e)}),t.addTrack(e),mn.dispatchAddTrackEvent(t,e)):"video"===e.kind&&(this.logger.debug(`SessionDescriptionHandler.setRemoteTrack - adding remote ${e.kind} track`),t.getVideoTracks().forEach(e=>{e.stop(),t.removeTrack(e),mn.dispatchRemoveTrackEvent(t,e)}),t.addTrack(e),mn.dispatchAddTrackEvent(t,e))}updateDirection(e){if(void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));switch(this._peerConnection.signalingState){case"stable":this.logger.debug("SessionDescriptionHandler.updateDirection - setting offer direction");{const t=t=>{switch(t){case"inactive":case"recvonly":return(null==e?void 0:e.hold)?"inactive":"recvonly";case"sendonly":case"sendrecv":return(null==e?void 0:e.hold)?"sendonly":"sendrecv";case"stopped":return"stopped";default:throw new Error("Should never happen")}};this._peerConnection.getTransceivers().forEach(e=>{if(e.direction){const n=t(e.direction);e.direction!==n&&(e.direction=n)}})}break;case"have-remote-offer":this.logger.debug("SessionDescriptionHandler.updateDirection - setting answer direction");{const t=(()=>{const e=this._peerConnection.remoteDescription;if(!e)throw new Error("Failed to read remote offer");const t=/a=sendrecv\r\n|a=sendonly\r\n|a=recvonly\r\n|a=inactive\r\n/.exec(e.sdp);if(t)switch(t[0]){case"a=inactive\r\n":return"inactive";case"a=recvonly\r\n":return"recvonly";case"a=sendonly\r\n":return"sendonly";case"a=sendrecv\r\n":return"sendrecv";default:throw new Error("Should never happen")}return"sendrecv"})(),n=(()=>{switch(t){case"inactive":return"inactive";case"recvonly":return"sendonly";case"sendonly":return(null==e?void 0:e.hold)?"inactive":"recvonly";case"sendrecv":return(null==e?void 0:e.hold)?"sendonly":"sendrecv";default:throw new Error("Should never happen")}})();this._peerConnection.getTransceivers().forEach(e=>{e.direction&&"stopped"!==e.direction&&e.direction!==n&&(e.direction=n)})}break;default:return Promise.reject(new Error("Invalid signaling state "+this._peerConnection.signalingState))}return Promise.resolve()}waitForIceGatheringComplete(e=!1,t=0){return this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete"),void 0===this._peerConnection?Promise.reject("Peer connection closed."):e||"complete"!==this._peerConnection.iceGatheringState?(void 0!==this.iceGatheringCompletePromise&&(this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - rejecting prior waiting promise"),this.iceGatheringCompleteReject&&this.iceGatheringCompleteReject(new Error("Promise superseded.")),this.iceGatheringCompletePromise=void 0,this.iceGatheringCompleteResolve=void 0,this.iceGatheringCompleteReject=void 0),this.iceGatheringCompletePromise=new Promise((e,n)=>{this.iceGatheringCompleteResolve=e,this.iceGatheringCompleteReject=n,t>0&&(this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - timeout in "+t),this.iceGatheringCompleteTimeoutId=setTimeout(()=>{this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - timeout"),this.iceGatheringComplete()},t))}),this.iceGatheringCompletePromise):(this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - already complete"),Promise.resolve())}initPeerConnectionEventHandlers(){if(this.logger.debug("SessionDescriptionHandler.initPeerConnectionEventHandlers"),!this._peerConnection)throw new Error("Peer connection undefined.");const e=this._peerConnection;e.onconnectionstatechange=t=>{var n;const r=e.connectionState;this.logger.debug(`SessionDescriptionHandler.onconnectionstatechange ${r}`),(null===(n=this._peerConnectionDelegate)||void 0===n?void 0:n.onconnectionstatechange)&&this._peerConnectionDelegate.onconnectionstatechange(t)},e.ondatachannel=e=>{var t;this.logger.debug("SessionDescriptionHandler.ondatachannel"),this._dataChannel=e.channel,this.onDataChannel&&this.onDataChannel(this._dataChannel),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.ondatachannel)&&this._peerConnectionDelegate.ondatachannel(e)},e.onicecandidate=e=>{var t;this.logger.debug("SessionDescriptionHandler.onicecandidate"),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.onicecandidate)&&this._peerConnectionDelegate.onicecandidate(e)},e.onicecandidateerror=e=>{var t;this.logger.debug("SessionDescriptionHandler.onicecandidateerror"),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.onicecandidateerror)&&this._peerConnectionDelegate.onicecandidateerror(e)},e.oniceconnectionstatechange=t=>{var n;const r=e.iceConnectionState;this.logger.debug(`SessionDescriptionHandler.oniceconnectionstatechange ${r}`),(null===(n=this._peerConnectionDelegate)||void 0===n?void 0:n.oniceconnectionstatechange)&&this._peerConnectionDelegate.oniceconnectionstatechange(t)},e.onicegatheringstatechange=t=>{var n;const r=e.iceGatheringState;this.logger.debug(`SessionDescriptionHandler.onicegatheringstatechange ${r}`),"complete"===r&&this.iceGatheringComplete(),(null===(n=this._peerConnectionDelegate)||void 0===n?void 0:n.onicegatheringstatechange)&&this._peerConnectionDelegate.onicegatheringstatechange(t)},e.onnegotiationneeded=e=>{var t;this.logger.debug("SessionDescriptionHandler.onnegotiationneeded"),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.onnegotiationneeded)&&this._peerConnectionDelegate.onnegotiationneeded(e)},e.onsignalingstatechange=t=>{var n;const r=e.signalingState;this.logger.debug(`SessionDescriptionHandler.onsignalingstatechange ${r}`),(null===(n=this._peerConnectionDelegate)||void 0===n?void 0:n.onsignalingstatechange)&&this._peerConnectionDelegate.onsignalingstatechange(t)},e.ontrack=e=>{var t;const n=e.track.kind,r=e.track.enabled?"enabled":"disabled";this.logger.debug(`SessionDescriptionHandler.ontrack ${n} ${r}`),this.setRemoteTrack(e.track),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.ontrack)&&this._peerConnectionDelegate.ontrack(e)}}}function vn(e){return(t,n)=>{void 0===e&&(e=e=>e.audio||e.video?void 0===navigator.mediaDevices?Promise.reject(new Error("Media devices not available in insecure contexts.")):navigator.mediaDevices.getUserMedia.call(navigator.mediaDevices,e):Promise.resolve(new MediaStream));const r={iceGatheringTimeout:void 0!==(null==n?void 0:n.iceGatheringTimeout)?null==n?void 0:n.iceGatheringTimeout:5e3,peerConnectionConfiguration:Object.assign(Object.assign({},{bundlePolicy:"balanced",certificates:void 0,iceCandidatePoolSize:0,iceServers:[{urls:"stun:stun.l.google.com:19302"}],iceTransportPolicy:"all",rtcpMuxPolicy:"require"}),null==n?void 0:n.peerConnectionConfiguration)},i=t.userAgent.getLogger("sip.SessionDescriptionHandler");return new mn(i,e,r)}}class yn{constructor(e,t){if(this._state=mt.Disconnected,this.transitioningState=!1,this._stateEventEmitter=new we,this.logger=e,t){const e=t,n=null==e?void 0:e.wsServers,r=null==e?void 0:e.maxReconnectionAttempts;if(void 0!==n){const e='The transport option "wsServers" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(e)}if(void 0!==r){const e='The transport option "maxReconnectionAttempts" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(e)}n&&!t.server&&("string"==typeof n&&(t.server=n),n instanceof Array&&(t.server=n[0]))}this.configuration=Object.assign(Object.assign({},yn.defaultOptions),t);const n=this.configuration.server,r=_e.parse(n,"absoluteURI");if(-1===r)throw this.logger.error(`Invalid WebSocket Server URL "${n}"`),new Error("Invalid WebSocket Server URL");if(!["wss","ws","udp"].includes(r.scheme))throw this.logger.error(`Invalid scheme in WebSocket Server URL "${n}"`),new Error("Invalid scheme in WebSocket Server URL");this._protocol=r.scheme.toUpperCase()}dispose(){return this.disconnect()}get protocol(){return this._protocol}get server(){return this.configuration.server}get state(){return this._state}get stateChange(){return this._stateEventEmitter}get ws(){return this._ws}connect(){return this._connect()}disconnect(){return this._disconnect()}isConnected(){return this.state===mt.Connected}send(e){return this._send(e)}_connect(){switch(this.logger.log(`Connecting ${this.server}`),this.state){case mt.Connecting:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(mt.Connecting));if(!this.connectPromise)throw new Error("Connect promise must be defined.");return this.connectPromise;case mt.Connected:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(mt.Connecting));if(this.connectPromise)throw new Error("Connect promise must not be defined.");return Promise.resolve();case mt.Disconnecting:if(this.connectPromise)throw new Error("Connect promise must not be defined.");try{this.transitionState(mt.Connecting)}catch(t){if(t instanceof me)return Promise.reject(t);throw t}break;case mt.Disconnected:if(this.connectPromise)throw new Error("Connect promise must not be defined.");try{this.transitionState(mt.Connecting)}catch(t){if(t instanceof me)return Promise.reject(t);throw t}break;default:throw new Error("Unknown state")}let e;try{e=new WebSocket(this.server,"sip"),e.binaryType="arraybuffer",e.addEventListener("close",t=>this.onWebSocketClose(t,e)),e.addEventListener("error",t=>this.onWebSocketError(t,e)),e.addEventListener("open",t=>this.onWebSocketOpen(t,e)),e.addEventListener("message",t=>this.onWebSocketMessage(t,e)),this._ws=e}catch(n){return this._ws=void 0,this.logger.error("WebSocket construction failed."),this.logger.error(n.toString()),new Promise((e,t)=>{this.connectResolve=e,this.connectReject=t,this.transitionState(mt.Disconnected,n)})}return this.connectPromise=new Promise((t,n)=>{this.connectResolve=t,this.connectReject=n,this.connectTimeout=setTimeout(()=>{this.logger.warn("Connect timed out. Exceeded time set in configuration.connectionTimeout: "+this.configuration.connectionTimeout+"s."),e.close(1e3)},1e3*this.configuration.connectionTimeout)}),this.connectPromise}_disconnect(){switch(this.logger.log(`Disconnecting ${this.server}`),this.state){case mt.Connecting:if(this.disconnectPromise)throw new Error("Disconnect promise must not be defined.");try{this.transitionState(mt.Disconnecting)}catch(t){if(t instanceof me)return Promise.reject(t);throw t}break;case mt.Connected:if(this.disconnectPromise)throw new Error("Disconnect promise must not be defined.");try{this.transitionState(mt.Disconnecting)}catch(t){if(t instanceof me)return Promise.reject(t);throw t}break;case mt.Disconnecting:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(mt.Disconnecting));if(!this.disconnectPromise)throw new Error("Disconnect promise must be defined.");return this.disconnectPromise;case mt.Disconnected:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(mt.Disconnecting));if(this.disconnectPromise)throw new Error("Disconnect promise must not be defined.");return Promise.resolve();default:throw new Error("Unknown state")}if(!this._ws)throw new Error("WebSocket must be defined.");const e=this._ws;return this.disconnectPromise=new Promise((t,n)=>{this.disconnectResolve=t,this.disconnectReject=n;try{e.close(1e3)}catch(r){throw this.logger.error("WebSocket close failed."),this.logger.error(r.toString()),r}}),this.disconnectPromise}_send(e){if(!0===this.configuration.traceSip&&this.logger.log("Sending WebSocket message:\n\n"+e+"\n"),this._state!==mt.Connected)return Promise.reject(new Error("Not connected."));if(!this._ws)throw new Error("WebSocket undefined.");try{this._ws.send(e)}catch(t){return t instanceof Error?Promise.reject(t):Promise.reject(new Error("WebSocket send failed."))}return Promise.resolve()}onWebSocketClose(e,t){if(t!==this._ws)return;const n=`WebSocket closed ${this.server} (code: ${e.code})`,r=this.disconnectPromise?void 0:new Error(n);r&&this.logger.warn("WebSocket closed unexpectedly"),this.logger.log(n),this._ws=void 0,this.transitionState(mt.Disconnected,r)}onWebSocketError(e,t){t===this._ws&&this.logger.error("WebSocket error occurred.")}onWebSocketMessage(e,t){if(t!==this._ws)return;const n=e.data;let r;if(/^(\r\n)+$/.test(n))return this.clearKeepAliveTimeout(),void(!0===this.configuration.traceSip&&this.logger.log("Received WebSocket message with CRLF Keep Alive response"));if(n){if("string"!=typeof n){try{r=(new TextDecoder).decode(new Uint8Array(n))}catch(i){return this.logger.error(i.toString()),void this.logger.error("Received WebSocket binary message failed to be converted into string, message discarded")}!0===this.configuration.traceSip&&this.logger.log("Received WebSocket binary message:\n\n"+r+"\n")}else r=n,!0===this.configuration.traceSip&&this.logger.log("Received WebSocket text message:\n\n"+r+"\n");if(this.state===mt.Connected){if(this.onMessage)try{this.onMessage(r)}catch(o){throw this.logger.error(o.toString()),this.logger.error("Exception thrown by onMessage callback"),o}}else this.logger.warn("Received message while not connected, discarding...")}else this.logger.warn("Received empty message, discarding...")}onWebSocketOpen(e,t){t===this._ws&&this._state===mt.Connecting&&(this.logger.log(`WebSocket opened ${this.server}`),this.transitionState(mt.Connected))}transitionLoopDetectedError(e){let t="A state transition loop has been detected.";return t+=` An attempt to transition from ${this._state} to ${e} before the prior transition completed.`,t+=" Perhaps you are synchronously calling connect() or disconnect() from a callback or state change handler?",this.logger.error(t),new me("Loop detected.")}transitionState(e,t){const n=()=>{throw new Error(`Invalid state transition from ${this._state} to ${e}`)};if(this.transitioningState)throw this.transitionLoopDetectedError(e);switch(this.transitioningState=!0,this._state){case mt.Connecting:e!==mt.Connected&&e!==mt.Disconnecting&&e!==mt.Disconnected&&n();break;case mt.Connected:e!==mt.Disconnecting&&e!==mt.Disconnected&&n();break;case mt.Disconnecting:e!==mt.Connecting&&e!==mt.Disconnected&&n();break;case mt.Disconnected:e!==mt.Connecting&&n();break;default:throw new Error("Unknown state.")}const r=this._state;this._state=e;const i=this.connectResolve,o=this.connectReject;r===mt.Connecting&&(this.connectPromise=void 0,this.connectResolve=void 0,this.connectReject=void 0);const a=this.disconnectResolve,s=this.disconnectReject;if(r===mt.Disconnecting&&(this.disconnectPromise=void 0,this.disconnectResolve=void 0,this.disconnectReject=void 0),this.connectTimeout&&(clearTimeout(this.connectTimeout),this.connectTimeout=void 0),this.logger.log(`Transitioned from ${r} to ${this._state}`),this._stateEventEmitter.emit(this._state),e===mt.Connected&&(this.startSendingKeepAlives(),this.onConnect))try{this.onConnect()}catch(l){throw this.logger.error(l.toString()),this.logger.error("Exception thrown by onConnect callback"),l}if(r===mt.Connected&&(this.stopSendingKeepAlives(),this.onDisconnect))try{t?this.onDisconnect(t):this.onDisconnect()}catch(l){throw this.logger.error(l.toString()),this.logger.error("Exception thrown by onDisconnect callback"),l}if(r===mt.Connecting){if(!i)throw new Error("Connect resolve undefined.");if(!o)throw new Error("Connect reject undefined.");e===mt.Connected?i():o(t||new Error("Connect aborted."))}if(r===mt.Disconnecting){if(!a)throw new Error("Disconnect resolve undefined.");if(!s)throw new Error("Disconnect reject undefined.");e===mt.Disconnected?a():s(t||new Error("Disconnect aborted."))}this.transitioningState=!1}clearKeepAliveTimeout(){this.keepAliveDebounceTimeout&&clearTimeout(this.keepAliveDebounceTimeout),this.keepAliveDebounceTimeout=void 0}sendKeepAlive(){return this.keepAliveDebounceTimeout?Promise.resolve():(this.keepAliveDebounceTimeout=setTimeout(()=>{this.clearKeepAliveTimeout()},1e3*this.configuration.keepAliveDebounce),this.send("\r\n\r\n"))}startSendingKeepAlives(){this.configuration.keepAliveInterval&&!this.keepAliveInterval&&(this.keepAliveInterval=setInterval(()=>{this.sendKeepAlive(),this.startSendingKeepAlives()},(e=>{const t=.8*e;return 1e3*(Math.random()*(e-t)+t)})(this.configuration.keepAliveInterval)))}stopSendingKeepAlives(){this.keepAliveInterval&&clearInterval(this.keepAliveInterval),this.keepAliveDebounceTimeout&&clearTimeout(this.keepAliveDebounceTimeout),this.keepAliveInterval=void 0,this.keepAliveDebounceTimeout=void 0}}yn.defaultOptions={server:"",connectionTimeout:5,keepAliveInterval:0,keepAliveDebounce:10,traceSip:!0};class bn{constructor(e={}){if(this._publishers={},this._registerers={},this._sessions={},this._subscriptions={},this._state=yt.Stopped,this._stateEventEmitter=new we,this.delegate=e.delegate,this.options=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},bn.defaultOptions()),{sipjsId:Ae(5)}),{uri:new Te("sip","anonymous."+Ae(6),"anonymous.invalid")}),{viaHost:Ae(12)+".invalid"}),bn.stripUndefinedProperties(e)),this.options.hackIpInContact)if("boolean"==typeof this.options.hackIpInContact&&this.options.hackIpInContact){const e=1,t=254,n=Math.floor(Math.random()*(t-e+1)+e);this.options.viaHost="192.0.2."+n}else this.options.hackIpInContact&&(this.options.viaHost=this.options.hackIpInContact);switch(this.loggerFactory=new Dt,this.logger=this.loggerFactory.getLogger("sip.UserAgent"),this.loggerFactory.builtinEnabled=this.options.logBuiltinEnabled,this.loggerFactory.connector=this.options.logConnector,this.options.logLevel){case"error":this.loggerFactory.level=wt.error;break;case"warn":this.loggerFactory.level=wt.warn;break;case"log":this.loggerFactory.level=wt.log;break;case"debug":this.loggerFactory.level=wt.debug}if(this.options.logConfiguration&&(this.logger.log("Configuration:"),Object.keys(this.options).forEach(e=>{const t=this.options[e];switch(e){case"uri":case"sessionDescriptionHandlerFactory":this.logger.log("· "+e+": "+t);break;case"authorizationPassword":this.logger.log("· "+e+": NOT SHOWN");break;case"transportConstructor":this.logger.log("· "+e+": "+t.name);break;default:this.logger.log("· "+e+": "+JSON.stringify(t))}})),this.options.transportOptions){const t=this.options.transportOptions,n=t.maxReconnectionAttempts,r=t.reconnectionTimeout;if(void 0!==n){const e='The transport option "maxReconnectionAttempts" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(e)}if(void 0!==r){const e='The transport option "reconnectionTimeout" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(e)}void 0===e.reconnectionDelay&&void 0!==r&&(this.options.reconnectionDelay=r),void 0===e.reconnectionAttempts&&void 0!==n&&(this.options.reconnectionAttempts=n)}if(void 0!==e.reconnectionDelay){const e='The user agent option "reconnectionDelay" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(e)}if(void 0!==e.reconnectionAttempts){const e='The user agent option "reconnectionAttempts" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(e)}if(this._transport=new this.options.transportConstructor(this.getLogger("sip.Transport"),this.options.transportOptions),this.initTransportCallbacks(),this._contact=this.initContact(),this._instanceId=this.options.instanceId?this.options.instanceId:bn.newUUID(),-1===_e.parse(this._instanceId,"uuid"))throw new Error("Invalid instanceId.");this._userAgentCore=this.initCore()}static makeURI(e){return _e.URIParse(e)}static defaultOptions(){return{allowLegacyNotifications:!1,authorizationHa1:"",authorizationPassword:"",authorizationUsername:"",delegate:{},contactName:"",contactParams:{transport:"ws"},displayName:"",forceRport:!1,gracefulShutdown:!0,hackAllowUnregisteredOptionTags:!1,hackIpInContact:!1,hackViaTcp:!1,instanceId:"",instanceIdAlwaysAdded:!1,logBuiltinEnabled:!0,logConfiguration:!0,logConnector:()=>{},logLevel:"log",noAnswerTimeout:60,preloadedRouteSet:[],reconnectionAttempts:0,reconnectionDelay:4,sendInitialProvisionalResponse:!0,sessionDescriptionHandlerFactory:vn(),sessionDescriptionHandlerFactoryOptions:{},sipExtension100rel:ot.Unsupported,sipExtensionReplaces:ot.Unsupported,sipExtensionExtraSupported:[],sipjsId:"",transportConstructor:yn,transportOptions:{},uri:new Te("sip","anonymous","anonymous.invalid"),userAgentString:"SIP.js/0.21.1",viaHost:""}}static newUUID(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=Math.floor(16*Math.random());return("x"===e?t:t%4+8).toString(16)})}static stripUndefinedProperties(e){return Object.keys(e).reduce((t,n)=>(void 0!==e[n]&&(t[n]=e[n]),t),{})}get configuration(){return this.options}get contact(){return this._contact}get instanceId(){return this._instanceId}get state(){return this._state}get stateChange(){return this._stateEventEmitter}get transport(){return this._transport}get userAgentCore(){return this._userAgentCore}getLogger(e,t){return this.loggerFactory.getLogger(e,t)}getLoggerFactory(){return this.loggerFactory}isConnected(){return this.transport.isConnected()}reconnect(){return this.state===yt.Stopped?Promise.reject(new Error("User agent stopped.")):Promise.resolve().then(()=>this.transport.connect())}start(){return this.state===yt.Started?(this.logger.warn("User agent already started"),Promise.resolve()):(this.logger.log(`Starting ${this.configuration.uri}`),this.transitionState(yt.Started),this.transport.connect())}async stop(){if(this.state===yt.Stopped)return this.logger.warn("User agent already stopped"),Promise.resolve();if(this.logger.log(`Stopping ${this.configuration.uri}`),!this.options.gracefulShutdown)return this.logger.log("Dispose of transport"),this.transport.dispose().catch(e=>{throw this.logger.error(e.message),e}),this.logger.log("Dispose of core"),this.userAgentCore.dispose(),this._publishers={},this._registerers={},this._sessions={},this._subscriptions={},this.transitionState(yt.Stopped),Promise.resolve();const e=Object.assign({},this._publishers),t=Object.assign({},this._registerers),n=Object.assign({},this._sessions),r=Object.assign({},this._subscriptions),i=this.transport,o=this.userAgentCore;this.logger.log("Dispose of registerers");for(const a in t)t[a]&&await t[a].dispose().catch(e=>{throw this.logger.error(e.message),delete this._registerers[a],e});this.logger.log("Dispose of sessions");for(const a in n)n[a]&&await n[a].dispose().catch(e=>{throw this.logger.error(e.message),delete this._sessions[a],e});this.logger.log("Dispose of subscriptions");for(const a in r)r[a]&&await r[a].dispose().catch(e=>{throw this.logger.error(e.message),delete this._subscriptions[a],e});this.logger.log("Dispose of publishers");for(const a in e)e[a]&&await e[a].dispose().catch(e=>{throw this.logger.error(e.message),delete this._publishers[a],e});this.logger.log("Dispose of transport"),await i.dispose().catch(e=>{throw this.logger.error(e.message),e}),this.logger.log("Dispose of core"),o.dispose(),this.transitionState(yt.Stopped)}_makeInviter(e,t){return new ut(this,e,t)}attemptReconnection(e=1){const t=this.options.reconnectionAttempts,n=this.options.reconnectionDelay;e>t?this.logger.log("Maximum reconnection attempts reached"):(this.logger.log(`Reconnection attempt ${e} of ${t} - trying`),setTimeout(()=>{this.reconnect().then(()=>{this.logger.log(`Reconnection attempt ${e} of ${t} - succeeded`)}).catch(n=>{this.logger.error(n.message),this.logger.log(`Reconnection attempt ${e} of ${t} - failed`),this.attemptReconnection(++e)})},1===e?0:1e3*n))}initContact(){const e=""!==this.options.contactName?this.options.contactName:Ae(8),t=this.options.contactParams;return{pubGruu:void 0,tempGruu:void 0,uri:new Te("sip",e,this.options.viaHost,void 0,t),toString:(e={})=>{const n=e.anonymous||!1,r=e.outbound||!1,i=e.register||!1;let o="<";return o+=n?this.contact.tempGruu||`sip:anonymous@anonymous.invalid;transport=${t.transport?t.transport:"ws"}`:i?this.contact.uri:this.contact.pubGruu||this.contact.uri,r&&(o+=";ob"),o+=">",this.options.instanceIdAlwaysAdded&&(o+=';+sip.instance=""'),o}}}initCore(){let e=[];e.push("outbound"),this.options.sipExtension100rel===ot.Supported&&e.push("100rel"),this.options.sipExtensionReplaces===ot.Supported&&e.push("replaces"),this.options.sipExtensionExtraSupported&&e.push(...this.options.sipExtensionExtraSupported),this.options.hackAllowUnregisteredOptionTags||(e=e.filter(e=>lt[e])),e=Array.from(new Set(e));const t=e.slice();(this.contact.pubGruu||this.contact.tempGruu)&&t.push("gruu");const n={aor:this.options.uri,contact:this.contact,displayName:this.options.displayName,loggerFactory:this.loggerFactory,hackViaTcp:this.options.hackViaTcp,routeSet:this.options.preloadedRouteSet,supportedOptionTags:e,supportedOptionTagsResponse:t,sipjsId:this.options.sipjsId,userAgentHeaderFieldValue:this.options.userAgentString,viaForceRport:this.options.forceRport,viaHost:this.options.viaHost,authenticationFactory:()=>{const e=this.options.authorizationUsername?this.options.authorizationUsername:this.options.uri.user,t=this.options.authorizationPassword?this.options.authorizationPassword:void 0,n=this.options.authorizationHa1?this.options.authorizationHa1:void 0;return new Pt(this.getLoggerFactory(),n,e,t)},transportAccessor:()=>this.transport};return new gn(n,{onInvite:e=>{var t;const n=new ct(this,e);if(e.delegate={onCancel:e=>{n._onCancel(e)},onTransportError:e=>{this.logger.error("A transport error has occurred while handling an incoming INVITE request.")}},e.trying(),this.options.sipExtensionReplaces!==ot.Unsupported){const t=e.message.parseHeader("replaces");if(t){const e=t.call_id;if("string"!=typeof e)throw new Error("Type of call id is not string");const r=t.replaces_to_tag;if("string"!=typeof r)throw new Error("Type of to tag is not string");const i=t.replaces_from_tag;if("string"!=typeof i)throw new Error("type of from tag is not string");const o=e+r+i,a=this.userAgentCore.dialogs.get(o);if(!a)return void n.reject({statusCode:481});if(!a.early&&!0===t.early_only)return void n.reject({statusCode:486});const s=this._sessions[e+i]||this._sessions[e+r]||void 0;if(!s)throw new Error("Session does not exist.");n._replacee=s}}if(null===(t=this.delegate)||void 0===t?void 0:t.onInvite)return n.autoSendAnInitialProvisionalResponse?void n.progress().then(()=>{var e;if(void 0===(null===(e=this.delegate)||void 0===e?void 0:e.onInvite))throw new Error("onInvite undefined.");this.delegate.onInvite(n)}):void this.delegate.onInvite(n);n.reject({statusCode:486})},onMessage:e=>{if(this.delegate&&this.delegate.onMessage){const t=new tt(e);this.delegate.onMessage(t)}else e.accept()},onNotify:e=>{if(this.delegate&&this.delegate.onNotify){const t=new nt(e);this.delegate.onNotify(t)}else this.options.allowLegacyNotifications?e.accept():e.reject({statusCode:481})},onRefer:e=>{this.logger.warn("Received an out of dialog REFER request"),this.delegate&&this.delegate.onReferRequest?this.delegate.onReferRequest(e):e.reject({statusCode:405})},onRegister:e=>{this.logger.warn("Received an out of dialog REGISTER request"),this.delegate&&this.delegate.onRegisterRequest?this.delegate.onRegisterRequest(e):e.reject({statusCode:405})},onSubscribe:e=>{this.logger.warn("Received an out of dialog SUBSCRIBE request"),this.delegate&&this.delegate.onSubscribeRequest?this.delegate.onSubscribeRequest(e):e.reject({statusCode:405})}})}initTransportCallbacks(){this.transport.onConnect=()=>this.onTransportConnect(),this.transport.onDisconnect=e=>this.onTransportDisconnect(e),this.transport.onMessage=e=>this.onTransportMessage(e)}onTransportConnect(){this.state!==yt.Stopped&&this.delegate&&this.delegate.onConnect&&this.delegate.onConnect()}onTransportDisconnect(e){this.state!==yt.Stopped&&(this.delegate&&this.delegate.onDisconnect&&this.delegate.onDisconnect(e),e&&this.options.reconnectionAttempts>0&&this.attemptReconnection())}onTransportMessage(e){const t=kt.parseMessage(e,this.getLogger("sip.Parser"));if(!t)return void this.logger.warn("Failed to parse incoming message. Dropping.");if(this.state===yt.Stopped&&t instanceof Le)return void this.logger.warn(`Received ${t.method} request while stopped. Dropping.`);const n=()=>{const e=["from","to","call_id","cseq","via"];for(const n of e)if(!t.hasHeader(n))return this.logger.warn(`Missing mandatory header field : ${n}.`),!1;return!0};if(t instanceof Le){if(!n())return void this.logger.warn("Request missing mandatory header field. Dropping.");if(!t.toTag&&t.callId.substr(0,5)===this.options.sipjsId)return void this.userAgentCore.replyStateless(t,{statusCode:482});const e=Oe(t.body),r=t.getHeader("content-length");if(r&&e1)return void this.logger.warn("More than one Via header field present in the response. Dropping.");if(t.via.host!==this.options.viaHost||void 0!==t.via.port)return void this.logger.warn("Via sent-by in the response does not match UA Via host value. Dropping.");const e=Oe(t.body),r=t.getHeader("content-length");if(r&&e{throw new Error(`Invalid state transition from ${this._state} to ${e}`)};switch(this._state){case yt.Started:e!==yt.Stopped&&n();break;case yt.Stopped:e!==yt.Started&&n();break;default:throw new Error("Unknown state.")}this.logger.log(`Transitioned from ${this._state} to ${e}`),this._state=e,this._stateEventEmitter.emit(this._state)}}class wn{constructor(e,t={}){this.managedSessions=[],this.attemptingReconnection=!1,this.optionsPingFailure=!1,this.optionsPingRunning=!1,this.shouldBeConnected=!1,this.shouldBeRegistered=!1,this.delegate=t.delegate,this.options=Object.assign({aor:"",autoStop:!0,delegate:{},iceStopWaitingOnServerReflexive:!1,managedSessionFactory:(e,t)=>({session:t,held:!1,muted:!1}),maxSimultaneousSessions:2,media:{},optionsPingInterval:-1,optionsPingRequestURI:"",reconnectionAttempts:3,reconnectionDelay:4,registrationRetry:!1,registrationRetryInterval:3,registerGuard:null,registererOptions:{},registererRegisterOptions:{},sendDTMFUsingSessionDescriptionHandler:!1,userAgentOptions:{}},wn.stripUndefinedProperties(t));const n=Object.assign({},t.userAgentOptions);if(n.transportConstructor||(n.transportConstructor=yn),n.transportOptions||(n.transportOptions={server:e}),!n.uri&&t.aor){const e=bn.makeURI(t.aor);if(!e)throw new Error(`Failed to create valid URI from ${t.aor}`);n.uri=e}if(this.userAgent=new bn(n),this.userAgent.delegate={onConnect:()=>{this.logger.log("Connected"),this.delegate&&this.delegate.onServerConnect&&this.delegate.onServerConnect(),this.shouldBeRegistered&&this.register(),this.options.optionsPingInterval>0&&this.optionsPingStart()},onDisconnect:async e=>{this.logger.log("Disconnected");let t=!1;this.options.optionsPingInterval>0&&(t=this.optionsPingFailure,this.optionsPingFailure=!1,this.optionsPingStop()),this.delegate&&this.delegate.onServerDisconnect&&this.delegate.onServerDisconnect(e),(e||t)&&(this.registerer&&(this.logger.log("Disposing of registerer..."),this.registerer.dispose().catch(e=>{this.logger.debug("Error occurred disposing of registerer after connection with server was lost."),this.logger.debug(e.toString())}),this.registerer=void 0),this.managedSessions.slice().map(e=>e.session).forEach(async e=>{this.logger.log("Disposing of session..."),e.dispose().catch(e=>{this.logger.debug("Error occurred disposing of a session after connection with server was lost."),this.logger.debug(e.toString())})}),this.shouldBeConnected&&this.attemptReconnection())},onInvite:e=>{this.logger.log(`[${e.id}] Received INVITE`);const t=this.options.maxSimultaneousSessions;if(0!==t&&this.managedSessions.length>t)return this.logger.warn(`[${e.id}] Session already in progress, rejecting INVITE...`),void e.reject().then(()=>{this.logger.log(`[${e.id}] Rejected INVITE`)}).catch(t=>{this.logger.error(`[${e.id}] Failed to reject INVITE`),this.logger.error(t.toString())});const n={sessionDescriptionHandlerOptions:{constraints:this.constraints}};this.initSession(e,n),this.delegate&&this.delegate.onCallReceived?this.delegate.onCallReceived(e):(this.logger.warn(`[${e.id}] No handler available, rejecting INVITE...`),e.reject().then(()=>{this.logger.log(`[${e.id}] Rejected INVITE`)}).catch(t=>{this.logger.error(`[${e.id}] Failed to reject INVITE`),this.logger.error(t.toString())}))},onMessage:e=>{e.accept().then(()=>{this.delegate&&this.delegate.onMessageReceived&&this.delegate.onMessageReceived(e)})},onNotify:e=>{e.accept().then(()=>{this.delegate&&this.delegate.onNotificationReceived&&this.delegate.onNotificationReceived(e)})}},this.registererOptions=Object.assign({},t.registererOptions),this.registererRegisterOptions=Object.assign({},t.registererRegisterOptions),this.options.registrationRetry){this.registererRegisterOptions.requestDelegate=this.registererRegisterOptions.requestDelegate||{};const e=this.registererRegisterOptions.requestDelegate.onReject;this.registererRegisterOptions.requestDelegate.onReject=t=>{e&&e(t),this.attemptRegistration()}}this.logger=this.userAgent.getLogger("sip.SessionManager"),window.addEventListener("online",()=>{this.logger.log("Online"),this.shouldBeConnected&&this.connect()}),this.options.autoStop&&window.addEventListener("beforeunload",async()=>{this.shouldBeConnected=!1,this.shouldBeRegistered=!1,this.userAgent.state!==yt.Stopped&&await this.userAgent.stop()})}static stripUndefinedProperties(e){return Object.keys(e).reduce((t,n)=>(void 0!==e[n]&&(t[n]=e[n]),t),{})}getLocalMediaStream(e){const t=e.sessionDescriptionHandler;if(t){if(!(t instanceof mn))throw new Error("Session description handler not instance of web SessionDescriptionHandler");return t.localMediaStream}}getRemoteMediaStream(e){const t=e.sessionDescriptionHandler;if(t){if(!(t instanceof mn))throw new Error("Session description handler not instance of web SessionDescriptionHandler");return t.remoteMediaStream}}getLocalAudioTrack(e){var t;return null===(t=this.getLocalMediaStream(e))||void 0===t?void 0:t.getTracks().find(e=>"audio"===e.kind)}getLocalVideoTrack(e){var t;return null===(t=this.getLocalMediaStream(e))||void 0===t?void 0:t.getTracks().find(e=>"video"===e.kind)}getRemoteAudioTrack(e){var t;return null===(t=this.getRemoteMediaStream(e))||void 0===t?void 0:t.getTracks().find(e=>"audio"===e.kind)}getRemoteVideoTrack(e){var t;return null===(t=this.getRemoteMediaStream(e))||void 0===t?void 0:t.getTracks().find(e=>"video"===e.kind)}async connect(){return this.logger.log("Connecting UserAgent..."),this.shouldBeConnected=!0,this.userAgent.state!==yt.Started?this.userAgent.start():this.userAgent.reconnect()}async disconnect(){return this.logger.log("Disconnecting UserAgent..."),this.userAgent.state===yt.Stopped?Promise.resolve():(this.shouldBeConnected=!1,this.shouldBeRegistered=!1,this.registerer=void 0,this.userAgent.stop())}isConnected(){return this.userAgent.isConnected()}async register(e){return this.logger.log("Registering UserAgent..."),this.shouldBeRegistered=!0,void 0!==e&&(this.registererRegisterOptions=Object.assign({},e)),this.registerer||(this.registerer=new Et(this.userAgent,this.registererOptions),this.registerer.stateChange.addListener(e=>{switch(e){case ht.Initial:break;case ht.Registered:this.delegate&&this.delegate.onRegistered&&this.delegate.onRegistered();break;case ht.Unregistered:this.delegate&&this.delegate.onUnregistered&&this.delegate.onUnregistered(),this.shouldBeRegistered&&this.attemptRegistration();break;case ht.Terminated:break;default:throw new Error("Unknown registerer state.")}})),this.attemptRegistration(!0)}async unregister(e){return this.logger.log("Unregistering UserAgent..."),this.shouldBeRegistered=!1,this.registerer?this.registerer.unregister(e).then(()=>{}):(this.logger.warn("No registerer to unregister."),Promise.resolve())}async call(e,t,n){this.logger.log("Beginning Session...");const r=this.options.maxSimultaneousSessions;if(0!==r&&this.managedSessions.length>r)return Promise.reject(new Error("Maximum number of sessions already exists."));const i=bn.makeURI(e);if(!i)return Promise.reject(new Error(`Failed to create a valid URI from "${e}"`));if(t||(t={}),t.sessionDescriptionHandlerOptions||(t.sessionDescriptionHandlerOptions={}),t.sessionDescriptionHandlerOptions.constraints||(t.sessionDescriptionHandlerOptions.constraints=this.constraints),t.earlyMedia){(n=n||{}).requestDelegate=n.requestDelegate||{};const e=n.requestDelegate.onProgress;n.requestDelegate.onProgress=t=>{183===t.message.statusCode&&this.setupRemoteMedia(o),e&&e(t)}}this.options.iceStopWaitingOnServerReflexive&&(t.delegate=t.delegate||{},t.delegate.onSessionDescriptionHandler=e=>{if(!(e instanceof mn))throw new Error("Session description handler not instance of SessionDescriptionHandler");e.peerConnectionDelegate={onicecandidate:t=>{var n;if("srflx"===(null===(n=t.candidate)||void 0===n?void 0:n.type)){this.logger.log(`[${o.id}] Found srflx ICE candidate, stop waiting...`);e.iceGatheringComplete()}}}});const o=new ut(this.userAgent,i,t);return this.sendInvite(o,t,n).then(()=>o)}async hangup(e){return this.logger.log(`[${e.id}] Hangup...`),this.sessionExists(e)?this.terminate(e):Promise.reject(new Error("Session does not exist."))}async answer(e,t){return this.logger.log(`[${e.id}] Accepting Invitation...`),this.sessionExists(e)?e instanceof ct?(t||(t={}),t.sessionDescriptionHandlerOptions||(t.sessionDescriptionHandlerOptions={}),t.sessionDescriptionHandlerOptions.constraints||(t.sessionDescriptionHandlerOptions.constraints=this.constraints),e.accept(t)):Promise.reject(new Error("Session not instance of Invitation.")):Promise.reject(new Error("Session does not exist."))}async decline(e){return this.logger.log(`[${e.id}] Rejecting Invitation...`),this.sessionExists(e)?e instanceof ct?e.reject():Promise.reject(new Error("Session not instance of Invitation.")):Promise.reject(new Error("Session does not exist."))}async hold(e){return this.logger.log(`[${e.id}] Holding session...`),this.setHold(e,!0)}async unhold(e){return this.logger.log(`[${e.id}] Unholding session...`),this.setHold(e,!1)}isHeld(e){const t=this.sessionManaged(e);return!!t&&t.held}mute(e){this.logger.log(`[${e.id}] Disabling media tracks...`),this.setMute(e,!0)}unmute(e){this.logger.log(`[${e.id}] Enabling media tracks...`),this.setMute(e,!1)}isMuted(e){const t=this.sessionManaged(e);return!!t&&t.muted}async sendDTMF(e,t){if(this.logger.log(`[${e.id}] Sending DTMF...`),!/^[0-9A-D#*,]$/.exec(t))return Promise.reject(new Error("Invalid DTMF tone."));if(!this.sessionExists(e))return Promise.reject(new Error("Session does not exist."));if(this.logger.log(`[${e.id}] Sending DTMF tone: ${t}`),this.options.sendDTMFUsingSessionDescriptionHandler)return e.sessionDescriptionHandler?e.sessionDescriptionHandler.sendDtmf(t)?Promise.resolve():Promise.reject(new Error("Failed to send DTMF")):Promise.reject(new Error("Session desciption handler undefined."));{const n={body:{contentDisposition:"render",contentType:"application/dtmf-relay",content:"Signal="+t+"\r\nDuration="+2e3}};return e.info({requestOptions:n}).then(()=>{})}}async transfer(e,t,n){if(this.logger.log(`[${e.id}] Referring session...`),t instanceof st)return e.refer(t,n).then(()=>{});const r=bn.makeURI(t);return r?e.refer(r,n).then(()=>{}):Promise.reject(new Error(`Failed to create a valid URI from "${t}"`))}async message(e,t){this.logger.log("Sending message...");const n=bn.makeURI(e);return n?new dt(this.userAgent,n,t).message():Promise.reject(new Error(`Failed to create a valid URI from "${e}"`))}get constraints(){let e={audio:!0,video:!1};return this.options.media.constraints&&(e=Object.assign({},this.options.media.constraints)),e}attemptReconnection(e=1){const t=this.options.reconnectionAttempts,n=this.options.reconnectionDelay;this.shouldBeConnected?(this.attemptingReconnection&&this.logger.log("Reconnection attempt already in progress"),e>t?this.logger.log("Reconnection maximum attempts reached"):(1===e?this.logger.log(`Reconnection attempt ${e} of ${t} - trying`):this.logger.log(`Reconnection attempt ${e} of ${t} - trying in ${n} seconds`),this.attemptingReconnection=!0,setTimeout(()=>{if(!this.shouldBeConnected)return this.logger.log(`Reconnection attempt ${e} of ${t} - aborted`),void(this.attemptingReconnection=!1);this.userAgent.reconnect().then(()=>{this.logger.log(`Reconnection attempt ${e} of ${t} - succeeded`),this.attemptingReconnection=!1}).catch(n=>{this.logger.log(`Reconnection attempt ${e} of ${t} - failed`),this.logger.error(n.message),this.attemptingReconnection=!1,this.attemptReconnection(++e)})},1===e?0:1e3*n))):this.logger.log("Should not be connected currently")}attemptRegistration(e=!1){if(this.logger.log("Registration attempt "+(e?"without delay":"")),!this.shouldBeRegistered)return this.logger.log("Should not be registered currently"),Promise.resolve();if(void 0!==this.registrationAttemptTimeout)return this.logger.log("Registration attempt already in progress"),Promise.resolve();const t=()=>this.registerer?this.isConnected()?this.userAgent.state===yt.Stopped?(this.logger.log("User agent stopped"),Promise.resolve()):this.options.registerGuard?this.options.registerGuard().catch(e=>{throw this.logger.log("Register guard rejected will making registration attempt"),e}).then(e=>e||!this.registerer?Promise.resolve():this.registerer.register(this.registererRegisterOptions).then(()=>{})):this.registerer.register(this.registererRegisterOptions).then(()=>{}):(this.logger.log("User agent not connected"),Promise.resolve()):(this.logger.log("Registerer undefined"),Promise.resolve());return new Promise((n,r)=>{this.registrationAttemptTimeout=setTimeout(()=>{t().then(()=>{this.registrationAttemptTimeout=void 0,n()}).catch(e=>{this.registrationAttemptTimeout=void 0,e instanceof fe?n():r(e)})},e?0:(e=>{const t=2*e;return 1e3*(Math.random()*(t-e)+e)})(this.options.registrationRetryInterval))})}cleanupMedia(e){const t=this.sessionManaged(e);if(!t)throw new Error("Managed session does not exist.");t.mediaLocal&&t.mediaLocal.video&&(t.mediaLocal.video.srcObject=null,t.mediaLocal.video.pause()),t.mediaRemote&&(t.mediaRemote.audio&&(t.mediaRemote.audio.srcObject=null,t.mediaRemote.audio.pause()),t.mediaRemote.video&&(t.mediaRemote.video.srcObject=null,t.mediaRemote.video.pause()))}enableReceiverTracks(e,t){if(!this.sessionExists(e))throw new Error("Session does not exist.");const n=e.sessionDescriptionHandler;if(!(n instanceof mn))throw new Error("Session's session description handler not instance of SessionDescriptionHandler.");n.enableReceiverTracks(t)}enableSenderTracks(e,t){if(!this.sessionExists(e))throw new Error("Session does not exist.");const n=e.sessionDescriptionHandler;if(!(n instanceof mn))throw new Error("Session's session description handler not instance of SessionDescriptionHandler.");n.enableSenderTracks(t)}initSession(e,t){this.sessionAdd(e),this.delegate&&this.delegate.onCallCreated&&this.delegate.onCallCreated(e),e.stateChange.addListener(t=>{switch(this.logger.log(`[${e.id}] Session state changed to ${t}`),t){case it.Initial:case it.Establishing:break;case it.Established:this.setupLocalMedia(e),this.setupRemoteMedia(e),this.delegate&&this.delegate.onCallAnswered&&this.delegate.onCallAnswered(e);break;case it.Terminating:case it.Terminated:this.sessionExists(e)&&(this.cleanupMedia(e),this.sessionRemove(e),this.delegate&&this.delegate.onCallHangup&&this.delegate.onCallHangup(e));break;default:throw new Error("Unknown session state.")}}),e.delegate=e.delegate||{},e.delegate.onInfo=t=>{var n;if(void 0===(null===(n=this.delegate)||void 0===n?void 0:n.onCallDTMFReceived))return void t.reject();const r=t.request.getHeader("content-type");if(!r||!/^application\/dtmf-relay/i.exec(r))return void t.reject();const i=t.request.body.split("\r\n",2);if(2!==i.length)return void t.reject();let o;const a=/^(Signal\s*?=\s*?)([0-9A-D#*]{1})(\s)?.*/;if(void 0!==i[0]&&a.test(i[0])&&(o=i[0].replace(a,"$2")),!o)return void t.reject();let s;const l=/^(Duration\s?=\s?)([0-9]{1,4})(\s)?.*/;void 0!==i[1]&&l.test(i[1])&&(s=parseInt(i[1].replace(l,"$2"),10)),s?t.accept().then(()=>{if(this.delegate&&this.delegate.onCallDTMFReceived){if(!o||!s)throw new Error("Tone or duration undefined.");this.delegate.onCallDTMFReceived(e,o,s)}}).catch(e=>{this.logger.error(e.message)}):t.reject()},e.delegate.onRefer=e=>{e.accept().then(()=>this.sendInvite(e.makeInviter(t),t)).catch(e=>{this.logger.error(e.message)})}}optionsPingRun(e,t,n){if(this.options.optionsPingInterval<1)throw new Error("Invalid options ping interval.");this.optionsPingRunning||(this.optionsPingRunning=!0,this.optionsPingTimeout=setTimeout(()=>{this.optionsPingTimeout=void 0;const r=()=>{this.optionsPingFailure=!1,this.optionsPingRunning&&(this.optionsPingRunning=!1,this.optionsPingRun(e,t,n))},i=()=>{this.logger.error("OPTIONS ping failed"),this.optionsPingFailure=!0,this.optionsPingRunning=!1,this.userAgent.transport.disconnect().catch(e=>this.logger.error(e))},o=this.userAgent.userAgentCore,a=o.makeOutgoingRequestMessage("OPTIONS",e,t,n,{});this.optionsPingRequest=o.request(a,{onAccept:()=>{this.optionsPingRequest=void 0,r()},onReject:e=>{this.optionsPingRequest=void 0,408===e.message.statusCode||503===e.message.statusCode?i():r()}})},1e3*this.options.optionsPingInterval))}optionsPingStart(){let e,t,n;if(this.logger.log("OPTIONS pings started"),this.options.optionsPingRequestURI){if(e=bn.makeURI(this.options.optionsPingRequestURI),!e)throw new Error("Failed to create Request URI.");t=this.userAgent.contact.uri.clone(),n=this.userAgent.contact.uri.clone()}else{if(!this.options.aor)return void this.logger.error("You have enabled sending OPTIONS pings and as such you must provide either a) an AOR to register, or b) an RURI to use for the target of the OPTIONS ping requests. ");{const r=bn.makeURI(this.options.aor);if(!r)throw new Error("Failed to create URI.");e=r.clone(),e.user=void 0,t=r.clone(),n=r.clone()}}this.optionsPingRun(e,t,n)}optionsPingStop(){this.logger.log("OPTIONS pings stopped"),this.optionsPingRunning=!1,this.optionsPingFailure=!1,this.optionsPingRequest&&(this.optionsPingRequest.dispose(),this.optionsPingRequest=void 0),this.optionsPingTimeout&&(clearTimeout(this.optionsPingTimeout),this.optionsPingTimeout=void 0)}async sendInvite(e,t,n){return this.initSession(e,t),e.invite(n).then(()=>{this.logger.log(`[${e.id}] Sent INVITE`)})}sessionAdd(e){const t=this.options.managedSessionFactory(this,e);this.managedSessions.push(t)}sessionExists(e){return void 0!==this.sessionManaged(e)}sessionManaged(e){return this.managedSessions.find(t=>t.session.id===e.id)}sessionRemove(e){this.managedSessions=this.managedSessions.filter(t=>t.session.id!==e.id)}async setHold(e,t){if(!this.sessionExists(e))return Promise.reject(new Error("Session does not exist."));if(this.isHeld(e)===t)return Promise.resolve();if(!(e.sessionDescriptionHandler instanceof mn))throw new Error("Session's session description handler not instance of SessionDescriptionHandler.");const n={requestDelegate:{onAccept:()=>{const n=this.sessionManaged(e);void 0!==n&&(n.held=t,this.enableReceiverTracks(e,!n.held),this.enableSenderTracks(e,!n.held&&!n.muted),this.delegate&&this.delegate.onCallHold&&this.delegate.onCallHold(e,n.held))},onReject:()=>{this.logger.warn(`[${e.id}] Re-invite request was rejected`);const n=this.sessionManaged(e);void 0!==n&&(n.held=!t,this.enableReceiverTracks(e,!n.held),this.enableSenderTracks(e,!n.held&&!n.muted),this.delegate&&this.delegate.onCallHold&&this.delegate.onCallHold(e,n.held))}}},r=e.sessionDescriptionHandlerOptionsReInvite;r.hold=t,e.sessionDescriptionHandlerOptionsReInvite=r;const i=this.sessionManaged(e);if(!i)throw new Error("Managed session is undefiend.");return i.held=t,e.invite(n).then(()=>{const t=this.sessionManaged(e);void 0!==t&&(this.enableReceiverTracks(e,!t.held),this.enableSenderTracks(e,!t.held&&!t.muted))}).catch(n=>{throw i.held=!t,n instanceof fe&&this.logger.error(`[${e.id}] A hold request is already in progress.`),n})}setMute(e,t){if(!this.sessionExists(e))return void this.logger.warn(`[${e.id}] A session is required to enabled/disable media tracks`);if(e.state!==it.Established)return void this.logger.warn(`[${e.id}] An established session is required to enable/disable media tracks`);const n=this.sessionManaged(e);void 0!==n&&(n.muted=t,this.enableSenderTracks(e,!n.held&&!n.muted))}setupLocalMedia(e){const t=this.sessionManaged(e);if(!t)throw new Error("Managed session does not exist.");const n="function"==typeof this.options.media.local?this.options.media.local(e):this.options.media.local;t.mediaLocal=n;const r=null==n?void 0:n.video;if(r){const t=this.getLocalMediaStream(e);if(!t)throw new Error("Local media stream undefiend.");r.srcObject=t,r.volume=0,r.play().catch(t=>{this.logger.error(`[${e.id}] Failed to play local media`),this.logger.error(t.message)})}}setupRemoteMedia(e){const t=this.sessionManaged(e);if(!t)throw new Error("Managed session does not exist.");const n="function"==typeof this.options.media.remote?this.options.media.remote(e):this.options.media.remote;t.mediaRemote=n;const r=(null==n?void 0:n.video)||(null==n?void 0:n.audio);if(r){const t=this.getRemoteMediaStream(e);if(!t)throw new Error("Remote media stream undefiend.");r.autoplay=!0,r.srcObject=t,r.play().catch(t=>{this.logger.error(`[${e.id}] Failed to play remote media`),this.logger.error(t.message)}),t.onaddtrack=()=>{this.logger.log("Remote media onaddtrack"),r.load(),r.play().catch(t=>{this.logger.error(`[${e.id}] Failed to play remote media`),this.logger.error(t.message)})}}}async terminate(e){switch(this.logger.log(`[${e.id}] Terminating...`),e.state){case it.Initial:if(e instanceof ut)return e.cancel().then(()=>{this.logger.log(`[${e.id}] Inviter never sent INVITE (canceled)`)});if(e instanceof ct)return e.reject().then(()=>{this.logger.log(`[${e.id}] Invitation rejected (sent 480)`)});throw new Error("Unknown session type.");case it.Establishing:if(e instanceof ut)return e.cancel().then(()=>{this.logger.log(`[${e.id}] Inviter canceled (sent CANCEL)`)});if(e instanceof ct)return e.reject().then(()=>{this.logger.log(`[${e.id}] Invitation rejected (sent 480)`)});throw new Error("Unknown session type.");case it.Established:return e.bye().then(()=>{this.logger.log(`[${e.id}] Session ended (sent BYE)`)});case it.Terminating:case it.Terminated:break;default:throw new Error("Unknown state")}return this.logger.log(`[${e.id}] Terminating in state ${e.state}, no action taken`),Promise.resolve()}}class xn{constructor(e,t={}){this.session=void 0,this.delegate=t.delegate,this.options=Object.assign({},t);const n={aor:this.options.aor,delegate:{onCallAnswered:()=>{var e,t;return null===(t=null===(e=this.delegate)||void 0===e?void 0:e.onCallAnswered)||void 0===t?void 0:t.call(e)},onCallCreated:e=>{var t,n;this.session=e,null===(n=null===(t=this.delegate)||void 0===t?void 0:t.onCallCreated)||void 0===n||n.call(t)},onCallReceived:()=>{var e,t;return null===(t=null===(e=this.delegate)||void 0===e?void 0:e.onCallReceived)||void 0===t?void 0:t.call(e)},onCallHangup:()=>{var e,t;this.session=void 0,(null===(e=this.delegate)||void 0===e?void 0:e.onCallHangup)&&(null===(t=this.delegate)||void 0===t||t.onCallHangup())},onCallHold:(e,t)=>{var n,r;return null===(r=null===(n=this.delegate)||void 0===n?void 0:n.onCallHold)||void 0===r?void 0:r.call(n,t)},onCallDTMFReceived:(e,t,n)=>{var r,i;return null===(i=null===(r=this.delegate)||void 0===r?void 0:r.onCallDTMFReceived)||void 0===i?void 0:i.call(r,t,n)},onMessageReceived:e=>{var t,n;return null===(n=null===(t=this.delegate)||void 0===t?void 0:t.onMessageReceived)||void 0===n?void 0:n.call(t,e.request.body)},onRegistered:()=>{var e,t;return null===(t=null===(e=this.delegate)||void 0===e?void 0:e.onRegistered)||void 0===t?void 0:t.call(e)},onUnregistered:()=>{var e,t;return null===(t=null===(e=this.delegate)||void 0===e?void 0:e.onUnregistered)||void 0===t?void 0:t.call(e)},onServerConnect:()=>{var e,t;return null===(t=null===(e=this.delegate)||void 0===e?void 0:e.onServerConnect)||void 0===t?void 0:t.call(e)},onServerDisconnect:()=>{var e,t;return null===(t=null===(e=this.delegate)||void 0===e?void 0:e.onServerDisconnect)||void 0===t?void 0:t.call(e)}},maxSimultaneousSessions:1,media:this.options.media,reconnectionAttempts:this.options.reconnectionAttempts,reconnectionDelay:this.options.reconnectionDelay,registererOptions:this.options.registererOptions,sendDTMFUsingSessionDescriptionHandler:this.options.sendDTMFUsingSessionDescriptionHandler,userAgentOptions:this.options.userAgentOptions};this.sessionManager=new wn(e,n),this.logger=this.sessionManager.userAgent.getLogger("sip.SimpleUser")}get id(){return this.options.userAgentOptions&&this.options.userAgentOptions.displayName||"Anonymous"}get localMediaStream(){return this.session&&this.sessionManager.getLocalMediaStream(this.session)}get remoteMediaStream(){return this.session&&this.sessionManager.getRemoteMediaStream(this.session)}get localAudioTrack(){return this.session&&this.sessionManager.getLocalAudioTrack(this.session)}get localVideoTrack(){return this.session&&this.sessionManager.getLocalVideoTrack(this.session)}get remoteAudioTrack(){return this.session&&this.sessionManager.getRemoteAudioTrack(this.session)}get remoteVideoTrack(){return this.session&&this.sessionManager.getRemoteVideoTrack(this.session)}connect(){return this.logger.log(`[${this.id}] Connecting UserAgent...`),this.sessionManager.connect()}disconnect(){return this.logger.log(`[${this.id}] Disconnecting UserAgent...`),this.sessionManager.disconnect()}isConnected(){return this.sessionManager.isConnected()}register(e){return this.logger.log(`[${this.id}] Registering UserAgent...`),this.sessionManager.register(e)}unregister(e){return this.logger.log(`[${this.id}] Unregistering UserAgent...`),this.sessionManager.unregister(e)}call(e,t,n){return this.logger.log(`[${this.id}] Beginning Session...`),this.session?Promise.reject(new Error("Session already exists.")):this.sessionManager.call(e,t,n).then(()=>{})}hangup(){return this.logger.log(`[${this.id}] Hangup...`),this.session?this.sessionManager.hangup(this.session).then(()=>{this.session=void 0}):Promise.reject(new Error("Session does not exist."))}answer(e){return this.logger.log(`[${this.id}] Accepting Invitation...`),this.session?this.sessionManager.answer(this.session,e):Promise.reject(new Error("Session does not exist."))}decline(){return this.logger.log(`[${this.id}] rejecting Invitation...`),this.session?this.sessionManager.decline(this.session):Promise.reject(new Error("Session does not exist."))}hold(){return this.logger.log(`[${this.id}] holding session...`),this.session?this.sessionManager.hold(this.session):Promise.reject(new Error("Session does not exist."))}unhold(){return this.logger.log(`[${this.id}] unholding session...`),this.session?this.sessionManager.unhold(this.session):Promise.reject(new Error("Session does not exist."))}isHeld(){return!!this.session&&this.sessionManager.isHeld(this.session)}mute(){return this.logger.log(`[${this.id}] disabling media tracks...`),this.session&&this.sessionManager.mute(this.session)}unmute(){return this.logger.log(`[${this.id}] enabling media tracks...`),this.session&&this.sessionManager.unmute(this.session)}isMuted(){return!!this.session&&this.sessionManager.isMuted(this.session)}sendDTMF(e){return this.logger.log(`[${this.id}] sending DTMF...`),this.session?this.sessionManager.sendDTMF(this.session,e):Promise.reject(new Error("Session does not exist."))}message(e,t){return this.logger.log(`[${this.id}] sending message...`),this.sessionManager.message(e,t)}}function kn(e){let t=e.replace(/\D/g,"");return t.startsWith("55")&&t.length>=12&&(t=t.slice(2)),11===t.length?`(${t.slice(0,2)}) ${t.slice(2,7)}-${t.slice(7)}`:10===t.length?`(${t.slice(0,2)}) ${t.slice(2,6)}-${t.slice(6)}`:9===t.length?`${t.slice(0,5)}-${t.slice(5)}`:8===t.length?`${t.slice(0,4)}-${t.slice(4)}`:e}const Sn="sip_config",Tn="handphone_call_logs",En="sip_manual_disconnect",Cn=(e,t)=>`handphone_contact_${e}@${t}`;let Rn=null;function Pn(){return"undefined"!=typeof crypto&&!!crypto.subtle}async function _n(){if(Rn)return Rn;const e=Uint8Array.from(atob("KsGDVvN8TLscWPFaYwpCR/wdqvCfxuvmeXsO3dNVA4A="),e=>e.charCodeAt(0));return Rn=await crypto.subtle.importKey("raw",e,"AES-GCM",!1,["encrypt","decrypt"]),Rn}async function Dn(e){if(!Pn())return function(e){return`plain:${btoa(unescape(encodeURIComponent(e)))}`}(e);const t=await _n(),n=crypto.getRandomValues(new Uint8Array(12)),r=await crypto.subtle.encrypt({name:"AES-GCM",iv:n},t,(new TextEncoder).encode(e));return`${btoa(String.fromCharCode(...n))}:${btoa(String.fromCharCode(...new Uint8Array(r)))}`}async function In(e){if(e.startsWith("plain:"))return function(e){try{return decodeURIComponent(escape(atob(e.slice(6))))}catch{return null}}(e);try{const[t,n]=e.split(":");if(!t||!n||!Pn())return null;const r=await _n(),i=Uint8Array.from(atob(t),e=>e.charCodeAt(0)),o=Uint8Array.from(atob(n),e=>e.charCodeAt(0)),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:i},r,o);return(new TextDecoder).decode(a)}catch{return null}}const An={async getSipConfig(){try{const e=localStorage.getItem(Sn);if(!e)return{};const t=JSON.parse(e);return t.password&&(t.password=await In(t.password)??""),t}catch{return{}}},async setSipConfig(e){const{password:t,server:n,aor:r,...i}=e,o={...i};if(!o.auth_user&&o.username&&(o.auth_user=o.username),t)o.password=await Dn(t);else try{const e=localStorage.getItem(Sn);if(e){const t=JSON.parse(e);t.password&&(o.password=t.password)}}catch{}localStorage.setItem(Sn,JSON.stringify(o))},buildAor:(e,t)=>e&&t?`sip:${e}@${t}`:null,async mergeConfig(e){const t=await this.getSipConfig(),n=e.server||"",r={...t,...e,server:n},i=this.buildAor(r.username,r.domain);return{...r,...i?{aor:i}:{}}},getCallLogs(){try{const e=localStorage.getItem(Tn);return e?JSON.parse(e):[]}catch{return[]}},addCallLog(e){const t=this.getCallLogs();t.unshift(e);const n=t.slice(0,50);localStorage.setItem(Tn,JSON.stringify(n))},clearCallLogs(){localStorage.removeItem(Tn)},getManualDisconnect:()=>"true"===localStorage.getItem(En),setManualDisconnect(e){e?localStorage.setItem(En,"true"):localStorage.removeItem(En)},getSipContact(e,t){const n=Cn(e,t);return localStorage.getItem(n)},setSipContact(e,t,n){const r=Cn(e,t);localStorage.setItem(r,n)},clearAll(){Object.keys(localStorage).forEach(e=>{(e.startsWith("handphone_")||"sip_config"===e||"sip_manual_disconnect"===e)&&localStorage.removeItem(e)})}};let Nn=null;function Mn(){return Nn&&"closed"!==Nn.state||(Nn=new(window.AudioContext||window.webkitAudioContext)),"suspended"===Nn.state&&Nn.resume(),Nn}function $n(e,t=.3){const n=Mn(),r=n.createGain();r.gain.setValueAtTime(0,n.currentTime),r.connect(n.destination);return{oscillators:e.map(e=>{const t=n.createOscillator();return t.type="sine",t.frequency.setValueAtTime(e,n.currentTime),t.connect(r),t.start(),t}),gainNode:r}}function On({oscillators:e,gainNode:t}){try{t.gain.setValueAtTime(0,Mn().currentTime),e.forEach(e=>{try{e.stop()}catch(t){}}),t.disconnect()}catch(n){}}const jn={1:[697,1209],2:[697,1336],3:[697,1477],4:[770,1209],5:[770,1336],6:[770,1477],7:[852,1209],8:[852,1336],9:[852,1477],"*":[941,1209],0:[941,1336],"#":[941,1477]};let Ln=null,Hn=null;function Fn(e,t=120){Un();const n=jn[e];if(!n)return;const r=Mn();Ln=$n(n,.25),Ln.gainNode.gain.setValueAtTime(.25,r.currentTime),Hn=setTimeout(()=>Un(),t)}function Un(){Hn&&(clearTimeout(Hn),Hn=null),Ln&&(On(Ln),Ln=null)}let zn=null,qn=null;function Vn(){Bn();const e=Mn();zn=$n([440,480],.2);const t=()=>{const t=e.currentTime;zn.gainNode.gain.setValueAtTime(.2,t),zn.gainNode.gain.setValueAtTime(0,t+2)};t(),qn=setInterval(t,6e3)}function Bn(){qn&&(clearInterval(qn),qn=null),zn&&(On(zn),zn=null)}let Wn=null,Yn=null;function Gn(){Yn&&(clearInterval(Yn),Yn=null),Wn&&(On(Wn),Wn=null)}let Kn=null,Qn=null;function Xn(e=!1){Qn&&(clearInterval(Qn),Qn=null),Kn&&(On(Kn),Kn=null)}function Zn(e={},t){const[n,r]=y.useState("disconnected"),[i,o]=y.useState("idle"),[a,s]=y.useState(!1),[l,c]=y.useState(!1),[u,d]=y.useState(null),[h,f]=y.useState(0),[p,g]=y.useState(!1),[m,v]=y.useState("dial"),[b,w]=y.useState(""),[x,k]=y.useState(!1),[S,T]=y.useState(!1),[E,C]=y.useState(""),R=y.useRef(null),P=y.useRef(null),_=y.useRef(null),D=y.useRef(null),I=y.useRef(null),A=y.useRef(null),N=y.useRef(null),M=y.useRef(null),$=y.useRef(null),O=y.useRef(null);y.useEffect(()=>{const e=e=>{const t=R.current;if(t)try{t.unregister()}catch(n){}};return window.addEventListener("beforeunload",e),()=>{window.removeEventListener("beforeunload",e),I.current&&clearInterval(I.current),A.current&&clearTimeout(A.current),R.current&&R.current.disconnect().catch(()=>{})}},[]);const j=()=>{I.current&&(clearInterval(I.current),I.current=null),f(0)},L=()=>{H(),A.current=setTimeout(()=>{console.warn("[useSip] Call timeout — forcing reset"),F()},6e4)},H=()=>{A.current&&(clearTimeout(A.current),A.current=null)},F=async()=>{var e,t;try{await(null==(e=R.current)?void 0:e.hangup())}catch(n){}try{await(null==(t=R.current)?void 0:t.decline())}catch(n){}_.current=null,D.current=null,o("idle"),d(null),g(!1),v("dial"),s(!1),c(!1),j(),H()},U=async n=>{var i,a;const l={...e,...n},u=l.aor.startsWith("sip:")?l.aor:`sip:${l.aor}`,h={...l,aor:u};r("connecting");const p={aor:h.aor,delegate:{onCallCreated:()=>{var e;_.current=(null==(e=R.current)?void 0:e.session)??null,o("calling"),s(!1),c(!1),Vn(),L()},onCallAnswered:()=>{var e;N.current=Date.now(),_.current=(null==(e=R.current)?void 0:e.session)??null,H(),Bn(),o("active"),f(0),I.current=setInterval(()=>{f(e=>e+1)},1e3),(null==t?void 0:t.current)&&t.current.play().catch(()=>{})},onCallHangup:()=>{const e=N.current?Math.round((Date.now()-N.current)/1e3):0,t=!!$.current,n=!t&&!!M.current&&0===e;(N.current||M.current||$.current)&&An.addCallLog({direction:t?"inbound":"outbound",number:t?$.current:M.current,startedAt:(new Date).toISOString(),duration:e,status:e>0?"answered":t?"missed":"rejected"}),N.current=null,M.current=null,$.current=null,Un(),Bn(),Gn(),Xn(),n&&(!function(){Xn();const e=Mn();Kn=$n([480,620],.2);const t=()=>{const t=e.currentTime;Kn.gainNode.gain.setValueAtTime(.2,t),Kn.gainNode.gain.setValueAtTime(0,t+.5)};t(),Qn=setInterval(t,1e3)}(),setTimeout(()=>Xn(),2e3)),_.current=null,H(),o("idle"),d(null),j(),s(!1),c(!1)},onCallReceived:()=>{var e,t,n,r,i,a,s,l,c;const u=R.current,h=(null==u?void 0:u.session)??(null==u?void 0:u._session)??(null==(e=null==u?void 0:u.sessionManager)?void 0:e.session)??null,f=(null==h?void 0:h.remoteIdentity)??(null==(n=null==(t=null==h?void 0:h.incomingRequestMessage)?void 0:t.from)?void 0:n.uri),p=(null==(r=null==f?void 0:f.uri)?void 0:r.user)||(null==(s=null==(a=null==(i=null==h?void 0:h.incomingRequestMessage)?void 0:i.from)?void 0:a.uri)?void 0:s.user)||null,g=(null==f?void 0:f.displayName)||(null==(c=null==(l=null==h?void 0:h.incomingRequestMessage)?void 0:l.from)?void 0:c.displayName)||p||"Desconhecido";$.current=p,d({from:kn(g)}),o("ringing"),function(){Gn();const e=Mn();Wn=$n([440,480],.35);const t=()=>{const t=e.currentTime;Wn.gainNode.gain.setValueAtTime(.35,t),Wn.gainNode.gain.setValueAtTime(0,t+2)};t(),Yn=setInterval(t,6e3)}(),L()},onCallHold:e=>{c(e)},onRegistered:()=>{r("registered")},onUnregistered:()=>{r("connected")},onServerConnect:()=>{r("connected")},onServerDisconnect:()=>{r("disconnected"),o("idle"),j()}},media:{remote:{audio:(null==t?void 0:t.current)??document.createElement("audio")}},userAgentOptions:{authorizationPassword:h.password||void 0,authorizationUsername:h.auth_user||(null==(i=h.aor.split(":")[1])?void 0:i.split("@")[0])||void 0,contactName:(null==(a=h.aor.split(":")[1])?void 0:a.split("@")[0])||void 0,contactParams:{transport:"wss"},userAgentString:h.system?`Handphone-2.0/${h.system}`:void 0}};try{if(R.current){try{await R.current.unregister(),await R.current.disconnect()}catch(g){}R.current=null}const e=new xn(h.server,p);return R.current=e,await e.connect(),P.current=e.userAgent??null,await e.register(),h}catch(m){throw console.error("[useSip] Connection failed",m),r("disconnected"),m}};return{connectionStatus:n,callStatus:i,isMuted:a,isOnHold:l,incomingCallInfo:u,callDuration:h,transferModal:p,setTransferModal:g,transferStep:m,setTransferStep:v,transferTarget:b,setTransferTarget:w,consultEstablished:x,setConsultEstablished:k,blindTransferModal:S,setBlindTransferModal:T,blindTransferTarget:E,setBlindTransferTarget:C,connect:e=>{if(O.current)return O.current;const t=U(e).finally(()=>{O.current=null});return O.current=t,t},disconnect:async()=>{var e,t;try{await(null==(e=R.current)?void 0:e.unregister()),await(null==(t=R.current)?void 0:t.disconnect())}catch(n){}R.current=null,r("disconnected"),o("idle"),j()},call:async(e,t)=>{if(e.trim()){M.current=e.trim();try{let n=e.trim();n.startsWith("sip:")||(n=t?`sip:${n}@${t}`:`sip:${n}`),o("calling"),s(!1),c(!1),Vn(),L(),await R.current.call(n)}catch(n){throw console.error("[useSip] Call failed",n),o("idle"),Bn(),n}}},hangup:async()=>{var e;try{await(null==(e=R.current)?void 0:e.hangup())}catch(t){throw console.error("[useSip] Hangup failed",t),t}},answer:async()=>{var e;try{Gn(),await(null==(e=R.current)?void 0:e.answer()),d(null)}catch(t){throw console.error("[useSip] Answer failed",t),t}},reject:async()=>{var e;try{Gn(),await(null==(e=R.current)?void 0:e.decline()),d(null),o("idle")}catch(t){throw console.error("[useSip] Reject failed",t),t}},toggleMute:()=>{R.current&&(a?R.current.unmute():R.current.mute(),s(!a))},toggleHold:async()=>{if(R.current)try{l?await R.current.unhold():await R.current.hold()}catch(e){throw console.error("[useSip] Hold failed",e),e}},sendDTMF:async e=>{var t;if("active"!==i)return;Fn(e);const n=(null==(t=R.current)?void 0:t.session)??_.current;if(!n)return void console.error("[useSip] No active session for DTMF");const r=n.sessionDescriptionHandler;if(r&&"function"==typeof r.sendDtmf)try{return void r.sendDtmf(e)}catch(o){console.warn("[useSip] RFC4733 failed, trying SIP INFO")}try{await n.info({requestOptions:{body:{contentDisposition:"render",contentType:"application/dtmf-relay",content:`Signal=${e}\r\nDuration=120`}}})}catch(a){console.error("[useSip] DTMF SIP INFO failed",a)}},openTransfer:async()=>{var e;try{l||await(null==(e=R.current)?void 0:e.hold())}catch(t){}v("dial"),w(""),k(!1),g(!0)},transferDial:async(e,n)=>{var r,i,o;w(e),v("connecting");const a=P.current??(null==(r=R.current)?void 0:r.userAgent)??(null==(o=null==(i=R.current)?void 0:i.sessionManager)?void 0:o.userAgent)??null;if(!a)throw new Error("Não foi possível acessar o UserAgent SIP");try{const r=e.startsWith("sip:")?e:`sip:${e}@${n}`,i=bn.makeURI(r);if(!i)throw new Error("URI inválida: "+r);const o=new ut(a,i,{sessionDescriptionHandlerOptions:{constraints:{audio:!0,video:!1}}});k(!1),o.stateChange.addListener(e=>{var n,r,i;if("Established"===e){k(!0),v("consulting");const e=null==(i=null==(r=null==(n=o.sessionDescriptionHandler)?void 0:n.peerConnection)?void 0:r.getReceivers())?void 0:i.find(e=>{var t;return"audio"===(null==(t=e.track)?void 0:t.kind)});e&&(null==t?void 0:t.current)&&(t.current.srcObject=new MediaStream([e.track]),t.current.play().catch(()=>{}))}"Terminated"===e&&(D.current=null,k(!1),v("dial"))}),D.current=o,await o.invite()}catch(s){throw console.error("[useSip] Consultation dial failed",s),v("dial"),s}},transferExecute:async()=>{var e,t;v("transferring");try{const n=D.current;if(!n)throw new Error("Sessão de consulta não encontrada");const r=(null==(e=R.current)?void 0:e.session)??_.current;if(!r)throw new Error("Sessão original não encontrada");if("Established"!==n.state)throw new Error("A sessão de consulta ainda não está estabelecida");await new Promise((e,t)=>{r.refer(n,{requestDelegate:{onAccept:()=>e(),onReject:()=>t(new Error("REFER rejeitado"))}});setTimeout(e,5e3)}),await n.bye().catch(()=>{}),D.current=null,await(null==(t=R.current)?void 0:t.hangup().catch(()=>{})),g(!1),v("dial")}catch(n){throw console.error("[useSip] Transfer failed",n),v("consulting"),n}},transferCancel:async()=>{var e;try{const e=D.current;e&&("Established"===e.state?await e.bye().catch(()=>{}):await e.cancel().catch(()=>{}))}catch(t){}D.current=null;try{await(null==(e=R.current)?void 0:e.unhold())}catch(t){}g(!1),v("dial")},blindTransfer:async(e,t)=>{var n,r;if(e.trim())try{const i=(null==(n=R.current)?void 0:n.session)??_.current;if(!i)throw new Error("Sessão ativa não encontrada");let o=e.trim();o.startsWith("sip:")||(o=t?`sip:${o}@${t}`:`sip:${o}`);const a=bn.makeURI(o);if(!a)throw new Error("URI inválida");await i.refer(a),T(!1),C(""),await(null==(r=R.current)?void 0:r.hangup().catch(()=>{}))}catch(i){throw console.error("[useSip] Blind transfer failed",i),i}},forceReset:F}}const Jn="handphone_logs",er={addLog(e,t){try{const n=this.getLogs(),r=(new Date).toISOString(),i=t.map(e=>"string"==typeof e?e:e instanceof Error?`${e.name}: ${e.message}`:JSON.stringify(e)).join(" ");n.push({timestamp:r,level:e,message:i});const o=n.slice(-200);localStorage.setItem(Jn,JSON.stringify(o))}catch(n){}},getLogs(){try{const e=localStorage.getItem(Jn);return e?JSON.parse(e):[]}catch{return[]}},clearLogs(){localStorage.removeItem(Jn)},exportLogs(){return this.getLogs().map(e=>`[${e.timestamp}] ${e.level}: ${e.message}`).join("\n")}},tr=["| sip.","sip.Transport","sip.UserAgent"];function nr(e){if(!Array.isArray(e)||0===e.length)return!1;const t=String(e[0]);return tr.some(e=>t.includes(e))}const rr=[{key:"1",sub:""},{key:"2",sub:""},{key:"3",sub:""},{key:"4",sub:""},{key:"5",sub:""},{key:"6",sub:""},{key:"7",sub:""},{key:"8",sub:""},{key:"9",sub:""},{key:"*",sub:""},{key:"0",sub:""},{key:"#",sub:""}];function ir({onPress:e,disabled:t}){return v.jsx("div",{className:"grid grid-cols-3 gap-2 mb-4",children:rr.map(({key:n,sub:r})=>v.jsxs("button",{onClick:()=>e(n),disabled:t,className:"bg-gray-800 hover:bg-gray-700 active:bg-gray-600 disabled:opacity-40 disabled:cursor-not-allowed rounded-[15px] py-3 flex flex-col items-center justify-center transition-colors select-none",children:[v.jsx("span",{className:"text-white text-xl font-light leading-none",children:n}),r&&v.jsx("span",{className:"text-gray-500 text-[9px] tracking-widest mt-0.5",children:r})]},n))})}function or({callStatus:e,isMuted:t,isOnHold:n,onCall:r,onHangup:i,onToggleMute:o,onToggleHold:a,onTransfer:s,onBlindTransfer:l,canCall:c}){const u="active"===e,d="calling"===e||"ringing"===e||u;return v.jsxs("div",{className:"space-y-3 mt-2",children:[v.jsxs("div",{className:"flex items-center justify-center gap-3",children:[v.jsx("button",{onClick:o,disabled:!u,title:t?"Desmutar":"Mutar",className:"w-12 h-12 rounded-full flex items-center justify-center transition-colors disabled:opacity-30 disabled:cursor-not-allowed "+(t?"bg-orange-500 hover:bg-orange-600 text-white":"bg-gray-700 hover:bg-gray-600 text-gray-300"),children:t?v.jsx(X,{className:"w-5 h-5"}):v.jsx(Z,{className:"w-5 h-5"})}),d?v.jsx("button",{onClick:i,title:"Desligar",className:"w-16 h-16 rounded-full bg-red-500 hover:bg-red-600 text-white flex items-center justify-center transition-colors shadow-lg shadow-red-500/30",children:v.jsx(re,{className:"w-7 h-7"})}):v.jsx("button",{onClick:r,disabled:!c,title:"Ligar",className:"w-16 h-16 rounded-full bg-green-500 hover:bg-green-600 disabled:bg-gray-700 disabled:text-gray-500 text-white flex items-center justify-center transition-colors shadow-lg shadow-green-500/30 disabled:shadow-none",children:v.jsx(oe,{className:"w-7 h-7"})}),v.jsx("button",{onClick:a,disabled:!u,title:n?"Retomar":"Colocar em espera",className:"w-12 h-12 rounded-full flex items-center justify-center transition-colors disabled:opacity-30 disabled:cursor-not-allowed "+(n?"bg-blue-500 hover:bg-blue-600 text-white":"bg-gray-700 hover:bg-gray-600 text-gray-300"),children:n?v.jsx(Y,{className:"w-5 h-5"}):v.jsx(W,{className:"w-5 h-5"})})]}),!d&&v.jsxs("p",{className:"text-gray-600 text-[10px] text-center",children:["v","2.3.0"]}),u&&v.jsx("div",{className:"flex justify-center",children:v.jsxs("div",{className:"bg-gray-800 border border-gray-700 rounded-[15px] p-3 w-full",children:[v.jsx("p",{className:"text-gray-400 text-xs uppercase tracking-wider mb-2",children:"Tipo de transferência"}),v.jsxs("div",{className:"flex gap-2",children:[v.jsxs("button",{onClick:s,title:"Transferência assistida",className:"flex items-center gap-2 bg-purple-700 hover:bg-purple-600 text-white rounded-lg px-4 py-2.5 text-sm font-medium transition-colors flex-1",children:[v.jsx(ee,{className:"w-4 h-4"}),"Assistida"]}),v.jsxs("button",{onClick:l,title:"Transferência direta",className:"flex items-center gap-2 bg-blue-700 hover:bg-blue-600 text-white rounded-lg px-4 py-2.5 text-sm font-medium transition-colors flex-1",children:[v.jsx(B,{className:"w-4 h-4"}),"Direta"]})]})]})})]})}function ar({onConnect:e,isConnecting:t,settings:n={},hideHeader:r=!1,onSave:i,onShowLogs:o}){const a=e=>({username:e.username||"",domain:e.domain||"",password:"",auth_user:e.auth_user||e.username||""}),s=e=>!!(e&&e.username&&e.domain),[l,c]=y.useState(()=>s(n)?a(n):a({})),[u,d]=y.useState(!1);y.useEffect(()=>{s(n)||An.getSipConfig().then(e=>{s(e)&&c(a(e))})},[]),y.useEffect(()=>{s(n)&&c(a(n))},[n]);const h=e=>{c({...l,[e.target.name]:e.target.value})};return v.jsxs("div",{className:r?"flex-1":"bg-gray-900 rounded-2xl shadow-2xl border border-gray-800 overflow-hidden",children:[!r&&v.jsxs("div",{className:"bg-gradient-to-r from-blue-600 to-blue-700 p-6 text-center",children:[v.jsx("div",{className:"w-16 h-16 bg-white/20 rounded-full flex items-center justify-center mx-auto mb-3",children:v.jsx(oe,{className:"w-8 h-8 text-white"})}),v.jsx("h1",{className:"text-white text-xl font-bold",children:"WebRTC Softphone"}),v.jsx("p",{className:"text-blue-200 text-sm mt-1",children:"SIP.js powered"})]}),v.jsxs("form",{onSubmit:async t=>{if(t.preventDefault(),!l.username||!l.domain)return;const n=`sip:${l.username}@${l.domain}`;r&&i?(await i({...l,aor:n}),d(!0),setTimeout(()=>d(!1),5e3)):(An.setManualDisconnect(!1),e({...l,aor:n}))},className:"p-6 space-y-5",children:[v.jsxs("div",{className:"flex gap-2",children:[v.jsxs("div",{className:"flex-1",children:[v.jsx("label",{className:"text-gray-400 text-xs font-medium uppercase tracking-wider mb-1 block",children:"Ramal *"}),v.jsx("input",{type:"text",name:"username",value:l.username,onChange:h,placeholder:"850",required:!0,className:"w-full bg-gray-800 border border-gray-700 rounded-lg px-3 py-2.5 text-white text-sm placeholder-gray-500 focus:outline-none focus:border-blue-500 transition-colors"})]}),v.jsxs("div",{className:"flex-[2]",children:[v.jsx("label",{className:"text-gray-400 text-xs font-medium uppercase tracking-wider mb-1 block",children:"Domínio *"}),v.jsx("input",{type:"text",name:"domain",value:l.domain,onChange:h,placeholder:"subdominio.falehandix.com.br",required:!0,className:"w-full bg-gray-800 border border-gray-700 rounded-lg px-3 py-2.5 text-white text-sm placeholder-gray-500 focus:outline-none focus:border-blue-500 transition-colors"})]})]}),v.jsxs("div",{children:[v.jsx("label",{className:"text-gray-400 text-xs font-medium uppercase tracking-wider mb-1 block",children:"Senha"}),v.jsx("input",{type:"password",name:"password",value:l.password,onChange:h,placeholder:"••••••••",className:"w-full bg-gray-800 border border-gray-700 rounded-lg px-3 py-2.5 text-white text-sm placeholder-gray-500 focus:outline-none focus:border-blue-500 transition-colors"})]}),v.jsx("button",{type:"submit",disabled:t||!l.username||!l.domain,className:"w-full text-white font-semibold py-3 rounded-[15px] transition-colors flex items-center justify-center gap-2 mt-2 disabled:bg-gray-700 disabled:text-gray-500 "+(r?"bg-green-600 hover:bg-green-700":"bg-blue-600 hover:bg-blue-700"),children:r?v.jsxs(v.Fragment,{children:[v.jsx(ae,{className:"w-4 h-4"}),"Salvar"]}):t?v.jsxs(v.Fragment,{children:[v.jsx("div",{className:"w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin"}),"Conectando..."]}):v.jsxs(v.Fragment,{children:[v.jsx(oe,{className:"w-4 h-4"}),"Conectar"]})}),r&&u&&v.jsx("p",{className:"text-green-400 text-xs text-center mt-1",children:"Configurações salvas com sucesso"}),r&&o&&v.jsx("button",{type:"button",onClick:o,className:"w-full text-gray-400 hover:text-gray-300 text-xs py-2 mt-3 transition-colors",children:"logs"})]})]})}const sr={disconnected:{icon:"phoneOff",color:"text-slate-500"},connecting:{icon:"phone",color:"text-amber-400 animate-pulse"},connected:{icon:"phone",color:"text-amber-400"},registered:{icon:"phone",color:"text-emerald-400"}},lr={idle:null,calling:{color:"text-yellow-400",label:"Chamando..."},ringing:{color:"text-blue-400 animate-pulse",label:"Entrada..."},active:{color:"text-green-400",label:"Em chamada"}};function cr({connectionStatus:e,callStatus:t,callDuration:n,aor:r,onDisconnect:i,onConnect:o}){var a;const s=sr[e]||sr.disconnected,l=lr[t],c=(null==(a=null==r?void 0:r.split("@")[0])?void 0:a.replace("sip:",""))||"",u="phoneOff"===s.icon?re:oe;return v.jsxs("div",{className:"bg-gray-900 border-b border-gray-800 px-4 py-3 flex items-center justify-between",children:[v.jsxs("div",{className:"flex items-center gap-2",children:[v.jsx(u,{className:`w-4 h-4 ${s.color}`}),v.jsx("span",{className:"font-semibold text-white text-sm",children:"Handphone"}),c&&v.jsxs("span",{className:"text-slate-400 text-xs",children:["· ",c]}),l&&v.jsxs(v.Fragment,{children:[v.jsxs("span",{className:`text-xs ${l.color}`,children:["· ",l.label]}),"active"===t&&v.jsx("span",{className:"text-green-400 text-xs font-mono",children:(d=n,`${Math.floor(d/60).toString().padStart(2,"0")}:${(d%60).toString().padStart(2,"0")}`)})]})]}),c&&v.jsx("button",{onClick:"disconnected"===e?o:i,style:{border:"1px solid rgba(156,163,175,0.7)"},className:"text-xs px-3 py-1 rounded-full text-slate-300 hover:text-white transition-colors",children:"disconnected"===e?"Conectar":"Desconectar"})]});var d}const ur=y.createContext({});function dr(e){const t=y.useRef(null);return null===t.current&&(t.current=e()),t.current}const hr=y.createContext(null),fr=y.createContext({transformPagePoint:e=>e,isStatic:!1,reducedMotion:"never"});class pr extends y.Component{getSnapshotBeforeUpdate(e){const t=this.props.childRef.current;if(t&&e.isPresent&&!this.props.isPresent){const e=this.props.sizeRef.current;e.height=t.offsetHeight||0,e.width=t.offsetWidth||0,e.top=t.offsetTop,e.left=t.offsetLeft}return null}componentDidUpdate(){}render(){return this.props.children}}function gr({children:e,isPresent:t}){const n=y.useId(),r=y.useRef(null),i=y.useRef({width:0,height:0,top:0,left:0}),{nonce:o}=y.useContext(fr);return y.useInsertionEffect(()=>{const{width:e,height:a,top:s,left:l}=i.current;if(t||!r.current||!e||!a)return;r.current.dataset.motionPopId=n;const c=document.createElement("style");return o&&(c.nonce=o),document.head.appendChild(c),c.sheet&&c.sheet.insertRule(`\n [data-motion-pop-id="${n}"] {\n position: absolute !important;\n width: ${e}px !important;\n height: ${a}px !important;\n top: ${s}px !important;\n left: ${l}px !important;\n }\n `),()=>{document.head.removeChild(c)}},[t]),v.jsx(pr,{isPresent:t,childRef:r,sizeRef:i,children:y.cloneElement(e,{ref:r})})}const mr=({children:e,initial:t,isPresent:n,onExitComplete:r,custom:i,presenceAffectsLayout:o,mode:a})=>{const s=dr(vr),l=y.useId(),c=y.useCallback(e=>{s.set(e,!0);for(const t of s.values())if(!t)return;r&&r()},[s,r]),u=y.useMemo(()=>({id:l,initial:t,isPresent:n,custom:i,onExitComplete:c,register:e=>(s.set(e,!1),()=>s.delete(e))}),o?[Math.random(),c]:[n,c]);return y.useMemo(()=>{s.forEach((e,t)=>s.set(t,!1))},[n]),y.useEffect(()=>{!n&&!s.size&&r&&r()},[n]),"popLayout"===a&&(e=v.jsx(gr,{isPresent:n,children:e})),v.jsx(hr.Provider,{value:u,children:e})};function vr(){return new Map}function yr(e=!0){const t=y.useContext(hr);if(null===t)return[!0,null];const{isPresent:n,onExitComplete:r,register:i}=t,o=y.useId();y.useEffect(()=>{e&&i(o)},[e]);const a=y.useCallback(()=>e&&r&&r(o),[o,r,e]);return!n&&r?[!1,a]:[!0]}const br=e=>e.key||"";function wr(e){const t=[];return y.Children.forEach(e,e=>{y.isValidElement(e)&&t.push(e)}),t}const xr="undefined"!=typeof window,kr=xr?y.useLayoutEffect:y.useEffect;var Sr={};const Tr=({children:e,custom:t,initial:n=!0,onExitComplete:r,presenceAffectsLayout:i=!0,mode:o="sync",propagate:a=!1})=>{const[s,l]=yr(a),c=y.useMemo(()=>wr(e),[e]),u=a&&!s?[]:c.map(br),d=y.useRef(!0),h=y.useRef(c),f=dr(()=>new Map),[p,g]=y.useState(c),[m,b]=y.useState(c);kr(()=>{d.current=!1,h.current=c;for(let e=0;e1&&console.warn('You\'re attempting to animate multiple children within AnimatePresence, but its mode is set to "wait". This will lead to odd visual behaviour.');const{forceRender:x}=y.useContext(ur);return v.jsx(v.Fragment,{children:m.map(e=>{const p=br(e),g=!(a&&!s)&&(c===m||u.includes(p));return v.jsx(mr,{isPresent:g,initial:!(d.current&&!n)&&void 0,custom:g?void 0:t,presenceAffectsLayout:i,mode:o,onExitComplete:g?void 0:()=>{if(!f.has(p))return;f.set(p,!0);let e=!0;f.forEach(t=>{t||(e=!1)}),e&&(null==x||x(),b(h.current),a&&(null==l||l()),r&&r())},children:e},p)})})},Er=e=>e;let Cr=Er,Rr=Er;function Pr(e){let t;return()=>(void 0===t&&(t=e()),t)}"production"!=={}.NODE_ENV&&(Cr=(e,t)=>{e||"undefined"==typeof console||console.warn(t)},Rr=(e,t)=>{if(!e)throw new Error(t)});const _r=(e,t,n)=>{const r=t-e;return 0===r?1:(n-e)/r},Dr=e=>1e3*e,Ir=e=>e/1e3,Ar=!1;const Nr=["read","resolveKeyframes","update","preRender","render","postRender"];function Mr(e,t){let n=!1,r=!0;const i={delta:0,timestamp:0,isProcessing:!1},o=()=>n=!0,a=Nr.reduce((e,t)=>(e[t]=function(e){let t=new Set,n=new Set,r=!1,i=!1;const o=new WeakSet;let a={delta:0,timestamp:0,isProcessing:!1};function s(t){o.has(t)&&(l.schedule(t),e()),t(a)}const l={schedule:(e,i=!1,a=!1)=>{const s=a&&r?t:n;return i&&o.add(e),s.has(e)||s.add(e),e},cancel:e=>{n.delete(e),o.delete(e)},process:e=>{a=e,r?i=!0:(r=!0,[t,n]=[n,t],t.forEach(s),t.clear(),r=!1,i&&(i=!1,l.process(e)))}};return l}(o),e),{}),{read:s,resolveKeyframes:l,update:c,preRender:u,render:d,postRender:h}=a,f=()=>{const o=performance.now();n=!1,i.delta=r?1e3/60:Math.max(Math.min(o-i.timestamp,40),1),i.timestamp=o,i.isProcessing=!0,s.process(i),l.process(i),c.process(i),u.process(i),d.process(i),h.process(i),i.isProcessing=!1,n&&t&&(r=!1,e(f))};return{schedule:Nr.reduce((t,o)=>{const s=a[o];return t[o]=(t,o=!1,a=!1)=>(n||(n=!0,r=!0,i.isProcessing||e(f)),s.schedule(t,o,a)),t},{}),cancel:e=>{for(let t=0;tFr[Ud].some(t=>!!e[t])};const zr=new Set(["animate","exit","variants","initial","style","values","variants","transition","transformTemplate","custom","inherit","onBeforeLayoutMeasure","onAnimationStart","onAnimationComplete","onUpdate","onDragStart","onDrag","onDragEnd","onMeasureDragConstraints","onDirectionLock","onDragTransitionEnd","_dragX","_dragY","onHoverStart","onHoverEnd","onViewportEnter","onViewportLeave","globalTapTarget","ignoreStrict","viewport"]);function qr(e){return e.startsWith("while")||e.startsWith("drag")&&"draggable"!==e||e.startsWith("layout")||e.startsWith("onTap")||e.startsWith("onPan")||e.startsWith("onLayout")||zr.has(e)}let Vr=e=>!qr(e);try{(Br=require("@emotion/is-prop-valid").default)&&(Vr=e=>e.startsWith("on")?!qr(e):Br(e))}catch(Fd){}var Br;const Wr=new Set;function Yr(e,t,n){e||Wr.has(t)||(console.warn(t),Wr.add(t))}var Gr={};function Kr(e){if("undefined"==typeof Proxy)return e;const t=new Map;return new Proxy((...t)=>("production"!==Gr.NODE_ENV&&Yr(!1,"motion() is deprecated. Use motion.create() instead."),e(...t)),{get:(n,r)=>"create"===r?e:(t.has(r)||t.set(r,e(r)),t.get(r))})}const Qr=y.createContext({});function Xr(e){return"string"==typeof e||Array.isArray(e)}function Zr(e){return null!==e&&"object"==typeof e&&"function"==typeof e.start}const Jr=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],ei=["initial",...Jr];function ti(e){return Zr(e.animate)||ei.some(t=>Xr(e[t]))}function ni(e){return Boolean(ti(e)||e.variants)}function ri(e){const{initial:t,animate:n}=function(e,t){if(ti(e)){const{initial:t,animate:n}=e;return{initial:!1===t||Xr(t)?t:void 0,animate:Xr(n)?n:void 0}}return!1!==e.inherit?t:{}}(e,y.useContext(Qr));return y.useMemo(()=>({initial:t,animate:n}),[ii(t),ii(n)])}function ii(e){return Array.isArray(e)?e.join(" "):e}const oi=Symbol.for("motionComponentSymbol");function ai(e){return e&&"object"==typeof e&&Object.prototype.hasOwnProperty.call(e,"current")}function si(e,t,n){return y.useCallback(r=>{r&&e.onMount&&e.onMount(r),t&&(r?t.mount(r):t.unmount()),n&&("function"==typeof n?n(r):ai(n)&&(n.current=r))},[t])}const li=e=>e.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),ci="data-"+li("framerAppearId"),{schedule:ui}=Mr(queueMicrotask,!1),di=y.createContext({});function hi(e,t,n,r,i){var o,a;const{visualElement:s}=y.useContext(Qr),l=y.useContext(Hr),c=y.useContext(hr),u=y.useContext(fr).reducedMotion,d=y.useRef(null);r=r||l.renderer,!d.current&&r&&(d.current=r(e,{visualState:t,parent:s,props:n,presenceContext:c,blockInitialAnimation:!!c&&!1===c.initial,reducedMotionConfig:u}));const h=d.current,f=y.useContext(di);!h||h.projection||!i||"html"!==h.type&&"svg"!==h.type||function(e,t,n,r){const{layoutId:i,layout:o,drag:a,dragConstraints:s,layoutScroll:l,layoutRoot:c}=t;e.projection=new n(e.latestValues,t["data-framer-portal-id"]?void 0:fi(e.parent)),e.projection.setOptions({layoutId:i,layout:o,alwaysMeasureLayout:Boolean(a)||s&&ai(s),visualElement:e,animationType:"string"==typeof o?o:"both",initialPromotionConfig:r,layoutScroll:l,layoutRoot:c})}(d.current,n,i,f);const p=y.useRef(!1);y.useInsertionEffect(()=>{h&&p.current&&h.update(n,c)});const g=n[ci],m=y.useRef(Boolean(g)&&!(null===(o=window.MotionHandoffIsComplete)||void 0===o?void 0:o.call(window,g))&&(null===(a=window.MotionHasOptimisedAnimation)||void 0===a?void 0:a.call(window,g)));return kr(()=>{h&&(p.current=!0,window.MotionIsMounted=!0,h.updateFeatures(),ui.render(h.render),m.current&&h.animationState&&h.animationState.animateChanges())}),y.useEffect(()=>{h&&(!m.current&&h.animationState&&h.animationState.animateChanges(),m.current&&(queueMicrotask(()=>{var e;null===(e=window.MotionHandoffMarkAsComplete)||void 0===e||e.call(window,g)}),m.current=!1))}),h}function fi(e){if(e)return!1!==e.options.allowProjection?e.projection:fi(e.parent)}var pi={};function gi({preloadedFeatures:e,createVisualElement:t,useRender:n,useVisualState:r,Component:i}){var o,a;function s(o,a){let s;const l={...y.useContext(fr),...o,layoutId:mi(o)},{isStatic:c}=l,u=ri(o),d=r(o,c);if(!c&&xr){!function(e,t){const n=y.useContext(Hr).strict;if("production"!==pi.NODE_ENV&&t&&n){const t="You have rendered a `motion` component within a `LazyMotion` component. This will break tree shaking. Import and render a `m` component instead.";e.ignoreStrict?Cr(!1,t):Rr(!1,t)}}(l,e);const n=function(e){const{drag:t,layout:n}=Ur;if(!t&&!n)return{};const r={...t,...n};return{MeasureLayout:(null==t?void 0:t.isEnabled(e))||(null==n?void 0:n.isEnabled(e))?r.MeasureLayout:void 0,ProjectionNode:r.ProjectionNode}}(l);s=n.MeasureLayout,u.visualElement=hi(i,d,l,t,n.ProjectionNode)}return v.jsxs(Qr.Provider,{value:u,children:[s&&u.visualElement?v.jsx(s,{visualElement:u.visualElement,...l}):null,n(i,o,si(d,u.visualElement,a),d,c,u.visualElement)]})}e&&function(e){for(const t in e)Ur[t]={...Ur[t],...e[t]}}(e),s.displayName=`motion.${"string"==typeof i?i:`create(${null!==(a=null!==(o=i.displayName)&&void 0!==o?o:i.name)&&void 0!==a?a:""})`}`;const l=y.forwardRef(s);return l[oi]=i,l}function mi({layoutId:e}){const t=y.useContext(ur).id;return t&&void 0!==e?t+"-"+e:e}const vi=["animate","circle","defs","desc","ellipse","g","image","line","filter","marker","mask","metadata","path","pattern","polygon","polyline","rect","stop","switch","symbol","svg","text","tspan","use","view"];function yi(e){return"string"==typeof e&&!e.includes("-")&&!!(vi.indexOf(e)>-1||/[A-Z]/u.test(e))}function bi(e){const t=[{},{}];return null==e||e.values.forEach((e,n)=>{t[0][n]=e.get(),t[1][n]=e.getVelocity()}),t}function wi(e,t,n,r){if("function"==typeof t){const[i,o]=bi(r);t=t(void 0!==n?n:e.custom,i,o)}if("string"==typeof t&&(t=e.variants&&e.variants[t]),"function"==typeof t){const[i,o]=bi(r);t=t(void 0!==n?n:e.custom,i,o)}return t}const xi=e=>Array.isArray(e),ki=e=>xi(e)?e[e.length-1]||0:e,Si=e=>Boolean(e&&e.getVelocity);function Ti(e){const t=Si(e)?e.get():e;return n=t,Boolean(n&&"object"==typeof n&&n.mix&&n.toValue)?t.toValue():t;var n}const Ei=e=>(t,n)=>{const r=y.useContext(Qr),i=y.useContext(hr),o=()=>function({scrapeMotionValuesFromProps:e,createRenderState:t,onUpdate:n},r,i,o){const a={latestValues:Ci(r,i,o,e),renderState:t()};return n&&(a.onMount=e=>n({props:r,current:e,...a}),a.onUpdate=e=>n(e)),a}(e,t,r,i);return n?o():dr(o)};function Ci(e,t,n,r){const i={},o=r(e,{});for(const h in o)i[h]=Ti(o[h]);let{initial:a,animate:s}=e;const l=ti(e),c=ni(e);t&&c&&!l&&!1!==e.inherit&&(void 0===a&&(a=t.initial),void 0===s&&(s=t.animate));let u=!!n&&!1===n.initial;u=u||!1===a;const d=u?s:a;if(d&&"boolean"!=typeof d&&!Zr(d)){const t=Array.isArray(d)?d:[d];for(let n=0;nt=>"string"==typeof t&&t.startsWith(e),Di=_i("--"),Ii=_i("var(--"),Ai=e=>!!Ii(e)&&Ni.test(e.split("/*")[0].trim()),Ni=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,Mi=(e,t)=>t&&"number"==typeof e?t.transform(e):e,$i=(e,t,n)=>n>t?t:n"number"==typeof e,parse:parseFloat,transform:e=>e},ji={...Oi,transform:e=>$i(0,1,e)},Li={...Oi,default:1},Hi=e=>({test:t=>"string"==typeof t&&t.endsWith(e)&&1===t.split(" ").length,parse:parseFloat,transform:t=>`${t}${e}`}),Fi=Hi("deg"),Ui=Hi("%"),zi=Hi("px"),qi=Hi("vh"),Vi=Hi("vw"),Bi={...Ui,parse:e=>Ui.parse(e)/100,transform:e=>Ui.transform(100*e)},Wi={borderWidth:zi,borderTopWidth:zi,borderRightWidth:zi,borderBottomWidth:zi,borderLeftWidth:zi,borderRadius:zi,radius:zi,borderTopLeftRadius:zi,borderTopRightRadius:zi,borderBottomRightRadius:zi,borderBottomLeftRadius:zi,width:zi,maxWidth:zi,height:zi,maxHeight:zi,top:zi,right:zi,bottom:zi,left:zi,padding:zi,paddingTop:zi,paddingRight:zi,paddingBottom:zi,paddingLeft:zi,margin:zi,marginTop:zi,marginRight:zi,marginBottom:zi,marginLeft:zi,backgroundPositionX:zi,backgroundPositionY:zi},Yi={rotate:Fi,rotateX:Fi,rotateY:Fi,rotateZ:Fi,scale:Li,scaleX:Li,scaleY:Li,scaleZ:Li,skew:Fi,skewX:Fi,skewY:Fi,distance:zi,translateX:zi,translateY:zi,translateZ:zi,x:zi,y:zi,z:zi,perspective:zi,transformPerspective:zi,opacity:ji,originX:Bi,originY:Bi,originZ:zi},Gi={...Oi,transform:Math.round},Ki={...Wi,...Yi,zIndex:Gi,size:zi,fillOpacity:ji,strokeOpacity:ji,numOctaves:Gi},Qi={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},Xi=Ri.length;function Zi(e,t,n){const{style:r,vars:i,transformOrigin:o}=e;let a=!1,s=!1;for(const l in t){const e=t[l];if(Pi.has(l))a=!0;else if(Di(l))i[l]=e;else{const t=Mi(e,Ki[l]);l.startsWith("origin")?(s=!0,o[l]=t):r[l]=t}}if(t.transform||(a||n?r.transform=function(e,t,n){let r="",i=!0;for(let o=0;o({style:{},transform:{},transformOrigin:{},vars:{}}),io=()=>({style:{},transform:{},transformOrigin:{},vars:{},attrs:{}}),oo=e=>"string"==typeof e&&"svg"===e.toLowerCase();function ao(e,{style:t,vars:n},r,i){Object.assign(e.style,t,i&&i.getProjectionStyles(r));for(const o in n)e.style.setProperty(o,n[o])}const so=new Set(["baseFrequency","diffuseConstant","kernelMatrix","kernelUnitLength","keySplines","keyTimes","limitingConeAngle","markerHeight","markerWidth","numOctaves","targetX","targetY","surfaceScale","specularConstant","specularExponent","stdDeviation","tableValues","viewBox","gradientTransform","pathLength","startOffset","textLength","lengthAdjust"]);function lo(e,t,n,r){ao(e,t,void 0,r);for(const i in t.attrs)e.setAttribute(so.has(i)?i:li(i),t.attrs[i])}const co={};function uo(e,{layout:t,layoutId:n}){return Pi.has(e)||e.startsWith("origin")||(t||void 0!==n)&&(!!co[e]||"opacity"===e)}function ho(e,t,n){var r;const{style:i}=e,o={};for(const a in i)(Si(i[a])||t.style&&Si(t.style[a])||uo(a,e)||void 0!==(null===(r=null==n?void 0:n.getValue(a))||void 0===r?void 0:r.liveStyle))&&(o[a]=i[a]);return o}function fo(e,t,n){const r=ho(e,t,n);for(const i in e)if(Si(e[i])||Si(t[i])){r[-1!==Ri.indexOf(i)?"attr"+i.charAt(0).toUpperCase()+i.substring(1):i]=e[i]}return r}const po=["x","y","width","height","cx","cy","r"],go={useVisualState:Ei({scrapeMotionValuesFromProps:fo,createRenderState:io,onUpdate:({props:e,prevProps:t,current:n,renderState:r,latestValues:i})=>{if(!n)return;let o=!!e.drag;if(!o)for(const s in i)if(Pi.has(s)){o=!0;break}if(!o)return;let a=!t;if(t)for(let s=0;s{!function(e,t){try{t.dimensions="function"==typeof e.getBBox?e.getBBox():e.getBoundingClientRect()}catch(n){t.dimensions={x:0,y:0,width:0,height:0}}}(n,r),$r.render(()=>{no(r,i,oo(n.tagName),e.transformTemplate),lo(n,r)})})}})},mo={useVisualState:Ei({scrapeMotionValuesFromProps:ho,createRenderState:ro})};function vo(e,t,n){for(const r in t)Si(t[r])||uo(r,n)||(e[r]=t[r])}function yo(e,t){const n={};return vo(n,e.style||{},e),Object.assign(n,function({transformTemplate:e},t){return y.useMemo(()=>{const n={style:{},transform:{},transformOrigin:{},vars:{}};return Zi(n,t,e),Object.assign({},n.vars,n.style)},[t])}(e,t)),n}function bo(e,t){const n={},r=yo(e,t);return e.drag&&!1!==e.dragListener&&(n.draggable=!1,r.userSelect=r.WebkitUserSelect=r.WebkitTouchCallout="none",r.touchAction=!0===e.drag?"none":"pan-"+("x"===e.drag?"y":"x")),void 0===e.tabIndex&&(e.onTap||e.onTapStart||e.whileTap)&&(n.tabIndex=0),n.style=r,n}function wo(e,t,n,r){const i=y.useMemo(()=>{const n={style:{},transform:{},transformOrigin:{},vars:{},attrs:{}};return no(n,t,oo(r),e.transformTemplate),{...n.attrs,style:{...n.style}}},[t]);if(e.style){const t={};vo(t,e.style,e),i.style={...t,...i.style}}return i}function xo(e=!1){return(t,n,r,{latestValues:i},o)=>{const a=(yi(t)?wo:bo)(n,i,o,t),s=function(e,t,n){const r={};for(const i in e)"values"===i&&"object"==typeof e.values||(Vr(i)||!0===n&&qr(i)||!t&&!qr(i)||e.draggable&&i.startsWith("onDrag"))&&(r[i]=e[i]);return r}(n,"string"==typeof t,e),l=t!==y.Fragment?{...s,...a,ref:r}:{},{children:c}=n,u=y.useMemo(()=>Si(c)?c.get():c,[c]);return y.createElement(t,{...l,children:u})}}function ko(e,t){return function(n,{forwardMotionProps:r}={forwardMotionProps:!1}){return gi({...yi(n)?go:mo,preloadedFeatures:e,useRender:xo(r),createVisualElement:t,Component:n})}}function So(e,t){if(!Array.isArray(t))return!1;const n=t.length;if(n!==e.length)return!1;for(let r=0;rvoid 0!==window.ScrollTimeline);class Co{constructor(e){this.stop=()=>this.runAll("stop"),this.animations=e.filter(Boolean)}get finished(){return Promise.all(this.animations.map(e=>"finished"in e?e.finished:e))}getAll(e){return this.animations[0][e]}setAll(e,t){for(let n=0;nEo()&&n.attachTimeline?n.attachTimeline(e):"function"==typeof t?t(n):void 0);return()=>{n.forEach((e,t)=>{e&&e(),this.animations[t].stop()})}}get time(){return this.getAll("time")}set time(e){this.setAll("time",e)}get speed(){return this.getAll("speed")}set speed(e){this.setAll("speed",e)}get startTime(){return this.getAll("startTime")}get duration(){let e=0;for(let t=0;tt[e]())}flatten(){this.runAll("flatten")}play(){this.runAll("play")}pause(){this.runAll("pause")}cancel(){this.runAll("cancel")}complete(){this.runAll("complete")}}class Ro extends Co{then(e,t){return Promise.all(this.animations).then(e).catch(t)}}function Po(e,t){return e?e[t]||e.default||e:void 0}const _o=2e4;function Do(e){let t=0;let n=e.next(t);for(;!n.done&&t<_o;)t+=50,n=e.next(t);return t>=_o?1/0:t}function Io(e){return"function"==typeof e}function Ao(e,t){e.timeline=t,e.onfinish=null}const No=e=>Array.isArray(e)&&"number"==typeof e[0],Mo={linearEasing:void 0};function $o(e,t){const n=Pr(e);return()=>{var e;return null!==(e=Mo[t])&&void 0!==e?e:n()}}const Oo=$o(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch(e){return!1}return!0},"linearEasing"),jo=(e,t,n=10)=>{let r="";const i=Math.max(Math.round(t/n),2);for(let o=0;o`cubic-bezier(${e}, ${t}, ${n}, ${r})`,Fo={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:Ho([0,.65,.55,1]),circOut:Ho([.55,0,1,.45]),backIn:Ho([.31,.01,.66,-.59]),backOut:Ho([.33,1.53,.69,.99])};function Uo(e,t){return e?"function"==typeof e&&Oo()?jo(e,t):No(e)?Ho(e):Array.isArray(e)?e.map(e=>Uo(e,t)||Fo.easeOut):Fo[e]:void 0}const zo={x:!1,y:!1};function qo(){return zo.x||zo.y}function Vo(e,t){const n=function(e){if(e instanceof Element)return[e];if("string"==typeof e){const t=document.querySelectorAll(e);return t?Array.from(t):[]}return Array.from(e)}(e),r=new AbortController;return[n,{passive:!0,...t,signal:r.signal},()=>r.abort()]}function Bo(e){return t=>{"touch"===t.pointerType||qo()||e(t)}}const Wo=(e,t)=>!!t&&(e===t||Wo(e,t.parentElement)),Yo=e=>"mouse"===e.pointerType?"number"!=typeof e.button||e.button<=0:!1!==e.isPrimary,Go=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);const Ko=new WeakSet;function Qo(e){return t=>{"Enter"===t.key&&e(t)}}function Xo(e,t){e.dispatchEvent(new PointerEvent("pointer"+t,{isPrimary:!0,bubbles:!0}))}function Zo(e){return Yo(e)&&!qo()}function Jo(e,t,n={}){const[r,i,o]=Vo(e,n),a=e=>{const r=e.currentTarget;if(!Zo(e)||Ko.has(r))return;Ko.add(r);const o=t(e),a=(e,t)=>{window.removeEventListener("pointerup",s),window.removeEventListener("pointercancel",l),Zo(e)&&Ko.has(r)&&(Ko.delete(r),"function"==typeof o&&o(e,{success:t}))},s=e=>{a(e,n.useGlobalTarget||Wo(r,e.target))},l=e=>{a(e,!1)};window.addEventListener("pointerup",s,i),window.addEventListener("pointercancel",l,i)};return r.forEach(e=>{(function(e){return Go.has(e.tagName)||-1!==e.tabIndex})(e)||null!==e.getAttribute("tabindex")||(e.tabIndex=0);(n.useGlobalTarget?window:e).addEventListener("pointerdown",a,i),e.addEventListener("focus",e=>((e,t)=>{const n=e.currentTarget;if(!n)return;const r=Qo(()=>{if(Ko.has(n))return;Xo(n,"down");const e=Qo(()=>{Xo(n,"up")});n.addEventListener("keyup",e,t),n.addEventListener("blur",()=>Xo(n,"cancel"),t)});n.addEventListener("keydown",r,t),n.addEventListener("blur",()=>n.removeEventListener("keydown",r),t)})(e,i),i)}),o}const ea=new Set(["width","height","top","left","right","bottom",...Ri]);let ta;function na(){ta=void 0}const ra={now:()=>(void 0===ta&&ra.set(jr.isProcessing||Ar?jr.timestamp:performance.now()),ta),set:e=>{ta=e,queueMicrotask(na)}};function ia(e,t){-1===e.indexOf(t)&&e.push(t)}function oa(e,t){const n=e.indexOf(t);n>-1&&e.splice(n,1)}class aa{constructor(){this.subscriptions=[]}add(e){return ia(this.subscriptions,e),()=>oa(this.subscriptions,e)}notify(e,t,n){const r=this.subscriptions.length;if(r)if(1===r)this.subscriptions[0](e,t,n);else for(let i=0;i{const n=ra.now();this.updatedAt!==n&&this.setPrevFrameValue(),this.prev=this.current,this.setCurrent(e),this.current!==this.prev&&this.events.change&&this.events.change.notify(this.current),t&&this.events.renderRequest&&this.events.renderRequest.notify(this.current)},this.hasAnimated=!1,this.setCurrent(e),this.owner=t.owner}setCurrent(e){var t;this.current=e,this.updatedAt=ra.now(),null===this.canTrackVelocity&&void 0!==e&&(this.canTrackVelocity=(t=this.current,!isNaN(parseFloat(t))))}setPrevFrameValue(e=this.current){this.prevFrameValue=e,this.prevUpdatedAt=this.updatedAt}onChange(e){return"production"!==la.NODE_ENV&&Yr(!1,'value.onChange(callback) is deprecated. Switch to value.on("change", callback).'),this.on("change",e)}on(e,t){this.events[e]||(this.events[e]=new aa);const n=this.events[e].add(t);return"change"===e?()=>{n(),$r.read(()=>{this.events.change.getSize()||this.stop()})}:n}clearListeners(){for(const e in this.events)this.events[e].clear()}attach(e,t){this.passiveEffect=e,this.stopPassiveEffect=t}set(e,t=!0){t&&this.passiveEffect?this.passiveEffect(e,this.updateAndNotify):this.updateAndNotify(e,t)}setWithVelocity(e,t,n){this.set(t),this.prev=void 0,this.prevFrameValue=e,this.prevUpdatedAt=this.updatedAt-n}jump(e,t=!0){this.updateAndNotify(e),this.prev=e,this.prevUpdatedAt=this.prevFrameValue=void 0,t&&this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}get(){return this.current}getPrevious(){return this.prev}getVelocity(){const e=ra.now();if(!this.canTrackVelocity||void 0===this.prevFrameValue||e-this.updatedAt>30)return 0;const t=Math.min(this.updatedAt-this.prevUpdatedAt,30);return sa(parseFloat(this.current)-parseFloat(this.prevFrameValue),t)}start(e){return this.stop(),new Promise(t=>{this.hasAnimated=!0,this.animation=e(t),this.events.animationStart&&this.events.animationStart.notify()}).then(()=>{this.events.animationComplete&&this.events.animationComplete.notify(),this.clearAnimation()})}stop(){this.animation&&(this.animation.stop(),this.events.animationCancel&&this.events.animationCancel.notify()),this.clearAnimation()}isAnimating(){return!!this.animation}clearAnimation(){delete this.animation}destroy(){this.clearListeners(),this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}}function ua(e,t){return new ca(e,t)}function da(e,t,n){e.hasValue(t)?e.getValue(t).set(n):e.addValue(t,ua(n))}function ha(e,t){const n=e.getValue("willChange");if(r=n,Boolean(Si(r)&&r.add))return n.add(t);var r}function fa(e){return e.props[ci]}const pa=(e,t,n)=>(((1-3*n+3*t)*e+(3*n-6*t))*e+3*t)*e;function ga(e,t,n,r){if(e===t&&n===r)return Er;const i=t=>function(e,t,n,r,i){let o,a,s=0;do{a=t+(n-t)/2,o=pa(a,r,i)-e,o>0?n=a:t=a}while(Math.abs(o)>1e-7&&++s<12);return a}(t,0,1,e,n);return e=>0===e||1===e?e:pa(i(e),t,r)}const ma=e=>t=>t<=.5?e(2*t)/2:(2-e(2*(1-t)))/2,va=e=>t=>1-e(1-t),ya=ga(.33,1.53,.69,.99),ba=va(ya),wa=ma(ba),xa=e=>(e*=2)<1?.5*ba(e):.5*(2-Math.pow(2,-10*(e-1))),ka=e=>1-Math.sin(Math.acos(e)),Sa=va(ka),Ta=ma(ka),Ea=e=>/^0[^.\s]+$/u.test(e);function Ca(e){return"number"==typeof e?0===e:null===e||("none"===e||"0"===e||Ea(e))}const Ra=e=>Math.round(1e5*e)/1e5,Pa=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;const _a=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,Da=(e,t)=>n=>Boolean("string"==typeof n&&_a.test(n)&&n.startsWith(e)||t&&!function(e){return null==e}(n)&&Object.prototype.hasOwnProperty.call(n,t)),Ia=(e,t,n)=>r=>{if("string"!=typeof r)return r;const[i,o,a,s]=r.match(Pa);return{[e]:parseFloat(i),[t]:parseFloat(o),[n]:parseFloat(a),alpha:void 0!==s?parseFloat(s):1}},Aa={...Oi,transform:e=>Math.round((e=>$i(0,255,e))(e))},Na={test:Da("rgb","red"),parse:Ia("red","green","blue"),transform:({red:e,green:t,blue:n,alpha:r=1})=>"rgba("+Aa.transform(e)+", "+Aa.transform(t)+", "+Aa.transform(n)+", "+Ra(ji.transform(r))+")"};const Ma={test:Da("#"),parse:function(e){let t="",n="",r="",i="";return e.length>5?(t=e.substring(1,3),n=e.substring(3,5),r=e.substring(5,7),i=e.substring(7,9)):(t=e.substring(1,2),n=e.substring(2,3),r=e.substring(3,4),i=e.substring(4,5),t+=t,n+=n,r+=r,i+=i),{red:parseInt(t,16),green:parseInt(n,16),blue:parseInt(r,16),alpha:i?parseInt(i,16)/255:1}},transform:Na.transform},$a={test:Da("hsl","hue"),parse:Ia("hue","saturation","lightness"),transform:({hue:e,saturation:t,lightness:n,alpha:r=1})=>"hsla("+Math.round(e)+", "+Ui.transform(Ra(t))+", "+Ui.transform(Ra(n))+", "+Ra(ji.transform(r))+")"},Oa={test:e=>Na.test(e)||Ma.test(e)||$a.test(e),parse:e=>Na.test(e)?Na.parse(e):$a.test(e)?$a.parse(e):Ma.parse(e),transform:e=>"string"==typeof e?e:e.hasOwnProperty("red")?Na.transform(e):$a.transform(e)},ja=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;const La="number",Ha="color",Fa=/var\s*\(\s*--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)|#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\)|-?(?:\d+(?:\.\d+)?|\.\d+)/giu;function Ua(e){const t=e.toString(),n=[],r={color:[],number:[],var:[]},i=[];let o=0;const a=t.replace(Fa,e=>(Oa.test(e)?(r.color.push(o),i.push(Ha),n.push(Oa.parse(e))):e.startsWith("var(")?(r.var.push(o),i.push("var"),n.push(e)):(r.number.push(o),i.push(La),n.push(parseFloat(e))),++o,"${}")).split("${}");return{values:n,split:a,indexes:r,types:i}}function za(e){return Ua(e).values}function qa(e){const{split:t,types:n}=Ua(e),r=t.length;return e=>{let i="";for(let o=0;o"number"==typeof e?0:e;const Ba={test:function(e){var t,n;return isNaN(e)&&"string"==typeof e&&((null===(t=e.match(Pa))||void 0===t?void 0:t.length)||0)+((null===(n=e.match(ja))||void 0===n?void 0:n.length)||0)>0},parse:za,createTransformer:qa,getAnimatableNone:function(e){const t=za(e);return qa(e)(t.map(Va))}},Wa=new Set(["brightness","contrast","saturate","opacity"]);function Ya(e){const[t,n]=e.slice(0,-1).split("(");if("drop-shadow"===t)return e;const[r]=n.match(Pa)||[];if(!r)return e;const i=n.replace(r,"");let o=Wa.has(t)?1:0;return r!==n&&(o*=100),t+"("+o+i+")"}const Ga=/\b([a-z-]*)\(.*?\)/gu,Ka={...Ba,getAnimatableNone:e=>{const t=e.match(Ga);return t?t.map(Ya).join(" "):e}},Qa={...Ki,color:Oa,backgroundColor:Oa,outlineColor:Oa,fill:Oa,stroke:Oa,borderColor:Oa,borderTopColor:Oa,borderRightColor:Oa,borderBottomColor:Oa,borderLeftColor:Oa,filter:Ka,WebkitFilter:Ka},Xa=e=>Qa[e];function Za(e,t){let n=Xa(e);return n!==Ka&&(n=Ba),n.getAnimatableNone?n.getAnimatableNone(t):void 0}const Ja=new Set(["auto","none","0"]);const es=e=>e===Oi||e===zi,ts=(e,t)=>parseFloat(e.split(", ")[t]),ns=(e,t)=>(n,{transform:r})=>{if("none"===r||!r)return 0;const i=r.match(/^matrix3d\((.+)\)$/u);if(i)return ts(i[1],t);{const t=r.match(/^matrix\((.+)\)$/u);return t?ts(t[1],e):0}},rs=new Set(["x","y","z"]),is=Ri.filter(e=>!rs.has(e));const os={width:({x:e},{paddingLeft:t="0",paddingRight:n="0"})=>e.max-e.min-parseFloat(t)-parseFloat(n),height:({y:e},{paddingTop:t="0",paddingBottom:n="0"})=>e.max-e.min-parseFloat(t)-parseFloat(n),top:(e,{top:t})=>parseFloat(t),left:(e,{left:t})=>parseFloat(t),bottom:({y:e},{top:t})=>parseFloat(t)+(e.max-e.min),right:({x:e},{left:t})=>parseFloat(t)+(e.max-e.min),x:ns(4,13),y:ns(5,14)};os.translateX=os.x,os.translateY=os.y;const as=new Set;let ss=!1,ls=!1;function cs(){if(ls){const e=Array.from(as).filter(e=>e.needsMeasurement),t=new Set(e.map(e=>e.element)),n=new Map;t.forEach(e=>{const t=function(e){const t=[];return is.forEach(n=>{const r=e.getValue(n);void 0!==r&&(t.push([n,r.get()]),r.set(n.startsWith("scale")?1:0))}),t}(e);t.length&&(n.set(e,t),e.render())}),e.forEach(e=>e.measureInitialState()),t.forEach(e=>{e.render();const t=n.get(e);t&&t.forEach(([t,n])=>{var r;null===(r=e.getValue(t))||void 0===r||r.set(n)})}),e.forEach(e=>e.measureEndState()),e.forEach(e=>{void 0!==e.suspendedScrollY&&window.scrollTo(0,e.suspendedScrollY)})}ls=!1,ss=!1,as.forEach(e=>e.complete()),as.clear()}function us(){as.forEach(e=>{e.readKeyframes(),e.needsMeasurement&&(ls=!0)})}class ds{constructor(e,t,n,r,i,o=!1){this.isComplete=!1,this.isAsync=!1,this.needsMeasurement=!1,this.isScheduled=!1,this.unresolvedKeyframes=[...e],this.onComplete=t,this.name=n,this.motionValue=r,this.element=i,this.isAsync=o}scheduleResolve(){this.isScheduled=!0,this.isAsync?(as.add(this),ss||(ss=!0,$r.read(us),$r.resolveKeyframes(cs))):(this.readKeyframes(),this.complete())}readKeyframes(){const{unresolvedKeyframes:e,name:t,element:n,motionValue:r}=this;for(let i=0;i/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(e),fs=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function ps(e,t,n=1){Rr(n<=4,`Max CSS variable fallback depth detected in property "${e}". This may indicate a circular fallback dependency.`);const[r,i]=function(e){const t=fs.exec(e);if(!t)return[,];const[,n,r,i]=t;return[`--${null!=n?n:r}`,i]}(e);if(!r)return;const o=window.getComputedStyle(t).getPropertyValue(r);if(o){const e=o.trim();return hs(e)?parseFloat(e):e}return Ai(i)?ps(i,t,n+1):i}const gs=e=>t=>t.test(e),ms=[Oi,zi,Ui,Fi,Vi,qi,{test:e=>"auto"===e,parse:e=>e}],vs=e=>ms.find(gs(e));class ys extends ds{constructor(e,t,n,r,i){super(e,t,n,r,i,!0)}readKeyframes(){const{unresolvedKeyframes:e,element:t,name:n}=this;if(!t||!t.current)return;super.readKeyframes();for(let s=0;s{t.getValue(e).set(n)}),this.resolveNoneKeyframes()}}const bs=(e,t)=>"zIndex"!==t&&(!("number"!=typeof e&&!Array.isArray(e))||!("string"!=typeof e||!Ba.test(e)&&"0"!==e||e.startsWith("url(")));const ws=e=>null!==e;function xs(e,{repeat:t,repeatType:n="loop"},r){const i=e.filter(ws),o=t&&"loop"!==n&&t%2==1?0:i.length-1;return o&&void 0!==r?r:i[o]}class ks{constructor({autoplay:e=!0,delay:t=0,type:n="keyframes",repeat:r=0,repeatDelay:i=0,repeatType:o="loop",...a}){this.isStopped=!1,this.hasAttemptedResolve=!1,this.createdAt=ra.now(),this.options={autoplay:e,delay:t,type:n,repeat:r,repeatDelay:i,repeatType:o,...a},this.updateFinishedPromise()}calcStartTime(){return this.resolvedAt&&this.resolvedAt-this.createdAt>40?this.resolvedAt:this.createdAt}get resolved(){return this._resolved||this.hasAttemptedResolve||(us(),cs()),this._resolved}onKeyframesResolved(e,t){this.resolvedAt=ra.now(),this.hasAttemptedResolve=!0;const{name:n,type:r,velocity:i,delay:o,onComplete:a,onUpdate:s,isGenerator:l}=this.options;if(!l&&!function(e,t,n,r){const i=e[0];if(null===i)return!1;if("display"===t||"visibility"===t)return!0;const o=e[e.length-1],a=bs(i,t),s=bs(o,t);return Cr(a===s,`You are trying to animate ${t} from "${i}" to "${o}". ${i} is not an animatable value - to enable this animation set ${i} to a value animatable to ${o} via the \`style\` property.`),!(!a||!s)&&(function(e){const t=e[0];if(1===e.length)return!0;for(let n=0;n{this.resolveFinishedPromise=e})}}const Ss=(e,t,n)=>e+(t-e)*n;function Ts(e,t,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?e+6*(t-e)*n:n<.5?t:n<2/3?e+(t-e)*(2/3-n)*6:e}function Es(e,t){return n=>n>0?t:e}const Cs=(e,t,n)=>{const r=e*e,i=n*(t*t-r)+r;return i<0?0:Math.sqrt(i)},Rs=[Ma,Na,$a];function Ps(e){const t=(n=e,Rs.find(e=>e.test(n)));var n;if(Cr(Boolean(t),`'${e}' is not an animatable color. Use the equivalent color code instead.`),!Boolean(t))return!1;let r=t.parse(e);return t===$a&&(r=function({hue:e,saturation:t,lightness:n,alpha:r}){e/=360,n/=100;let i=0,o=0,a=0;if(t/=100){const r=n<.5?n*(1+t):n+t-n*t,s=2*n-r;i=Ts(s,r,e+1/3),o=Ts(s,r,e),a=Ts(s,r,e-1/3)}else i=o=a=n;return{red:Math.round(255*i),green:Math.round(255*o),blue:Math.round(255*a),alpha:r}}(r)),r}const _s=(e,t)=>{const n=Ps(e),r=Ps(t);if(!n||!r)return Es(e,t);const i={...n};return e=>(i.red=Cs(n.red,r.red,e),i.green=Cs(n.green,r.green,e),i.blue=Cs(n.blue,r.blue,e),i.alpha=Ss(n.alpha,r.alpha,e),Na.transform(i))},Ds=(e,t)=>n=>t(e(n)),Is=(...e)=>e.reduce(Ds),As=new Set(["none","hidden"]);function Ns(e,t){return n=>Ss(e,t,n)}function Ms(e){return"number"==typeof e?Ns:"string"==typeof e?Ai(e)?Es:Oa.test(e)?_s:js:Array.isArray(e)?$s:"object"==typeof e?Oa.test(e)?_s:Os:Es}function $s(e,t){const n=[...e],r=n.length,i=e.map((e,n)=>Ms(e)(e,t[n]));return e=>{for(let t=0;t{for(const t in r)n[t]=r[t](e);return n}}const js=(e,t)=>{const n=Ba.createTransformer(t),r=Ua(e),i=Ua(t);return r.indexes.var.length===i.indexes.var.length&&r.indexes.color.length===i.indexes.color.length&&r.indexes.number.length>=i.indexes.number.length?As.has(e)&&!i.values.length||As.has(t)&&!r.values.length?function(e,t){return As.has(e)?n=>n<=0?e:t:n=>n>=1?t:e}(e,t):Is($s(function(e,t){var n;const r=[],i={color:0,var:0,number:0};for(let o=0;o{const r=t*a,i=r*e,o=r-n,s=nl(t,a),l=Math.exp(-i);return Js-o/s*l},o=t=>{const r=t*a*e,o=r*n+n,s=Math.pow(a,2)*Math.pow(t,2)*e,l=Math.exp(-r),c=nl(Math.pow(t,2),a);return(-i(t)+Js>0?-1:1)*((o-s)*l)/c}):(i=t=>Math.exp(-t*e)*((t-n)*e+1)-.001,o=t=>Math.exp(-t*e)*(e*e*(n-t)));const s=function(e,t,n){let r=n;for(let i=1;ivoid 0!==e[t])}function al(e=Ws,t=Bs){const n="object"!=typeof e?{visualDuration:e,keyframes:[0,1],bounce:t}:e;let{restSpeed:r,restDelta:i}=n;const o=n.keyframes[0],a=n.keyframes[n.keyframes.length-1],s={done:!1,value:o},{stiffness:l,damping:c,mass:u,duration:d,velocity:h,isResolvedFromDuration:f}=function(e){let t={velocity:qs,stiffness:Fs,damping:Us,mass:zs,isResolvedFromDuration:!1,...e};if(!ol(e,il)&&ol(e,rl))if(e.visualDuration){const n=e.visualDuration,r=2*Math.PI/(1.2*n),i=r*r,o=2*$i(.05,1,1-(e.bounce||0))*Math.sqrt(i);t={...t,mass:zs,stiffness:i,damping:o}}else{const n=el(e);t={...t,...n,mass:zs},t.isResolvedFromDuration=!0}return t}({...n,velocity:-Ir(n.velocity||0)}),p=h||0,g=c/(2*Math.sqrt(l*u)),m=a-o,v=Ir(Math.sqrt(l/u)),y=Math.abs(m)<5;let b;if(r||(r=y?Ys.granular:Ys.default),i||(i=y?Gs.granular:Gs.default),g<1){const e=nl(v,g);b=t=>{const n=Math.exp(-g*v*t);return a-n*((p+g*v*m)/e*Math.sin(e*t)+m*Math.cos(e*t))}}else if(1===g)b=e=>a-Math.exp(-v*e)*(m+(p+v*m)*e);else{const e=v*Math.sqrt(g*g-1);b=t=>{const n=Math.exp(-g*v*t),r=Math.min(e*t,300);return a-n*((p+g*v*m)*Math.sinh(r)+e*m*Math.cosh(r))/e}}const w={calculatedDuration:f&&d||null,next:e=>{const t=b(e);if(f)s.done=e>=d;else{let n=0;g<1&&(n=0===e?Dr(p):Hs(b,e,t));const o=Math.abs(n)<=r,l=Math.abs(a-t)<=i;s.done=o&&l}return s.value=s.done?a:t,s},toString:()=>{const e=Math.min(Do(w),_o),t=jo(t=>w.next(e*t).value,e,30);return e+"ms "+t}};return w}function sl({keyframes:e,velocity:t=0,power:n=.8,timeConstant:r=325,bounceDamping:i=10,bounceStiffness:o=500,modifyTarget:a,min:s,max:l,restDelta:c=.5,restSpeed:u}){const d=e[0],h={done:!1,value:d},f=e=>void 0===s?l:void 0===l||Math.abs(s-e)-p*Math.exp(-e/r),y=e=>m+v(e),b=e=>{const t=v(e),n=y(e);h.done=Math.abs(t)<=c,h.value=h.done?m:n};let w,x;const k=e=>{var t;(t=h.value,void 0!==s&&tl)&&(w=e,x=al({keyframes:[h.value,f(h.value)],velocity:Hs(y,e,h.value),damping:i,stiffness:o,restDelta:c,restSpeed:u}))};return k(0),{calculatedDuration:null,next:e=>{let t=!1;return x||void 0!==w||(t=!0,b(e),k(e)),void 0!==w&&e>=w?x.next(e-w):(!t&&b(e),h)}}}const ll=ga(.42,0,1,1),cl=ga(0,0,.58,1),ul=ga(.42,0,.58,1),dl={linear:Er,easeIn:ll,easeInOut:ul,easeOut:cl,circIn:ka,circInOut:Ta,circOut:Sa,backIn:ba,backInOut:wa,backOut:ya,anticipate:xa},hl=e=>{if(No(e)){Rr(4===e.length,"Cubic bezier arrays must contain four numerical values.");const[t,n,r,i]=e;return ga(t,n,r,i)}return"string"==typeof e?(Rr(void 0!==dl[e],`Invalid easing type '${e}'`),dl[e]):e};function fl(e,t,{clamp:n=!0,ease:r,mixer:i}={}){const o=e.length;if(Rr(o===t.length,"Both input and output ranges must be the same length"),1===o)return()=>t[0];if(2===o&&t[0]===t[1])return()=>t[1];const a=e[0]===e[1];e[0]>e[o-1]&&(e=[...e].reverse(),t=[...t].reverse());const s=function(e,t,n){const r=[],i=n||Ls,o=e.length-1;for(let a=0;a{if(a&&n1)for(;rc($i(e[0],e[o-1],t)):c}function pl(e){const t=[0];return function(e,t){const n=e[e.length-1];for(let r=1;r<=t;r++){const i=_r(0,t,r);e.push(Ss(n,1,i))}}(t,e.length-1),t}function gl({duration:e=300,keyframes:t,times:n,ease:r="easeInOut"}){const i=(e=>Array.isArray(e)&&"number"!=typeof e[0])(r)?r.map(hl):hl(r),o={done:!1,value:t[0]},a=function(e,t){return e.map(e=>e*t)}(n&&n.length===t.length?n:pl(t),e),s=fl(a,t,{ease:Array.isArray(i)?i:(l=t,c=i,l.map(()=>c||ul).splice(0,l.length-1))});var l,c;return{calculatedDuration:e,next:t=>(o.value=s(t),o.done=t>=e,o)}}const ml=e=>{const t=({timestamp:t})=>e(t);return{start:()=>$r.update(t,!0),stop:()=>Or(t),now:()=>jr.isProcessing?jr.timestamp:ra.now()}};var vl={};const yl={decay:sl,inertia:sl,tween:gl,keyframes:gl,spring:al},bl=e=>e/100;class wl extends ks{constructor(e){super(e),this.holdTime=null,this.cancelTime=null,this.currentTime=0,this.playbackSpeed=1,this.pendingPlayState="running",this.startTime=null,this.state="idle",this.stop=()=>{if(this.resolver.cancel(),this.isStopped=!0,"idle"===this.state)return;this.teardown();const{onStop:e}=this.options;e&&e()};const{name:t,motionValue:n,element:r,keyframes:i}=this.options,o=(null==r?void 0:r.KeyframeResolver)||ds;this.resolver=new o(i,(e,t)=>this.onKeyframesResolved(e,t),t,n,r),this.resolver.scheduleResolve()}flatten(){super.flatten(),this._resolved&&Object.assign(this._resolved,this.initPlayback(this._resolved.keyframes))}initPlayback(e){const{type:t="keyframes",repeat:n=0,repeatDelay:r=0,repeatType:i,velocity:o=0}=this.options,a=Io(t)?t:yl[t]||gl;let s,l;a!==gl&&"number"!=typeof e[0]&&("production"!==vl.NODE_ENV&&Rr(2===e.length,`Only two keyframes currently supported with spring and inertia animations. Trying to animate ${e}`),s=Is(bl,Ls(e[0],e[1])),e=[0,100]);const c=a({...this.options,keyframes:e});"mirror"===i&&(l=a({...this.options,keyframes:[...e].reverse(),velocity:-o})),null===c.calculatedDuration&&(c.calculatedDuration=Do(c));const{calculatedDuration:u}=c,d=u+r;return{generator:c,mirroredGenerator:l,mapPercentToKeyframes:s,calculatedDuration:u,resolvedDuration:d,totalDuration:d*(n+1)-r}}onPostResolved(){const{autoplay:e=!0}=this.options;this.play(),"paused"!==this.pendingPlayState&&e?this.state=this.pendingPlayState:this.pause()}tick(e,t=!1){const{resolved:n}=this;if(!n){const{keyframes:e}=this.options;return{done:!0,value:e[e.length-1]}}const{finalKeyframe:r,generator:i,mirroredGenerator:o,mapPercentToKeyframes:a,keyframes:s,calculatedDuration:l,totalDuration:c,resolvedDuration:u}=n;if(null===this.startTime)return i.next(0);const{delay:d,repeat:h,repeatType:f,repeatDelay:p,onUpdate:g}=this.options;this.speed>0?this.startTime=Math.min(this.startTime,e):this.speed<0&&(this.startTime=Math.min(e-c/this.speed,this.startTime)),t?this.currentTime=e:null!==this.holdTime?this.currentTime=this.holdTime:this.currentTime=Math.round(e-this.startTime)*this.speed;const m=this.currentTime-d*(this.speed>=0?1:-1),v=this.speed>=0?m<0:m>c;this.currentTime=Math.max(m,0),"finished"===this.state&&null===this.holdTime&&(this.currentTime=c);let y=this.currentTime,b=i;if(h){const e=Math.min(this.currentTime,c)/u;let t=Math.floor(e),n=e%1;!n&&e>=1&&(n=1),1===n&&t--,t=Math.min(t,h+1);Boolean(t%2)&&("reverse"===f?(n=1-n,p&&(n-=p/u)):"mirror"===f&&(b=o)),y=$i(0,1,n)*u}const w=v?{done:!1,value:s[0]}:b.next(y);a&&(w.value=a(w.value));let{done:x}=w;v||null===l||(x=this.speed>=0?this.currentTime>=c:this.currentTime<=0);const k=null===this.holdTime&&("finished"===this.state||"running"===this.state&&x);return k&&void 0!==r&&(w.value=xs(s,this.options,r)),g&&g(w.value),k&&this.finish(),w}get duration(){const{resolved:e}=this;return e?Ir(e.calculatedDuration):0}get time(){return Ir(this.currentTime)}set time(e){e=Dr(e),this.currentTime=e,null!==this.holdTime||0===this.speed?this.holdTime=e:this.driver&&(this.startTime=this.driver.now()-e/this.speed)}get speed(){return this.playbackSpeed}set speed(e){const t=this.playbackSpeed!==e;this.playbackSpeed=e,t&&(this.time=Ir(this.currentTime))}play(){if(this.resolver.isScheduled||this.resolver.resume(),!this._resolved)return void(this.pendingPlayState="running");if(this.isStopped)return;const{driver:e=ml,onPlay:t,startTime:n}=this.options;this.driver||(this.driver=e(e=>this.tick(e))),t&&t();const r=this.driver.now();null!==this.holdTime?this.startTime=r-this.holdTime:this.startTime?"finished"===this.state&&(this.startTime=r):this.startTime=null!=n?n:this.calcStartTime(),"finished"===this.state&&this.updateFinishedPromise(),this.cancelTime=this.startTime,this.holdTime=null,this.state="running",this.driver.start()}pause(){var e;this._resolved?(this.state="paused",this.holdTime=null!==(e=this.currentTime)&&void 0!==e?e:0):this.pendingPlayState="paused"}complete(){"running"!==this.state&&this.play(),this.pendingPlayState=this.state="finished",this.holdTime=null}finish(){this.teardown(),this.state="finished";const{onComplete:e}=this.options;e&&e()}cancel(){null!==this.cancelTime&&this.tick(this.cancelTime),this.teardown(),this.updateFinishedPromise()}teardown(){this.state="idle",this.stopDriver(),this.resolveFinishedPromise(),this.updateFinishedPromise(),this.startTime=this.cancelTime=null,this.resolver.cancel()}stopDriver(){this.driver&&(this.driver.stop(),this.driver=void 0)}sample(e){return this.startTime=0,this.tick(e,!0)}}const xl=new Set(["opacity","clipPath","filter","transform"]);function kl(e,t,n,{delay:r=0,duration:i=300,repeat:o=0,repeatType:a="loop",ease:s="easeInOut",times:l}={}){const c={[t]:n};l&&(c.offset=l);const u=Uo(s,i);return Array.isArray(u)&&(c.easing=u),e.animate(c,{delay:r,duration:i,easing:Array.isArray(u)?"linear":u,fill:"both",iterations:o+1,direction:"reverse"===a?"alternate":"normal"})}const Sl=Pr(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));const Tl={anticipate:xa,backInOut:wa,circInOut:Ta};class El extends ks{constructor(e){super(e);const{name:t,motionValue:n,element:r,keyframes:i}=this.options;this.resolver=new ys(i,(e,t)=>this.onKeyframesResolved(e,t),t,n,r),this.resolver.scheduleResolve()}initPlayback(e,t){let{duration:n=300,times:r,ease:i,type:o,motionValue:a,name:s,startTime:l}=this.options;if(!a.owner||!a.owner.current)return!1;var c;if("string"==typeof i&&Oo()&&i in Tl&&(i=Tl[i]),Io((c=this.options).type)||"spring"===c.type||!Lo(c.ease)){const{onComplete:t,onUpdate:a,motionValue:s,element:l,...c}=this.options,u=function(e,t){const n=new wl({...t,keyframes:e,repeat:0,delay:0,isGenerator:!0});let r={done:!1,value:e[0]};const i=[];let o=0;for(;!r.done&&o<2e4;)r=n.sample(o),i.push(r.value),o+=10;return{times:void 0,keyframes:i,duration:o-10,ease:"linear"}}(e,c);1===(e=u.keyframes).length&&(e[1]=e[0]),n=u.duration,r=u.times,i=u.ease,o="keyframes"}const u=kl(a.owner.current,s,e,{...this.options,duration:n,times:r,ease:i});return u.startTime=null!=l?l:this.calcStartTime(),this.pendingTimeline?(Ao(u,this.pendingTimeline),this.pendingTimeline=void 0):u.onfinish=()=>{const{onComplete:n}=this.options;a.set(xs(e,this.options,t)),n&&n(),this.cancel(),this.resolveFinishedPromise()},{animation:u,duration:n,times:r,type:o,ease:i,keyframes:e}}get duration(){const{resolved:e}=this;if(!e)return 0;const{duration:t}=e;return Ir(t)}get time(){const{resolved:e}=this;if(!e)return 0;const{animation:t}=e;return Ir(t.currentTime||0)}set time(e){const{resolved:t}=this;if(!t)return;const{animation:n}=t;n.currentTime=Dr(e)}get speed(){const{resolved:e}=this;if(!e)return 1;const{animation:t}=e;return t.playbackRate}set speed(e){const{resolved:t}=this;if(!t)return;const{animation:n}=t;n.playbackRate=e}get state(){const{resolved:e}=this;if(!e)return"idle";const{animation:t}=e;return t.playState}get startTime(){const{resolved:e}=this;if(!e)return null;const{animation:t}=e;return t.startTime}attachTimeline(e){if(this._resolved){const{resolved:t}=this;if(!t)return Er;const{animation:n}=t;Ao(n,e)}else this.pendingTimeline=e;return Er}play(){if(this.isStopped)return;const{resolved:e}=this;if(!e)return;const{animation:t}=e;"finished"===t.playState&&this.updateFinishedPromise(),t.play()}pause(){const{resolved:e}=this;if(!e)return;const{animation:t}=e;t.pause()}stop(){if(this.resolver.cancel(),this.isStopped=!0,"idle"===this.state)return;this.resolveFinishedPromise(),this.updateFinishedPromise();const{resolved:e}=this;if(!e)return;const{animation:t,keyframes:n,duration:r,type:i,ease:o,times:a}=e;if("idle"===t.playState||"finished"===t.playState)return;if(this.time){const{motionValue:e,onUpdate:t,onComplete:s,element:l,...c}=this.options,u=new wl({...c,keyframes:n,duration:r,type:i,ease:o,times:a,isGenerator:!0}),d=Dr(this.time);e.setWithVelocity(u.sample(d-10).value,u.sample(d).value,10)}const{onStop:s}=this.options;s&&s(),this.cancel()}complete(){const{resolved:e}=this;e&&e.animation.finish()}cancel(){const{resolved:e}=this;e&&e.animation.cancel()}static supports(e){const{motionValue:t,name:n,repeatDelay:r,repeatType:i,damping:o,type:a}=e;if(!(t&&t.owner&&t.owner.current instanceof HTMLElement))return!1;const{onUpdate:s,transformTemplate:l}=t.owner.getProps();return Sl()&&n&&xl.has(n)&&!s&&!l&&!r&&"mirror"!==i&&0!==o&&"inertia"!==a}}const Cl={type:"spring",stiffness:500,damping:25,restSpeed:10},Rl={type:"keyframes",duration:.8},Pl={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},_l=(e,{keyframes:t})=>t.length>2?Rl:Pi.has(e)?e.startsWith("scale")?{type:"spring",stiffness:550,damping:0===t[1]?2*Math.sqrt(550):30,restSpeed:10}:Cl:Pl;const Dl=(e,t,n,r={},i,o)=>a=>{const s=Po(r,e)||{},l=s.delay||r.delay||0;let{elapsed:c=0}=r;c-=Dr(l);let u={keyframes:Array.isArray(n)?n:[null,n],ease:"easeOut",velocity:t.getVelocity(),...s,delay:-c,onUpdate:e=>{t.set(e),s.onUpdate&&s.onUpdate(e)},onComplete:()=>{a(),s.onComplete&&s.onComplete()},name:e,motionValue:t,element:o?void 0:i};(function({when:e,delay:t,delayChildren:n,staggerChildren:r,staggerDirection:i,repeat:o,repeatType:a,repeatDelay:s,from:l,elapsed:c,...u}){return!!Object.keys(u).length})(s)||(u={...u,..._l(e,u)}),u.duration&&(u.duration=Dr(u.duration)),u.repeatDelay&&(u.repeatDelay=Dr(u.repeatDelay)),void 0!==u.from&&(u.keyframes[0]=u.from);let d=!1;if((!1===u.type||0===u.duration&&!u.repeatDelay)&&(u.duration=0,0===u.delay&&(d=!0)),d&&!o&&void 0!==t.get()){const e=xs(u.keyframes,s);if(void 0!==e)return $r.update(()=>{u.onUpdate(e),u.onComplete()}),new Ro([])}return!o&&El.supports(u)?new El(u):new wl(u)};function Il({protectedKeys:e,needsAnimating:t},n){const r=e.hasOwnProperty(n)&&!0!==t[n];return t[n]=!1,r}function Al(e,t,{delay:n=0,transitionOverride:r,type:i}={}){var o;let{transition:a=e.getDefaultTransition(),transitionEnd:s,...l}=t;r&&(a=r);const c=[],u=i&&e.animationState&&e.animationState.getState()[i];for(const d in l){const t=e.getValue(d,null!==(o=e.latestValues[d])&&void 0!==o?o:null),r=l[d];if(void 0===r||u&&Il(u,d))continue;const i={delay:n,...Po(a||{},d)};let s=!1;if(window.MotionHandoffAnimation){const t=fa(e);if(t){const e=window.MotionHandoffAnimation(t,d,$r);null!==e&&(i.startTime=e,s=!0)}}ha(e,d),t.start(Dl(d,t,r,e.shouldReduceMotion&&ea.has(d)?{type:!1}:i,e,s));const h=t.animation;h&&c.push(h)}return s&&Promise.all(c).then(()=>{$r.update(()=>{s&&function(e,t){const n=To(e,t);let{transitionEnd:r={},transition:i={},...o}=n||{};o={...o,...r};for(const a in o)da(e,a,ki(o[a]))}(e,s)})}),c}function Nl(e,t,n={}){var r;const i=To(e,t,"exit"===n.type?null===(r=e.presenceContext)||void 0===r?void 0:r.custom:void 0);let{transition:o=e.getDefaultTransition()||{}}=i||{};n.transitionOverride&&(o=n.transitionOverride);const a=i?()=>Promise.all(Al(e,i,n)):()=>Promise.resolve(),s=e.variantChildren&&e.variantChildren.size?(r=0)=>{const{delayChildren:i=0,staggerChildren:a,staggerDirection:s}=o;return function(e,t,n=0,r=0,i=1,o){const a=[],s=(e.variantChildren.size-1)*r,l=1===i?(e=0)=>e*r:(e=0)=>s-e*r;return Array.from(e.variantChildren).sort(Ml).forEach((e,r)=>{e.notify("AnimationStart",t),a.push(Nl(e,t,{...o,delay:n+l(r)}).then(()=>e.notify("AnimationComplete",t)))}),Promise.all(a)}(e,t,i+r,a,s,n)}:()=>Promise.resolve(),{when:l}=o;if(l){const[e,t]="beforeChildren"===l?[a,s]:[s,a];return e().then(()=>t())}return Promise.all([a(),s(n.delay)])}function Ml(e,t){return e.sortNodePosition(t)}const $l=ei.length;function Ol(e){if(!e)return;if(!e.isControllingVariants){const t=e.parent&&Ol(e.parent)||{};return void 0!==e.props.initial&&(t.initial=e.props.initial),t}const t={};for(let n=0;n<$l;n++){const r=ei[n],i=e.props[r];(Xr(i)||!1===i)&&(t[r]=i)}return t}const jl=[...Jr].reverse(),Ll=Jr.length;function Hl(e){return t=>Promise.all(t.map(({animation:t,options:n})=>function(e,t,n={}){let r;if(e.notify("AnimationStart",t),Array.isArray(t)){const i=t.map(t=>Nl(e,t,n));r=Promise.all(i)}else if("string"==typeof t)r=Nl(e,t,n);else{const i="function"==typeof t?To(e,t,n.custom):t;r=Promise.all(Al(e,i,n))}return r.then(()=>{e.notify("AnimationComplete",t)})}(e,t,n)))}function Fl(e){let t=Hl(e),n=ql(),r=!0;const i=t=>(n,r)=>{var i;const o=To(e,r,"exit"===t?null===(i=e.presenceContext)||void 0===i?void 0:i.custom:void 0);if(o){const{transition:e,transitionEnd:t,...r}=o;n={...n,...r,...t}}return n};function o(o){const{props:a}=e,s=Ol(e.parent)||{},l=[],c=new Set;let u={},d=1/0;for(let t=0;td&&g,w=!1;const x=Array.isArray(p)?p:[p];let k=x.reduce(i(h),{});!1===m&&(k={});const{prevResolvedValues:S={}}=f,T={...S,...k},E=t=>{b=!0,c.has(t)&&(w=!0,c.delete(t)),f.needsAnimating[t]=!0;const n=e.getValue(t);n&&(n.liveStyle=!1)};for(const e in T){const t=k[e],n=S[e];if(u.hasOwnProperty(e))continue;let r=!1;r=xi(t)&&xi(n)?!So(t,n):t!==n,r?null!=t?E(e):c.add(e):void 0!==t&&c.has(e)?E(e):f.protectedKeys[e]=!0}f.prevProp=p,f.prevResolvedValues=k,f.isActive&&(u={...u,...k}),r&&e.blockInitialAnimation&&(b=!1);b&&(!(v&&y)||w)&&l.push(...x.map(e=>({animation:e,options:{type:h}})))}if(c.size){const t={};c.forEach(n=>{const r=e.getBaseTarget(n),i=e.getValue(n);i&&(i.liveStyle=!0),t[n]=null!=r?r:null}),l.push({animation:t})}let h=Boolean(l.length);return!r||!1!==a.initial&&a.initial!==a.animate||e.manuallyAnimateOnMount||(h=!1),r=!1,h?t(l):Promise.resolve()}return{animateChanges:o,setActive:function(t,r){var i;if(n[t].isActive===r)return Promise.resolve();null===(i=e.variantChildren)||void 0===i||i.forEach(e=>{var n;return null===(n=e.animationState)||void 0===n?void 0:n.setActive(t,r)}),n[t].isActive=r;const a=o(t);for(const e in n)n[e].protectedKeys={};return a},setAnimateFunction:function(n){t=n(e)},getState:()=>n,reset:()=>{n=ql(),r=!0}}}function Ul(e,t){return"string"==typeof t?t!==e:!!Array.isArray(t)&&!So(t,e)}function zl(e=!1){return{isActive:e,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function ql(){return{animate:zl(!0),whileInView:zl(),whileHover:zl(),whileTap:zl(),whileDrag:zl(),whileFocus:zl(),exit:zl()}}class Vl{constructor(e){this.isMounted=!1,this.node=e}update(){}}let Bl=0;const Wl={animation:{Feature:class extends Vl{constructor(e){super(e),e.animationState||(e.animationState=Fl(e))}updateAnimationControlsSubscription(){const{animate:e}=this.node.getProps();Zr(e)&&(this.unmountControls=e.subscribe(this.node))}mount(){this.updateAnimationControlsSubscription()}update(){const{animate:e}=this.node.getProps(),{animate:t}=this.node.prevProps||{};e!==t&&this.updateAnimationControlsSubscription()}unmount(){var e;this.node.animationState.reset(),null===(e=this.unmountControls)||void 0===e||e.call(this)}}},exit:{Feature:class extends Vl{constructor(){super(...arguments),this.id=Bl++}update(){if(!this.node.presenceContext)return;const{isPresent:e,onExitComplete:t}=this.node.presenceContext,{isPresent:n}=this.node.prevPresenceContext||{};if(!this.node.animationState||e===n)return;const r=this.node.animationState.setActive("exit",!e);t&&!e&&r.then(()=>t(this.id))}mount(){const{register:e}=this.node.presenceContext||{};e&&(this.unmount=e(this.id))}unmount(){}}}};function Yl(e,t,n,r={passive:!0}){return e.addEventListener(t,n,r),()=>e.removeEventListener(t,n)}function Gl(e){return{point:{x:e.pageX,y:e.pageY}}}function Kl(e,t,n,r){return Yl(e,t,(e=>t=>Yo(t)&&e(t,Gl(t)))(n),r)}const Ql=(e,t)=>Math.abs(e-t);class Xl{constructor(e,t,{transformPagePoint:n,contextWindow:r,dragSnapToOrigin:i=!1}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.updatePoint=()=>{if(!this.lastMoveEvent||!this.lastMoveEventInfo)return;const e=ec(this.lastMoveEventInfo,this.history),t=null!==this.startEvent,n=function(e,t){const n=Ql(e.x,t.x),r=Ql(e.y,t.y);return Math.sqrt(n**2+r**2)}(e.offset,{x:0,y:0})>=3;if(!t&&!n)return;const{point:r}=e,{timestamp:i}=jr;this.history.push({...r,timestamp:i});const{onStart:o,onMove:a}=this.handlers;t||(o&&o(this.lastMoveEvent,e),this.startEvent=this.lastMoveEvent),a&&a(this.lastMoveEvent,e)},this.handlePointerMove=(e,t)=>{this.lastMoveEvent=e,this.lastMoveEventInfo=Zl(t,this.transformPagePoint),$r.update(this.updatePoint,!0)},this.handlePointerUp=(e,t)=>{this.end();const{onEnd:n,onSessionEnd:r,resumeAnimation:i}=this.handlers;if(this.dragSnapToOrigin&&i&&i(),!this.lastMoveEvent||!this.lastMoveEventInfo)return;const o=ec("pointercancel"===e.type?this.lastMoveEventInfo:Zl(t,this.transformPagePoint),this.history);this.startEvent&&n&&n(e,o),r&&r(e,o)},!Yo(e))return;this.dragSnapToOrigin=i,this.handlers=t,this.transformPagePoint=n,this.contextWindow=r||window;const o=Zl(Gl(e),this.transformPagePoint),{point:a}=o,{timestamp:s}=jr;this.history=[{...a,timestamp:s}];const{onSessionStart:l}=t;l&&l(e,ec(o,this.history)),this.removeListeners=Is(Kl(this.contextWindow,"pointermove",this.handlePointerMove),Kl(this.contextWindow,"pointerup",this.handlePointerUp),Kl(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(e){this.handlers=e}end(){this.removeListeners&&this.removeListeners(),Or(this.updatePoint)}}function Zl(e,t){return t?{point:t(e.point)}:e}function Jl(e,t){return{x:e.x-t.x,y:e.y-t.y}}function ec({point:e},t){return{point:e,delta:Jl(e,nc(t)),offset:Jl(e,tc(t)),velocity:rc(t,.1)}}function tc(e){return e[0]}function nc(e){return e[e.length-1]}function rc(e,t){if(e.length<2)return{x:0,y:0};let n=e.length-1,r=null;const i=nc(e);for(;n>=0&&(r=e[n],!(i.timestamp-r.timestamp>Dr(t)));)n--;if(!r)return{x:0,y:0};const o=Ir(i.timestamp-r.timestamp);if(0===o)return{x:0,y:0};const a={x:(i.x-r.x)/o,y:(i.y-r.y)/o};return a.x===1/0&&(a.x=0),a.y===1/0&&(a.y=0),a}function ic(e){return e.max-e.min}function oc(e,t,n,r=.5){e.origin=r,e.originPoint=Ss(t.min,t.max,e.origin),e.scale=ic(n)/ic(t),e.translate=Ss(n.min,n.max,e.origin)-e.originPoint,(e.scale>=.9999&&e.scale<=1.0001||isNaN(e.scale))&&(e.scale=1),(e.translate>=-.01&&e.translate<=.01||isNaN(e.translate))&&(e.translate=0)}function ac(e,t,n,r){oc(e.x,t.x,n.x,r?r.originX:void 0),oc(e.y,t.y,n.y,r?r.originY:void 0)}function sc(e,t,n){e.min=n.min+t.min,e.max=e.min+ic(t)}function lc(e,t,n){e.min=t.min-n.min,e.max=e.min+ic(t)}function cc(e,t,n){lc(e.x,t.x,n.x),lc(e.y,t.y,n.y)}function uc(e,t,n){return{min:void 0!==t?e.min+t:void 0,max:void 0!==n?e.max+n-(e.max-e.min):void 0}}function dc(e,t){let n=t.min-e.min,r=t.max-e.max;return t.max-t.min({x:{min:0,max:0},y:{min:0,max:0}});function mc(e){return[e("x"),e("y")]}function vc({top:e,left:t,right:n,bottom:r}){return{x:{min:t,max:n},y:{min:e,max:r}}}function yc(e){return void 0===e||1===e}function bc({scale:e,scaleX:t,scaleY:n}){return!yc(e)||!yc(t)||!yc(n)}function wc(e){return bc(e)||xc(e)||e.z||e.rotate||e.rotateX||e.rotateY||e.skewX||e.skewY}function xc(e){return kc(e.x)||kc(e.y)}function kc(e){return e&&"0%"!==e}function Sc(e,t,n){return n+t*(e-n)}function Tc(e,t,n,r,i){return void 0!==i&&(e=Sc(e,i,r)),Sc(e,n,r)+t}function Ec(e,t=0,n=1,r,i){e.min=Tc(e.min,t,n,r,i),e.max=Tc(e.max,t,n,r,i)}function Cc(e,{x:t,y:n}){Ec(e.x,t.translate,t.scale,t.originPoint),Ec(e.y,n.translate,n.scale,n.originPoint)}const Rc=.999999999999,Pc=1.0000000000001;function _c(e,t){e.min=e.min+t,e.max=e.max+t}function Dc(e,t,n,r,i=.5){Ec(e,t,n,Ss(e.min,e.max,i),r)}function Ic(e,t){Dc(e.x,t.x,t.scaleX,t.scale,t.originX),Dc(e.y,t.y,t.scaleY,t.scale,t.originY)}function Ac(e,t){return vc(function(e,t){if(!t)return e;const n=t({x:e.left,y:e.top}),r=t({x:e.right,y:e.bottom});return{top:n.y,left:n.x,bottom:r.y,right:r.x}}(e.getBoundingClientRect(),t))}const Nc=({current:e})=>e?e.ownerDocument.defaultView:null,Mc=new WeakMap;class $c{constructor(e){this.openDragLock=null,this.isDragging=!1,this.currentDirection=null,this.originPoint={x:0,y:0},this.constraints=!1,this.hasMutatedConstraints=!1,this.elastic={x:{min:0,max:0},y:{min:0,max:0}},this.visualElement=e}start(e,{snapToCursor:t=!1}={}){const{presenceContext:n}=this.visualElement;if(n&&!1===n.isPresent)return;const{dragSnapToOrigin:r}=this.getProps();this.panSession=new Xl(e,{onSessionStart:e=>{const{dragSnapToOrigin:n}=this.getProps();n?this.pauseAnimation():this.stopAnimation(),t&&this.snapToCursor(Gl(e).point)},onStart:(e,t)=>{const{drag:n,dragPropagation:r,onDragStart:i}=this.getProps();if(n&&!r&&(this.openDragLock&&this.openDragLock(),this.openDragLock="x"===(o=n)||"y"===o?zo[o]?null:(zo[o]=!0,()=>{zo[o]=!1}):zo.x||zo.y?null:(zo.x=zo.y=!0,()=>{zo.x=zo.y=!1}),!this.openDragLock))return;var o;this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),mc(e=>{let t=this.getAxisMotionValue(e).get()||0;if(Ui.test(t)){const{projection:n}=this.visualElement;if(n&&n.layout){const r=n.layout.layoutBox[e];if(r){t=ic(r)*(parseFloat(t)/100)}}}this.originPoint[e]=t}),i&&$r.postRender(()=>i(e,t)),ha(this.visualElement,"transform");const{animationState:a}=this.visualElement;a&&a.setActive("whileDrag",!0)},onMove:(e,t)=>{const{dragPropagation:n,dragDirectionLock:r,onDirectionLock:i,onDrag:o}=this.getProps();if(!n&&!this.openDragLock)return;const{offset:a}=t;if(r&&null===this.currentDirection)return this.currentDirection=function(e,t=10){let n=null;Math.abs(e.y)>t?n="y":Math.abs(e.x)>t&&(n="x");return n}(a),void(null!==this.currentDirection&&i&&i(this.currentDirection));this.updateAxis("x",t.point,a),this.updateAxis("y",t.point,a),this.visualElement.render(),o&&o(e,t)},onSessionEnd:(e,t)=>this.stop(e,t),resumeAnimation:()=>mc(e=>{var t;return"paused"===this.getAnimationState(e)&&(null===(t=this.getAxisMotionValue(e).animation)||void 0===t?void 0:t.play())})},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:r,contextWindow:Nc(this.visualElement)})}stop(e,t){const n=this.isDragging;if(this.cancel(),!n)return;const{velocity:r}=t;this.startAnimation(r);const{onDragEnd:i}=this.getProps();i&&$r.postRender(()=>i(e,t))}cancel(){this.isDragging=!1;const{projection:e,animationState:t}=this.visualElement;e&&(e.isAnimationBlocked=!1),this.panSession&&this.panSession.end(),this.panSession=void 0;const{dragPropagation:n}=this.getProps();!n&&this.openDragLock&&(this.openDragLock(),this.openDragLock=null),t&&t.setActive("whileDrag",!1)}updateAxis(e,t,n){const{drag:r}=this.getProps();if(!n||!Oc(e,r,this.currentDirection))return;const i=this.getAxisMotionValue(e);let o=this.originPoint[e]+n[e];this.constraints&&this.constraints[e]&&(o=function(e,{min:t,max:n},r){return void 0!==t&&en&&(e=r?Ss(n,e,r.max):Math.min(e,n)),e}(o,this.constraints[e],this.elastic[e])),i.set(o)}resolveConstraints(){var e;const{dragConstraints:t,dragElastic:n}=this.getProps(),r=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):null===(e=this.visualElement.projection)||void 0===e?void 0:e.layout,i=this.constraints;t&&ai(t)?this.constraints||(this.constraints=this.resolveRefConstraints()):this.constraints=!(!t||!r)&&function(e,{top:t,left:n,bottom:r,right:i}){return{x:uc(e.x,n,i),y:uc(e.y,t,r)}}(r.layoutBox,t),this.elastic=function(e=hc){return!1===e?e=0:!0===e&&(e=hc),{x:fc(e,"left","right"),y:fc(e,"top","bottom")}}(n),i!==this.constraints&&r&&this.constraints&&!this.hasMutatedConstraints&&mc(e=>{!1!==this.constraints&&this.getAxisMotionValue(e)&&(this.constraints[e]=function(e,t){const n={};return void 0!==t.min&&(n.min=t.min-e.min),void 0!==t.max&&(n.max=t.max-e.min),n}(r.layoutBox[e],this.constraints[e]))})}resolveRefConstraints(){const{dragConstraints:e,onMeasureDragConstraints:t}=this.getProps();if(!e||!ai(e))return!1;const n=e.current;Rr(null!==n,"If `dragConstraints` is set as a React ref, that ref must be passed to another component's `ref` prop.");const{projection:r}=this.visualElement;if(!r||!r.layout)return!1;const i=function(e,t,n){const r=Ac(e,n),{scroll:i}=t;return i&&(_c(r.x,i.offset.x),_c(r.y,i.offset.y)),r}(n,r.root,this.visualElement.getTransformPagePoint());let o=function(e,t){return{x:dc(e.x,t.x),y:dc(e.y,t.y)}}(r.layout.layoutBox,i);if(t){const e=t(function({x:e,y:t}){return{top:t.min,right:e.max,bottom:t.max,left:e.min}}(o));this.hasMutatedConstraints=!!e,e&&(o=vc(e))}return o}startAnimation(e){const{drag:t,dragMomentum:n,dragElastic:r,dragTransition:i,dragSnapToOrigin:o,onDragTransitionEnd:a}=this.getProps(),s=this.constraints||{},l=mc(a=>{if(!Oc(a,t,this.currentDirection))return;let l=s&&s[a]||{};o&&(l={min:0,max:0});const c=r?200:1e6,u=r?40:1e7,d={type:"inertia",velocity:n?e[a]:0,bounceStiffness:c,bounceDamping:u,timeConstant:750,restDelta:1,restSpeed:10,...i,...l};return this.startAxisValueAnimation(a,d)});return Promise.all(l).then(a)}startAxisValueAnimation(e,t){const n=this.getAxisMotionValue(e);return ha(this.visualElement,e),n.start(Dl(e,n,0,t,this.visualElement,!1))}stopAnimation(){mc(e=>this.getAxisMotionValue(e).stop())}pauseAnimation(){mc(e=>{var t;return null===(t=this.getAxisMotionValue(e).animation)||void 0===t?void 0:t.pause()})}getAnimationState(e){var t;return null===(t=this.getAxisMotionValue(e).animation)||void 0===t?void 0:t.state}getAxisMotionValue(e){const t=`_drag${e.toUpperCase()}`,n=this.visualElement.getProps(),r=n[t];return r||this.visualElement.getValue(e,(n.initial?n.initial[e]:void 0)||0)}snapToCursor(e){mc(t=>{const{drag:n}=this.getProps();if(!Oc(t,n,this.currentDirection))return;const{projection:r}=this.visualElement,i=this.getAxisMotionValue(t);if(r&&r.layout){const{min:n,max:o}=r.layout.layoutBox[t];i.set(e[t]-Ss(n,o,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:e,dragConstraints:t}=this.getProps(),{projection:n}=this.visualElement;if(!ai(t)||!n||!this.constraints)return;this.stopAnimation();const r={x:0,y:0};mc(e=>{const t=this.getAxisMotionValue(e);if(t&&!1!==this.constraints){const n=t.get();r[e]=function(e,t){let n=.5;const r=ic(e),i=ic(t);return i>r?n=_r(t.min,t.max-r,e.min):r>i&&(n=_r(e.min,e.max-i,t.min)),$i(0,1,n)}({min:n,max:n},this.constraints[e])}});const{transformTemplate:i}=this.visualElement.getProps();this.visualElement.current.style.transform=i?i({},""):"none",n.root&&n.root.updateScroll(),n.updateLayout(),this.resolveConstraints(),mc(t=>{if(!Oc(t,e,null))return;const n=this.getAxisMotionValue(t),{min:i,max:o}=this.constraints[t];n.set(Ss(i,o,r[t]))})}addListeners(){if(!this.visualElement.current)return;Mc.set(this.visualElement,this);const e=Kl(this.visualElement.current,"pointerdown",e=>{const{drag:t,dragListener:n=!0}=this.getProps();t&&n&&this.start(e)}),t=()=>{const{dragConstraints:e}=this.getProps();ai(e)&&e.current&&(this.constraints=this.resolveRefConstraints())},{projection:n}=this.visualElement,r=n.addEventListener("measure",t);n&&!n.layout&&(n.root&&n.root.updateScroll(),n.updateLayout()),$r.read(t);const i=Yl(window,"resize",()=>this.scalePositionWithinConstraints()),o=n.addEventListener("didUpdate",({delta:e,hasLayoutChanged:t})=>{this.isDragging&&t&&(mc(t=>{const n=this.getAxisMotionValue(t);n&&(this.originPoint[t]+=e[t].translate,n.set(n.get()+e[t].translate))}),this.visualElement.render())});return()=>{i(),e(),r(),o&&o()}}getProps(){const e=this.visualElement.getProps(),{drag:t=!1,dragDirectionLock:n=!1,dragPropagation:r=!1,dragConstraints:i=!1,dragElastic:o=hc,dragMomentum:a=!0}=e;return{...e,drag:t,dragDirectionLock:n,dragPropagation:r,dragConstraints:i,dragElastic:o,dragMomentum:a}}}function Oc(e,t,n){return!(!0!==t&&t!==e||null!==n&&n!==e)}const jc=e=>(t,n)=>{e&&$r.postRender(()=>e(t,n))};const Lc={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function Hc(e,t){return t.max===t.min?0:e/(t.max-t.min)*100}const Fc={correct:(e,t)=>{if(!t.target)return e;if("string"==typeof e){if(!zi.test(e))return e;e=parseFloat(e)}return`${Hc(e,t.target.x)}% ${Hc(e,t.target.y)}%`}},Uc={correct:(e,{treeScale:t,projectionDelta:n})=>{const r=e,i=Ba.parse(e);if(i.length>5)return r;const o=Ba.createTransformer(e),a="number"!=typeof i[0]?1:0,s=n.x.scale*t.x,l=n.y.scale*t.y;i[0+a]/=s,i[1+a]/=l;const c=Ss(s,l,.5);return"number"==typeof i[2+a]&&(i[2+a]/=c),"number"==typeof i[3+a]&&(i[3+a]/=c),o(i)}};class zc extends y.Component{componentDidMount(){const{visualElement:e,layoutGroup:t,switchLayoutGroup:n,layoutId:r}=this.props,{projection:i}=e;var o;o=Vc,Object.assign(co,o),i&&(t.group&&t.group.add(i),n&&n.register&&r&&n.register(i),i.root.didUpdate(),i.addEventListener("animationComplete",()=>{this.safeToRemove()}),i.setOptions({...i.options,onExitComplete:()=>this.safeToRemove()})),Lc.hasEverUpdated=!0}getSnapshotBeforeUpdate(e){const{layoutDependency:t,visualElement:n,drag:r,isPresent:i}=this.props,o=n.projection;return o?(o.isPresent=i,r||e.layoutDependency!==t||void 0===t?o.willUpdate():this.safeToRemove(),e.isPresent!==i&&(i?o.promote():o.relegate()||$r.postRender(()=>{const e=o.getStack();e&&e.members.length||this.safeToRemove()})),null):null}componentDidUpdate(){const{projection:e}=this.props.visualElement;e&&(e.root.didUpdate(),ui.postRender(()=>{!e.currentAnimation&&e.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:e,layoutGroup:t,switchLayoutGroup:n}=this.props,{projection:r}=e;r&&(r.scheduleCheckAfterUnmount(),t&&t.group&&t.group.remove(r),n&&n.deregister&&n.deregister(r))}safeToRemove(){const{safeToRemove:e}=this.props;e&&e()}render(){return null}}function qc(e){const[t,n]=yr(),r=y.useContext(ur);return v.jsx(zc,{...e,layoutGroup:r,switchLayoutGroup:y.useContext(di),isPresent:t,safeToRemove:n})}const Vc={borderRadius:{...Fc,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:Fc,borderTopRightRadius:Fc,borderBottomLeftRadius:Fc,borderBottomRightRadius:Fc,boxShadow:Uc};const Bc=(e,t)=>e.depth-t.depth;class Wc{constructor(){this.children=[],this.isDirty=!1}add(e){ia(this.children,e),this.isDirty=!0}remove(e){oa(this.children,e),this.isDirty=!0}forEach(e){this.isDirty&&this.children.sort(Bc),this.isDirty=!1,this.children.forEach(e)}}const Yc=["TopLeft","TopRight","BottomLeft","BottomRight"],Gc=Yc.length,Kc=e=>"string"==typeof e?parseFloat(e):e,Qc=e=>"number"==typeof e||zi.test(e);function Xc(e,t){return void 0!==e[t]?e[t]:e.borderRadius}const Zc=eu(0,.5,Sa),Jc=eu(.5,.95,Er);function eu(e,t,n){return r=>rt?1:n(_r(e,t,r))}function tu(e,t){e.min=t.min,e.max=t.max}function nu(e,t){tu(e.x,t.x),tu(e.y,t.y)}function ru(e,t){e.translate=t.translate,e.scale=t.scale,e.originPoint=t.originPoint,e.origin=t.origin}function iu(e,t,n,r,i){return e=Sc(e-=t,1/n,r),void 0!==i&&(e=Sc(e,1/i,r)),e}function ou(e,t,[n,r,i],o,a){!function(e,t=0,n=1,r=.5,i,o=e,a=e){Ui.test(t)&&(t=parseFloat(t),t=Ss(a.min,a.max,t/100)-a.min);if("number"!=typeof t)return;let s=Ss(o.min,o.max,r);e===o&&(s-=t),e.min=iu(e.min,t,n,s,i),e.max=iu(e.max,t,n,s,i)}(e,t[n],t[r],t[i],t.scale,o,a)}const au=["x","scaleX","originX"],su=["y","scaleY","originY"];function lu(e,t,n,r){ou(e.x,t,au,n?n.x:void 0,r?r.x:void 0),ou(e.y,t,su,n?n.y:void 0,r?r.y:void 0)}function cu(e){return 0===e.translate&&1===e.scale}function uu(e){return cu(e.x)&&cu(e.y)}function du(e,t){return e.min===t.min&&e.max===t.max}function hu(e,t){return Math.round(e.min)===Math.round(t.min)&&Math.round(e.max)===Math.round(t.max)}function fu(e,t){return hu(e.x,t.x)&&hu(e.y,t.y)}function pu(e){return ic(e.x)/ic(e.y)}function gu(e,t){return e.translate===t.translate&&e.scale===t.scale&&e.originPoint===t.originPoint}class mu{constructor(){this.members=[]}add(e){ia(this.members,e),e.scheduleRender()}remove(e){if(oa(this.members,e),e===this.prevLead&&(this.prevLead=void 0),e===this.lead){const e=this.members[this.members.length-1];e&&this.promote(e)}}relegate(e){const t=this.members.findIndex(t=>e===t);if(0===t)return!1;let n;for(let r=t;r>=0;r--){const e=this.members[r];if(!1!==e.isPresent){n=e;break}}return!!n&&(this.promote(n),!0)}promote(e,t){const n=this.lead;if(e!==n&&(this.prevLead=n,this.lead=e,e.show(),n)){n.instance&&n.scheduleRender(),e.scheduleRender(),e.resumeFrom=n,t&&(e.resumeFrom.preserveOpacity=!0),n.snapshot&&(e.snapshot=n.snapshot,e.snapshot.latestValues=n.animationValues||n.latestValues),e.root&&e.root.isUpdating&&(e.isLayoutDirty=!0);const{crossfade:r}=e.options;!1===r&&n.hide()}}exitAnimationComplete(){this.members.forEach(e=>{const{options:t,resumingFrom:n}=e;t.onExitComplete&&t.onExitComplete(),n&&n.options.onExitComplete&&n.options.onExitComplete()})}scheduleRender(){this.members.forEach(e=>{e.instance&&e.scheduleRender(!1)})}removeLeadSnapshot(){this.lead&&this.lead.snapshot&&(this.lead.snapshot=void 0)}}const vu={type:"projectionFrame",totalNodes:0,resolvedTargetDeltas:0,recalculatedProjection:0},yu="undefined"!=typeof window&&void 0!==window.MotionDebug,bu=["","X","Y","Z"],wu={visibility:"hidden"};let xu=0;function ku(e,t,n,r){const{latestValues:i}=t;i[e]&&(n[e]=i[e],t.setStaticValue(e,0),r&&(r[e]=0))}function Su(e){if(e.hasCheckedOptimisedAppear=!0,e.root===e)return;const{visualElement:t}=e.options;if(!t)return;const n=fa(t);if(window.MotionHasOptimisedAnimation(n,"transform")){const{layout:t,layoutId:r}=e.options;window.MotionCancelOptimisedAnimation(n,"transform",$r,!(t||r))}const{parent:r}=e;r&&!r.hasCheckedOptimisedAppear&&Su(r)}function Tu({attachResizeListener:e,defaultParent:t,measureScroll:n,checkIsScrollRoot:r,resetTransform:i}){return class{constructor(e={},n=(null==t?void 0:t())){this.id=xu++,this.animationId=0,this.children=new Set,this.options={},this.isTreeAnimating=!1,this.isAnimationBlocked=!1,this.isLayoutDirty=!1,this.isProjectionDirty=!1,this.isSharedProjectionDirty=!1,this.isTransformDirty=!1,this.updateManuallyBlocked=!1,this.updateBlockedByResize=!1,this.isUpdating=!1,this.isSVG=!1,this.needsReset=!1,this.shouldResetTransform=!1,this.hasCheckedOptimisedAppear=!1,this.treeScale={x:1,y:1},this.eventHandlers=new Map,this.hasTreeAnimated=!1,this.updateScheduled=!1,this.scheduleUpdate=()=>this.update(),this.projectionUpdateScheduled=!1,this.checkUpdateFailed=()=>{this.isUpdating&&(this.isUpdating=!1,this.clearAllSnapshots())},this.updateProjection=()=>{this.projectionUpdateScheduled=!1,yu&&(vu.totalNodes=vu.resolvedTargetDeltas=vu.recalculatedProjection=0),this.nodes.forEach(Ru),this.nodes.forEach(Mu),this.nodes.forEach($u),this.nodes.forEach(Pu),yu&&window.MotionDebug.record(vu)},this.resolvedRelativeTargetAt=0,this.hasProjected=!1,this.isVisible=!0,this.animationProgress=0,this.sharedNodes=new Map,this.latestValues=e,this.root=n?n.root||n:this,this.path=n?[...n.path,n]:[],this.parent=n,this.depth=n?n.depth+1:0;for(let t=0;tthis.root.updateBlockedByResize=!1;e(t,()=>{this.root.updateBlockedByResize=!0,n&&n(),n=function(e,t){const n=ra.now(),r=({timestamp:i})=>{const o=i-n;o>=t&&(Or(r),e(o-t))};return $r.read(r,!0),()=>Or(r)}(r,250),Lc.hasAnimatedSinceResize&&(Lc.hasAnimatedSinceResize=!1,this.nodes.forEach(Nu))})}i&&this.root.registerSharedNode(i,this),!1!==this.options.animate&&a&&(i||o)&&this.addEventListener("didUpdate",({delta:e,hasLayoutChanged:t,hasRelativeTargetChanged:n,layout:r})=>{if(this.isTreeAnimationBlocked())return this.target=void 0,void(this.relativeTarget=void 0);const i=this.options.transition||a.getDefaultTransition()||Uu,{onLayoutAnimationStart:o,onLayoutAnimationComplete:s}=a.getProps(),l=!this.targetLayout||!fu(this.targetLayout,r)||n,c=!t&&n;if(this.options.layoutRoot||this.resumeFrom&&this.resumeFrom.instance||c||t&&(l||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0),this.setAnimationOrigin(e,c);const t={...Po(i,"layout"),onPlay:o,onComplete:s};(a.shouldReduceMotion||this.options.layoutRoot)&&(t.delay=0,t.type=!1),this.startAnimation(t)}else t||Nu(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=r})}unmount(){this.options.layoutId&&this.willUpdate(),this.root.nodes.remove(this);const e=this.getStack();e&&e.remove(this),this.parent&&this.parent.children.delete(this),this.instance=void 0,Or(this.updateProjection)}blockUpdate(){this.updateManuallyBlocked=!0}unblockUpdate(){this.updateManuallyBlocked=!1}isUpdateBlocked(){return this.updateManuallyBlocked||this.updateBlockedByResize}isTreeAnimationBlocked(){return this.isAnimationBlocked||this.parent&&this.parent.isTreeAnimationBlocked()||!1}startUpdate(){this.isUpdateBlocked()||(this.isUpdating=!0,this.nodes&&this.nodes.forEach(Ou),this.animationId++)}getTransformTemplate(){const{visualElement:e}=this.options;return e&&e.getProps().transformTemplate}willUpdate(e=!0){if(this.root.hasTreeAnimated=!0,this.root.isUpdateBlocked())return void(this.options.onExitComplete&&this.options.onExitComplete());if(window.MotionCancelOptimisedAnimation&&!this.hasCheckedOptimisedAppear&&Su(this),!this.root.isUpdating&&this.root.startUpdate(),this.isLayoutDirty)return;this.isLayoutDirty=!0;for(let i=0;i{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){!this.snapshot&&this.instance&&(this.snapshot=this.measure())}updateLayout(){if(!this.instance)return;if(this.updateScroll(),!(this.options.alwaysMeasureLayout&&this.isLead()||this.isLayoutDirty))return;if(this.resumeFrom&&!this.resumeFrom.instance)for(let n=0;nRc&&(t.x=1),t.yRc&&(t.y=1)}(this.layoutCorrected,this.treeScale,this.path,n),!t.layout||t.target||1===this.treeScale.x&&1===this.treeScale.y||(t.target=t.layout.layoutBox,t.targetWithTransforms={x:{min:0,max:0},y:{min:0,max:0}});const{target:l}=t;l?(this.projectionDelta&&this.prevProjectionDelta?(ru(this.prevProjectionDelta.x,this.projectionDelta.x),ru(this.prevProjectionDelta.y,this.projectionDelta.y)):this.createProjectionDeltas(),ac(this.projectionDelta,this.layoutCorrected,l,this.latestValues),this.treeScale.x===a&&this.treeScale.y===s&&gu(this.projectionDelta.x,this.prevProjectionDelta.x)&&gu(this.projectionDelta.y,this.prevProjectionDelta.y)||(this.hasProjected=!0,this.scheduleRender(),this.notifyListeners("projectionUpdate",l)),yu&&vu.recalculatedProjection++):this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender())}hide(){this.isVisible=!1}show(){this.isVisible=!0}scheduleRender(e=!0){var t;if(null===(t=this.options.visualElement)||void 0===t||t.scheduleRender(),e){const e=this.getStack();e&&e.scheduleRender()}this.resumingFrom&&!this.resumingFrom.instance&&(this.resumingFrom=void 0)}createProjectionDeltas(){this.prevProjectionDelta={x:{translate:0,scale:1,origin:0,originPoint:0},y:{translate:0,scale:1,origin:0,originPoint:0}},this.projectionDelta={x:{translate:0,scale:1,origin:0,originPoint:0},y:{translate:0,scale:1,origin:0,originPoint:0}},this.projectionDeltaWithTransform={x:{translate:0,scale:1,origin:0,originPoint:0},y:{translate:0,scale:1,origin:0,originPoint:0}}}setAnimationOrigin(e,t=!1){const n=this.snapshot,r=n?n.latestValues:{},i={...this.latestValues},o={x:{translate:0,scale:1,origin:0,originPoint:0},y:{translate:0,scale:1,origin:0,originPoint:0}};this.relativeParent&&this.relativeParent.options.layoutRoot||(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!t;const a={x:{min:0,max:0},y:{min:0,max:0}},s=(n?n.source:void 0)!==(this.layout?this.layout.source:void 0),l=this.getStack(),c=!l||l.members.length<=1,u=Boolean(s&&!c&&!0===this.options.crossfade&&!this.path.some(Fu));let d;this.animationProgress=0,this.mixTargetDelta=t=>{const n=t/1e3;var l,h,f,p,g,m;Lu(o.x,e.x,n),Lu(o.y,e.y,n),this.setTargetDelta(o),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(cc(a,this.layout.layoutBox,this.relativeParent.layout.layoutBox),f=this.relativeTarget,p=this.relativeTargetOrigin,g=a,m=n,Hu(f.x,p.x,g.x,m),Hu(f.y,p.y,g.y,m),d&&(l=this.relativeTarget,h=d,du(l.x,h.x)&&du(l.y,h.y))&&(this.isProjectionDirty=!1),d||(d={x:{min:0,max:0},y:{min:0,max:0}}),nu(d,this.relativeTarget)),s&&(this.animationValues=i,function(e,t,n,r,i,o){i?(e.opacity=Ss(0,void 0!==n.opacity?n.opacity:1,Zc(r)),e.opacityExit=Ss(void 0!==t.opacity?t.opacity:1,0,Jc(r))):o&&(e.opacity=Ss(void 0!==t.opacity?t.opacity:1,void 0!==n.opacity?n.opacity:1,r));for(let a=0;a{Lc.hasAnimatedSinceResize=!0,this.currentAnimation=function(e,t,n){const r=Si(e)?e:ua(e);return r.start(Dl("",r,t,n)),r.animation}(0,1e3,{...e,onUpdate:t=>{this.mixTargetDelta(t),e.onUpdate&&e.onUpdate(t)},onComplete:()=>{e.onComplete&&e.onComplete(),this.completeAnimation()}}),this.resumingFrom&&(this.resumingFrom.currentAnimation=this.currentAnimation),this.pendingAnimation=void 0})}completeAnimation(){this.resumingFrom&&(this.resumingFrom.currentAnimation=void 0,this.resumingFrom.preserveOpacity=void 0);const e=this.getStack();e&&e.exitAnimationComplete(),this.resumingFrom=this.currentAnimation=this.animationValues=void 0,this.notifyListeners("animationComplete")}finishAnimation(){this.currentAnimation&&(this.mixTargetDelta&&this.mixTargetDelta(1e3),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const e=this.getLead();let{targetWithTransforms:t,target:n,layout:r,latestValues:i}=e;if(t&&n&&r){if(this!==e&&this.layout&&r&&Bu(this.options.animationType,this.layout.layoutBox,r.layoutBox)){n=this.target||{x:{min:0,max:0},y:{min:0,max:0}};const t=ic(this.layout.layoutBox.x);n.x.min=e.target.x.min,n.x.max=n.x.min+t;const r=ic(this.layout.layoutBox.y);n.y.min=e.target.y.min,n.y.max=n.y.min+r}nu(t,n),Ic(t,i),ac(this.projectionDeltaWithTransform,this.layoutCorrected,t,i)}}registerSharedNode(e,t){this.sharedNodes.has(e)||this.sharedNodes.set(e,new mu);this.sharedNodes.get(e).add(t);const n=t.options.initialPromotionConfig;t.promote({transition:n?n.transition:void 0,preserveFollowOpacity:n&&n.shouldPreserveFollowOpacity?n.shouldPreserveFollowOpacity(t):void 0})}isLead(){const e=this.getStack();return!e||e.lead===this}getLead(){var e;const{layoutId:t}=this.options;return t&&(null===(e=this.getStack())||void 0===e?void 0:e.lead)||this}getPrevLead(){var e;const{layoutId:t}=this.options;return t?null===(e=this.getStack())||void 0===e?void 0:e.prevLead:void 0}getStack(){const{layoutId:e}=this.options;if(e)return this.root.sharedNodes.get(e)}promote({needsReset:e,transition:t,preserveFollowOpacity:n}={}){const r=this.getStack();r&&r.promote(this,n),e&&(this.projectionDelta=void 0,this.needsReset=!0),t&&this.setOptions({transition:t})}relegate(){const e=this.getStack();return!!e&&e.relegate(this)}resetSkewAndRotation(){const{visualElement:e}=this.options;if(!e)return;let t=!1;const{latestValues:n}=e;if((n.z||n.rotate||n.rotateX||n.rotateY||n.rotateZ||n.skewX||n.skewY)&&(t=!0),!t)return;const r={};n.z&&ku("z",e,r,this.animationValues);for(let i=0;i{var t;return null===(t=e.currentAnimation)||void 0===t?void 0:t.stop()}),this.root.nodes.forEach(Du),this.root.sharedNodes.clear()}}}function Eu(e){e.updateLayout()}function Cu(e){var t;const n=(null===(t=e.resumeFrom)||void 0===t?void 0:t.snapshot)||e.snapshot;if(e.isLead()&&e.layout&&n&&e.hasListeners("didUpdate")){const{layoutBox:t,measuredBox:r}=e.layout,{animationType:i}=e.options,o=n.source!==e.layout.source;"size"===i?mc(e=>{const r=o?n.measuredBox[e]:n.layoutBox[e],i=ic(r);r.min=t[e].min,r.max=r.min+i}):Bu(i,n.layoutBox,t)&&mc(r=>{const i=o?n.measuredBox[r]:n.layoutBox[r],a=ic(t[r]);i.max=i.min+a,e.relativeTarget&&!e.currentAnimation&&(e.isProjectionDirty=!0,e.relativeTarget[r].max=e.relativeTarget[r].min+a)});const a={x:{translate:0,scale:1,origin:0,originPoint:0},y:{translate:0,scale:1,origin:0,originPoint:0}};ac(a,t,n.layoutBox);const s={x:{translate:0,scale:1,origin:0,originPoint:0},y:{translate:0,scale:1,origin:0,originPoint:0}};o?ac(s,e.applyTransform(r,!0),n.measuredBox):ac(s,t,n.layoutBox);const l=!uu(a);let c=!1;if(!e.resumeFrom){const r=e.getClosestProjectingParent();if(r&&!r.resumeFrom){const{snapshot:i,layout:o}=r;if(i&&o){const a={x:{min:0,max:0},y:{min:0,max:0}};cc(a,n.layoutBox,i.layoutBox);const s={x:{min:0,max:0},y:{min:0,max:0}};cc(s,t,o.layoutBox),fu(a,s)||(c=!0),r.options.layoutRoot&&(e.relativeTarget=s,e.relativeTargetOrigin=a,e.relativeParent=r)}}}e.notifyListeners("didUpdate",{layout:t,snapshot:n,delta:s,layoutDelta:a,hasLayoutChanged:l,hasRelativeTargetChanged:c})}else if(e.isLead()){const{onExitComplete:t}=e.options;t&&t()}e.options.transition=void 0}function Ru(e){yu&&vu.totalNodes++,e.parent&&(e.isProjecting()||(e.isProjectionDirty=e.parent.isProjectionDirty),e.isSharedProjectionDirty||(e.isSharedProjectionDirty=Boolean(e.isProjectionDirty||e.parent.isProjectionDirty||e.parent.isSharedProjectionDirty)),e.isTransformDirty||(e.isTransformDirty=e.parent.isTransformDirty))}function Pu(e){e.isProjectionDirty=e.isSharedProjectionDirty=e.isTransformDirty=!1}function _u(e){e.clearSnapshot()}function Du(e){e.clearMeasurements()}function Iu(e){e.isLayoutDirty=!1}function Au(e){const{visualElement:t}=e.options;t&&t.getProps().onBeforeLayoutMeasure&&t.notify("BeforeLayoutMeasure"),e.resetTransform()}function Nu(e){e.finishAnimation(),e.targetDelta=e.relativeTarget=e.target=void 0,e.isProjectionDirty=!0}function Mu(e){e.resolveTargetDelta()}function $u(e){e.calcProjection()}function Ou(e){e.resetSkewAndRotation()}function ju(e){e.removeLeadSnapshot()}function Lu(e,t,n){e.translate=Ss(t.translate,0,n),e.scale=Ss(t.scale,1,n),e.origin=t.origin,e.originPoint=t.originPoint}function Hu(e,t,n,r){e.min=Ss(t.min,n.min,r),e.max=Ss(t.max,n.max,r)}function Fu(e){return e.animationValues&&void 0!==e.animationValues.opacityExit}const Uu={duration:.45,ease:[.4,0,.1,1]},zu=e=>"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(e),qu=zu("applewebkit/")&&!zu("chrome/")?Math.round:Er;function Vu(e){e.min=qu(e.min),e.max=qu(e.max)}function Bu(e,t,n){return"position"===e||"preserve-aspect"===e&&(r=pu(t),i=pu(n),o=.2,!(Math.abs(r-i)<=o));var r,i,o}function Wu(e){var t;return e!==e.root&&(null===(t=e.scroll)||void 0===t?void 0:t.wasRoot)}const Yu=Tu({attachResizeListener:(e,t)=>Yl(e,"resize",t),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),Gu={current:void 0},Ku=Tu({measureScroll:e=>({x:e.scrollLeft,y:e.scrollTop}),defaultParent:()=>{if(!Gu.current){const e=new Yu({});e.mount(window),e.setOptions({layoutScroll:!0}),Gu.current=e}return Gu.current},resetTransform:(e,t)=>{e.style.transform=void 0!==t?t:"none"},checkIsScrollRoot:e=>Boolean("fixed"===window.getComputedStyle(e).position)}),Qu={pan:{Feature:class extends Vl{constructor(){super(...arguments),this.removePointerDownListener=Er}onPointerDown(e){this.session=new Xl(e,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:Nc(this.node)})}createPanHandlers(){const{onPanSessionStart:e,onPanStart:t,onPan:n,onPanEnd:r}=this.node.getProps();return{onSessionStart:jc(e),onStart:jc(t),onMove:n,onEnd:(e,t)=>{delete this.session,r&&$r.postRender(()=>r(e,t))}}}mount(){this.removePointerDownListener=Kl(this.node.current,"pointerdown",e=>this.onPointerDown(e))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}}},drag:{Feature:class extends Vl{constructor(e){super(e),this.removeGroupControls=Er,this.removeListeners=Er,this.controls=new $c(e)}mount(){const{dragControls:e}=this.node.getProps();e&&(this.removeGroupControls=e.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||Er}unmount(){this.removeGroupControls(),this.removeListeners()}},ProjectionNode:Ku,MeasureLayout:qc}};function Xu(e,t,n){const{props:r}=e;e.animationState&&r.whileHover&&e.animationState.setActive("whileHover","Start"===n);const i=r["onHover"+n];i&&$r.postRender(()=>i(t,Gl(t)))}function Zu(e,t,n){const{props:r}=e;e.animationState&&r.whileTap&&e.animationState.setActive("whileTap","Start"===n);const i=r["onTap"+("End"===n?"":n)];i&&$r.postRender(()=>i(t,Gl(t)))}const Ju=new WeakMap,ed=new WeakMap,td=e=>{const t=Ju.get(e.target);t&&t(e)},nd=e=>{e.forEach(td)};function rd(e,t,n){const r=function({root:e,...t}){const n=e||document;ed.has(n)||ed.set(n,{});const r=ed.get(n),i=JSON.stringify(t);return r[i]||(r[i]=new IntersectionObserver(nd,{root:e,...t})),r[i]}(t);return Ju.set(e,n),r.observe(e),()=>{Ju.delete(e),r.unobserve(e)}}const id={some:0,all:1};const od={inView:{Feature:class extends Vl{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.unmount();const{viewport:e={}}=this.node.getProps(),{root:t,margin:n,amount:r="some",once:i}=e,o={root:t?t.current:void 0,rootMargin:n,threshold:"number"==typeof r?r:id[r]};return rd(this.node.current,o,e=>{const{isIntersecting:t}=e;if(this.isInView===t)return;if(this.isInView=t,i&&!t&&this.hasEnteredView)return;t&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",t);const{onViewportEnter:n,onViewportLeave:r}=this.node.getProps(),o=t?n:r;o&&o(e)})}mount(){this.startObserver()}update(){if("undefined"==typeof IntersectionObserver)return;const{props:e,prevProps:t}=this.node;["amount","margin","root"].some(function({viewport:e={}},{viewport:t={}}={}){return n=>e[n]!==t[n]}(e,t))&&this.startObserver()}unmount(){}}},tap:{Feature:class extends Vl{mount(){const{current:e}=this.node;e&&(this.unmount=Jo(e,e=>(Zu(this.node,e,"Start"),(e,{success:t})=>Zu(this.node,e,t?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}},focus:{Feature:class extends Vl{constructor(){super(...arguments),this.isActive=!1}onFocus(){let e=!1;try{e=this.node.current.matches(":focus-visible")}catch(t){e=!0}e&&this.node.animationState&&(this.node.animationState.setActive("whileFocus",!0),this.isActive=!0)}onBlur(){this.isActive&&this.node.animationState&&(this.node.animationState.setActive("whileFocus",!1),this.isActive=!1)}mount(){this.unmount=Is(Yl(this.node.current,"focus",()=>this.onFocus()),Yl(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}},hover:{Feature:class extends Vl{mount(){const{current:e}=this.node;e&&(this.unmount=function(e,t,n={}){const[r,i,o]=Vo(e,n),a=Bo(e=>{const{target:n}=e,r=t(e);if("function"!=typeof r||!n)return;const o=Bo(e=>{r(e),n.removeEventListener("pointerleave",o)});n.addEventListener("pointerleave",o,i)});return r.forEach(e=>{e.addEventListener("pointerenter",a,i)}),o}(e,e=>(Xu(this.node,e,"Start"),e=>Xu(this.node,e,"End"))))}unmount(){}}}},ad={layout:{ProjectionNode:Ku,MeasureLayout:qc}},sd={current:null},ld={current:!1};const cd=[...ms,Oa,Ba],ud=new WeakMap;var dd={};var hd={};const fd=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class pd{scrapeMotionValuesFromProps(e,t,n){return{}}constructor({parent:e,props:t,presenceContext:n,reducedMotionConfig:r,blockInitialAnimation:i,visualState:o},a={}){this.current=null,this.children=new Set,this.isVariantNode=!1,this.isControllingVariants=!1,this.shouldReduceMotion=null,this.values=new Map,this.KeyframeResolver=ds,this.features={},this.valueSubscriptions=new Map,this.prevMotionValues={},this.events={},this.propEventSubscriptions={},this.notifyUpdate=()=>this.notify("Update",this.latestValues),this.render=()=>{this.current&&(this.triggerBuild(),this.renderInstance(this.current,this.renderState,this.props.style,this.projection))},this.renderScheduledAt=0,this.scheduleRender=()=>{const e=ra.now();this.renderScheduledAtthis.bindToMotionValue(t,e)),ld.current||function(){if(ld.current=!0,xr)if(window.matchMedia){const e=window.matchMedia("(prefers-reduced-motion)"),t=()=>sd.current=e.matches;e.addListener(t),t()}else sd.current=!1}(),this.shouldReduceMotion="never"!==this.reducedMotionConfig&&("always"===this.reducedMotionConfig||sd.current),"production"!==hd.NODE_ENV&&Yr(!0!==this.shouldReduceMotion,"You have Reduced Motion enabled on your device. Animations may not appear as expected."),this.parent&&this.parent.children.add(this),this.update(this.props,this.presenceContext)}unmount(){ud.delete(this.current),this.projection&&this.projection.unmount(),Or(this.notifyUpdate),Or(this.render),this.valueSubscriptions.forEach(e=>e()),this.valueSubscriptions.clear(),this.removeFromVariantTree&&this.removeFromVariantTree(),this.parent&&this.parent.children.delete(this);for(const e in this.events)this.events[e].clear();for(const e in this.features){const t=this.features[e];t&&(t.unmount(),t.isMounted=!1)}this.current=null}bindToMotionValue(e,t){this.valueSubscriptions.has(e)&&this.valueSubscriptions.get(e)();const n=Pi.has(e),r=t.on("change",t=>{this.latestValues[e]=t,this.props.onUpdate&&$r.preRender(this.notifyUpdate),n&&this.projection&&(this.projection.isTransformDirty=!0)}),i=t.on("renderRequest",this.scheduleRender);let o;window.MotionCheckAppearSync&&(o=window.MotionCheckAppearSync(this,e,t)),this.valueSubscriptions.set(e,()=>{r(),i(),o&&o(),t.owner&&t.stop()})}sortNodePosition(e){return this.current&&this.sortInstanceNodePosition&&this.type===e.type?this.sortInstanceNodePosition(this.current,e.current):0}updateFeatures(){let e="animation";for(e in Ur){const t=Ur[e];if(!t)continue;const{isEnabled:n,Feature:r}=t;if(!this.features[e]&&r&&n(this.props)&&(this.features[e]=new r(this)),this.features[e]){const t=this.features[e];t.isMounted?t.update():(t.mount(),t.isMounted=!0)}}}triggerBuild(){this.build(this.renderState,this.latestValues,this.props)}measureViewportBox(){return this.current?this.measureInstanceViewportBox(this.current,this.props):{x:{min:0,max:0},y:{min:0,max:0}}}getStaticValue(e){return this.latestValues[e]}setStaticValue(e,t){this.latestValues[e]=t}update(e,t){(e.transformTemplate||this.props.transformTemplate)&&this.scheduleRender(),this.prevProps=this.props,this.props=e,this.prevPresenceContext=this.presenceContext,this.presenceContext=t;for(let n=0;nt.variantChildren.delete(e)}addValue(e,t){const n=this.values.get(e);t!==n&&(n&&this.removeValue(e),this.bindToMotionValue(e,t),this.values.set(e,t),this.latestValues[e]=t.get())}removeValue(e){this.values.delete(e);const t=this.valueSubscriptions.get(e);t&&(t(),this.valueSubscriptions.delete(e)),delete this.latestValues[e],this.removeValueFromRenderState(e,this.renderState)}hasValue(e){return this.values.has(e)}getValue(e,t){if(this.props.values&&this.props.values[e])return this.props.values[e];let n=this.values.get(e);return void 0===n&&void 0!==t&&(n=ua(null===t?void 0:t,{owner:this}),this.addValue(e,n)),n}readValue(e,t){var n;let r=void 0===this.latestValues[e]&&this.current?null!==(n=this.getBaseTargetFromProps(this.props,e))&&void 0!==n?n:this.readValueFromInstance(this.current,e,this.options):this.latestValues[e];var i;return null!=r&&("string"==typeof r&&(hs(r)||Ea(r))?r=parseFloat(r):(i=r,!cd.find(gs(i))&&Ba.test(t)&&(r=Za(e,t))),this.setBaseTarget(e,Si(r)?r.get():r)),Si(r)?r.get():r}setBaseTarget(e,t){this.baseTarget[e]=t}getBaseTarget(e){var t;const{initial:n}=this.props;let r;if("string"==typeof n||"object"==typeof n){const i=wi(this.props,n,null===(t=this.presenceContext)||void 0===t?void 0:t.custom);i&&(r=i[e])}if(n&&void 0!==r)return r;const i=this.getBaseTargetFromProps(this.props,e);return void 0===i||Si(i)?void 0!==this.initialValues[e]&&void 0===r?void 0:this.baseTarget[e]:i}on(e,t){return this.events[e]||(this.events[e]=new aa),this.events[e].add(t)}notify(e,...t){this.events[e]&&this.events[e].notify(...t)}}class gd extends pd{constructor(){super(...arguments),this.KeyframeResolver=ys}sortInstanceNodePosition(e,t){return 2&e.compareDocumentPosition(t)?1:-1}getBaseTargetFromProps(e,t){return e.style?e.style[t]:void 0}removeValueFromRenderState(e,{vars:t,style:n}){delete t[e],delete n[e]}handleChildMotionValue(){this.childSubscription&&(this.childSubscription(),delete this.childSubscription);const{children:e}=this.props;Si(e)&&(this.childSubscription=e.on("change",e=>{this.current&&(this.current.textContent=`${e}`)}))}}class md extends gd{constructor(){super(...arguments),this.type="html",this.renderInstance=ao}readValueFromInstance(e,t){if(Pi.has(t)){const e=Xa(t);return e&&e.default||0}{const r=(n=e,window.getComputedStyle(n)),i=(Di(t)?r.getPropertyValue(t):r[t])||0;return"string"==typeof i?i.trim():i}var n}measureInstanceViewportBox(e,{transformPagePoint:t}){return Ac(e,t)}build(e,t,n){Zi(e,t,n.transformTemplate)}scrapeMotionValuesFromProps(e,t,n){return ho(e,t,n)}}class vd extends gd{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=gc}getBaseTargetFromProps(e,t){return e[t]}readValueFromInstance(e,t){if(Pi.has(t)){const e=Xa(t);return e&&e.default||0}return t=so.has(t)?t:li(t),e.getAttribute(t)}scrapeMotionValuesFromProps(e,t,n){return fo(e,t,n)}build(e,t,n){no(e,t,this.isSVGTag,n.transformTemplate)}renderInstance(e,t,n,r){lo(e,t,0,r)}mount(e){this.isSVGTag=oo(e.tagName),super.mount(e)}}const yd=Kr(ko({...Wl,...od,...Qu,...ad},(e,t)=>yi(e)?new vd(t):new md(t,{allowProjection:e!==y.Fragment})));function bd({from:e,onAnswer:t,onReject:n}){const r=e;return v.jsxs(yd.div,{initial:{opacity:0,y:-10},animate:{opacity:1,y:0},className:"bg-gradient-to-r from-blue-900 to-blue-800 border-b border-blue-700 px-4 py-4",children:[v.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[v.jsx("div",{className:"w-10 h-10 bg-blue-600 rounded-full flex items-center justify-center",children:v.jsx(ce,{className:"w-5 h-5 text-white"})}),v.jsxs("div",{children:[v.jsx("p",{className:"text-blue-300 text-xs",children:"Chamada recebida"}),v.jsx("p",{className:"text-white font-semibold text-sm truncate max-w-[180px]",children:r})]})]}),v.jsxs("div",{className:"flex gap-3",children:[v.jsxs("button",{onClick:t,className:"flex-1 bg-green-500 hover:bg-green-600 text-white rounded-[15px] py-2.5 flex items-center justify-center gap-2 transition-colors font-medium text-sm",children:[v.jsx(oe,{className:"w-4 h-4"}),"Atender"]}),v.jsxs("button",{onClick:n,className:"flex-1 bg-red-500 hover:bg-red-600 text-white rounded-[15px] py-2.5 flex items-center justify-center gap-2 transition-colors font-medium text-sm",children:[v.jsx(re,{className:"w-4 h-4"}),"Recusar"]})]})]})}function wd({open:e,step:t,consultTarget:n,consultEstablished:r,onDial:i,onTransfer:o,onCancel:a}){const[s,l]=y.useState("");if(!e)return null;const c=()=>{s.trim()&&i(s.trim())};return v.jsx(Tr,{children:v.jsx(yd.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:v.jsxs(yd.div,{initial:{scale:.92,opacity:0},animate:{scale:1,opacity:1},exit:{scale:.92,opacity:0},className:"bg-gray-900 border border-gray-700 rounded-[15px] w-full max-w-xs shadow-2xl overflow-hidden",children:[v.jsxs("div",{className:"bg-gradient-to-r from-purple-700 to-purple-600 px-4 py-4 flex items-center gap-3",children:[v.jsx("div",{className:"w-9 h-9 bg-white/20 rounded-full flex items-center justify-center",children:v.jsx(ee,{className:"w-5 h-5 text-white"})}),v.jsxs("div",{className:"flex-1",children:[v.jsx("p",{className:"text-white font-semibold text-sm",children:"Transferência Assistida"}),v.jsxs("p",{className:"text-purple-200 text-xs",children:["dial"===t&&"Informe o destino","connecting"===t&&`Chamando: ${n}...`,"consulting"===t&&`Consultando: ${n}`,"transferring"===t&&"Transferindo..."]})]}),v.jsx("button",{onClick:a,className:"text-purple-200 hover:text-white",children:v.jsx(ue,{className:"w-5 h-5"})})]}),v.jsxs("div",{className:"p-4 space-y-4",children:["dial"===t&&v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"space-y-1",children:[v.jsx("label",{className:"text-gray-400 text-xs uppercase tracking-wider",children:"Destino da transferência"}),v.jsx("input",{type:"text",value:s,onChange:e=>l(e.target.value),onKeyDown:e=>{"Enter"===e.key?c():/^\d$|[\*\#]/.test(e.key)&&Fn(e.key,80)},placeholder:"Ramal ou número",autoFocus:!0,className:"w-full bg-gray-800 border border-gray-700 rounded-lg px-3 py-2.5 text-white text-sm placeholder-gray-500 focus:outline-none focus:border-purple-500 transition-colors"})]}),v.jsxs("div",{className:"bg-gray-800 rounded-lg p-3 text-xs text-gray-400 space-y-1",children:[v.jsx("p",{className:"text-gray-300 font-medium text-xs",children:"Como funciona:"}),v.jsx("p",{children:"1. A chamada atual entra em espera"}),v.jsx("p",{children:"2. Você liga para o destino"}),v.jsxs("p",{children:["3. Após consultar, clica em ",v.jsx("span",{className:"text-purple-300",children:"Transferir"})]})]}),v.jsxs("div",{className:"flex gap-2",children:[v.jsx("button",{onClick:a,className:"flex-1 bg-gray-700 hover:bg-gray-600 text-gray-300 rounded-[15px] py-2.5 text-sm font-medium transition-colors",children:"Cancelar"}),v.jsxs("button",{onClick:c,disabled:!s.trim(),className:"flex-1 bg-purple-600 hover:bg-purple-700 disabled:bg-gray-700 disabled:text-gray-500 text-white rounded-[15px] py-2.5 text-sm font-medium transition-colors flex items-center justify-center gap-2",children:[v.jsx(oe,{className:"w-4 h-4"}),"Consultar"]})]})]}),"connecting"===t&&v.jsxs("div",{className:"flex flex-col items-center gap-3 py-4",children:[v.jsx(Q,{className:"w-8 h-8 text-purple-400 animate-spin"}),v.jsxs("p",{className:"text-gray-300 text-sm",children:["Chamando ",n,"..."]}),v.jsx("button",{onClick:a,className:"mt-2 bg-gray-700 hover:bg-gray-600 text-gray-300 rounded-[15px] px-5 py-2 text-sm font-medium transition-colors",children:"Cancelar"})]}),"consulting"===t&&v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"bg-gray-800 rounded-[15px] p-4 space-y-2",children:[v.jsxs("div",{className:"flex items-center gap-2",children:[v.jsx("div",{className:"w-2 h-2 bg-green-400 rounded-full animate-pulse"}),v.jsx("span",{className:"text-gray-400 text-xs",children:"Em consulta com"})]}),v.jsx("p",{className:"text-white font-semibold truncate",children:n}),v.jsx("p",{className:"text-gray-500 text-xs",children:"Chamada original em espera"})]}),v.jsxs("p",{className:"text-gray-400 text-xs text-center",children:["Quando pronto, clique em ",v.jsx("span",{className:"text-purple-300",children:"Transferir"})," para conectar as duas chamadas."]}),v.jsxs("div",{className:"flex gap-2",children:[v.jsx("button",{onClick:a,className:"flex-1 bg-gray-700 hover:bg-gray-600 text-gray-300 rounded-[15px] py-2.5 text-sm font-medium transition-colors",children:"Cancelar"}),v.jsxs("button",{onClick:o,className:"flex-1 bg-green-600 hover:bg-green-700 text-white rounded-[15px] py-2.5 text-sm font-medium transition-colors flex items-center justify-center gap-2",children:[v.jsx(q,{className:"w-4 h-4"}),"Transferir"]})]})]}),"transferring"===t&&v.jsxs("div",{className:"flex flex-col items-center gap-3 py-4",children:[v.jsx(Q,{className:"w-8 h-8 text-purple-400 animate-spin"}),v.jsx("p",{className:"text-gray-300 text-sm",children:"Executando transferência..."})]})]})]})})})}function xd(e){const t=new Date(e),n=new Date,r=new Date(n.getFullYear(),n.getMonth(),n.getDate()),i=new Date(r);i.setDate(i.getDate()-1);const o=new Date(t.getFullYear(),t.getMonth(),t.getDate()),a=o.getTime()===r.getTime(),s=o.getTime()===i.getTime(),l=t.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"});if(a)return`Hoje ${l}`;if(s)return`Ontem ${l}`;return`${t.toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit",year:"2-digit"})} ${l}`}function kd({direction:e,status:t}){const n="w-4 h-4";return"missed"===t||"rejected"===t?v.jsx(ne,{className:`${n} text-red-400`}):"inbound"===e?v.jsx(te,{className:`${n} text-green-400`}):v.jsx(ie,{className:`${n} text-blue-400`})}function Sd({onSelect:e,onCallDirect:t,canCall:n}){const r=An.getCallLogs();return r.length?v.jsx("div",{className:"flex-1 overflow-y-auto divide-y divide-gray-800",children:r.map((r,i)=>{return v.jsxs("div",{className:"flex items-center gap-3 px-4 py-3 hover:bg-white/5 transition-colors cursor-pointer",onClick:()=>null==e?void 0:e(r.number),children:[v.jsx(kd,{direction:r.direction,status:r.status}),v.jsxs("div",{className:"flex-1 min-w-0",children:[v.jsx("p",{className:"text-white text-sm truncate font-medium",children:r.number}),v.jsx("p",{className:"text-slate-500 text-xs",children:xd(r.startedAt)})]}),v.jsx("span",{className:"text-slate-500 text-xs whitespace-nowrap mr-1",children:"answered"===r.status?(o=r.duration,`${Math.floor(o/60).toString().padStart(2,"0")}:${(o%60).toString().padStart(2,"0")}`):"missed"===r.status?"Perdida":"Recusada"}),v.jsx("button",{onClick:e=>{e.stopPropagation(),null==t||t(r.number)},disabled:!n,className:"w-7 h-7 bg-emerald-600 hover:bg-emerald-500 disabled:bg-gray-700 disabled:opacity-50 rounded-full flex items-center justify-center flex-shrink-0 transition-colors",title:"Ligar",children:v.jsx(oe,{className:"w-3.5 h-3.5 text-white"})})]},i);var o})}):v.jsx("div",{className:"flex-1 flex items-center justify-center text-slate-500 text-sm",children:"Sem chamadas recentes"})}function Td({onBack:e}){const[t,n]=y.useState(er.getLogs());return v.jsxs("div",{className:"flex flex-col h-full bg-gray-900",children:[v.jsxs("div",{className:"px-4 py-4 border-b border-gray-800 flex items-center justify-between flex-shrink-0",children:[v.jsxs("div",{className:"flex items-center gap-2",children:[e&&v.jsx("button",{onClick:e,className:"text-gray-400 hover:text-white transition-colors p-1",title:"Voltar",children:v.jsx(V,{size:16})}),v.jsxs("h3",{className:"text-white font-semibold text-sm",children:["Logs (",t.length,")"]})]}),v.jsxs("div",{className:"flex gap-2",children:[v.jsx("button",{onClick:()=>{n(er.getLogs())},className:"text-gray-400 hover:text-white text-xs px-2 py-1 bg-gray-800 hover:bg-gray-700 rounded transition-colors",children:"Atualizar"}),v.jsxs("button",{onClick:()=>{const e=er.exportLogs();navigator.clipboard.writeText(e).then(()=>{alert("Logs copiados para a área de transferência")})},disabled:0===t.length,className:"text-gray-400 hover:text-white disabled:opacity-40 text-xs px-2 py-1 bg-gray-800 hover:bg-gray-700 rounded transition-colors flex items-center gap-1",children:[v.jsx(K,{size:12}),"Copiar"]}),v.jsx("button",{onClick:()=>{confirm("Tem certeza que deseja limpar todos os logs?")&&(er.clearLogs(),n([]))},disabled:0===t.length,className:"text-gray-400 hover:text-red-400 disabled:opacity-40 text-xs px-2 py-1 bg-gray-800 hover:bg-gray-700 rounded transition-colors flex items-center gap-1",children:v.jsx(le,{size:12})})]})]}),v.jsx("div",{className:"px-4 py-4",children:0===t.length?v.jsx("p",{className:"text-gray-500 text-xs text-center py-8",children:"Nenhum log registrado"}):v.jsx("div",{className:"space-y-2",children:t.map((e,t)=>v.jsxs("div",{className:"text-xs font-mono text-gray-400 break-words",children:[v.jsxs("span",{className:"text-gray-600",children:["[",e.timestamp,"]"]})," ",v.jsx("span",{className:"ERROR"===e.level?"text-red-400":"text-yellow-400",children:e.level}),": ",v.jsx("span",{className:"text-gray-300",children:e.message})]},t))})})]})}function Ed({connectionStatus:e,callStatus:t,isMuted:n,isOnHold:r,incomingCallInfo:i,callDuration:o,dialInput:a,setDialInput:s,dtmfLog:l,transferModal:c,setTransferModal:u,transferStep:d,setTransferStep:h,transferTarget:f,setTransferTarget:p,consultEstablished:g,setConsultEstablished:m,blindTransferModal:b,setBlindTransferModal:w,blindTransferTarget:x,setBlindTransferTarget:k,settings:S,onConnect:T,onDisconnect:E,onCall:C,onHangup:R,onAnswer:P,onReject:_,onToggleMute:D,onToggleHold:I,onDialPadPress:A,onTransfer:N,onBlindTransfer:M,onTransferDial:$,onTransferExecute:O,onTransferCancel:j,onBlindTransferExecute:L,onClose:H,isConnecting:F,onTabChange:U,onCallDirect:z}){const[q,V]=y.useState("dialpad"),B=y.useRef(null);y.useEffect(()=>{"dialpad"===q&&B.current&&B.current.focus()},[q]);const W=e=>{V(e),null==U||U(e)};return v.jsxs("div",{className:"bg-gray-900 flex-1 border-t border-gray-800 relative w-full flex flex-col min-h-0",children:[v.jsx(cr,{connectionStatus:e,callStatus:t,callDuration:o,aor:S.aor,onDisconnect:()=>{An.setManualDisconnect(!0),E()},onConnect:async()=>{const e=await An.mergeConfig({});e&&e.server&&e.username&&e.domain&&e.password&&(An.setManualDisconnect(!1),await T(e),W("dialpad"))}}),v.jsxs("div",{className:"flex gap-0.5 px-3 py-2 bg-gray-900 border-b border-gray-800 flex-shrink-0",children:[v.jsxs("button",{onClick:()=>W("dialpad"),className:"flex-1 flex flex-col items-center gap-0.5 py-1.5 rounded-[15px] text-[10px] font-medium transition-all "+("dialpad"===q?"bg-white/10 text-white":"text-slate-500 hover:text-slate-300 hover:bg-white/5"),children:[v.jsx(oe,{className:"w-3.5 h-3.5"}),"Teclado"]}),v.jsxs("button",{onClick:()=>W("recentes"),className:"flex-1 flex flex-col items-center gap-0.5 py-1.5 rounded-[15px] text-[10px] font-medium transition-all "+("recentes"===q?"bg-white/10 text-white":"text-slate-500 hover:text-slate-300 hover:bg-white/5"),children:[v.jsx(G,{className:"w-3.5 h-3.5"}),"Recentes"]}),v.jsxs("button",{onClick:()=>W("settings"),className:"flex-1 flex flex-col items-center gap-0.5 py-1.5 rounded-[15px] text-[10px] font-medium transition-all "+("settings"===q?"bg-white/10 text-white":"text-slate-500 hover:text-slate-300 hover:bg-white/5"),children:[v.jsx(se,{className:"w-3.5 h-3.5"}),"Config"]})]}),"settings"===q&&v.jsx("div",{className:"flex-1 min-h-0",children:v.jsx(ar,{settings:S,onConnect:e=>{T(e),W("dialpad")},onSave:async e=>{await An.setSipConfig(e)},isConnecting:F,hideHeader:!0,onShowLogs:()=>W("logs")})}),"recentes"===q&&v.jsx("div",{className:"flex-1 overflow-y-auto min-h-0",children:v.jsx(Sd,{onSelect:e=>{s(e??""),W("dialpad")},onCallDirect:e=>{W("dialpad"),null==z||z(e)},canCall:"registered"===e&&"idle"===t})}),"logs"===q&&v.jsx("div",{className:"flex-1 overflow-y-auto min-h-0",children:v.jsx(Td,{onBack:()=>W("settings")})}),"dialpad"===q&&v.jsxs(v.Fragment,{children:[i&&"ringing"===t&&v.jsx(bd,{from:i.from,onAnswer:P,onReject:_}),v.jsxs("div",{className:"px-4 pt-4 pb-2 flex-1 relative",children:[v.jsxs("div",{className:"bg-gray-800 rounded-[15px] px-4 py-3 mb-4 flex items-center gap-2",children:[v.jsx("input",{ref:B,type:"tel",value:a,onChange:e=>s(e.target.value.replace(/[^\d\*\#]/g,"")),onKeyDown:n=>{"Enter"===n.key?a.trim()&&"registered"===e&&"idle"===t&&C():/^\d$|[\*\#]/.test(n.key)&&"active"!==t&&Fn(n.key,80)},placeholder:"Digite o número",className:"flex-1 bg-transparent text-white text-lg outline-none placeholder-gray-500",disabled:"active"===t||"calling"===t,inputMode:"numeric"}),a&&v.jsxs(v.Fragment,{children:[v.jsx("button",{onClick:()=>s(a.slice(0,-1)),disabled:"active"===t||"calling"===t,className:"text-gray-400 hover:text-white disabled:opacity-40 text-xs px-2 py-1 bg-gray-700 hover:bg-gray-600 rounded transition-colors",title:"Backspace",children:"⌫"}),v.jsx("button",{onClick:()=>s(""),disabled:"active"===t||"calling"===t,className:"text-gray-400 hover:text-white disabled:opacity-40 text-sm transition-colors",children:"✕"})]})]}),l&&"active"===t&&v.jsx("div",{className:"text-center text-gray-400 text-sm mb-3 tracking-widest",children:l}),v.jsx(ir,{onPress:A,disabled:"calling"===t||"ringing"===t}),v.jsx(or,{callStatus:t,isMuted:n,isOnHold:r,onCall:C,onHangup:R,onToggleMute:D,onToggleHold:I,onTransfer:N,onBlindTransfer:M,canCall:"registered"===e&&!!a.trim()}),b&&v.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:v.jsxs("div",{className:"bg-gray-900 border border-gray-700 rounded-[15px] w-full max-w-xs shadow-2xl overflow-hidden",children:[v.jsxs("div",{className:"bg-gradient-to-r from-blue-700 to-blue-600 px-4 py-4 flex items-center gap-3",children:[v.jsx("div",{className:"w-9 h-9 bg-white/20 rounded-full flex items-center justify-center",children:v.jsx("svg",{className:"w-5 h-5 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:v.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.949V19a2 2 0 01-2 2h-1C9.716 21 3 14.284 3 6V5z"})})}),v.jsx("p",{className:"text-white font-semibold text-sm",children:"Transferência Cega"})]}),v.jsxs("div",{className:"p-4 space-y-4",children:[v.jsxs("div",{className:"space-y-1",children:[v.jsx("label",{className:"text-gray-400 text-xs uppercase tracking-wider",children:"Destino"}),v.jsx("input",{type:"tel",value:x,onChange:e=>k(e.target.value.replace(/[^\d\*\#]/g,"")),onKeyDown:e=>{"Enter"===e.key?L(x):/^\d$|[\*\#]/.test(e.key)&&Fn(e.key,80)},placeholder:"Ramal ou número",autoFocus:!0,inputMode:"numeric",className:"w-full bg-gray-800 border border-gray-700 rounded-lg px-3 py-2.5 text-white text-sm placeholder-gray-500 focus:outline-none focus:border-blue-500 transition-colors"})]}),v.jsx("p",{className:"text-gray-400 text-xs",children:"A chamada será transferida imediatamente sem consulta prévia."}),v.jsxs("div",{className:"flex gap-2",children:[v.jsx("button",{onClick:()=>{w(!1),k("")},className:"flex-1 bg-gray-700 hover:bg-gray-600 text-gray-300 rounded-[15px] py-2.5 text-sm font-medium transition-colors",children:"Cancelar"}),v.jsx("button",{onClick:()=>L(x),disabled:!x.trim(),className:"flex-1 bg-blue-600 hover:bg-blue-700 disabled:bg-gray-700 disabled:text-gray-500 text-white rounded-[15px] py-2.5 text-sm font-medium transition-colors",children:"Transferir"})]})]})]})}),v.jsx(wd,{open:c,step:d,consultTarget:f,consultEstablished:g,onDial:$,onTransfer:O,onCancel:j})]})]})]})}const Cd={registered:"bg-emerald-500",connecting:"bg-amber-500",disconnected:"bg-slate-500",failed:"bg-red-500"},Rd={"bottom-right":"bottom-6 right-6","bottom-left":"bottom-6 left-6","top-right":"top-6 right-6","top-left":"top-6 left-6"};function Pd({config:e,api:t,embedded:n=!1}){y.useEffect(()=>{const e=console.error,t=console.warn,n=console.log;return console.error=function(...t){er.addLog("ERROR",t),nr(t)||e.apply(console,t)},console.warn=function(...e){er.addLog("WARN",e),nr(e)||t.apply(console,e)},console.log=function(...e){nr(e)||n.apply(console,e)},()=>{console.error=e,console.warn=t,console.log=n}},[]);const[r,i]=y.useState(!1),[o,a]=y.useState(""),[s,l]=y.useState(""),[c,u]=y.useState(null),[d,h]=y.useState("dialpad"),[f,p]=y.useState({}),g=b.useRef(null),m=b.useRef(!1),w=b.useRef(0),x=b.useRef("idle"),k=b.useRef(null),S=Zn(f,g),{connectionStatus:T,callStatus:E,isMuted:C,isOnHold:R,incomingCallInfo:P,callDuration:_,transferModal:D,setTransferModal:I,transferStep:A,setTransferStep:N,transferTarget:M,setTransferTarget:$,consultEstablished:O,setConsultEstablished:j,blindTransferModal:L,setBlindTransferModal:H,blindTransferTarget:F,setBlindTransferTarget:U,connect:z,disconnect:q,call:V,hangup:B,answer:W,reject:Y,toggleMute:G,toggleHold:K,sendDTMF:Q,openTransfer:X,transferDial:Z,transferExecute:ee,transferCancel:te,blindTransfer:ne}=S;k.current=V,y.useEffect(()=>{An.mergeConfig(e||{}).then(e=>p(e))},[]),y.useEffect(()=>{r?An.mergeConfig(e||{}).then(e=>p(e)):h("dialpad")},[r,e]),y.useEffect(()=>{P&&"ringing"===E&&!r&&i(!0)},[P,E,r]),y.useEffect(()=>{(async()=>{if(await new Promise(e=>setTimeout(e,0)),"disconnected"===T){const t=await An.mergeConfig(e||{});if(t.username&&t.domain&&t.server&&t.password){An.getManualDisconnect()||(w.current=Date.now(),ie(t))}}})()},[]),y.useEffect(()=>{if("disconnected"===T&&f.username&&f.domain&&f.server&&f.password){!An.getManualDisconnect()&&Date.now()-w.current>5e3&&(w.current=Date.now(),ie(f))}},[T]),y.useEffect(()=>{t.emit("statusChange",T),t.emit("__connectionStatusChange",T)},[T,t]),y.useEffect(()=>{const e=x.current,n=E;x.current=n,t.emit("callStateChange",n),t.emit("__callStatusChange",n),"active"===n&&t.emit("call:start",{direction:"ringing"===e?"inbound":"outbound"}),"active"===e&&"idle"===n&&t.emit("call:end",{}),"ringing"===e&&"idle"===n&&t.emit("call:missed",{})},[E,t]),y.useEffect(()=>{const e=null!==P;t.emit("incomingChange",e),t.emit("__incomingCallChange",P)},[P,t]),y.useEffect(()=>{var e;if(!c)return;const{number:t,auto:n}=c;if(a(t),u(null),!n)return;if("registered"!==T||"idle"!==E)return;const r=null==(e=f.aor)?void 0:e.split("@")[1];r&&k.current(t,r).catch(e=>console.error("[Widget] Auto call failed:",e))},[c]),t._emitter={open:()=>i(!0),close:()=>i(!1),dial:(e,t={})=>{i(!0),u({number:e,auto:Boolean(t.auto)})},answer:W,hangup:B,reject:Y,toggleHold:K,toggleMute:G,blindTransfer:ne,openTransfer:X,transferDial:Z,transferExecute:ee,transferCancel:te};const ie=async e=>{if(!m.current){m.current=!0;try{const t=await z(e);p(t)}catch(t){console.error("[Widget] Connect failed:",t)}finally{m.current=!1}}},ae=(null==e?void 0:e.position)||"bottom-right",se=(null==e?void 0:e.fabStyle)||"round",le=Rd[ae]||Rd["bottom-right"],ce="settings"===d||"logs"===d?"360px":"active"===E?"620px":"520px",de="disconnected"===T||"failed"===T,he="connecting"===T,fe=["calling","ringing","ringing_in","connected","active"].includes(E),pe=null!==P,ge=fe?"bg-blue-600":de?"bg-slate-500":he?"bg-amber-500":"bg-emerald-500",me=fe?J:de?re:oe,ve="pill"===se?v.jsxs("button",{onClick:()=>i(!r),className:`inline-flex items-center gap-2 px-3 h-8 rounded-lg text-white text-xs font-semibold transition-colors ${ge} hover:brightness-110 shadow-lg`,children:[v.jsx(me,{size:14}),v.jsx("span",{children:fe?"Em ligação":de?"Ramal Offline":he?"Conectando...":"Ramal Online"}),pe&&!r&&v.jsx("span",{className:"absolute inset-0 rounded-lg bg-green-400/20 animate-ping"})]}):v.jsxs("button",{onClick:()=>i(!r),className:`relative w-14 h-14 rounded-full flex items-center justify-center ${ge} hover:brightness-110 transition-colors shadow-lg`,children:[v.jsx(me,{size:24,className:"text-white"}),v.jsx("div",{className:`absolute top-0.5 right-0.5 w-3.5 h-3.5 rounded-full border-2 border-white ${Cd[T]||"bg-slate-500"}`}),pe&&!r&&v.jsx("span",{className:"absolute inset-0 rounded-full bg-green-400/20 animate-ping"})]});return v.jsxs(v.Fragment,{children:[v.jsx("audio",{ref:g,autoPlay:!0,playsInline:!0,controls:!1,style:{display:"none"}}),!n&&v.jsx("div",{className:`fixed ${le} z-50`,children:ve}),r&&v.jsx("div",{className:"fixed inset-0 z-[9998] bg-black/40 backdrop-blur-sm flex items-center justify-center",onClick:()=>i(!1),children:v.jsxs("div",{className:"relative w-full max-w-sm transition-[height] duration-300 ease-in-out",style:{height:ce,maxHeight:"calc(100vh - 48px)"},onClick:e=>e.stopPropagation(),children:[v.jsx("button",{onClick:()=>i(!1),className:"absolute -top-3 -right-3 w-7 h-7 bg-slate-800 border border-slate-600 rounded-full flex items-center justify-center text-gray-400 hover:text-white transition-colors z-10",children:v.jsx(ue,{size:14})}),v.jsx("div",{className:"rounded-[15px] overflow-hidden flex flex-col h-full",style:{boxShadow:"0 0px 6px 7px rgb(163 161 161 / 15%)"},children:v.jsx(Ed,{connectionStatus:T,callStatus:E,isMuted:C,isOnHold:R,incomingCallInfo:P,callDuration:_,dialInput:o,setDialInput:a,dtmfLog:s,transferModal:D,setTransferModal:I,transferStep:A,setTransferStep:N,transferTarget:M,setTransferTarget:$,consultEstablished:O,setConsultEstablished:j,blindTransferModal:L,setBlindTransferModal:H,blindTransferTarget:F,setBlindTransferTarget:U,settings:f,onConnect:ie,onDisconnect:q,onCall:async()=>{try{if(!f.aor)return void console.error("[Widget] Cannot call: not connected (missing aor)");const e=f.aor.split("@")[1];await V(o,e)}catch(e){console.error("[Widget] Call failed:",e)}},onHangup:B,onAnswer:W,onReject:Y,onToggleMute:G,onToggleHold:K,onDialPadPress:e=>{"active"===E?(l(t=>t+e),Q(e)):(a(t=>t+e),Fn(e,80))},onTransfer:X,onBlindTransfer:()=>H(!0),onTransferDial:e=>{var t;return Z(e,null==(t=f.aor)?void 0:t.split("@")[1])},onTransferExecute:ee,onTransferCancel:te,onTabChange:h,onBlindTransferExecute:e=>{var t;return ne(e,null==(t=f.aor)?void 0:t.split("@")[1])},onCallDirect:e=>{var t;if(!e)return;a(e);const n=null==(t=f.aor)?void 0:t.split("@")[1];n&&V(e,n).catch(e=>console.error("[Widget] Call failed:",e))},onClose:()=>i(!1),isConnecting:"connecting"===T})})]})})]})}const _d={registered:"bg-emerald-500",connecting:"bg-amber-500",disconnected:"bg-slate-500",failed:"bg-red-500"};function Dd({status:e,callStatus:t,hasIncomingCall:n,onClick:r,variant:i="round"}){const o="disconnected"===e||"failed"===e,a="connecting"===e,s=["ringing","ringing_in","connected"].includes(t),l=s?"bg-blue-600":o?"bg-slate-500":a?"bg-amber-500":"bg-emerald-500",c=s?J:o?re:oe;return"pill"===i?v.jsxs("button",{onClick:r,className:`inline-flex items-center gap-2 px-3 h-8 rounded-lg text-white text-xs font-semibold transition-colors ${l} hover:brightness-110 shadow-lg`,children:[v.jsx(c,{size:14}),v.jsx("span",{children:s?"Em ligação":o?"Ramal Offline":a?"Conectando...":"Ramal Online"}),n&&v.jsx("span",{className:"absolute inset-0 rounded-lg bg-green-400/20 animate-ping"})]}):v.jsxs("button",{onClick:r,className:`relative w-14 h-14 rounded-full flex items-center justify-center ${l} hover:brightness-110 transition-colors shadow-lg`,children:[v.jsx(c,{size:24,className:"text-white"}),v.jsx("div",{className:`absolute top-0.5 right-0.5 w-3.5 h-3.5 rounded-full border-2 border-white ${_d[e]||"bg-slate-500"}`}),n&&v.jsx("span",{className:"absolute inset-0 rounded-full bg-green-400/20 animate-ping"})]})}const Id={};let Ad=null,Nd=null,Md=null;const $d={statusChange:()=>Ad,callStateChange:()=>Nd,incomingChange:()=>Md},Od={open(){var e;null==(e=Od._emitter)||e.open()},close(){var e;null==(e=Od._emitter)||e.close()},dial(e,t={}){var n;null==(n=Od._emitter)||n.dial(e,t)},answer(){var e;null==(e=Od._emitter)||e.answer()},hangup(){var e;null==(e=Od._emitter)||e.hangup()},reject(){var e;null==(e=Od._emitter)||e.reject()},toggleHold(){var e;null==(e=Od._emitter)||e.toggleHold()},toggleMute(){var e;null==(e=Od._emitter)||e.toggleMute()},blindTransfer(e){var t;null==(t=Od._emitter)||t.blindTransfer(e)},openTransfer(){var e;null==(e=Od._emitter)||e.openTransfer()},transferDial(e){var t;null==(t=Od._emitter)||t.transferDial(e)},transferExecute(){var e;null==(e=Od._emitter)||e.transferExecute()},transferCancel(){var e;null==(e=Od._emitter)||e.transferCancel()},on(e,t){var n;(Id[e]??(Id[e]=[])).push(t);const r=null==(n=$d[e])?void 0:n.call($d);if(null!=r)try{t(r)}catch(i){}},off(e,t){Id[e]&&(Id[e]=Id[e].filter(e=>e!==t))},emit(e,t){var n;"statusChange"===e&&(Ad=t),"callStateChange"===e&&(Nd=t),"incomingChange"===e&&(Md=t),null==(n=Id[e])||n.forEach(e=>{try{e(t)}catch(n){}})},get status(){return Ad},_emitter:null};function jd(e,t){const n=document.createElement("div");n.style.cssText=e,t.appendChild(n);const r=n.attachShadow({mode:"open"}),i=document.createElement("style");i.textContent='*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:#e5e7eb}:before,:after{--tw-content: ""}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji",Segoe UI Symbol,"Noto Color Emoji";font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]:where(:not([hidden=until-found])){display:none}:host{--background: 0 0% 100%;--foreground: 0 0% 3.9%;--card: 0 0% 100%;--card-foreground: 0 0% 3.9%;--popover: 0 0% 100%;--popover-foreground: 0 0% 3.9%;--primary: 0 0% 9%;--primary-foreground: 0 0% 98%;--secondary: 0 0% 96.1%;--secondary-foreground: 0 0% 9%;--muted: 0 0% 96.1%;--muted-foreground: 0 0% 45.1%;--accent: 0 0% 96.1%;--accent-foreground: 0 0% 9%;--destructive: 0 84.2% 60.2%;--destructive-foreground: 0 0% 98%;--border: 0 0% 89.8%;--input: 0 0% 89.8%;--ring: 0 0% 3.9%;--chart-1: 12 76% 61%;--chart-2: 173 58% 39%;--chart-3: 197 37% 24%;--chart-4: 43 74% 66%;--chart-5: 27 87% 67%;--radius: .5rem;--sidebar-background: 0 0% 98%;--sidebar-foreground: 240 5.3% 26.1%;--sidebar-primary: 240 5.9% 10%;--sidebar-primary-foreground: 0 0% 98%;--sidebar-accent: 240 4.8% 95.9%;--sidebar-accent-foreground: 240 5.9% 10%;--sidebar-border: 220 13% 91%;--sidebar-ring: 217.2 91.2% 59.8%}:host(.dark){--background: 0 0% 3.9%;--foreground: 0 0% 98%;--card: 0 0% 3.9%;--card-foreground: 0 0% 98%;--popover: 0 0% 3.9%;--popover-foreground: 0 0% 98%;--primary: 0 0% 98%;--primary-foreground: 0 0% 9%;--secondary: 0 0% 14.9%;--secondary-foreground: 0 0% 98%;--muted: 0 0% 14.9%;--muted-foreground: 0 0% 63.9%;--accent: 0 0% 14.9%;--accent-foreground: 0 0% 98%;--destructive: 0 62.8% 30.6%;--destructive-foreground: 0 0% 98%;--border: 0 0% 14.9%;--input: 0 0% 14.9%;--ring: 0 0% 83.1%;--chart-1: 220 70% 50%;--chart-2: 160 60% 45%;--chart-3: 30 80% 55%;--chart-4: 280 65% 60%;--chart-5: 340 75% 55%;--sidebar-background: 240 5.9% 10%;--sidebar-foreground: 240 4.8% 95.9%;--sidebar-primary: 224.3 76.3% 48%;--sidebar-primary-foreground: 0 0% 100%;--sidebar-accent: 240 3.7% 15.9%;--sidebar-accent-foreground: 240 4.8% 95.9%;--sidebar-border: 240 3.7% 15.9%;--sidebar-ring: 217.2 91.2% 59.8%}:host *{border-color:hsl(var(--border));outline-color:hsl(var(--ring) / .5)}:host{color:hsl(var(--foreground))}.container{width:100%}@media(min-width:640px){.container{max-width:640px}}@media(min-width:768px){.container{max-width:768px}}@media(min-width:1024px){.container{max-width:1024px}}@media(min-width:1280px){.container{max-width:1280px}}@media(min-width:1536px){.container{max-width:1536px}}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border-width:0}.pointer-events-none{pointer-events:none}.pointer-events-auto{pointer-events:auto}.visible{visibility:visible}.invisible{visibility:hidden}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.inset-0{top:0;right:0;bottom:0;left:0}.inset-x-0{left:0;right:0}.inset-y-0{top:0;bottom:0}.-bottom-12{bottom:-3rem}.-left-12{left:-3rem}.-right-12{right:-3rem}.-right-3{right:-.75rem}.-top-12{top:-3rem}.-top-3{top:-.75rem}.bottom-0{bottom:0}.bottom-6{bottom:1.5rem}.left-0{left:0}.left-1{left:.25rem}.left-1\\/2{left:50%}.left-2{left:.5rem}.left-6{left:1.5rem}.left-\\[50\\%\\]{left:50%}.right-0{right:0}.right-0\\.5{right:.125rem}.right-1{right:.25rem}.right-2{right:.5rem}.right-3{right:.75rem}.right-4{right:1rem}.right-6{right:1.5rem}.top-0{top:0}.top-0\\.5{top:.125rem}.top-1\\.5{top:.375rem}.top-1\\/2{top:50%}.top-2{top:.5rem}.top-3\\.5{top:.875rem}.top-4{top:1rem}.top-6{top:1.5rem}.top-\\[1px\\]{top:1px}.top-\\[50\\%\\]{top:50%}.top-\\[60\\%\\]{top:60%}.top-full{top:100%}.z-10{z-index:10}.z-20{z-index:20}.z-50{z-index:50}.z-\\[100\\]{z-index:100}.z-\\[1\\]{z-index:1}.z-\\[9998\\]{z-index:9998}.-mx-1{margin-left:-.25rem;margin-right:-.25rem}.mx-2{margin-left:.5rem;margin-right:.5rem}.mx-3\\.5{margin-left:.875rem;margin-right:.875rem}.mx-auto{margin-left:auto;margin-right:auto}.my-0\\.5{margin-top:.125rem;margin-bottom:.125rem}.my-1{margin-top:.25rem;margin-bottom:.25rem}.-ml-4{margin-left:-1rem}.-mt-4{margin-top:-1rem}.mb-1{margin-bottom:.25rem}.mb-2{margin-bottom:.5rem}.mb-3{margin-bottom:.75rem}.mb-4{margin-bottom:1rem}.ml-1{margin-left:.25rem}.ml-auto{margin-left:auto}.mr-1{margin-right:.25rem}.mr-2{margin-right:.5rem}.mt-0\\.5{margin-top:.125rem}.mt-1{margin-top:.25rem}.mt-1\\.5{margin-top:.375rem}.mt-2{margin-top:.5rem}.mt-24{margin-top:6rem}.mt-3{margin-top:.75rem}.mt-4{margin-top:1rem}.mt-auto{margin-top:auto}.block{display:block}.inline{display:inline}.flex{display:flex}.inline-flex{display:inline-flex}.table{display:table}.grid{display:grid}.hidden{display:none}.aspect-square{aspect-ratio:1 / 1}.aspect-video{aspect-ratio:16 / 9}.size-4{width:1rem;height:1rem}.h-1\\.5{height:.375rem}.h-10{height:2.5rem}.h-12{height:3rem}.h-14{height:3.5rem}.h-16{height:4rem}.h-2{height:.5rem}.h-2\\.5{height:.625rem}.h-3{height:.75rem}.h-3\\.5{height:.875rem}.h-4{height:1rem}.h-5{height:1.25rem}.h-7{height:1.75rem}.h-8{height:2rem}.h-9{height:2.25rem}.h-\\[1px\\]{height:1px}.h-\\[var\\(--radix-navigation-menu-viewport-height\\)\\]{height:var(--radix-navigation-menu-viewport-height)}.h-\\[var\\(--radix-select-trigger-height\\)\\]{height:var(--radix-select-trigger-height)}.h-auto{height:auto}.h-full{height:100%}.h-px{height:1px}.h-svh{height:100svh}.max-h-96{max-height:24rem}.max-h-\\[300px\\]{max-height:300px}.max-h-screen{max-height:100vh}.min-h-0{min-height:0px}.min-h-\\[60px\\]{min-height:60px}.min-h-svh{min-height:100svh}.w-0{width:0px}.w-1{width:.25rem}.w-10{width:2.5rem}.w-12{width:3rem}.w-14{width:3.5rem}.w-16{width:4rem}.w-2{width:.5rem}.w-2\\.5{width:.625rem}.w-3{width:.75rem}.w-3\\.5{width:.875rem}.w-3\\/4{width:75%}.w-4{width:1rem}.w-5{width:1.25rem}.w-64{width:16rem}.w-7{width:1.75rem}.w-72{width:18rem}.w-8{width:2rem}.w-9{width:2.25rem}.w-\\[--sidebar-width\\]{width:var(--sidebar-width)}.w-\\[100px\\]{width:100px}.w-\\[1px\\]{width:1px}.w-auto{width:auto}.w-full{width:100%}.w-max{width:-moz-max-content;width:max-content}.w-px{width:1px}.min-w-0{min-width:0px}.min-w-10{min-width:2.5rem}.min-w-5{min-width:1.25rem}.min-w-8{min-width:2rem}.min-w-9{min-width:2.25rem}.min-w-\\[12rem\\]{min-width:12rem}.min-w-\\[8rem\\]{min-width:8rem}.min-w-\\[var\\(--radix-select-trigger-width\\)\\]{min-width:var(--radix-select-trigger-width)}.max-w-\\[--skeleton-width\\]{max-width:var(--skeleton-width)}.max-w-\\[180px\\]{max-width:180px}.max-w-lg{max-width:32rem}.max-w-max{max-width:-moz-max-content;max-width:max-content}.max-w-sm{max-width:24rem}.max-w-xs{max-width:20rem}.flex-1{flex:1 1 0%}.flex-\\[2\\]{flex:2}.flex-shrink-0,.shrink-0{flex-shrink:0}.grow{flex-grow:1}.grow-0{flex-grow:0}.basis-full{flex-basis:100%}.caption-bottom{caption-side:bottom}.border-collapse{border-collapse:collapse}.-translate-x-1\\/2{--tw-translate-x: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.-translate-x-px{--tw-translate-x: -1px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.-translate-y-1\\/2{--tw-translate-y: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-x-\\[-50\\%\\]{--tw-translate-x: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-x-px{--tw-translate-x: 1px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-y-\\[-50\\%\\]{--tw-translate-y: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.rotate-45{--tw-rotate: 45deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.rotate-90{--tw-rotate: 90deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.transform{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}@keyframes ping{75%,to{transform:scale(2);opacity:0}}.animate-ping{animation:ping 1s cubic-bezier(0,0,.2,1) infinite}@keyframes pulse{50%{opacity:.5}}.animate-pulse{animation:pulse 2s cubic-bezier(.4,0,.6,1) infinite}@keyframes spin{to{transform:rotate(360deg)}}.animate-spin{animation:spin 1s linear infinite}.cursor-default{cursor:default}.cursor-pointer{cursor:pointer}.touch-none{touch-action:none}.select-none{-webkit-user-select:none;-moz-user-select:none;user-select:none}.list-none{list-style-type:none}.grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.flex-row{flex-direction:row}.flex-col{flex-direction:column}.flex-col-reverse{flex-direction:column-reverse}.flex-wrap{flex-wrap:wrap}.items-start{align-items:flex-start}.items-end{align-items:flex-end}.items-center{align-items:center}.items-stretch{align-items:stretch}.justify-center{justify-content:center}.justify-between{justify-content:space-between}.gap-0\\.5{gap:.125rem}.gap-1{gap:.25rem}.gap-1\\.5{gap:.375rem}.gap-2{gap:.5rem}.gap-3{gap:.75rem}.gap-4{gap:1rem}.space-x-1>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(.25rem * var(--tw-space-x-reverse));margin-left:calc(.25rem * calc(1 - var(--tw-space-x-reverse)))}.space-x-4>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(1rem * var(--tw-space-x-reverse));margin-left:calc(1rem * calc(1 - var(--tw-space-x-reverse)))}.space-y-1>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.25rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.25rem * var(--tw-space-y-reverse))}.space-y-1\\.5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.375rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.375rem * var(--tw-space-y-reverse))}.space-y-2>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.5rem * var(--tw-space-y-reverse))}.space-y-3>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.75rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.75rem * var(--tw-space-y-reverse))}.space-y-4>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1rem * var(--tw-space-y-reverse))}.space-y-5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1.25rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1.25rem * var(--tw-space-y-reverse))}.divide-y>:not([hidden])~:not([hidden]){--tw-divide-y-reverse: 0;border-top-width:calc(1px * calc(1 - var(--tw-divide-y-reverse)));border-bottom-width:calc(1px * var(--tw-divide-y-reverse))}.divide-gray-800>:not([hidden])~:not([hidden]){--tw-divide-opacity: 1;border-color:rgb(31 41 55 / var(--tw-divide-opacity, 1))}.overflow-auto{overflow:auto}.overflow-hidden{overflow:hidden}.overflow-y-auto{overflow-y:auto}.overflow-x-hidden{overflow-x:hidden}.truncate{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.whitespace-nowrap{white-space:nowrap}.break-words{overflow-wrap:break-word}.rounded{border-radius:.25rem}.rounded-2xl{border-radius:1rem}.rounded-\\[15px\\]{border-radius:15px}.rounded-\\[2px\\]{border-radius:2px}.rounded-\\[inherit\\]{border-radius:inherit}.rounded-full{border-radius:9999px}.rounded-lg{border-radius:var(--radius)}.rounded-md{border-radius:calc(var(--radius) - 2px)}.rounded-sm{border-radius:calc(var(--radius) - 4px)}.rounded-xl{border-radius:.75rem}.rounded-t-\\[10px\\]{border-top-left-radius:10px;border-top-right-radius:10px}.rounded-tl-sm{border-top-left-radius:calc(var(--radius) - 4px)}.border{border-width:1px}.border-2{border-width:2px}.border-\\[1\\.5px\\]{border-width:1.5px}.border-y{border-top-width:1px;border-bottom-width:1px}.border-b{border-bottom-width:1px}.border-l{border-left-width:1px}.border-r{border-right-width:1px}.border-t{border-top-width:1px}.border-dashed{border-style:dashed}.border-\\[--color-border\\]{border-color:var(--color-border)}.border-blue-700{--tw-border-opacity: 1;border-color:rgb(29 78 216 / var(--tw-border-opacity, 1))}.border-border\\/50{border-color:hsl(var(--border) / .5)}.border-destructive{border-color:hsl(var(--destructive))}.border-destructive\\/50{border-color:hsl(var(--destructive) / .5)}.border-gray-700{--tw-border-opacity: 1;border-color:rgb(55 65 81 / var(--tw-border-opacity, 1))}.border-gray-800{--tw-border-opacity: 1;border-color:rgb(31 41 55 / var(--tw-border-opacity, 1))}.border-input{border-color:hsl(var(--input))}.border-primary{border-color:hsl(var(--primary))}.border-primary\\/50{border-color:hsl(var(--primary) / .5)}.border-sidebar-border{border-color:hsl(var(--sidebar-border))}.border-slate-600{--tw-border-opacity: 1;border-color:rgb(71 85 105 / var(--tw-border-opacity, 1))}.border-transparent{border-color:transparent}.border-white{--tw-border-opacity: 1;border-color:rgb(255 255 255 / var(--tw-border-opacity, 1))}.border-white\\/30{border-color:#ffffff4d}.border-l-transparent{border-left-color:transparent}.border-t-transparent{border-top-color:transparent}.border-t-white{--tw-border-opacity: 1;border-top-color:rgb(255 255 255 / var(--tw-border-opacity, 1))}.bg-\\[--color-bg\\]{background-color:var(--color-bg)}.bg-accent{background-color:hsl(var(--accent))}.bg-amber-500{--tw-bg-opacity: 1;background-color:rgb(245 158 11 / var(--tw-bg-opacity, 1))}.bg-background{background-color:hsl(var(--background))}.bg-black\\/40{background-color:#0006}.bg-black\\/70{background-color:#000000b3}.bg-black\\/80{background-color:#000c}.bg-blue-500{--tw-bg-opacity: 1;background-color:rgb(59 130 246 / var(--tw-bg-opacity, 1))}.bg-blue-600{--tw-bg-opacity: 1;background-color:rgb(37 99 235 / var(--tw-bg-opacity, 1))}.bg-blue-700{--tw-bg-opacity: 1;background-color:rgb(29 78 216 / var(--tw-bg-opacity, 1))}.bg-border{background-color:hsl(var(--border))}.bg-card{background-color:hsl(var(--card))}.bg-destructive{background-color:hsl(var(--destructive))}.bg-emerald-500{--tw-bg-opacity: 1;background-color:rgb(16 185 129 / var(--tw-bg-opacity, 1))}.bg-emerald-600{--tw-bg-opacity: 1;background-color:rgb(5 150 105 / var(--tw-bg-opacity, 1))}.bg-foreground{background-color:hsl(var(--foreground))}.bg-gray-700{--tw-bg-opacity: 1;background-color:rgb(55 65 81 / var(--tw-bg-opacity, 1))}.bg-gray-800{--tw-bg-opacity: 1;background-color:rgb(31 41 55 / var(--tw-bg-opacity, 1))}.bg-gray-900{--tw-bg-opacity: 1;background-color:rgb(17 24 39 / var(--tw-bg-opacity, 1))}.bg-green-400{--tw-bg-opacity: 1;background-color:rgb(74 222 128 / var(--tw-bg-opacity, 1))}.bg-green-400\\/20{background-color:#4ade8033}.bg-green-500{--tw-bg-opacity: 1;background-color:rgb(34 197 94 / var(--tw-bg-opacity, 1))}.bg-green-600{--tw-bg-opacity: 1;background-color:rgb(22 163 74 / var(--tw-bg-opacity, 1))}.bg-muted{background-color:hsl(var(--muted))}.bg-muted\\/50{background-color:hsl(var(--muted) / .5)}.bg-orange-500{--tw-bg-opacity: 1;background-color:rgb(249 115 22 / var(--tw-bg-opacity, 1))}.bg-popover{background-color:hsl(var(--popover))}.bg-primary{background-color:hsl(var(--primary))}.bg-primary\\/10{background-color:hsl(var(--primary) / .1)}.bg-primary\\/20{background-color:hsl(var(--primary) / .2)}.bg-purple-600{--tw-bg-opacity: 1;background-color:rgb(147 51 234 / var(--tw-bg-opacity, 1))}.bg-purple-700{--tw-bg-opacity: 1;background-color:rgb(126 34 206 / var(--tw-bg-opacity, 1))}.bg-red-500{--tw-bg-opacity: 1;background-color:rgb(239 68 68 / var(--tw-bg-opacity, 1))}.bg-secondary{background-color:hsl(var(--secondary))}.bg-sidebar{background-color:hsl(var(--sidebar-background))}.bg-sidebar-border{background-color:hsl(var(--sidebar-border))}.bg-slate-500{--tw-bg-opacity: 1;background-color:rgb(100 116 139 / var(--tw-bg-opacity, 1))}.bg-slate-800{--tw-bg-opacity: 1;background-color:rgb(30 41 59 / var(--tw-bg-opacity, 1))}.bg-transparent{background-color:transparent}.bg-white\\/10{background-color:#ffffff1a}.bg-white\\/20{background-color:#fff3}.bg-gradient-to-r{background-image:linear-gradient(to right,var(--tw-gradient-stops))}.from-blue-600{--tw-gradient-from: #2563eb var(--tw-gradient-from-position);--tw-gradient-to: rgb(37 99 235 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-blue-700{--tw-gradient-from: #1d4ed8 var(--tw-gradient-from-position);--tw-gradient-to: rgb(29 78 216 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-blue-900{--tw-gradient-from: #1e3a8a var(--tw-gradient-from-position);--tw-gradient-to: rgb(30 58 138 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-purple-700{--tw-gradient-from: #7e22ce var(--tw-gradient-from-position);--tw-gradient-to: rgb(126 34 206 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.to-blue-600{--tw-gradient-to: #2563eb var(--tw-gradient-to-position)}.to-blue-700{--tw-gradient-to: #1d4ed8 var(--tw-gradient-to-position)}.to-blue-800{--tw-gradient-to: #1e40af var(--tw-gradient-to-position)}.to-purple-600{--tw-gradient-to: #9333ea var(--tw-gradient-to-position)}.fill-current{fill:currentColor}.fill-primary{fill:hsl(var(--primary))}.p-0{padding:0}.p-1{padding:.25rem}.p-2{padding:.5rem}.p-3{padding:.75rem}.p-4{padding:1rem}.p-6{padding:1.5rem}.p-\\[1px\\]{padding:1px}.px-1{padding-left:.25rem;padding-right:.25rem}.px-1\\.5{padding-left:.375rem;padding-right:.375rem}.px-2{padding-left:.5rem;padding-right:.5rem}.px-2\\.5{padding-left:.625rem;padding-right:.625rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-4{padding-left:1rem;padding-right:1rem}.px-5{padding-left:1.25rem;padding-right:1.25rem}.px-8{padding-left:2rem;padding-right:2rem}.py-0\\.5{padding-top:.125rem;padding-bottom:.125rem}.py-1{padding-top:.25rem;padding-bottom:.25rem}.py-1\\.5{padding-top:.375rem;padding-bottom:.375rem}.py-2{padding-top:.5rem;padding-bottom:.5rem}.py-2\\.5{padding-top:.625rem;padding-bottom:.625rem}.py-3{padding-top:.75rem;padding-bottom:.75rem}.py-4{padding-top:1rem;padding-bottom:1rem}.py-6{padding-top:1.5rem;padding-bottom:1.5rem}.py-8{padding-top:2rem;padding-bottom:2rem}.pb-2{padding-bottom:.5rem}.pb-3{padding-bottom:.75rem}.pb-4{padding-bottom:1rem}.pl-2{padding-left:.5rem}.pl-2\\.5{padding-left:.625rem}.pl-4{padding-left:1rem}.pl-8{padding-left:2rem}.pr-2{padding-right:.5rem}.pr-2\\.5{padding-right:.625rem}.pr-8{padding-right:2rem}.pt-0{padding-top:0}.pt-1{padding-top:.25rem}.pt-3{padding-top:.75rem}.pt-4{padding-top:1rem}.text-left{text-align:left}.text-center{text-align:center}.align-middle{vertical-align:middle}.font-mono{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace}.text-\\[0\\.8rem\\]{font-size:.8rem}.text-\\[10px\\]{font-size:10px}.text-\\[9px\\]{font-size:9px}.text-base{font-size:1rem;line-height:1.5rem}.text-lg{font-size:1.125rem;line-height:1.75rem}.text-sm{font-size:.875rem;line-height:1.25rem}.text-xl{font-size:1.25rem;line-height:1.75rem}.text-xs{font-size:.75rem;line-height:1rem}.font-bold{font-weight:700}.font-light{font-weight:300}.font-medium{font-weight:500}.font-normal{font-weight:400}.font-semibold{font-weight:600}.uppercase{text-transform:uppercase}.tabular-nums{--tw-numeric-spacing: tabular-nums;font-variant-numeric:var(--tw-ordinal) var(--tw-slashed-zero) var(--tw-numeric-figure) var(--tw-numeric-spacing) var(--tw-numeric-fraction)}.leading-none{line-height:1}.tracking-tight{letter-spacing:-.025em}.tracking-wider{letter-spacing:.05em}.tracking-widest{letter-spacing:.1em}.text-accent-foreground{color:hsl(var(--accent-foreground))}.text-amber-400{--tw-text-opacity: 1;color:rgb(251 191 36 / var(--tw-text-opacity, 1))}.text-blue-200{--tw-text-opacity: 1;color:rgb(191 219 254 / var(--tw-text-opacity, 1))}.text-blue-300{--tw-text-opacity: 1;color:rgb(147 197 253 / var(--tw-text-opacity, 1))}.text-blue-400{--tw-text-opacity: 1;color:rgb(96 165 250 / var(--tw-text-opacity, 1))}.text-card-foreground{color:hsl(var(--card-foreground))}.text-current{color:currentColor}.text-destructive{color:hsl(var(--destructive))}.text-destructive-foreground{color:hsl(var(--destructive-foreground))}.text-emerald-400{--tw-text-opacity: 1;color:rgb(52 211 153 / var(--tw-text-opacity, 1))}.text-foreground{color:hsl(var(--foreground))}.text-foreground\\/50{color:hsl(var(--foreground) / .5)}.text-gray-300{--tw-text-opacity: 1;color:rgb(209 213 219 / var(--tw-text-opacity, 1))}.text-gray-400{--tw-text-opacity: 1;color:rgb(156 163 175 / var(--tw-text-opacity, 1))}.text-gray-500{--tw-text-opacity: 1;color:rgb(107 114 128 / var(--tw-text-opacity, 1))}.text-gray-600{--tw-text-opacity: 1;color:rgb(75 85 99 / var(--tw-text-opacity, 1))}.text-green-400{--tw-text-opacity: 1;color:rgb(74 222 128 / var(--tw-text-opacity, 1))}.text-muted-foreground{color:hsl(var(--muted-foreground))}.text-popover-foreground{color:hsl(var(--popover-foreground))}.text-primary{color:hsl(var(--primary))}.text-primary-foreground{color:hsl(var(--primary-foreground))}.text-purple-200{--tw-text-opacity: 1;color:rgb(233 213 255 / var(--tw-text-opacity, 1))}.text-purple-300{--tw-text-opacity: 1;color:rgb(216 180 254 / var(--tw-text-opacity, 1))}.text-purple-400{--tw-text-opacity: 1;color:rgb(192 132 252 / var(--tw-text-opacity, 1))}.text-red-400{--tw-text-opacity: 1;color:rgb(248 113 113 / var(--tw-text-opacity, 1))}.text-secondary-foreground{color:hsl(var(--secondary-foreground))}.text-sidebar-foreground{color:hsl(var(--sidebar-foreground))}.text-sidebar-foreground\\/70{color:hsl(var(--sidebar-foreground) / .7)}.text-slate-300{--tw-text-opacity: 1;color:rgb(203 213 225 / var(--tw-text-opacity, 1))}.text-slate-400{--tw-text-opacity: 1;color:rgb(148 163 184 / var(--tw-text-opacity, 1))}.text-slate-500{--tw-text-opacity: 1;color:rgb(100 116 139 / var(--tw-text-opacity, 1))}.text-white{--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1))}.text-yellow-400{--tw-text-opacity: 1;color:rgb(250 204 21 / var(--tw-text-opacity, 1))}.underline-offset-4{text-underline-offset:4px}.placeholder-gray-500::-moz-placeholder{--tw-placeholder-opacity: 1;color:rgb(107 114 128 / var(--tw-placeholder-opacity, 1))}.placeholder-gray-500::placeholder{--tw-placeholder-opacity: 1;color:rgb(107 114 128 / var(--tw-placeholder-opacity, 1))}.opacity-0{opacity:0}.opacity-50{opacity:.5}.opacity-60{opacity:.6}.opacity-70{opacity:.7}.opacity-90{opacity:.9}.shadow{--tw-shadow: 0 1px 3px 0 rgb(0 0 0 / .1), 0 1px 2px -1px rgb(0 0 0 / .1);--tw-shadow-colored: 0 1px 3px 0 var(--tw-shadow-color), 0 1px 2px -1px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-2xl{--tw-shadow: 0 25px 50px -12px rgb(0 0 0 / .25);--tw-shadow-colored: 0 25px 50px -12px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-\\[0_0_0_1px_hsl\\(var\\(--sidebar-border\\)\\)\\]{--tw-shadow: 0 0 0 1px hsl(var(--sidebar-border));--tw-shadow-colored: 0 0 0 1px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-lg{--tw-shadow: 0 10px 15px -3px rgb(0 0 0 / .1), 0 4px 6px -4px rgb(0 0 0 / .1);--tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-md{--tw-shadow: 0 4px 6px -1px rgb(0 0 0 / .1), 0 2px 4px -2px rgb(0 0 0 / .1);--tw-shadow-colored: 0 4px 6px -1px var(--tw-shadow-color), 0 2px 4px -2px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-none{--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-sm{--tw-shadow: 0 1px 2px 0 rgb(0 0 0 / .05);--tw-shadow-colored: 0 1px 2px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-xl{--tw-shadow: 0 20px 25px -5px rgb(0 0 0 / .1), 0 8px 10px -6px rgb(0 0 0 / .1);--tw-shadow-colored: 0 20px 25px -5px var(--tw-shadow-color), 0 8px 10px -6px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-green-500\\/30{--tw-shadow-color: rgb(34 197 94 / .3);--tw-shadow: var(--tw-shadow-colored)}.shadow-red-500\\/30{--tw-shadow-color: rgb(239 68 68 / .3);--tw-shadow: var(--tw-shadow-colored)}.outline-none{outline:2px solid transparent;outline-offset:2px}.outline{outline-style:solid}.ring{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(3px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.ring-0{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(0px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.ring-1{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.ring-ring{--tw-ring-color: hsl(var(--ring))}.ring-sidebar-ring{--tw-ring-color: hsl(var(--sidebar-ring))}.ring-offset-background{--tw-ring-offset-color: hsl(var(--background))}.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.backdrop-blur-sm{--tw-backdrop-blur: blur(4px);-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.transition{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-\\[height\\]{transition-property:height;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-\\[left\\,right\\,width\\]{transition-property:left,right,width;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-\\[margin\\,opacity\\]{transition-property:margin,opacity;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-\\[width\\,height\\,padding\\]{transition-property:width,height,padding;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-\\[width\\]{transition-property:width;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-all{transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-colors{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-opacity{transition-property:opacity;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-transform{transition-property:transform;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.duration-1000{transition-duration:1s}.duration-200{transition-duration:.2s}.duration-300{transition-duration:.3s}.ease-in-out{transition-timing-function:cubic-bezier(.4,0,.2,1)}.ease-linear{transition-timing-function:linear}@keyframes enter{0%{opacity:var(--tw-enter-opacity, 1);transform:translate3d(var(--tw-enter-translate-x, 0),var(--tw-enter-translate-y, 0),0) scale3d(var(--tw-enter-scale, 1),var(--tw-enter-scale, 1),var(--tw-enter-scale, 1)) rotate(var(--tw-enter-rotate, 0))}}@keyframes exit{to{opacity:var(--tw-exit-opacity, 1);transform:translate3d(var(--tw-exit-translate-x, 0),var(--tw-exit-translate-y, 0),0) scale3d(var(--tw-exit-scale, 1),var(--tw-exit-scale, 1),var(--tw-exit-scale, 1)) rotate(var(--tw-exit-rotate, 0))}}.animate-in{animation-name:enter;animation-duration:.15s;--tw-enter-opacity: initial;--tw-enter-scale: initial;--tw-enter-rotate: initial;--tw-enter-translate-x: initial;--tw-enter-translate-y: initial}.fade-in-0{--tw-enter-opacity: 0}.zoom-in-95{--tw-enter-scale: .95}.duration-1000{animation-duration:1s}.duration-200{animation-duration:.2s}.duration-300{animation-duration:.3s}.ease-in-out{animation-timing-function:cubic-bezier(.4,0,.2,1)}.ease-linear{animation-timing-function:linear}.file\\:border-0::file-selector-button{border-width:0px}.file\\:bg-transparent::file-selector-button{background-color:transparent}.file\\:text-sm::file-selector-button{font-size:.875rem;line-height:1.25rem}.file\\:font-medium::file-selector-button{font-weight:500}.file\\:text-foreground::file-selector-button{color:hsl(var(--foreground))}.placeholder\\:text-muted-foreground::-moz-placeholder{color:hsl(var(--muted-foreground))}.placeholder\\:text-muted-foreground::placeholder{color:hsl(var(--muted-foreground))}.after\\:absolute:after{content:var(--tw-content);position:absolute}.after\\:-inset-2:after{content:var(--tw-content);top:-.5rem;right:-.5rem;bottom:-.5rem;left:-.5rem}.after\\:inset-y-0:after{content:var(--tw-content);top:0;bottom:0}.after\\:left-1\\/2:after{content:var(--tw-content);left:50%}.after\\:w-1:after{content:var(--tw-content);width:.25rem}.after\\:w-\\[2px\\]:after{content:var(--tw-content);width:2px}.after\\:-translate-x-1\\/2:after{content:var(--tw-content);--tw-translate-x: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.first\\:rounded-l-md:first-child{border-top-left-radius:calc(var(--radius) - 2px);border-bottom-left-radius:calc(var(--radius) - 2px)}.first\\:border-l:first-child{border-left-width:1px}.last\\:rounded-r-md:last-child{border-top-right-radius:calc(var(--radius) - 2px);border-bottom-right-radius:calc(var(--radius) - 2px)}.focus-within\\:relative:focus-within{position:relative}.focus-within\\:z-20:focus-within{z-index:20}.hover\\:bg-accent:hover{background-color:hsl(var(--accent))}.hover\\:bg-blue-600:hover{--tw-bg-opacity: 1;background-color:rgb(37 99 235 / var(--tw-bg-opacity, 1))}.hover\\:bg-blue-700:hover{--tw-bg-opacity: 1;background-color:rgb(29 78 216 / var(--tw-bg-opacity, 1))}.hover\\:bg-destructive\\/80:hover{background-color:hsl(var(--destructive) / .8)}.hover\\:bg-destructive\\/90:hover{background-color:hsl(var(--destructive) / .9)}.hover\\:bg-emerald-500:hover{--tw-bg-opacity: 1;background-color:rgb(16 185 129 / var(--tw-bg-opacity, 1))}.hover\\:bg-gray-600:hover{--tw-bg-opacity: 1;background-color:rgb(75 85 99 / var(--tw-bg-opacity, 1))}.hover\\:bg-gray-700:hover{--tw-bg-opacity: 1;background-color:rgb(55 65 81 / var(--tw-bg-opacity, 1))}.hover\\:bg-green-600:hover{--tw-bg-opacity: 1;background-color:rgb(22 163 74 / var(--tw-bg-opacity, 1))}.hover\\:bg-green-700:hover{--tw-bg-opacity: 1;background-color:rgb(21 128 61 / var(--tw-bg-opacity, 1))}.hover\\:bg-muted:hover{background-color:hsl(var(--muted))}.hover\\:bg-muted\\/50:hover{background-color:hsl(var(--muted) / .5)}.hover\\:bg-orange-600:hover{--tw-bg-opacity: 1;background-color:rgb(234 88 12 / var(--tw-bg-opacity, 1))}.hover\\:bg-primary:hover{background-color:hsl(var(--primary))}.hover\\:bg-primary\\/80:hover{background-color:hsl(var(--primary) / .8)}.hover\\:bg-primary\\/90:hover{background-color:hsl(var(--primary) / .9)}.hover\\:bg-purple-600:hover{--tw-bg-opacity: 1;background-color:rgb(147 51 234 / var(--tw-bg-opacity, 1))}.hover\\:bg-purple-700:hover{--tw-bg-opacity: 1;background-color:rgb(126 34 206 / var(--tw-bg-opacity, 1))}.hover\\:bg-red-600:hover{--tw-bg-opacity: 1;background-color:rgb(220 38 38 / var(--tw-bg-opacity, 1))}.hover\\:bg-secondary:hover{background-color:hsl(var(--secondary))}.hover\\:bg-secondary\\/80:hover{background-color:hsl(var(--secondary) / .8)}.hover\\:bg-sidebar-accent:hover{background-color:hsl(var(--sidebar-accent))}.hover\\:bg-white\\/5:hover{background-color:#ffffff0d}.hover\\:text-accent-foreground:hover{color:hsl(var(--accent-foreground))}.hover\\:text-foreground:hover{color:hsl(var(--foreground))}.hover\\:text-gray-300:hover{--tw-text-opacity: 1;color:rgb(209 213 219 / var(--tw-text-opacity, 1))}.hover\\:text-muted-foreground:hover{color:hsl(var(--muted-foreground))}.hover\\:text-primary-foreground:hover{color:hsl(var(--primary-foreground))}.hover\\:text-red-400:hover{--tw-text-opacity: 1;color:rgb(248 113 113 / var(--tw-text-opacity, 1))}.hover\\:text-sidebar-accent-foreground:hover{color:hsl(var(--sidebar-accent-foreground))}.hover\\:text-slate-300:hover{--tw-text-opacity: 1;color:rgb(203 213 225 / var(--tw-text-opacity, 1))}.hover\\:text-white:hover{--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1))}.hover\\:underline:hover{text-decoration-line:underline}.hover\\:opacity-100:hover{opacity:1}.hover\\:shadow-\\[0_0_0_1px_hsl\\(var\\(--sidebar-accent\\)\\)\\]:hover{--tw-shadow: 0 0 0 1px hsl(var(--sidebar-accent));--tw-shadow-colored: 0 0 0 1px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.hover\\:brightness-110:hover{--tw-brightness: brightness(1.1);filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.hover\\:after\\:bg-sidebar-border:hover:after{content:var(--tw-content);background-color:hsl(var(--sidebar-border))}.focus\\:border-blue-500:focus{--tw-border-opacity: 1;border-color:rgb(59 130 246 / var(--tw-border-opacity, 1))}.focus\\:border-purple-500:focus{--tw-border-opacity: 1;border-color:rgb(168 85 247 / var(--tw-border-opacity, 1))}.focus\\:bg-accent:focus{background-color:hsl(var(--accent))}.focus\\:bg-primary:focus{background-color:hsl(var(--primary))}.focus\\:text-accent-foreground:focus{color:hsl(var(--accent-foreground))}.focus\\:text-primary-foreground:focus{color:hsl(var(--primary-foreground))}.focus\\:opacity-100:focus{opacity:1}.focus\\:outline-none:focus{outline:2px solid transparent;outline-offset:2px}.focus\\:ring-1:focus{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus\\:ring-2:focus{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus\\:ring-ring:focus{--tw-ring-color: hsl(var(--ring))}.focus\\:ring-offset-2:focus{--tw-ring-offset-width: 2px}.focus-visible\\:outline-none:focus-visible{outline:2px solid transparent;outline-offset:2px}.focus-visible\\:ring-1:focus-visible{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus-visible\\:ring-2:focus-visible{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus-visible\\:ring-ring:focus-visible{--tw-ring-color: hsl(var(--ring))}.focus-visible\\:ring-sidebar-ring:focus-visible{--tw-ring-color: hsl(var(--sidebar-ring))}.focus-visible\\:ring-offset-1:focus-visible{--tw-ring-offset-width: 1px}.focus-visible\\:ring-offset-2:focus-visible{--tw-ring-offset-width: 2px}.focus-visible\\:ring-offset-background:focus-visible{--tw-ring-offset-color: hsl(var(--background))}.active\\:bg-gray-600:active{--tw-bg-opacity: 1;background-color:rgb(75 85 99 / var(--tw-bg-opacity, 1))}.active\\:bg-sidebar-accent:active{background-color:hsl(var(--sidebar-accent))}.active\\:text-sidebar-accent-foreground:active{color:hsl(var(--sidebar-accent-foreground))}.disabled\\:pointer-events-none:disabled{pointer-events:none}.disabled\\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\\:bg-gray-700:disabled{--tw-bg-opacity: 1;background-color:rgb(55 65 81 / var(--tw-bg-opacity, 1))}.disabled\\:text-gray-500:disabled{--tw-text-opacity: 1;color:rgb(107 114 128 / var(--tw-text-opacity, 1))}.disabled\\:opacity-30:disabled{opacity:.3}.disabled\\:opacity-40:disabled{opacity:.4}.disabled\\:opacity-50:disabled{opacity:.5}.disabled\\:shadow-none:disabled{--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.group\\/menu-item:focus-within .group-focus-within\\/menu-item\\:opacity-100{opacity:1}.group\\/menu-item:hover .group-hover\\/menu-item\\:opacity-100,.group:hover .group-hover\\:opacity-100{opacity:1}.group.destructive .group-\\[\\.destructive\\]\\:border-muted\\/40{border-color:hsl(var(--muted) / .4)}.group.toaster .group-\\[\\.toaster\\]\\:border-border{border-color:hsl(var(--border))}.group.toast .group-\\[\\.toast\\]\\:bg-muted{background-color:hsl(var(--muted))}.group.toast .group-\\[\\.toast\\]\\:bg-primary{background-color:hsl(var(--primary))}.group.toaster .group-\\[\\.toaster\\]\\:bg-background{background-color:hsl(var(--background))}.group.destructive .group-\\[\\.destructive\\]\\:text-red-300{--tw-text-opacity: 1;color:rgb(252 165 165 / var(--tw-text-opacity, 1))}.group.toast .group-\\[\\.toast\\]\\:text-muted-foreground{color:hsl(var(--muted-foreground))}.group.toast .group-\\[\\.toast\\]\\:text-primary-foreground{color:hsl(var(--primary-foreground))}.group.toaster .group-\\[\\.toaster\\]\\:text-foreground{color:hsl(var(--foreground))}.group.toaster .group-\\[\\.toaster\\]\\:shadow-lg{--tw-shadow: 0 10px 15px -3px rgb(0 0 0 / .1), 0 4px 6px -4px rgb(0 0 0 / .1);--tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.group.destructive .group-\\[\\.destructive\\]\\:hover\\:border-destructive\\/30:hover{border-color:hsl(var(--destructive) / .3)}.group.destructive .group-\\[\\.destructive\\]\\:hover\\:bg-destructive:hover{background-color:hsl(var(--destructive))}.group.destructive .group-\\[\\.destructive\\]\\:hover\\:text-destructive-foreground:hover{color:hsl(var(--destructive-foreground))}.group.destructive .group-\\[\\.destructive\\]\\:hover\\:text-red-50:hover{--tw-text-opacity: 1;color:rgb(254 242 242 / var(--tw-text-opacity, 1))}.group.destructive .group-\\[\\.destructive\\]\\:focus\\:ring-destructive:focus{--tw-ring-color: hsl(var(--destructive))}.group.destructive .group-\\[\\.destructive\\]\\:focus\\:ring-red-400:focus{--tw-ring-opacity: 1;--tw-ring-color: rgb(248 113 113 / var(--tw-ring-opacity, 1))}.group.destructive .group-\\[\\.destructive\\]\\:focus\\:ring-offset-red-600:focus{--tw-ring-offset-color: #dc2626}.peer\\/menu-button:hover~.peer-hover\\/menu-button\\:text-sidebar-accent-foreground{color:hsl(var(--sidebar-accent-foreground))}.peer:disabled~.peer-disabled\\:cursor-not-allowed{cursor:not-allowed}.peer:disabled~.peer-disabled\\:opacity-70{opacity:.7}.has-\\[\\[data-variant\\=inset\\]\\]\\:bg-sidebar:has([data-variant=inset]){background-color:hsl(var(--sidebar-background))}.has-\\[\\:disabled\\]\\:opacity-50:has(:disabled){opacity:.5}.group\\/menu-item:has([data-sidebar=menu-action]) .group-has-\\[\\[data-sidebar\\=menu-action\\]\\]\\/menu-item\\:pr-8{padding-right:2rem}.aria-disabled\\:pointer-events-none[aria-disabled=true]{pointer-events:none}.aria-disabled\\:opacity-50[aria-disabled=true]{opacity:.5}.aria-selected\\:bg-accent[aria-selected=true]{background-color:hsl(var(--accent))}.aria-selected\\:bg-accent\\/50[aria-selected=true]{background-color:hsl(var(--accent) / .5)}.aria-selected\\:text-accent-foreground[aria-selected=true]{color:hsl(var(--accent-foreground))}.aria-selected\\:text-muted-foreground[aria-selected=true]{color:hsl(var(--muted-foreground))}.aria-selected\\:opacity-100[aria-selected=true]{opacity:1}.data-\\[disabled\\=true\\]\\:pointer-events-none[data-disabled=true],.data-\\[disabled\\]\\:pointer-events-none[data-disabled]{pointer-events:none}.data-\\[panel-group-direction\\=vertical\\]\\:h-px[data-panel-group-direction=vertical]{height:1px}.data-\\[panel-group-direction\\=vertical\\]\\:w-full[data-panel-group-direction=vertical]{width:100%}.data-\\[side\\=bottom\\]\\:translate-y-1[data-side=bottom]{--tw-translate-y: .25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\\[side\\=left\\]\\:-translate-x-1[data-side=left]{--tw-translate-x: -.25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\\[side\\=right\\]\\:translate-x-1[data-side=right]{--tw-translate-x: .25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\\[side\\=top\\]\\:-translate-y-1[data-side=top]{--tw-translate-y: -.25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\\[state\\=checked\\]\\:translate-x-4[data-state=checked]{--tw-translate-x: 1rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\\[state\\=unchecked\\]\\:translate-x-0[data-state=unchecked],.data-\\[swipe\\=cancel\\]\\:translate-x-0[data-swipe=cancel]{--tw-translate-x: 0px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\\[swipe\\=end\\]\\:translate-x-\\[var\\(--radix-toast-swipe-end-x\\)\\][data-swipe=end]{--tw-translate-x: var(--radix-toast-swipe-end-x);transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\\[swipe\\=move\\]\\:translate-x-\\[var\\(--radix-toast-swipe-move-x\\)\\][data-swipe=move]{--tw-translate-x: var(--radix-toast-swipe-move-x);transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}@keyframes accordion-up{0%{height:var(--radix-accordion-content-height)}to{height:0}}.data-\\[state\\=closed\\]\\:animate-accordion-up[data-state=closed]{animation:accordion-up .2s ease-out}@keyframes accordion-down{0%{height:0}to{height:var(--radix-accordion-content-height)}}.data-\\[state\\=open\\]\\:animate-accordion-down[data-state=open]{animation:accordion-down .2s ease-out}.data-\\[panel-group-direction\\=vertical\\]\\:flex-col[data-panel-group-direction=vertical]{flex-direction:column}.data-\\[active\\=true\\]\\:bg-sidebar-accent[data-active=true]{background-color:hsl(var(--sidebar-accent))}.data-\\[active\\]\\:bg-accent\\/50[data-active]{background-color:hsl(var(--accent) / .5)}.data-\\[selected\\=true\\]\\:bg-accent[data-selected=true]{background-color:hsl(var(--accent))}.data-\\[state\\=active\\]\\:bg-background[data-state=active]{background-color:hsl(var(--background))}.data-\\[state\\=checked\\]\\:bg-primary[data-state=checked]{background-color:hsl(var(--primary))}.data-\\[state\\=on\\]\\:bg-accent[data-state=on],.data-\\[state\\=open\\]\\:bg-accent[data-state=open]{background-color:hsl(var(--accent))}.data-\\[state\\=open\\]\\:bg-accent\\/50[data-state=open]{background-color:hsl(var(--accent) / .5)}.data-\\[state\\=open\\]\\:bg-secondary[data-state=open]{background-color:hsl(var(--secondary))}.data-\\[state\\=selected\\]\\:bg-muted[data-state=selected]{background-color:hsl(var(--muted))}.data-\\[state\\=unchecked\\]\\:bg-input[data-state=unchecked]{background-color:hsl(var(--input))}.data-\\[active\\=true\\]\\:font-medium[data-active=true]{font-weight:500}.data-\\[active\\=true\\]\\:text-sidebar-accent-foreground[data-active=true]{color:hsl(var(--sidebar-accent-foreground))}.data-\\[placeholder\\]\\:text-muted-foreground[data-placeholder]{color:hsl(var(--muted-foreground))}.data-\\[selected\\=true\\]\\:text-accent-foreground[data-selected=true]{color:hsl(var(--accent-foreground))}.data-\\[state\\=active\\]\\:text-foreground[data-state=active]{color:hsl(var(--foreground))}.data-\\[state\\=checked\\]\\:text-primary-foreground[data-state=checked]{color:hsl(var(--primary-foreground))}.data-\\[state\\=on\\]\\:text-accent-foreground[data-state=on],.data-\\[state\\=open\\]\\:text-accent-foreground[data-state=open]{color:hsl(var(--accent-foreground))}.data-\\[state\\=open\\]\\:text-muted-foreground[data-state=open]{color:hsl(var(--muted-foreground))}.data-\\[disabled\\=true\\]\\:opacity-50[data-disabled=true],.data-\\[disabled\\]\\:opacity-50[data-disabled]{opacity:.5}.data-\\[state\\=open\\]\\:opacity-100[data-state=open]{opacity:1}.data-\\[state\\=active\\]\\:shadow[data-state=active]{--tw-shadow: 0 1px 3px 0 rgb(0 0 0 / .1), 0 1px 2px -1px rgb(0 0 0 / .1);--tw-shadow-colored: 0 1px 3px 0 var(--tw-shadow-color), 0 1px 2px -1px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.data-\\[swipe\\=move\\]\\:transition-none[data-swipe=move]{transition-property:none}.data-\\[state\\=closed\\]\\:duration-300[data-state=closed]{transition-duration:.3s}.data-\\[state\\=open\\]\\:duration-500[data-state=open]{transition-duration:.5s}.data-\\[motion\\^\\=from-\\]\\:animate-in[data-motion^=from-],.data-\\[state\\=open\\]\\:animate-in[data-state=open],.data-\\[state\\=visible\\]\\:animate-in[data-state=visible]{animation-name:enter;animation-duration:.15s;--tw-enter-opacity: initial;--tw-enter-scale: initial;--tw-enter-rotate: initial;--tw-enter-translate-x: initial;--tw-enter-translate-y: initial}.data-\\[motion\\^\\=to-\\]\\:animate-out[data-motion^=to-],.data-\\[state\\=closed\\]\\:animate-out[data-state=closed],.data-\\[state\\=hidden\\]\\:animate-out[data-state=hidden],.data-\\[swipe\\=end\\]\\:animate-out[data-swipe=end]{animation-name:exit;animation-duration:.15s;--tw-exit-opacity: initial;--tw-exit-scale: initial;--tw-exit-rotate: initial;--tw-exit-translate-x: initial;--tw-exit-translate-y: initial}.data-\\[motion\\^\\=from-\\]\\:fade-in[data-motion^=from-]{--tw-enter-opacity: 0}.data-\\[motion\\^\\=to-\\]\\:fade-out[data-motion^=to-],.data-\\[state\\=closed\\]\\:fade-out-0[data-state=closed]{--tw-exit-opacity: 0}.data-\\[state\\=closed\\]\\:fade-out-80[data-state=closed]{--tw-exit-opacity: .8}.data-\\[state\\=hidden\\]\\:fade-out[data-state=hidden]{--tw-exit-opacity: 0}.data-\\[state\\=open\\]\\:fade-in-0[data-state=open],.data-\\[state\\=visible\\]\\:fade-in[data-state=visible]{--tw-enter-opacity: 0}.data-\\[state\\=closed\\]\\:zoom-out-95[data-state=closed]{--tw-exit-scale: .95}.data-\\[state\\=open\\]\\:zoom-in-90[data-state=open]{--tw-enter-scale: .9}.data-\\[state\\=open\\]\\:zoom-in-95[data-state=open]{--tw-enter-scale: .95}.data-\\[motion\\=from-end\\]\\:slide-in-from-right-52[data-motion=from-end]{--tw-enter-translate-x: 13rem}.data-\\[motion\\=from-start\\]\\:slide-in-from-left-52[data-motion=from-start]{--tw-enter-translate-x: -13rem}.data-\\[motion\\=to-end\\]\\:slide-out-to-right-52[data-motion=to-end]{--tw-exit-translate-x: 13rem}.data-\\[motion\\=to-start\\]\\:slide-out-to-left-52[data-motion=to-start]{--tw-exit-translate-x: -13rem}.data-\\[side\\=bottom\\]\\:slide-in-from-top-2[data-side=bottom]{--tw-enter-translate-y: -.5rem}.data-\\[side\\=left\\]\\:slide-in-from-right-2[data-side=left]{--tw-enter-translate-x: .5rem}.data-\\[side\\=right\\]\\:slide-in-from-left-2[data-side=right]{--tw-enter-translate-x: -.5rem}.data-\\[side\\=top\\]\\:slide-in-from-bottom-2[data-side=top]{--tw-enter-translate-y: .5rem}.data-\\[state\\=closed\\]\\:slide-out-to-bottom[data-state=closed]{--tw-exit-translate-y: 100%}.data-\\[state\\=closed\\]\\:slide-out-to-left[data-state=closed]{--tw-exit-translate-x: -100%}.data-\\[state\\=closed\\]\\:slide-out-to-left-1\\/2[data-state=closed]{--tw-exit-translate-x: -50%}.data-\\[state\\=closed\\]\\:slide-out-to-right[data-state=closed],.data-\\[state\\=closed\\]\\:slide-out-to-right-full[data-state=closed]{--tw-exit-translate-x: 100%}.data-\\[state\\=closed\\]\\:slide-out-to-top[data-state=closed]{--tw-exit-translate-y: -100%}.data-\\[state\\=closed\\]\\:slide-out-to-top-\\[48\\%\\][data-state=closed]{--tw-exit-translate-y: -48%}.data-\\[state\\=open\\]\\:slide-in-from-bottom[data-state=open]{--tw-enter-translate-y: 100%}.data-\\[state\\=open\\]\\:slide-in-from-left[data-state=open]{--tw-enter-translate-x: -100%}.data-\\[state\\=open\\]\\:slide-in-from-left-1\\/2[data-state=open]{--tw-enter-translate-x: -50%}.data-\\[state\\=open\\]\\:slide-in-from-right[data-state=open]{--tw-enter-translate-x: 100%}.data-\\[state\\=open\\]\\:slide-in-from-top[data-state=open]{--tw-enter-translate-y: -100%}.data-\\[state\\=open\\]\\:slide-in-from-top-\\[48\\%\\][data-state=open]{--tw-enter-translate-y: -48%}.data-\\[state\\=open\\]\\:slide-in-from-top-full[data-state=open]{--tw-enter-translate-y: -100%}.data-\\[state\\=closed\\]\\:duration-300[data-state=closed]{animation-duration:.3s}.data-\\[state\\=open\\]\\:duration-500[data-state=open]{animation-duration:.5s}.data-\\[panel-group-direction\\=vertical\\]\\:after\\:left-0[data-panel-group-direction=vertical]:after{content:var(--tw-content);left:0}.data-\\[panel-group-direction\\=vertical\\]\\:after\\:h-1[data-panel-group-direction=vertical]:after{content:var(--tw-content);height:.25rem}.data-\\[panel-group-direction\\=vertical\\]\\:after\\:w-full[data-panel-group-direction=vertical]:after{content:var(--tw-content);width:100%}.data-\\[panel-group-direction\\=vertical\\]\\:after\\:-translate-y-1\\/2[data-panel-group-direction=vertical]:after{content:var(--tw-content);--tw-translate-y: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\\[panel-group-direction\\=vertical\\]\\:after\\:translate-x-0[data-panel-group-direction=vertical]:after{content:var(--tw-content);--tw-translate-x: 0px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\\[state\\=open\\]\\:hover\\:bg-sidebar-accent:hover[data-state=open]{background-color:hsl(var(--sidebar-accent))}.data-\\[state\\=open\\]\\:hover\\:text-sidebar-accent-foreground:hover[data-state=open]{color:hsl(var(--sidebar-accent-foreground))}.group[data-collapsible=offcanvas] .group-data-\\[collapsible\\=offcanvas\\]\\:left-\\[calc\\(var\\(--sidebar-width\\)\\*-1\\)\\]{left:calc(var(--sidebar-width) * -1)}.group[data-collapsible=offcanvas] .group-data-\\[collapsible\\=offcanvas\\]\\:right-\\[calc\\(var\\(--sidebar-width\\)\\*-1\\)\\]{right:calc(var(--sidebar-width) * -1)}.group[data-side=left] .group-data-\\[side\\=left\\]\\:-right-4{right:-1rem}.group[data-side=right] .group-data-\\[side\\=right\\]\\:left-0{left:0}.group[data-collapsible=icon] .group-data-\\[collapsible\\=icon\\]\\:-mt-8{margin-top:-2rem}.group[data-collapsible=icon] .group-data-\\[collapsible\\=icon\\]\\:hidden{display:none}.group[data-collapsible=icon] .group-data-\\[collapsible\\=icon\\]\\:\\!size-8{width:2rem!important;height:2rem!important}.group[data-collapsible=icon] .group-data-\\[collapsible\\=icon\\]\\:w-\\[--sidebar-width-icon\\]{width:var(--sidebar-width-icon)}.group[data-collapsible=icon] .group-data-\\[collapsible\\=icon\\]\\:w-\\[calc\\(var\\(--sidebar-width-icon\\)_\\+_theme\\(spacing\\.4\\)\\)\\]{width:calc(var(--sidebar-width-icon) + 1rem)}.group[data-collapsible=icon] .group-data-\\[collapsible\\=icon\\]\\:w-\\[calc\\(var\\(--sidebar-width-icon\\)_\\+_theme\\(spacing\\.4\\)_\\+2px\\)\\]{width:calc(var(--sidebar-width-icon) + 1rem + 2px)}.group[data-collapsible=offcanvas] .group-data-\\[collapsible\\=offcanvas\\]\\:w-0{width:0px}.group[data-collapsible=offcanvas] .group-data-\\[collapsible\\=offcanvas\\]\\:translate-x-0{--tw-translate-x: 0px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.group[data-side=right] .group-data-\\[side\\=right\\]\\:rotate-180,.group[data-state=open] .group-data-\\[state\\=open\\]\\:rotate-180{--tw-rotate: 180deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.group[data-collapsible=icon] .group-data-\\[collapsible\\=icon\\]\\:overflow-hidden{overflow:hidden}.group[data-variant=floating] .group-data-\\[variant\\=floating\\]\\:rounded-lg{border-radius:var(--radius)}.group[data-variant=floating] .group-data-\\[variant\\=floating\\]\\:border{border-width:1px}.group[data-side=left] .group-data-\\[side\\=left\\]\\:border-r{border-right-width:1px}.group[data-side=right] .group-data-\\[side\\=right\\]\\:border-l{border-left-width:1px}.group[data-variant=floating] .group-data-\\[variant\\=floating\\]\\:border-sidebar-border{border-color:hsl(var(--sidebar-border))}.group[data-collapsible=icon] .group-data-\\[collapsible\\=icon\\]\\:\\!p-0{padding:0!important}.group[data-collapsible=icon] .group-data-\\[collapsible\\=icon\\]\\:\\!p-2{padding:.5rem!important}.group[data-collapsible=icon] .group-data-\\[collapsible\\=icon\\]\\:opacity-0{opacity:0}.group[data-variant=floating] .group-data-\\[variant\\=floating\\]\\:shadow{--tw-shadow: 0 1px 3px 0 rgb(0 0 0 / .1), 0 1px 2px -1px rgb(0 0 0 / .1);--tw-shadow-colored: 0 1px 3px 0 var(--tw-shadow-color), 0 1px 2px -1px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.group[data-collapsible=offcanvas] .group-data-\\[collapsible\\=offcanvas\\]\\:after\\:left-full:after{content:var(--tw-content);left:100%}.group[data-collapsible=offcanvas] .group-data-\\[collapsible\\=offcanvas\\]\\:hover\\:bg-sidebar:hover{background-color:hsl(var(--sidebar-background))}.peer\\/menu-button[data-size=default]~.peer-data-\\[size\\=default\\]\\/menu-button\\:top-1\\.5{top:.375rem}.peer\\/menu-button[data-size=lg]~.peer-data-\\[size\\=lg\\]\\/menu-button\\:top-2\\.5{top:.625rem}.peer\\/menu-button[data-size=sm]~.peer-data-\\[size\\=sm\\]\\/menu-button\\:top-1{top:.25rem}.peer[data-variant=inset]~.peer-data-\\[variant\\=inset\\]\\:min-h-\\[calc\\(100svh-theme\\(spacing\\.4\\)\\)\\]{min-height:calc(100svh - 1rem)}.peer\\/menu-button[data-active=true]~.peer-data-\\[active\\=true\\]\\/menu-button\\:text-sidebar-accent-foreground{color:hsl(var(--sidebar-accent-foreground))}.dark\\:border-destructive:is(.dark *){border-color:hsl(var(--destructive))}@media(min-width:640px){.sm\\:bottom-0{bottom:0}.sm\\:right-0{right:0}.sm\\:top-auto{top:auto}.sm\\:mt-0{margin-top:0}.sm\\:flex{display:flex}.sm\\:max-w-sm{max-width:24rem}.sm\\:flex-row{flex-direction:row}.sm\\:flex-col{flex-direction:column}.sm\\:justify-end{justify-content:flex-end}.sm\\:gap-2\\.5{gap:.625rem}.sm\\:space-x-2>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(.5rem * var(--tw-space-x-reverse));margin-left:calc(.5rem * calc(1 - var(--tw-space-x-reverse)))}.sm\\:space-x-4>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(1rem * var(--tw-space-x-reverse));margin-left:calc(1rem * calc(1 - var(--tw-space-x-reverse)))}.sm\\:space-y-0>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(0px * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(0px * var(--tw-space-y-reverse))}.sm\\:rounded-lg{border-radius:var(--radius)}.sm\\:text-left{text-align:left}.data-\\[state\\=open\\]\\:sm\\:slide-in-from-bottom-full[data-state=open]{--tw-enter-translate-y: 100%}}@media(min-width:768px){.md\\:absolute{position:absolute}.md\\:block{display:block}.md\\:flex{display:flex}.md\\:w-\\[var\\(--radix-navigation-menu-viewport-width\\)\\]{width:var(--radix-navigation-menu-viewport-width)}.md\\:w-auto{width:auto}.md\\:max-w-\\[420px\\]{max-width:420px}.md\\:text-sm{font-size:.875rem;line-height:1.25rem}.md\\:opacity-0{opacity:0}.after\\:md\\:hidden:after{content:var(--tw-content);display:none}.peer[data-variant=inset]~.md\\:peer-data-\\[variant\\=inset\\]\\:m-2{margin:.5rem}.peer[data-state=collapsed][data-variant=inset]~.md\\:peer-data-\\[state\\=collapsed\\]\\:peer-data-\\[variant\\=inset\\]\\:ml-2{margin-left:.5rem}.peer[data-variant=inset]~.md\\:peer-data-\\[variant\\=inset\\]\\:ml-0{margin-left:0}.peer[data-variant=inset]~.md\\:peer-data-\\[variant\\=inset\\]\\:rounded-xl{border-radius:.75rem}.peer[data-variant=inset]~.md\\:peer-data-\\[variant\\=inset\\]\\:shadow{--tw-shadow: 0 1px 3px 0 rgb(0 0 0 / .1), 0 1px 2px -1px rgb(0 0 0 / .1);--tw-shadow-colored: 0 1px 3px 0 var(--tw-shadow-color), 0 1px 2px -1px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}}.\\[\\&\\:has\\(\\>\\.day-range-end\\)\\]\\:rounded-r-md:has(>.day-range-end){border-top-right-radius:calc(var(--radius) - 2px);border-bottom-right-radius:calc(var(--radius) - 2px)}.\\[\\&\\:has\\(\\>\\.day-range-start\\)\\]\\:rounded-l-md:has(>.day-range-start){border-top-left-radius:calc(var(--radius) - 2px);border-bottom-left-radius:calc(var(--radius) - 2px)}.\\[\\&\\:has\\(\\[aria-selected\\]\\)\\]\\:rounded-md:has([aria-selected]){border-radius:calc(var(--radius) - 2px)}.\\[\\&\\:has\\(\\[aria-selected\\]\\)\\]\\:bg-accent:has([aria-selected]){background-color:hsl(var(--accent))}.first\\:\\[\\&\\:has\\(\\[aria-selected\\]\\)\\]\\:rounded-l-md:has([aria-selected]):first-child{border-top-left-radius:calc(var(--radius) - 2px);border-bottom-left-radius:calc(var(--radius) - 2px)}.last\\:\\[\\&\\:has\\(\\[aria-selected\\]\\)\\]\\:rounded-r-md:has([aria-selected]):last-child{border-top-right-radius:calc(var(--radius) - 2px);border-bottom-right-radius:calc(var(--radius) - 2px)}.\\[\\&\\:has\\(\\[aria-selected\\]\\.day-outside\\)\\]\\:bg-accent\\/50:has([aria-selected].day-outside){background-color:hsl(var(--accent) / .5)}.\\[\\&\\:has\\(\\[aria-selected\\]\\.day-range-end\\)\\]\\:rounded-r-md:has([aria-selected].day-range-end){border-top-right-radius:calc(var(--radius) - 2px);border-bottom-right-radius:calc(var(--radius) - 2px)}.\\[\\&\\:has\\(\\[role\\=checkbox\\]\\)\\]\\:pr-0:has([role=checkbox]){padding-right:0}.\\[\\&\\>\\[role\\=checkbox\\]\\]\\:translate-y-\\[2px\\]>[role=checkbox]{--tw-translate-y: 2px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.\\[\\&\\>button\\]\\:hidden>button{display:none}.\\[\\&\\>span\\:last-child\\]\\:truncate>span:last-child{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.\\[\\&\\>span\\]\\:line-clamp-1>span{overflow:hidden;display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:1}.\\[\\&\\>svg\\+div\\]\\:translate-y-\\[-3px\\]>svg+div{--tw-translate-y: -3px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.\\[\\&\\>svg\\]\\:absolute>svg{position:absolute}.\\[\\&\\>svg\\]\\:left-4>svg{left:1rem}.\\[\\&\\>svg\\]\\:top-4>svg{top:1rem}.\\[\\&\\>svg\\]\\:size-4>svg{width:1rem;height:1rem}.\\[\\&\\>svg\\]\\:h-2\\.5>svg{height:.625rem}.\\[\\&\\>svg\\]\\:h-3>svg{height:.75rem}.\\[\\&\\>svg\\]\\:h-3\\.5>svg{height:.875rem}.\\[\\&\\>svg\\]\\:w-2\\.5>svg{width:.625rem}.\\[\\&\\>svg\\]\\:w-3>svg{width:.75rem}.\\[\\&\\>svg\\]\\:w-3\\.5>svg{width:.875rem}.\\[\\&\\>svg\\]\\:shrink-0>svg{flex-shrink:0}.\\[\\&\\>svg\\]\\:text-destructive>svg{color:hsl(var(--destructive))}.\\[\\&\\>svg\\]\\:text-foreground>svg{color:hsl(var(--foreground))}.\\[\\&\\>svg\\]\\:text-muted-foreground>svg{color:hsl(var(--muted-foreground))}.\\[\\&\\>svg\\]\\:text-sidebar-accent-foreground>svg{color:hsl(var(--sidebar-accent-foreground))}.\\[\\&\\>svg\\~\\*\\]\\:pl-7>svg~*{padding-left:1.75rem}.\\[\\&\\>tr\\]\\:last\\:border-b-0:last-child>tr{border-bottom-width:0px}.\\[\\&\\[data-panel-group-direction\\=vertical\\]\\>div\\]\\:rotate-90[data-panel-group-direction=vertical]>div{--tw-rotate: 90deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.\\[\\&\\[data-state\\=open\\]\\>svg\\]\\:rotate-180[data-state=open]>svg{--tw-rotate: 180deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.\\[\\&_\\.recharts-cartesian-axis-tick_text\\]\\:fill-muted-foreground .recharts-cartesian-axis-tick text{fill:hsl(var(--muted-foreground))}.\\[\\&_\\.recharts-cartesian-grid_line\\[stroke\\=\\\'\\#ccc\\\'\\]\\]\\:stroke-border\\/50 .recharts-cartesian-grid line[stroke="#ccc"]{stroke:hsl(var(--border) / .5)}.\\[\\&_\\.recharts-curve\\.recharts-tooltip-cursor\\]\\:stroke-border .recharts-curve.recharts-tooltip-cursor{stroke:hsl(var(--border))}.\\[\\&_\\.recharts-dot\\[stroke\\=\\\'\\#fff\\\'\\]\\]\\:stroke-transparent .recharts-dot[stroke="#fff"]{stroke:transparent}.\\[\\&_\\.recharts-layer\\]\\:outline-none .recharts-layer{outline:2px solid transparent;outline-offset:2px}.\\[\\&_\\.recharts-polar-grid_\\[stroke\\=\\\'\\#ccc\\\'\\]\\]\\:stroke-border .recharts-polar-grid [stroke="#ccc"]{stroke:hsl(var(--border))}.\\[\\&_\\.recharts-radial-bar-background-sector\\]\\:fill-muted .recharts-radial-bar-background-sector,.\\[\\&_\\.recharts-rectangle\\.recharts-tooltip-cursor\\]\\:fill-muted .recharts-rectangle.recharts-tooltip-cursor{fill:hsl(var(--muted))}.\\[\\&_\\.recharts-reference-line_\\[stroke\\=\\\'\\#ccc\\\'\\]\\]\\:stroke-border .recharts-reference-line [stroke="#ccc"]{stroke:hsl(var(--border))}.\\[\\&_\\.recharts-sector\\[stroke\\=\\\'\\#fff\\\'\\]\\]\\:stroke-transparent .recharts-sector[stroke="#fff"]{stroke:transparent}.\\[\\&_\\.recharts-sector\\]\\:outline-none .recharts-sector,.\\[\\&_\\.recharts-surface\\]\\:outline-none .recharts-surface{outline:2px solid transparent;outline-offset:2px}.\\[\\&_\\[cmdk-group-heading\\]\\]\\:px-2 [cmdk-group-heading]{padding-left:.5rem;padding-right:.5rem}.\\[\\&_\\[cmdk-group-heading\\]\\]\\:py-1\\.5 [cmdk-group-heading]{padding-top:.375rem;padding-bottom:.375rem}.\\[\\&_\\[cmdk-group-heading\\]\\]\\:text-xs [cmdk-group-heading]{font-size:.75rem;line-height:1rem}.\\[\\&_\\[cmdk-group-heading\\]\\]\\:font-medium [cmdk-group-heading]{font-weight:500}.\\[\\&_\\[cmdk-group-heading\\]\\]\\:text-muted-foreground [cmdk-group-heading]{color:hsl(var(--muted-foreground))}.\\[\\&_\\[cmdk-group\\]\\:not\\(\\[hidden\\]\\)_\\~\\[cmdk-group\\]\\]\\:pt-0 [cmdk-group]:not([hidden])~[cmdk-group]{padding-top:0}.\\[\\&_\\[cmdk-group\\]\\]\\:px-2 [cmdk-group]{padding-left:.5rem;padding-right:.5rem}.\\[\\&_\\[cmdk-input-wrapper\\]_svg\\]\\:h-5 [cmdk-input-wrapper] svg{height:1.25rem}.\\[\\&_\\[cmdk-input-wrapper\\]_svg\\]\\:w-5 [cmdk-input-wrapper] svg{width:1.25rem}.\\[\\&_\\[cmdk-input\\]\\]\\:h-12 [cmdk-input]{height:3rem}.\\[\\&_\\[cmdk-item\\]\\]\\:px-2 [cmdk-item]{padding-left:.5rem;padding-right:.5rem}.\\[\\&_\\[cmdk-item\\]\\]\\:py-3 [cmdk-item]{padding-top:.75rem;padding-bottom:.75rem}.\\[\\&_\\[cmdk-item\\]_svg\\]\\:h-5 [cmdk-item] svg{height:1.25rem}.\\[\\&_\\[cmdk-item\\]_svg\\]\\:w-5 [cmdk-item] svg{width:1.25rem}.\\[\\&_p\\]\\:leading-relaxed p{line-height:1.625}.\\[\\&_svg\\]\\:pointer-events-none svg{pointer-events:none}.\\[\\&_svg\\]\\:size-4 svg{width:1rem;height:1rem}.\\[\\&_svg\\]\\:shrink-0 svg{flex-shrink:0}.\\[\\&_tr\\:last-child\\]\\:border-0 tr:last-child{border-width:0px}.\\[\\&_tr\\]\\:border-b tr{border-bottom-width:1px}[data-side=left][data-collapsible=offcanvas] .\\[\\[data-side\\=left\\]\\[data-collapsible\\=offcanvas\\]_\\&\\]\\:-right-2{right:-.5rem}[data-side=left][data-state=collapsed] .\\[\\[data-side\\=left\\]\\[data-state\\=collapsed\\]_\\&\\]\\:cursor-e-resize{cursor:e-resize}[data-side=left] .\\[\\[data-side\\=left\\]_\\&\\]\\:cursor-w-resize{cursor:w-resize}[data-side=right][data-collapsible=offcanvas] .\\[\\[data-side\\=right\\]\\[data-collapsible\\=offcanvas\\]_\\&\\]\\:-left-2{left:-.5rem}[data-side=right][data-state=collapsed] .\\[\\[data-side\\=right\\]\\[data-state\\=collapsed\\]_\\&\\]\\:cursor-w-resize{cursor:w-resize}[data-side=right] .\\[\\[data-side\\=right\\]_\\&\\]\\:cursor-e-resize{cursor:e-resize}',r.appendChild(i);const o=document.createElement("div");return o.style.cssText="pointer-events:auto;",r.appendChild(o),{container:o,shadow:r,host:n}}function Ld(e,t){if(Boolean(t)&&t){const{container:n}=jd("display:inline-flex;align-items:center;height:100%;pointer-events:auto;",t),{container:r}=jd("position:fixed;z-index:2147483647;bottom:0;right:0;pointer-events:auto;width:0;height:0;",document.body),i=L.createRoot(n),o=L.createRoot(r);let a={status:"disconnected",callStatus:"idle",incomingCallInfo:null};const s=()=>{i.render(v.jsx(Dd,{status:a.status,callStatus:a.callStatus,hasIncomingCall:null!==a.incomingCallInfo,onClick:()=>Od.open(),variant:e.fabStyle||"round"}))};Od.on("__connectionStatusChange",e=>{a.status!==e&&(a.status=e,s())}),Od.on("__callStatusChange",e=>{a.callStatus!==e&&(a.callStatus=e,s())}),Od.on("__incomingCallChange",e=>{a.incomingCallInfo!==e&&(a.incomingCallInfo=e,s())}),o.render(v.jsx(Pd,{config:e,api:Od,embedded:!0})),s()}else{const{container:t}=jd("position:fixed;z-index:2147483647;bottom:0;right:0;pointer-events:auto;width:0;height:0;",document.body);L.createRoot(t).render(v.jsx(Pd,{config:e,api:Od,embedded:!1}))}}function Hd(){const e=function(){const e={},t=document.currentScript||Array.from(document.scripts).find(e=>{var t;return null==(t=e.src)?void 0:t.includes("handphone.js")});if(t){const n=t.dataset.sipUser,r=t.dataset.sipPassword,i=t.dataset.sipDomain,o=t.dataset.sipServer,a=t.dataset.position,s=t.dataset.element,l=t.dataset.fabStyle,c="true"===t.dataset.autoConnect,u=t.dataset.dial;if(n&&(e.username=n),r&&(e.password=r),i&&(e.domain=i),o&&(e.server=o),a&&(e.position=a),s&&(e.element=s),l&&(e.fabStyle=l),c&&(e.autoConnect=!0),u)try{e.dial=JSON.parse(u)}catch{e.dial={number:u,auto:!1}}}return window.HandphoneConfig?{...e,...window.HandphoneConfig}:e}();if(!e.element)return void Ld(e,null);const t=document.querySelector(e.element);if(t)return void Ld(e,t);const n=new MutationObserver(()=>{const t=document.querySelector(e.element);t&&(n.disconnect(),Ld(e,t))});n.observe(document.body,{childList:!0,subtree:!0})}window.Handphone=Od,window.addEventListener("message",e=>{const t=e.data;if(!t||"handphone:dial"!==t.type)return;const n=String(t.number??"").trim();n&&Od.dial(n,{auto:Boolean(t.auto)})}),"loading"===document.readyState?document.addEventListener("DOMContentLoaded",Hd):Hd()}();