@shenyin/embedded-call-widget 3.0.1 → 3.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/checksums.txt +3 -3
- package/embedded-call-widget-runtime.iife.js +5 -5
- package/embedded-call-widget-runtime.js +49 -44
- package/manifest.json +11 -11
- package/package.json +1 -1
|
@@ -5,7 +5,7 @@ var EmbeddedCallWidgetRuntimeBundle=(function(Fe){"use strict";const Pt="0.21.1"
|
|
|
5
5
|
`+d+" | "+Le("",r.column-1," ")+Le("",h-r.column,"^")}else t+=`
|
|
6
6
|
at `+n}return t}}function Ft(a,e){e=e!==void 0?e:{};const t={},i=e.grammarSource,s={Contact:119,Name_Addr_Header:156,Record_Route:176,Request_Response:81,SIP_URI:45,Subscription_State:186,Supported:191,Require:182,Via:194,absoluteURI:84,Call_ID:118,Content_Disposition:130,Content_Length:135,Content_Type:136,CSeq:146,displayName:122,Event:149,From:151,host:52,Max_Forwards:154,Min_SE:213,Proxy_Authenticate:157,quoted_string:40,Refer_To:178,Replaces:179,Session_Expires:210,stun_URI:217,To:192,turn_URI:223,uuid:226,WWW_Authenticate:209,challenge:158,sipfrag:230,Referred_By:231};let r=119;const n=[`\r
|
|
7
7
|
`,p(`\r
|
|
8
|
-
`,!1),/^[0-9]/,$([["0","9"]],!1,!1),/^[a-zA-Z]/,$([["a","z"],["A","Z"]],!1,!1),/^[0-9a-fA-F]/,$([["0","9"],["a","f"],["A","F"]],!1,!1),/^[\0-\xFF]/,$([["\0","ÿ"]],!1,!1),/^["]/,$(['"'],!1,!1)," ",p(" ",!1)," ",p(" ",!1),/^[a-zA-Z0-9]/,$([["a","z"],["A","Z"],["0","9"]],!1,!1),";",p(";",!1),"/",p("/",!1),"?",p("?",!1),":",p(":",!1),"@",p("@",!1),"&",p("&",!1),"=",p("=",!1),"+",p("+",!1),"$",p("$",!1),",",p(",",!1),"-",p("-",!1),"_",p("_",!1),".",p(".",!1),"!",p("!",!1),"~",p("~",!1),"*",p("*",!1),"'",p("'",!1),"(",p("(",!1),")",p(")",!1),"%",p("%",!1),function(){return" "},function(){return":"},/^[!-~]/,$([["!","~"]],!1,!1),/^[\x80-\uFFFF]/,$([["",""]],!1,!1),/^[\x80-\xBF]/,$([["","¿"]],!1,!1),/^[a-f]/,$([["a","f"]],!1,!1),"`",p("`",!1),"<",p("<",!1),">",p(">",!1),"\\",p("\\",!1),"[",p("[",!1),"]",p("]",!1),"{",p("{",!1),"}",p("}",!1),function(){return"*"},function(){return"/"},function(){return"="},function(){return"("},function(){return")"},function(){return">"},function(){return"<"},function(){return","},function(){return";"},function(){return":"},function(){return'"'},/^[!-']/,$([["!","'"]],!1,!1),/^[*-[]/,$([["*","["]],!1,!1),/^[\]-~]/,$([["]","~"]],!1,!1),function(l){return l},/^[#-[]/,$([["#","["]],!1,!1),/^[\0-\t]/,$([["\0"," "]],!1,!1),/^[\v-\f]/,$([["\v","\f"]],!1,!1),/^[\x0E-\x7F]/,$([["",""]],!1,!1),function(){e=e||{data:{}},e.data.uri=new z(e.data.scheme,e.data.user,e.data.host,e.data.port),delete e.data.scheme,delete e.data.user,delete e.data.host,delete e.data.host_type,delete e.data.port},function(){e=e||{data:{}},e.data.uri=new z(e.data.scheme,e.data.user,e.data.host,e.data.port,e.data.uri_params,e.data.uri_headers),delete e.data.scheme,delete e.data.user,delete e.data.host,delete e.data.host_type,delete e.data.port,delete e.data.uri_params,e.startRule==="SIP_URI"&&(e.data=e.data.uri)},"sips",p("sips",!0),"sip",p("sip",!0),function(l){e=e||{data:{}},e.data.scheme=l},function(){e=e||{data:{}},e.data.user=decodeURIComponent(C().slice(0,-1))},function(){e=e||{data:{}},e.data.password=C()},function(){return e=e||{data:{}},e.data.host=C(),e.data.host},function(){return e=e||{data:{}},e.data.host_type="domain",C()},/^[a-zA-Z0-9_\-]/,$([["a","z"],["A","Z"],["0","9"],"_","-"],!1,!1),/^[a-zA-Z0-9\-]/,$([["a","z"],["A","Z"],["0","9"],"-"],!1,!1),function(){return e=e||{data:{}},e.data.host_type="IPv6",C()},"::",p("::",!1),function(){return e=e||{data:{}},e.data.host_type="IPv6",C()},function(){return e=e||{data:{}},e.data.host_type="IPv4",C()},"25",p("25",!1),/^[0-5]/,$([["0","5"]],!1,!1),"2",p("2",!1),/^[0-4]/,$([["0","4"]],!1,!1),"1",p("1",!1),/^[1-9]/,$([["1","9"]],!1,!1),function(l){return e=e||{data:{}},l=parseInt(l.join("")),e.data.port=l,l},"transport=",p("transport=",!0),"udp",p("udp",!0),"tcp",p("tcp",!0),"sctp",p("sctp",!0),"tls",p("tls",!0),function(l){e=e||{data:{}},e.data.uri_params||(e.data.uri_params={}),e.data.uri_params.transport=l.toLowerCase()},"user=",p("user=",!0),"phone",p("phone",!0),"ip",p("ip",!0),function(l){e=e||{data:{}},e.data.uri_params||(e.data.uri_params={}),e.data.uri_params.user=l.toLowerCase()},"method=",p("method=",!0),function(l){e=e||{data:{}},e.data.uri_params||(e.data.uri_params={}),e.data.uri_params.method=l},"ttl=",p("ttl=",!0),function(l){e=e||{data:{}},e.data.params||(e.data.params={}),e.data.params.ttl=l},"maddr=",p("maddr=",!0),function(l){e=e||{data:{}},e.data.uri_params||(e.data.uri_params={}),e.data.uri_params.maddr=l},"lr",p("lr",!0),function(){e=e||{data:{}},e.data.uri_params||(e.data.uri_params={}),e.data.uri_params.lr=void 0},function(l,b){e=e||{data:{}},e.data.uri_params||(e.data.uri_params={}),b===null?b=void 0:b=b[1],e.data.uri_params[l.toLowerCase()]=b},function(l,b){l=l.join("").toLowerCase(),b=b.join(""),e=e||{data:{}},e.data.uri_headers||(e.data.uri_headers={}),e.data.uri_headers[l]?e.data.uri_headers[l].push(b):e.data.uri_headers[l]=[b]},function(){e=e||{data:{}},e.startRule==="Refer_To"&&(e.data.uri=new z(e.data.scheme,e.data.user,e.data.host,e.data.port,e.data.uri_params,e.data.uri_headers),delete e.data.scheme,delete e.data.user,delete e.data.host,delete e.data.host_type,delete e.data.port,delete e.data.uri_params)},"//",p("//",!1),function(){e=e||{data:{}},e.data.scheme=C()},p("SIP",!0),function(){e=e||{data:{}},e.data.sip_version=C()},"INVITE",p("INVITE",!1),"ACK",p("ACK",!1),"VXACH",p("VXACH",!1),"OPTIONS",p("OPTIONS",!1),"BYE",p("BYE",!1),"CANCEL",p("CANCEL",!1),"REGISTER",p("REGISTER",!1),"SUBSCRIBE",p("SUBSCRIBE",!1),"NOTIFY",p("NOTIFY",!1),"REFER",p("REFER",!1),"PUBLISH",p("PUBLISH",!1),function(){return e=e||{data:{}},e.data.method=C(),e.data.method},function(l){e=e||{data:{}},e.data.status_code=parseInt(l.join(""))},function(){e=e||{data:{}},e.data.reason_phrase=C()},function(){e=e||{data:{}},e.data=C()},function(){var l,b;for(e=e||{data:{}},b=e.data.multi_header.length,l=0;l<b;l++)if(e.data.multi_header[l].parsed===null){e.data=null;break}e.data!==null?e.data=e.data.multi_header:e.data=-1},function(){var l;e=e||{data:{}},e.data.multi_header||(e.data.multi_header=[]);try{l=new N(e.data.uri,e.data.displayName,e.data.params),delete e.data.uri,delete e.data.displayName,delete e.data.params}catch{l=null}e.data.multi_header.push({position:d,offset:Q().start.offset,parsed:l})},function(l){l=C().trim(),l[0]==='"'&&(l=l.substring(1,l.length-1)),e=e||{data:{}},e.data.displayName=l},"q",p("q",!0),function(l){e=e||{data:{}},e.data.params||(e.data.params={}),e.data.params.q=l},"expires",p("expires",!0),function(l){e=e||{data:{}},e.data.params||(e.data.params={}),e.data.params.expires=l},function(l){return parseInt(l.join(""))},"0",p("0",!1),function(){return parseFloat(C())},function(l,b){e=e||{data:{}},e.data.params||(e.data.params={}),b===null?b=void 0:b=b[1],e.data.params[l.toLowerCase()]=b},"render",p("render",!0),"session",p("session",!0),"icon",p("icon",!0),"alert",p("alert",!0),function(){e=e||{data:{}},e.startRule==="Content_Disposition"&&(e.data.type=C().toLowerCase())},"handling",p("handling",!0),"optional",p("optional",!0),"required",p("required",!0),function(l){e=e||{data:{}},e.data=parseInt(l.join(""))},function(){e=e||{data:{}},e.data=C()},"text",p("text",!0),"image",p("image",!0),"audio",p("audio",!0),"video",p("video",!0),"application",p("application",!0),"message",p("message",!0),"multipart",p("multipart",!0),"x-",p("x-",!0),function(l){e=e||{data:{}},e.data.value=parseInt(l.join(""))},function(l){e=e||{data:{}},e.data=l},function(l){e=e||{data:{}},e.data.event=l.toLowerCase()},function(){e=e||{data:{}};var l=e.data.tag;e.data=new N(e.data.uri,e.data.displayName,e.data.params),l&&e.data.setParam("tag",l)},"tag",p("tag",!0),function(l){e=e||{data:{}},e.data.tag=l},function(l){e=e||{data:{}},e.data=parseInt(l.join(""))},function(l){e=e||{data:{}},e.data=l},function(){e=e||{data:{}},e.data=new N(e.data.uri,e.data.displayName,e.data.params)},"digest",p("Digest",!0),"realm",p("realm",!0),function(l){e=e||{data:{}},e.data.realm=l},"domain",p("domain",!0),"nonce",p("nonce",!0),function(l){e=e||{data:{}},e.data.nonce=l},"opaque",p("opaque",!0),function(l){e=e||{data:{}},e.data.opaque=l},"stale",p("stale",!0),"true",p("true",!0),function(){e=e||{data:{}},e.data.stale=!0},"false",p("false",!0),function(){e=e||{data:{}},e.data.stale=!1},"algorithm",p("algorithm",!0),"md5",p("MD5",!0),"md5-sess",p("MD5-sess",!0),function(l){e=e||{data:{}},e.data.algorithm=l.toUpperCase()},"qop",p("qop",!0),"auth-int",p("auth-int",!0),"auth",p("auth",!0),function(l){e=e||{data:{}},e.data.qop||(e.data.qop=[]),e.data.qop.push(l.toLowerCase())},function(l){e=e||{data:{}},e.data.value=parseInt(l.join(""))},function(){var l,b;for(e=e||{data:{}},b=e.data.multi_header.length,l=0;l<b;l++)if(e.data.multi_header[l].parsed===null){e.data=null;break}e.data!==null?e.data=e.data.multi_header:e.data=-1},function(){var l;e=e||{data:{}},e.data.multi_header||(e.data.multi_header=[]);try{l=new N(e.data.uri,e.data.displayName,e.data.params),delete e.data.uri,delete e.data.displayName,delete e.data.params}catch{l=null}e.data.multi_header.push({position:d,offset:Q().start.offset,parsed:l})},function(){e=e||{data:{}},e.data=new N(e.data.uri,e.data.displayName,e.data.params)},function(){e=e||{data:{}},e.data.replaces_from_tag&&e.data.replaces_to_tag||(e.data=-1)},function(){e=e||{data:{}},e.data={call_id:e.data}},"from-tag",p("from-tag",!0),function(l){e=e||{data:{}},e.data.replaces_from_tag=l},"to-tag",p("to-tag",!0),function(l){e=e||{data:{}},e.data.replaces_to_tag=l},"early-only",p("early-only",!0),function(){e=e||{data:{}},e.data.early_only=!0},function(l,b){return b},function(l,b){return zi(l,b)},function(l){e=e||{data:{}},e.startRule==="Require"&&(e.data=l||[])},function(l){e=e||{data:{}},e.data.value=parseInt(l.join(""))},"active",p("active",!0),"pending",p("pending",!0),"terminated",p("terminated",!0),function(){e=e||{data:{}},e.data.state=C()},"reason",p("reason",!0),function(l){e=e||{data:{}},typeof l<"u"&&(e.data.reason=l)},function(l){e=e||{data:{}},typeof l<"u"&&(e.data.expires=l)},"retry_after",p("retry_after",!0),function(l){e=e||{data:{}},typeof l<"u"&&(e.data.retry_after=l)},"deactivated",p("deactivated",!0),"probation",p("probation",!0),"rejected",p("rejected",!0),"timeout",p("timeout",!0),"giveup",p("giveup",!0),"noresource",p("noresource",!0),"invariant",p("invariant",!0),function(l){e=e||{data:{}},e.startRule==="Supported"&&(e.data=l||[])},function(){e=e||{data:{}};var l=e.data.tag;e.data=new N(e.data.uri,e.data.displayName,e.data.params),l&&e.data.setParam("tag",l)},"ttl",p("ttl",!0),function(l){e=e||{data:{}},e.data.ttl=l},"maddr",p("maddr",!0),function(l){e=e||{data:{}},e.data.maddr=l},"received",p("received",!0),function(l){e=e||{data:{}},e.data.received=l},"branch",p("branch",!0),function(l){e=e||{data:{}},e.data.branch=l},"rport",p("rport",!0),function(l){e=e||{data:{}},typeof l<"u"&&(e.data.rport=l.join(""))},function(l){e=e||{data:{}},e.data.protocol=l},p("UDP",!0),p("TCP",!0),p("TLS",!0),p("SCTP",!0),function(l){e=e||{data:{}},e.data.transport=l},function(){e=e||{data:{}},e.data.host=C()},function(l){e=e||{data:{}},e.data.port=parseInt(l.join(""))},function(l){return parseInt(l.join(""))},function(l){e=e||{data:{}},e.startRule==="Session_Expires"&&(e.data.deltaSeconds=l)},"refresher",p("refresher",!1),"uas",p("uas",!1),"uac",p("uac",!1),function(l){e=e||{data:{}},e.startRule==="Session_Expires"&&(e.data.refresher=l)},function(l){e=e||{data:{}},e.startRule==="Min_SE"&&(e.data=l)},"stuns",p("stuns",!0),"stun",p("stun",!0),function(l){e=e||{data:{}},e.data.scheme=l},function(l){e=e||{data:{}},e.data.host=l},"?transport=",p("?transport=",!1),"turns",p("turns",!0),"turn",p("turn",!0),function(l){e=e||{data:{}},e.data.transport=l},function(){e=e||{data:{}},e.data=C()},"Referred-By",p("Referred-By",!1),"b",p("b",!1),"cid",p("cid",!1)],o=[c('2 ""6 7!'),c('4"""5!7#'),c('4$""5!7%'),c(`4&""5!7'`),c(";'.# &;("),c('4(""5!7)'),c('4*""5!7+'),c('2,""6,7-'),c('2.""6.7/'),c('40""5!71'),c('22""6273. &24""6475.} &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'),c(";).# &;,"),c('2F""6F7G.} &2H""6H7I.q &2J""6J7K.e &2L""6L7M.Y &2N""6N7O.M &2P""6P7Q.A &2R""6R7S.5 &2T""6T7U.) &2V""6V7W'),c(`%%2X""6X7Y/5#;#/,$;#/#$+#)(#'#("'#&'#/"!&,)`),c(`%%$;$0#*;$&/,#; /#$+")("'#&'#." &"/=#$;$/�#*;$&&&#/'$8":Z" )("'#&'#`),c(';.." &"'),c(`%$;'.# &;(0)*;'.# &;(&/?#28""6879/0$;//'$8#:[# )(#'#("'#&'#`),c(`%%$;2/�#*;2&&&#/g#$%$;.0#*;.&/,#;2/#$+")("'#&'#0=*%$;.0#*;.&/,#;2/#$+")("'#&'#&/#$+")("'#&'#/"!&,)`),c('4\\""5!7].# &;3'),c('4^""5!7_'),c('4`""5!7a'),c(';!.) &4b""5!7c'),c('%$;). &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&&&#/"!&,)'),c('%$;). &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&&&#/"!&,)'),c(`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.) &;'.# &;(`),c('%$;).ī &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&&&#/"!&,)'),c(`%;//?#2P""6P7Q/0$;//'$8#:t# )(#'#("'#&'#`),c(`%;//?#24""6475/0$;//'$8#:u# )(#'#("'#&'#`),c(`%;//?#2>""6>7?/0$;//'$8#:v# )(#'#("'#&'#`),c(`%;//?#2T""6T7U/0$;//'$8#:w# )(#'#("'#&'#`),c(`%;//?#2V""6V7W/0$;//'$8#:x# )(#'#("'#&'#`),c(`%2h""6h7i/0#;//'$8":y" )("'#&'#`),c(`%;//6#2f""6f7g/'$8":z" )("'#&'#`),c(`%;//?#2D""6D7E/0$;//'$8#:{# )(#'#("'#&'#`),c(`%;//?#22""6273/0$;//'$8#:|# )(#'#("'#&'#`),c(`%;//?#28""6879/0$;//'$8#:}# )(#'#("'#&'#`),c(`%;//0#;&/'$8":~" )("'#&'#`),c(`%;&/0#;//'$8":~" )("'#&'#`),c(`%;=/T#$;G.) &;K.# &;F0/*;G.) &;K.# &;F&/,$;>/#$+#)(#'#("'#&'#`),c('4""5!7.A &4""5!7.5 &4""5!7.) &;3.# &;.'),c(`%%;//Q#;&/H$$;J.# &;K0)*;J.# &;K&/,$;&/#$+$)($'#(#'#("'#&'#/"!&,)`),c(`%;//]#;&/T$%$;J.# &;K0)*;J.# &;K&/"!&,)/1$;&/($8$:
$!!)($'#(#'#("'#&'#`),c(';..G &2L""6L7M.; &4""5!7./ &4""5!7.# &;3'),c(`%2j""6j7k/J#4""5!7.5 &4""5!7.) &4""5!7/#$+")("'#&'#`),c(`%;N/M#28""6879/>$;O." &"/0$;S/'$8$:$ )($'#(#'#("'#&'#`),c(`%;N/d#28""6879/U$;O." &"/G$;S/>$;_/5$;l." &"/'$8&:& )(&'#(%'#($'#(#'#("'#&'#`),c(`%3""5$7.) &3""5#7/' 8!:!! )`),c(`%;P/]#%28""6879/,#;R/#$+")("'#&'#." &"/6$2:""6:7;/'$8#:# )(#'#("'#&'#`),c("$;+.) &;-.# &;Q/2#0/*;+.) &;-.# &;Q&&&#"),c('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'),c('%$;+._ &;-.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!:! )'),c(`%;T/J#%28""6879/,#;^/#$+")("'#&'#." &"/#$+")("'#&'#`),c("%;U.) &;\\.# &;X/& 8!:! )"),c(`%$%;V/2#2J""6J7K/#$+")("'#&'#0<*%;V/2#2J""6J7K/#$+")("'#&'#&/D#;W/;$2J""6J7K." &"/'$8#:# )(#'#("'#&'#`),c('$4""5!7/,#0)*4""5!7&&&#'),c(`%4$""5!7%/?#$4""5!70)*4""5!7&/#$+")("'#&'#`),c(`%2l""6l7m/?#;Y/6$2n""6n7o/'$8#:# )(#'#("'#&'#`),c(`%%;Z/³#28""6879/¤$;Z/$28""6879/$;Z/$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+-)(-'#(,'#(+'#(*'#()'#(('#(''#(&'#(%'#($'#(#'#("'#&'#.ސ &%2""67/¤#;Z/$28""6879/$;Z/$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+,)(,'#(+'#(*'#()'#(('#(''#(&'#(%'#($'#(#'#("'#&'#.۹ &%2""67/#;Z/$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+*)(*'#()'#(('#(''#(&'#(%'#($'#(#'#("'#&'#.ٺ &%2""67/t#;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+()(('#(''#(&'#(%'#($'#(#'#("'#&'#.ؓ &%2""67/\\#;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+&)(&'#(%'#($'#(#'#("'#&'#.ׄ &%2""67/D#;Z/;$28""6879/,$;[/#$+$)($'#(#'#("'#&'#.֍ &%2""67/,#;[/#$+")("'#&'#.ծ &%2""67/,#;Z/#$+")("'#&'#.Տ &%;Z/#2""67/$;Z/$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$++)(+'#(*'#()'#(('#(''#(&'#(%'#($'#(#'#("'#&'#.Ӈ &%;Z/ª#%28""6879/,#;Z/#$+")("'#&'#." &"/$2""67/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+*)(*'#()'#(('#(''#(&'#(%'#($'#(#'#("'#&'#.а &%;Z/¹#%28""6879/,#;Z/#$+")("'#&'#." &"/$%28""6879/,#;Z/#$+")("'#&'#." &"/k$2""67/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+))()'#(('#(''#(&'#(%'#($'#(#'#("'#&'#.Ί &%;Z/È#%28""6879/,#;Z/#$+")("'#&'#." &"/¡$%28""6879/,#;Z/#$+")("'#&'#." &"/z$%28""6879/,#;Z/#$+")("'#&'#." &"/S$2""67/D$;Z/;$28""6879/,$;[/#$+()(('#(''#(&'#(%'#($'#(#'#("'#&'#.˕ &%;Z/×#%28""6879/,#;Z/#$+")("'#&'#." &"/°$%28""6879/,#;Z/#$+")("'#&'#." &"/$%28""6879/,#;Z/#$+")("'#&'#." &"/b$%28""6879/,#;Z/#$+")("'#&'#." &"/;$2""67/,$;[/#$+')(''#(&'#(%'#($'#(#'#("'#&'#.ȑ &%;Z/þ#%28""6879/,#;Z/#$+")("'#&'#." &"/×$%28""6879/,#;Z/#$+")("'#&'#." &"/°$%28""6879/,#;Z/#$+")("'#&'#." &"/$%28""6879/,#;Z/#$+")("'#&'#." &"/b$%28""6879/,#;Z/#$+")("'#&'#." &"/;$2""67/,$;Z/#$+()(('#(''#(&'#(%'#($'#(#'#("'#&'#.Ħ &%;Z/Ĝ#%28""6879/,#;Z/#$+")("'#&'#." &"/õ$%28""6879/,#;Z/#$+")("'#&'#." &"/Î$%28""6879/,#;Z/#$+")("'#&'#." &"/§$%28""6879/,#;Z/#$+")("'#&'#." &"/$%28""6879/,#;Z/#$+")("'#&'#." &"/Y$%28""6879/,#;Z/#$+")("'#&'#." &"/2$2""67/#$+()(('#(''#(&'#(%'#($'#(#'#("'#&'#/& 8!: ! )`),c(`%;#/M#;#." &"/?$;#." &"/1$;#." &"/#$+$)($'#(#'#("'#&'#`),c(`%;Z/;#28""6879/,$;Z/#$+#)(#'#("'#&'#.# &;\\`),c(`%;]/o#2J""6J7K/\`$;]/W$2J""6J7K/H$;]/?$2J""6J7K/0$;]/'$8':¡' )(''#(&'#(%'#($'#(#'#("'#&'#`),c(`%2¢""6¢7£/2#4¤""5!7¥/#$+")("'#&'#. &%2¦""6¦7§/;#4¨""5!7©/,$;!/#$+#)(#'#("'#&'#.j &%2ª""6ª7«/5#;!/,$;!/#$+#)(#'#("'#&'#.B &%4¬""5!7/,#;!/#$+")("'#&'#.# &;!`),c(`%%;!." &"/[#;!." &"/M$;!." &"/?$;!." &"/1$;!." &"/#$+%)(%'#($'#(#'#("'#&'#/' 8!:®!! )`),c(`$%22""6273/,#;\`/#$+")("'#&'#0<*%22""6273/,#;\`/#$+")("'#&'#&`),c(";a.A &;b.; &;c.5 &;d./ &;e.) &;f.# &;g"),c(`%3¯""5*7°/a#3±""5#7².G &3³""5#7´.; &3µ""5$7¶./ &3·""5#7¸.# &;6/($8":¹"! )("'#&'#`),c(`%3º""5%7»/I#3¼""5%7½./ &3¾""5"7¿.# &;6/($8":À"! )("'#&'#`),c(`%3Á""5'7Â/1#;/($8":Ã"! )("'#&'#`),c(`%3Ä""5$7Å/1#;ð/($8":Æ"! )("'#&'#`),c(`%3Ç""5&7È/1#;T/($8":É"! )("'#&'#`),c(`%3Ê""5"7Ë/N#%2>""6>7?/,#;6/#$+")("'#&'#." &"/'$8":Ì" )("'#&'#`),c(`%;h/P#%2>""6>7?/,#;i/#$+")("'#&'#." &"/)$8":Í""! )("'#&'#`),c('%$;j/�#*;j&&&#/"!&,)'),c('%$;j/�#*;j&&&#/"!&,)'),c(";k.) &;+.# &;-"),c('2l""6l7m.e &2n""6n7o.Y &24""6475.M &28""6879.A &2<""6<7=.5 &2@""6@7A.) &2B""6B7C'),c(`%26""6677/n#;m/e$$%2<""6<7=/,#;m/#$+")("'#&'#0<*%2<""6<7=/,#;m/#$+")("'#&'#&/#$+#)(#'#("'#&'#`),c(`%;n/A#2>""6>7?/2$;o/)$8#:Î#"" )(#'#("'#&'#`),c("$;p.) &;+.# &;-/2#0/*;p.) &;+.# &;-&&&#"),c("$;p.) &;+.# &;-0/*;p.) &;+.# &;-&"),c('2l""6l7m.e &2n""6n7o.Y &24""6475.M &26""6677.A &28""6879.5 &2@""6@7A.) &2B""6B7C'),c(";.# &;r"),c(`%;/G#;'/>$;s/5$;'/,$;/#$+%)(%'#($'#(#'#("'#&'#`),c(";M.# &;t"),c(`%;/E#28""6879/6$;u.# &;x/'$8#:Ï# )(#'#("'#&'#`),c(`%;v.# &;w/J#%26""6677/,#;/#$+")("'#&'#." &"/#$+")("'#&'#`),c(`%2Ð""6Ð7Ñ/:#;/1$;w." &"/#$+#)(#'#("'#&'#`),c(`%24""6475/,#;{/#$+")("'#&'#`),c(`%;z/3#$;y0#*;y&/#$+")("'#&'#`),c(";*.) &;+.# &;-"),c(';+. &;-. &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'),c(`%;|/e#$%24""6475/,#;|/#$+")("'#&'#0<*%24""6475/,#;|/#$+")("'#&'#&/#$+")("'#&'#`),c(`%$;~0#*;~&/e#$%22""6273/,#;}/#$+")("'#&'#0<*%22""6273/,#;}/#$+")("'#&'#&/#$+")("'#&'#`),c("$;~0#*;~&"),c(';+.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'),c(`%%;"/#$;".G &;!.A &2@""6@7A.5 &2F""6F7G.) &2J""6J7K0M*;".G &;!.A &2@""6@7A.5 &2F""6F7G.) &2J""6J7K&/#$+")("'#&'#/& 8!:Ò! )`),c(";.# &;"),c(`%%;O/2#2:""6:7;/#$+")("'#&'#." &"/,#;S/#$+")("'#&'#." &"`),c('$;+. &;-.} &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&&&#'),c("$;y0#*;y&"),c(`%3""5#7Ó/q#24""6475/b$$;!/�#*;!&&&#/L$2J""6J7K/=$$;!/�#*;!&&&#/'$8%:Ô% )(%'#($'#(#'#("'#&'#`),c('2Õ""6Õ7Ö'),c('2×""6×7Ø'),c('2Ù""6Ù7Ú'),c('2Û""6Û7Ü'),c('2Ý""6Ý7Þ'),c('2ß""6ß7à'),c('2á""6á7â'),c('2ã""6ã7ä'),c('2å""6å7æ'),c('2ç""6ç7è'),c('2é""6é7ê'),c("%;
.Y &;.S &;.M &;.G &;.A &;.; &;.5 &;./ &;.) &;.# &;6/& 8!:ë! )"),c(`%;/G#;'/>$;/5$;'/,$;/#$+%)(%'#($'#(#'#("'#&'#`),c("%;/' 8!:ì!! )"),c(`%;!/5#;!/,$;!/#$+#)(#'#("'#&'#`),c("%$;*.A &;+.; &;-.5 &;3./ &;4.) &;'.# &;(0G*;*.A &;+.; &;-.5 &;3./ &;4.) &;'.# &;(&/& 8!:í! )"),c(`%;¶/Y#$%;A/,#;¶/#$+")("'#&'#06*%;A/,#;¶/#$+")("'#&'#&/#$+")("'#&'#`),c(`%;9/N#%2:""6:7;/,#;9/#$+")("'#&'#." &"/'$8":î" )("'#&'#`),c(`%;:.c &%;/Y#$%;A/,#;/#$+")("'#&'#06*%;A/,#;/#$+")("'#&'#&/#$+")("'#&'#/& 8!:ï! )`),c(`%;L.# &;/]#$%;B/,#;/#$+")("'#&'#06*%;B/,#;/#$+")("'#&'#&/'$8":ð" )("'#&'#`),c(`%;." &"/>#;@/5$;M/,$;?/#$+$)($'#(#'#("'#&'#`),c(`%%;6/Y#$%;./,#;6/#$+")("'#&'#06*%;./,#;6/#$+")("'#&'#&/#$+")("'#&'#.# &;H/' 8!:ñ!! )`),c(";.) &;.# &; "),c(`%3ò""5!7ó/:#;</1$;/($8#:ô#! )(#'#("'#&'#`),c(`%3õ""5'7ö/:#;</1$;/($8#:÷#! )(#'#("'#&'#`),c("%$;!/�#*;!&&&#/' 8!:ø!! )"),c(`%2ù""6ù7ú/o#%2J""6J7K/M#;!." &"/?$;!." &"/1$;!." &"/#$+$)($'#(#'#("'#&'#." &"/'$8":û" )("'#&'#`),c(`%;6/J#%;</,#;¡/#$+")("'#&'#." &"/)$8":ü""! )("'#&'#`),c(";6.) &;T.# &;H"),c(`%;£/Y#$%;B/,#;¤/#$+")("'#&'#06*%;B/,#;¤/#$+")("'#&'#&/#$+")("'#&'#`),c(`%3ý""5&7þ.G &3ÿ""5'7Ā.; &3ā""5$7Ă./ &3ă""5%7Ą.# &;6/& 8!:ą! )`),c(";¥.# &; "),c(`%3Ć""5(7ć/M#;</D$3Ĉ""5(7ĉ./ &3Ċ""5(7ċ.# &;6/#$+#)(#'#("'#&'#`),c(`%;6/Y#$%;A/,#;6/#$+")("'#&'#06*%;A/,#;6/#$+")("'#&'#&/#$+")("'#&'#`),c("%$;!/�#*;!&&&#/' 8!:Č!! )"),c("%;©/& 8!:č! )"),c(`%;ª/k#;;/b$;¯/Y$$%;B/,#;°/#$+")("'#&'#06*%;B/,#;°/#$+")("'#&'#&/#$+$)($'#(#'#("'#&'#`),c(";«.# &;¬"),c('3Ď""5$7ď.S &3Đ""5%7đ.G &3Ē""5%7ē.; &3Ĕ""5%7ĕ./ &3Ė""5+7ė.# &;'),c(`3Ę""5'7ę./ &3Ě""5)7ě.# &;`),c(";6.# &;®"),c(`%3Ĝ""5"7ĝ/,#;6/#$+")("'#&'#`),c(";.# &;6"),c(`%;6/5#;</,$;±/#$+#)(#'#("'#&'#`),c(";6.# &;H"),c(`%;³/5#;./,$;/#$+#)(#'#("'#&'#`),c("%$;!/�#*;!&&&#/' 8!:Ğ!! )"),c("%;/' 8!:ğ!! )"),c(`%;¶/^#$%;B/,#; /#$+")("'#&'#06*%;B/,#; /#$+")("'#&'#&/($8":Ġ"!!)("'#&'#`),c(`%%;7/e#$%2J""6J7K/,#;7/#$+")("'#&'#0<*%2J""6J7K/,#;7/#$+")("'#&'#&/#$+")("'#&'#/"!&,)`),c(`%;L.# &;/]#$%;B/,#;¸/#$+")("'#&'#06*%;B/,#;¸/#$+")("'#&'#&/'$8":ġ" )("'#&'#`),c(";¹.# &; "),c(`%3Ģ""5#7ģ/:#;</1$;6/($8#:Ĥ#! )(#'#("'#&'#`),c("%$;!/�#*;!&&&#/' 8!:ĥ!! )"),c("%;/' 8!:Ħ!! )"),c(`%$;0#*;&/x#;@/o$;M/f$;?/]$$%;B/,#; /#$+")("'#&'#06*%;B/,#; /#$+")("'#&'#&/'$8%:ħ% )(%'#($'#(#'#("'#&'#`),c(";¾"),c(`%3Ĩ""5&7ĩ/k#;./b$;Á/Y$$%;A/,#;Á/#$+")("'#&'#06*%;A/,#;Á/#$+")("'#&'#&/#$+$)($'#(#'#("'#&'#.# &;¿`),c(`%;6/k#;./b$;À/Y$$%;A/,#;À/#$+")("'#&'#06*%;A/,#;À/#$+")("'#&'#&/#$+$)($'#(#'#("'#&'#`),c(`%;6/;#;</2$;6.# &;H/#$+#)(#'#("'#&'#`),c(";Â.G &;Ä.A &;Æ.; &;È.5 &;É./ &;Ê.) &;Ë.# &;À"),c(`%3Ī""5%7ī/5#;</,$;Ã/#$+#)(#'#("'#&'#`),c("%;I/' 8!:Ĭ!! )"),c(`%3ĭ""5&7Į/#;</$;D/
$;Å/|$$%$;'/�#*;'&&&#/,#;Å/#$+")("'#&'#0C*%$;'/�#*;'&&&#/,#;Å/#$+")("'#&'#&/,$;E/#$+&)(&'#(%'#($'#(#'#("'#&'#`),c(";t.# &;w"),c(`%3į""5%7İ/5#;</,$;Ç/#$+#)(#'#("'#&'#`),c("%;I/' 8!:ı!! )"),c(`%3IJ""5&7ij/:#;</1$;I/($8#:Ĵ#! )(#'#("'#&'#`),c(`%3ĵ""5%7Ķ/]#;</T$%3ķ""5$7ĸ/& 8!:Ĺ! ).4 &%3ĺ""5%7Ļ/& 8!:ļ! )/#$+#)(#'#("'#&'#`),c(`%3Ľ""5)7ľ/R#;</I$3Ŀ""5#7ŀ./ &3Ł""5(7ł.# &;6/($8#:Ń#! )(#'#("'#&'#`),c(`%3ń""5#7Ņ/#;</$;D/$%;Ì/e#$%2D""6D7E/,#;Ì/#$+")("'#&'#0<*%2D""6D7E/,#;Ì/#$+")("'#&'#&/#$+")("'#&'#/,$;E/#$+%)(%'#($'#(#'#("'#&'#`),c(`%3ņ""5(7Ň./ &3ň""5$7ʼn.# &;6/' 8!:Ŋ!! )`),c(`%;6/Y#$%;A/,#;6/#$+")("'#&'#06*%;A/,#;6/#$+")("'#&'#&/#$+")("'#&'#`),c(`%;Ï/G#;./>$;Ï/5$;./,$;/#$+%)(%'#($'#(#'#("'#&'#`),c("%$;!/�#*;!&&&#/' 8!:ŋ!! )"),c(`%;Ñ/]#$%;A/,#;Ñ/#$+")("'#&'#06*%;A/,#;Ñ/#$+")("'#&'#&/'$8":Ō" )("'#&'#`),c(`%;/]#$%;B/,#; /#$+")("'#&'#06*%;B/,#; /#$+")("'#&'#&/'$8":ō" )("'#&'#`),c(`%;L.O &;.I &%;@." &"/:#;t/1$;?." &"/#$+#)(#'#("'#&'#/]#$%;B/,#; /#$+")("'#&'#06*%;B/,#; /#$+")("'#&'#&/'$8":Ŏ" )("'#&'#`),c(`%;Ô/]#$%;B/,#;Õ/#$+")("'#&'#06*%;B/,#;Õ/#$+")("'#&'#&/'$8":ŏ" )("'#&'#`),c("%;/& 8!:Ő! )"),c(`%3ő""5(7Œ/:#;</1$;6/($8#:œ#! )(#'#("'#&'#.g &%3Ŕ""5&7ŕ/:#;</1$;6/($8#:Ŗ#! )(#'#("'#&'#.: &%3ŗ""5*7Ř/& 8!:ř! ).# &; `),c(`%%;6/k#$%;A/2#;6/)$8":Ś""$ )("'#&'#0<*%;A/2#;6/)$8":Ś""$ )("'#&'#&/)$8":ś""! )("'#&'#." &"/' 8!:Ŝ!! )`),c(`%;Ø/Y#$%;A/,#;Ø/#$+")("'#&'#06*%;A/,#;Ø/#$+")("'#&'#&/#$+")("'#&'#`),c(`%;/Y#$%;B/,#; /#$+")("'#&'#06*%;B/,#; /#$+")("'#&'#&/#$+")("'#&'#`),c("%$;!/�#*;!&&&#/' 8!:ŝ!! )"),c(`%;Û/Y#$%;B/,#;Ü/#$+")("'#&'#06*%;B/,#;Ü/#$+")("'#&'#&/#$+")("'#&'#`),c(`%3Ş""5&7ş.; &3Š""5'7š./ &3Ţ""5*7ţ.# &;6/& 8!:Ť! )`),c(`%3ť""5&7Ŧ/:#;</1$;Ý/($8#:ŧ#! )(#'#("'#&'#.} &%3õ""5'7ö/:#;</1$;/($8#:Ũ#! )(#'#("'#&'#.P &%3ũ""5+7Ū/:#;</1$;/($8#:ū#! )(#'#("'#&'#.# &; `),c(`3Ŭ""5+7ŭ.k &3Ů""5)7ů._ &3Ű""5(7ű.S &3Ų""5'7ų.G &3Ŵ""5&7ŵ.; &3Ŷ""5*7ŷ./ &3Ÿ""5)7Ź.# &;6`),c(';1." &"'),c(`%%;6/k#$%;A/2#;6/)$8":Ś""$ )("'#&'#0<*%;A/2#;6/)$8":Ś""$ )("'#&'#&/)$8":ś""! )("'#&'#." &"/' 8!:ź!! )`),c(`%;L.# &;/]#$%;B/,#;á/#$+")("'#&'#06*%;B/,#;á/#$+")("'#&'#&/'$8":Ż" )("'#&'#`),c(";¹.# &; "),c(`%;ã/Y#$%;A/,#;ã/#$+")("'#&'#06*%;A/,#;ã/#$+")("'#&'#&/#$+")("'#&'#`),c(`%;ê/k#;./b$;í/Y$$%;B/,#;ä/#$+")("'#&'#06*%;B/,#;ä/#$+")("'#&'#&/#$+$)($'#(#'#("'#&'#`),c(";å.; &;æ.5 &;ç./ &;è.) &;é.# &; "),c(`%3ż""5#7Ž/:#;</1$;ð/($8#:ž#! )(#'#("'#&'#`),c(`%3ſ""5%7ƀ/:#;</1$;T/($8#:Ɓ#! )(#'#("'#&'#`),c(`%3Ƃ""5(7ƃ/F#;</=$;\\.) &;Y.# &;X/($8#:Ƅ#! )(#'#("'#&'#`),c(`%3ƅ""5&7Ɔ/:#;</1$;6/($8#:Ƈ#! )(#'#("'#&'#`),c(`%3ƈ""5%7Ɖ/A#;</8$$;!0#*;!&/($8#:Ɗ#! )(#'#("'#&'#`),c(`%;ë/G#;;/>$;6/5$;;/,$;ì/#$+%)(%'#($'#(#'#("'#&'#`),c(`%3""5#7Ó.# &;6/' 8!:Ƌ!! )`),c(`%3±""5#7ƌ.G &3³""5#7ƍ.; &3·""5#7Ǝ./ &3µ""5$7Ə.# &;6/' 8!:Ɛ!! )`),c(`%;î/D#%;C/,#;ï/#$+")("'#&'#." &"/#$+")("'#&'#`),c("%;U.) &;\\.# &;X/& 8!:Ƒ! )"),c(`%%;!." &"/[#;!." &"/M$;!." &"/?$;!." &"/1$;!." &"/#$+%)(%'#($'#(#'#("'#&'#/' 8!:ƒ!! )`),c(`%%;!/?#;!." &"/1$;!." &"/#$+#)(#'#("'#&'#/' 8!:Ɠ!! )`),c(";¾"),c(`%;/^#$%;B/,#;ó/#$+")("'#&'#06*%;B/,#;ó/#$+")("'#&'#&/($8":Ɣ"!!)("'#&'#`),c(";ô.# &; "),c(`%2ƕ""6ƕ7Ɩ/L#;</C$2Ɨ""6Ɨ7Ƙ.) &2ƙ""6ƙ7ƚ/($8#:ƛ#! )(#'#("'#&'#`),c(`%;/^#$%;B/,#; /#$+")("'#&'#06*%;B/,#; /#$+")("'#&'#&/($8":Ɯ"!!)("'#&'#`),c(`%;6/5#;0/,$;÷/#$+#)(#'#("'#&'#`),c("$;2.) &;4.# &;.0/*;2.) &;4.# &;.&"),c("$;%0#*;%&"),c(`%;ú/;#28""6879/,$;û/#$+#)(#'#("'#&'#`),c(`%3Ɲ""5%7ƞ.) &3Ɵ""5$7Ơ/' 8!:ơ!! )`),c(`%;ü/J#%28""6879/,#;^/#$+")("'#&'#." &"/#$+")("'#&'#`),c("%;\\.) &;X.# &;/' 8!:Ƣ!! )"),c(';".S &;!.M &2F""6F7G.A &2J""6J7K.5 &2H""6H7I.) &2N""6N7O'),c('2L""6L7M. &2B""6B7C. &2<""6<7=.} &2R""6R7S.q &2T""6T7U.e &2V""6V7W.Y &2P""6P7Q.M &2@""6@7A.A &2D""6D7E.5 &22""6273.) &2>""6>7?'),c(`%;Ā/b#28""6879/S$;û/J$%2ƣ""6ƣ7Ƥ/,#;ì/#$+")("'#&'#." &"/#$+$)($'#(#'#("'#&'#`),c(`%3ƥ""5%7Ʀ.) &3Ƨ""5$7ƨ/' 8!:ơ!! )`),c(`%3±""5#7².6 &3³""5#7´.* &$;+0#*;+&/' 8!:Ʃ!! )`),c(`%;Ą/#2F""6F7G/x$;ă/o$2F""6F7G/\`$;ă/W$2F""6F7G/H$;ă/?$2F""6F7G/0$;ą/'$8):ƪ) )()'#(('#(''#(&'#(%'#($'#(#'#("'#&'#`),c(`%;#/>#;#/5$;#/,$;#/#$+$)($'#(#'#("'#&'#`),c(`%;ă/,#;ă/#$+")("'#&'#`),c(`%;ă/5#;ă/,$;ă/#$+#)(#'#("'#&'#`),c(`%;q/T#$;m0#*;m&/D$%; /,#;ø/#$+")("'#&'#." &"/#$+#)(#'#("'#&'#`),c(`%2ƫ""6ƫ7Ƭ.) &2ƭ""6ƭ7Ʈ/w#;0/n$;Ĉ/e$$%;B/2#;ĉ.# &; /#$+")("'#&'#0<*%;B/2#;ĉ.# &; /#$+")("'#&'#&/#$+$)($'#(#'#("'#&'#`),c(";.# &;L"),c(`%2Ư""6Ư7ư/5#;</,$;Ċ/#$+#)(#'#("'#&'#`),c(`%;D/S#;,/J$2:""6:7;/;$;,.# &;T/,$;E/#$+%)(%'#($'#(#'#("'#&'#`)];let d=0,u=0;const h=[{line:1,column:1}];let m=0,S=[],x=0,_;if(e.startRule!==void 0){if(!(e.startRule in s))throw new Error(`Can't start parsing from rule "`+e.startRule+'".');r=s[e.startRule]}function C(){return a.substring(u,d)}function Q(){return tt(u,d)}function p(l,b){return{type:"literal",text:l,ignoreCase:b}}function $(l,b,g){return{type:"class",parts:l,inverted:b,ignoreCase:g}}function et(){return{type:"end"}}function It(l){let b=h[l],g;if(b)return b;for(g=l-1;!h[g];)g--;for(b=h[g],b={line:b.line,column:b.column};g<l;)a.charCodeAt(g)===10?(b.line++,b.column=1):b.column++,g++;return h[l]=b,b}function tt(l,b){const g=It(l),G=It(b);return{source:i,start:{offset:l,line:g.line,column:g.column},end:{offset:b,line:G.line,column:G.column}}}function At(l){d<m||(d>m&&(m=d,S=[]),S.push(l))}function Ki(l,b,g){return new pe(pe.buildMessage(l,b),l,b,g)}function c(l){return l.split("").map(b=>b.charCodeAt(0)-32)}function $t(l){const b=o[l];let g=0;const G=[];let D=b.length;const ee=[],E=[];let Dt;for(;;){for(;g<D;)switch(b[g]){case 0:E.push(n[b[g+1]]),g+=2;break;case 1:E.push(void 0),g++;break;case 2:E.push(null),g++;break;case 3:E.push(t),g++;break;case 4:E.push([]),g++;break;case 5:E.push(d),g++;break;case 6:E.pop(),g++;break;case 7:d=E.pop(),g++;break;case 8:E.length-=b[g+1],g+=2;break;case 9:E.splice(-2,1),g++;break;case 10:E[E.length-2].push(E.pop()),g++;break;case 11:E.push(E.splice(E.length-b[g+1],b[g+1])),g+=2;break;case 12:E.push(a.substring(E.pop(),d)),g++;break;case 13:ee.push(D),G.push(g+3+b[g+1]+b[g+2]),E[E.length-1]?(D=g+3+b[g+1],g+=3):(D=g+3+b[g+1]+b[g+2],g+=3+b[g+1]);break;case 14:ee.push(D),G.push(g+3+b[g+1]+b[g+2]),E[E.length-1]===t?(D=g+3+b[g+1],g+=3):(D=g+3+b[g+1]+b[g+2],g+=3+b[g+1]);break;case 15:ee.push(D),G.push(g+3+b[g+1]+b[g+2]),E[E.length-1]!==t?(D=g+3+b[g+1],g+=3):(D=g+3+b[g+1]+b[g+2],g+=3+b[g+1]);break;case 16:E[E.length-1]!==t?(ee.push(D),G.push(g),D=g+2+b[g+1],g+=2):g+=2+b[g+1];break;case 17:ee.push(D),G.push(g+3+b[g+1]+b[g+2]),a.length>d?(D=g+3+b[g+1],g+=3):(D=g+3+b[g+1]+b[g+2],g+=3+b[g+1]);break;case 18:ee.push(D),G.push(g+4+b[g+2]+b[g+3]),a.substr(d,n[b[g+1]].length)===n[b[g+1]]?(D=g+4+b[g+2],g+=4):(D=g+4+b[g+2]+b[g+3],g+=4+b[g+2]);break;case 19:ee.push(D),G.push(g+4+b[g+2]+b[g+3]),a.substr(d,n[b[g+1]].length).toLowerCase()===n[b[g+1]]?(D=g+4+b[g+2],g+=4):(D=g+4+b[g+2]+b[g+3],g+=4+b[g+2]);break;case 20:ee.push(D),G.push(g+4+b[g+2]+b[g+3]),n[b[g+1]].test(a.charAt(d))?(D=g+4+b[g+2],g+=4):(D=g+4+b[g+2]+b[g+3],g+=4+b[g+2]);break;case 21:E.push(a.substr(d,b[g+1])),d+=b[g+1],g+=2;break;case 22:E.push(n[b[g+1]]),d+=n[b[g+1]].length,g+=2;break;case 23:E.push(t),x===0&&At(n[b[g+1]]),g+=2;break;case 24:u=E[E.length-1-b[g+1]],g+=2;break;case 25:u=d,g++;break;case 26:Dt=b.slice(g+4,g+4+b[g+3]).map(function(Yi){return E[E.length-1-Yi]}),E.splice(E.length-b[g+2],b[g+2],n[b[g+1]].apply(null,Dt)),g+=4+b[g+3];break;case 27:E.push($t(b[g+1])),g+=2;break;case 28:x++,g++;break;case 29:x--,g++;break;default:throw new Error("Invalid opcode: "+b[g]+".")}if(ee.length>0)D=ee.pop(),g=G.pop();else break}return E[0]}e.data={};function zi(l,b){return[l].concat(b)}if(_=$t(r),_!==t&&d===a.length)return _;throw _!==t&&d<a.length&&At(et()),Ki(S,m<a.length?a.charAt(m):null,m<a.length?tt(m,m+1):tt(m,m))}const Nt=Ft;var P;(function(a){function e(s,r){const n={startRule:r};try{Nt(s,n)}catch{n.data=-1}return n.data}a.parse=e;function t(s){const r=a.parse(s,"Name_Addr_Header");return r!==-1?r:void 0}a.nameAddrHeaderParse=t;function i(s){const r=a.parse(s,"SIP_URI");return r!==-1?r:void 0}a.URIParse=i})(P=P||(P={}));const Ut={100:"Trying",180:"Ringing",181:"Call Is Being Forwarded",182:"Queued",183:"Session Progress",199:"Early Dialog Terminated",200:"OK",202:"Accepted",204:"No Notification",300:"Multiple Choices",301:"Moved Permanently",302:"Moved Temporarily",305:"Use Proxy",380:"Alternative Service",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",410:"Gone",412:"Conditional Request Failed",413:"Request Entity Too Large",414:"Request-URI Too Long",415:"Unsupported Media Type",416:"Unsupported URI Scheme",417:"Unknown Resource-Priority",420:"Bad Extension",421:"Extension Required",422:"Session Interval Too Small",423:"Interval Too Brief",428:"Use Identity Header",429:"Provide Referrer Identity",430:"Flow Failed",433:"Anonymity Disallowed",436:"Bad Identity-Info",437:"Unsupported Certificate",438:"Invalid Identity Header",439:"First Hop Lacks Outbound Support",440:"Max-Breadth Exceeded",469:"Bad Info Package",470:"Consent Needed",478:"Unresolvable Destination",480:"Temporarily Unavailable",481:"Call/Transaction Does Not Exist",482:"Loop Detected",483:"Too Many Hops",484:"Address Incomplete",485:"Ambiguous",486:"Busy Here",487:"Request Terminated",488:"Not Acceptable Here",489:"Bad Event",491:"Request Pending",493:"Undecipherable",494:"Security Agreement Required",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Server Time-out",505:"Version Not Supported",513:"Message Too Large",580:"Precondition Failure",600:"Busy Everywhere",603:"Decline",604:"Does Not Exist Anywhere",606:"Not Acceptable"};function ue(a,e=32){let t="";for(let i=0;i<a;i++){const s=Math.floor(Math.random()*e);t+=s.toString(e)}return t}function Ae(a){return Ut[a]||""}function $e(){return ue(10)}function Y(a){const e={"Call-Id":"Call-ID",Cseq:"CSeq","Min-Se":"Min-SE",Rack:"RAck",Rseq:"RSeq","Www-Authenticate":"WWW-Authenticate"},t=a.toLowerCase().replace(/_/g,"-").split("-"),i=t.length;let s="";for(let r=0;r<i;r++)r!==0&&(s+="-"),s+=t[r].charAt(0).toUpperCase()+t[r].substring(1);return e[s]&&(s=e[s]),s}function Ce(a){return encodeURIComponent(a).replace(/%[A-F\d]{2}/g,"U").length}class rt{constructor(){this.headers={}}addHeader(e,t){const i={raw:t};e=Y(e),this.headers[e]?this.headers[e].push(i):this.headers[e]=[i]}getHeader(e){const t=this.headers[Y(e)];if(t){if(t[0])return t[0].raw}else return}getHeaders(e){const t=this.headers[Y(e)],i=[];if(!t)return[];for(const s of t)i.push(s.raw);return i}hasHeader(e){return!!this.headers[Y(e)]}parseHeader(e,t=0){if(e=Y(e),this.headers[e]){if(t>=this.headers[e].length)return}else return;const i=this.headers[e][t],s=i.raw;if(i.parsed)return i.parsed;const r=P.parse(s,e.replace(/-/g,"_"));if(r===-1){this.headers[e].splice(t,1);return}else return i.parsed=r,r}s(e,t=0){return this.parseHeader(e,t)}setHeader(e,t){this.headers[Y(e)]=[{raw:t}]}toString(){return this.data}}class me extends rt{constructor(){super()}}class re extends rt{constructor(){super()}}class ge{constructor(e,t,i,s,r,n,o){this.headers={},this.extraHeaders=[],this.options=ge.getDefaultOptions(),r&&(this.options=Object.assign(Object.assign({},this.options),r),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())),n&&n.length&&(this.extraHeaders=n.slice()),o&&(this.body={body:o.content,contentType:o.contentType}),this.method=e,this.ruri=t.clone(),this.fromURI=i.clone(),this.fromTag=this.options.fromTag?this.options.fromTag:$e(),this.from=ge.makeNameAddrHeader(this.fromURI,this.options.fromDisplayName,this.fromTag),this.toURI=s.clone(),this.toTag=this.options.toTag,this.to=ge.makeNameAddrHeader(this.toURI,this.options.toDisplayName,this.toTag),this.callId=this.options.callId?this.options.callId:this.options.callIdPrefix+ue(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,i){const s={};return i&&(s.tag=i),new N(e,t,s)}getHeader(e){const t=this.headers[Y(e)];if(t){if(t[0])return t[0]}else{const i=new RegExp("^\\s*"+e+"\\s*:","i");for(const s of this.extraHeaders)if(i.test(s))return s.substring(s.indexOf(":")+1).trim()}}getHeaders(e){const t=[],i=this.headers[Y(e)];if(i)for(const s of i)t.push(s);else{const s=new RegExp("^\\s*"+e+"\\s*:","i");for(const r of this.extraHeaders)s.test(r)&&t.push(r.substring(r.indexOf(":")+1).trim())}return t}hasHeader(e){if(this.headers[Y(e)])return!0;{const t=new RegExp("^\\s*"+e+"\\s*:","i");for(const i of this.extraHeaders)if(t.test(i))return!0}return!1}setHeader(e,t){this.headers[Y(e)]=t instanceof Array?t:[t]}setViaHeader(e,t){this.options.hackViaTcp&&(t="TCP");let i="SIP/2.0/"+t;i+=" "+this.options.viaHost+";branch="+e,this.options.forceRport&&(i+=";rport"),this.setHeader("via",i),this.branch=e}toString(){let e="";e+=this.method+" "+this.ruri.toRaw()+` SIP/2.0\r
|
|
8
|
+
`,!1),/^[0-9]/,$([["0","9"]],!1,!1),/^[a-zA-Z]/,$([["a","z"],["A","Z"]],!1,!1),/^[0-9a-fA-F]/,$([["0","9"],["a","f"],["A","F"]],!1,!1),/^[\0-\xFF]/,$([["\0","ÿ"]],!1,!1),/^["]/,$(['"'],!1,!1)," ",p(" ",!1)," ",p(" ",!1),/^[a-zA-Z0-9]/,$([["a","z"],["A","Z"],["0","9"]],!1,!1),";",p(";",!1),"/",p("/",!1),"?",p("?",!1),":",p(":",!1),"@",p("@",!1),"&",p("&",!1),"=",p("=",!1),"+",p("+",!1),"$",p("$",!1),",",p(",",!1),"-",p("-",!1),"_",p("_",!1),".",p(".",!1),"!",p("!",!1),"~",p("~",!1),"*",p("*",!1),"'",p("'",!1),"(",p("(",!1),")",p(")",!1),"%",p("%",!1),function(){return" "},function(){return":"},/^[!-~]/,$([["!","~"]],!1,!1),/^[\x80-\uFFFF]/,$([["",""]],!1,!1),/^[\x80-\xBF]/,$([["","¿"]],!1,!1),/^[a-f]/,$([["a","f"]],!1,!1),"`",p("`",!1),"<",p("<",!1),">",p(">",!1),"\\",p("\\",!1),"[",p("[",!1),"]",p("]",!1),"{",p("{",!1),"}",p("}",!1),function(){return"*"},function(){return"/"},function(){return"="},function(){return"("},function(){return")"},function(){return">"},function(){return"<"},function(){return","},function(){return";"},function(){return":"},function(){return'"'},/^[!-']/,$([["!","'"]],!1,!1),/^[*-[]/,$([["*","["]],!1,!1),/^[\]-~]/,$([["]","~"]],!1,!1),function(l){return l},/^[#-[]/,$([["#","["]],!1,!1),/^[\0-\t]/,$([["\0"," "]],!1,!1),/^[\v-\f]/,$([["\v","\f"]],!1,!1),/^[\x0E-\x7F]/,$([["",""]],!1,!1),function(){e=e||{data:{}},e.data.uri=new z(e.data.scheme,e.data.user,e.data.host,e.data.port),delete e.data.scheme,delete e.data.user,delete e.data.host,delete e.data.host_type,delete e.data.port},function(){e=e||{data:{}},e.data.uri=new z(e.data.scheme,e.data.user,e.data.host,e.data.port,e.data.uri_params,e.data.uri_headers),delete e.data.scheme,delete e.data.user,delete e.data.host,delete e.data.host_type,delete e.data.port,delete e.data.uri_params,e.startRule==="SIP_URI"&&(e.data=e.data.uri)},"sips",p("sips",!0),"sip",p("sip",!0),function(l){e=e||{data:{}},e.data.scheme=l},function(){e=e||{data:{}},e.data.user=decodeURIComponent(C().slice(0,-1))},function(){e=e||{data:{}},e.data.password=C()},function(){return e=e||{data:{}},e.data.host=C(),e.data.host},function(){return e=e||{data:{}},e.data.host_type="domain",C()},/^[a-zA-Z0-9_\-]/,$([["a","z"],["A","Z"],["0","9"],"_","-"],!1,!1),/^[a-zA-Z0-9\-]/,$([["a","z"],["A","Z"],["0","9"],"-"],!1,!1),function(){return e=e||{data:{}},e.data.host_type="IPv6",C()},"::",p("::",!1),function(){return e=e||{data:{}},e.data.host_type="IPv6",C()},function(){return e=e||{data:{}},e.data.host_type="IPv4",C()},"25",p("25",!1),/^[0-5]/,$([["0","5"]],!1,!1),"2",p("2",!1),/^[0-4]/,$([["0","4"]],!1,!1),"1",p("1",!1),/^[1-9]/,$([["1","9"]],!1,!1),function(l){return e=e||{data:{}},l=parseInt(l.join("")),e.data.port=l,l},"transport=",p("transport=",!0),"udp",p("udp",!0),"tcp",p("tcp",!0),"sctp",p("sctp",!0),"tls",p("tls",!0),function(l){e=e||{data:{}},e.data.uri_params||(e.data.uri_params={}),e.data.uri_params.transport=l.toLowerCase()},"user=",p("user=",!0),"phone",p("phone",!0),"ip",p("ip",!0),function(l){e=e||{data:{}},e.data.uri_params||(e.data.uri_params={}),e.data.uri_params.user=l.toLowerCase()},"method=",p("method=",!0),function(l){e=e||{data:{}},e.data.uri_params||(e.data.uri_params={}),e.data.uri_params.method=l},"ttl=",p("ttl=",!0),function(l){e=e||{data:{}},e.data.params||(e.data.params={}),e.data.params.ttl=l},"maddr=",p("maddr=",!0),function(l){e=e||{data:{}},e.data.uri_params||(e.data.uri_params={}),e.data.uri_params.maddr=l},"lr",p("lr",!0),function(){e=e||{data:{}},e.data.uri_params||(e.data.uri_params={}),e.data.uri_params.lr=void 0},function(l,b){e=e||{data:{}},e.data.uri_params||(e.data.uri_params={}),b===null?b=void 0:b=b[1],e.data.uri_params[l.toLowerCase()]=b},function(l,b){l=l.join("").toLowerCase(),b=b.join(""),e=e||{data:{}},e.data.uri_headers||(e.data.uri_headers={}),e.data.uri_headers[l]?e.data.uri_headers[l].push(b):e.data.uri_headers[l]=[b]},function(){e=e||{data:{}},e.startRule==="Refer_To"&&(e.data.uri=new z(e.data.scheme,e.data.user,e.data.host,e.data.port,e.data.uri_params,e.data.uri_headers),delete e.data.scheme,delete e.data.user,delete e.data.host,delete e.data.host_type,delete e.data.port,delete e.data.uri_params)},"//",p("//",!1),function(){e=e||{data:{}},e.data.scheme=C()},p("SIP",!0),function(){e=e||{data:{}},e.data.sip_version=C()},"INVITE",p("INVITE",!1),"ACK",p("ACK",!1),"VXACH",p("VXACH",!1),"OPTIONS",p("OPTIONS",!1),"BYE",p("BYE",!1),"CANCEL",p("CANCEL",!1),"REGISTER",p("REGISTER",!1),"SUBSCRIBE",p("SUBSCRIBE",!1),"NOTIFY",p("NOTIFY",!1),"REFER",p("REFER",!1),"PUBLISH",p("PUBLISH",!1),function(){return e=e||{data:{}},e.data.method=C(),e.data.method},function(l){e=e||{data:{}},e.data.status_code=parseInt(l.join(""))},function(){e=e||{data:{}},e.data.reason_phrase=C()},function(){e=e||{data:{}},e.data=C()},function(){var l,b;for(e=e||{data:{}},b=e.data.multi_header.length,l=0;l<b;l++)if(e.data.multi_header[l].parsed===null){e.data=null;break}e.data!==null?e.data=e.data.multi_header:e.data=-1},function(){var l;e=e||{data:{}},e.data.multi_header||(e.data.multi_header=[]);try{l=new N(e.data.uri,e.data.displayName,e.data.params),delete e.data.uri,delete e.data.displayName,delete e.data.params}catch{l=null}e.data.multi_header.push({position:d,offset:ee().start.offset,parsed:l})},function(l){l=C().trim(),l[0]==='"'&&(l=l.substring(1,l.length-1)),e=e||{data:{}},e.data.displayName=l},"q",p("q",!0),function(l){e=e||{data:{}},e.data.params||(e.data.params={}),e.data.params.q=l},"expires",p("expires",!0),function(l){e=e||{data:{}},e.data.params||(e.data.params={}),e.data.params.expires=l},function(l){return parseInt(l.join(""))},"0",p("0",!1),function(){return parseFloat(C())},function(l,b){e=e||{data:{}},e.data.params||(e.data.params={}),b===null?b=void 0:b=b[1],e.data.params[l.toLowerCase()]=b},"render",p("render",!0),"session",p("session",!0),"icon",p("icon",!0),"alert",p("alert",!0),function(){e=e||{data:{}},e.startRule==="Content_Disposition"&&(e.data.type=C().toLowerCase())},"handling",p("handling",!0),"optional",p("optional",!0),"required",p("required",!0),function(l){e=e||{data:{}},e.data=parseInt(l.join(""))},function(){e=e||{data:{}},e.data=C()},"text",p("text",!0),"image",p("image",!0),"audio",p("audio",!0),"video",p("video",!0),"application",p("application",!0),"message",p("message",!0),"multipart",p("multipart",!0),"x-",p("x-",!0),function(l){e=e||{data:{}},e.data.value=parseInt(l.join(""))},function(l){e=e||{data:{}},e.data=l},function(l){e=e||{data:{}},e.data.event=l.toLowerCase()},function(){e=e||{data:{}};var l=e.data.tag;e.data=new N(e.data.uri,e.data.displayName,e.data.params),l&&e.data.setParam("tag",l)},"tag",p("tag",!0),function(l){e=e||{data:{}},e.data.tag=l},function(l){e=e||{data:{}},e.data=parseInt(l.join(""))},function(l){e=e||{data:{}},e.data=l},function(){e=e||{data:{}},e.data=new N(e.data.uri,e.data.displayName,e.data.params)},"digest",p("Digest",!0),"realm",p("realm",!0),function(l){e=e||{data:{}},e.data.realm=l},"domain",p("domain",!0),"nonce",p("nonce",!0),function(l){e=e||{data:{}},e.data.nonce=l},"opaque",p("opaque",!0),function(l){e=e||{data:{}},e.data.opaque=l},"stale",p("stale",!0),"true",p("true",!0),function(){e=e||{data:{}},e.data.stale=!0},"false",p("false",!0),function(){e=e||{data:{}},e.data.stale=!1},"algorithm",p("algorithm",!0),"md5",p("MD5",!0),"md5-sess",p("MD5-sess",!0),function(l){e=e||{data:{}},e.data.algorithm=l.toUpperCase()},"qop",p("qop",!0),"auth-int",p("auth-int",!0),"auth",p("auth",!0),function(l){e=e||{data:{}},e.data.qop||(e.data.qop=[]),e.data.qop.push(l.toLowerCase())},function(l){e=e||{data:{}},e.data.value=parseInt(l.join(""))},function(){var l,b;for(e=e||{data:{}},b=e.data.multi_header.length,l=0;l<b;l++)if(e.data.multi_header[l].parsed===null){e.data=null;break}e.data!==null?e.data=e.data.multi_header:e.data=-1},function(){var l;e=e||{data:{}},e.data.multi_header||(e.data.multi_header=[]);try{l=new N(e.data.uri,e.data.displayName,e.data.params),delete e.data.uri,delete e.data.displayName,delete e.data.params}catch{l=null}e.data.multi_header.push({position:d,offset:ee().start.offset,parsed:l})},function(){e=e||{data:{}},e.data=new N(e.data.uri,e.data.displayName,e.data.params)},function(){e=e||{data:{}},e.data.replaces_from_tag&&e.data.replaces_to_tag||(e.data=-1)},function(){e=e||{data:{}},e.data={call_id:e.data}},"from-tag",p("from-tag",!0),function(l){e=e||{data:{}},e.data.replaces_from_tag=l},"to-tag",p("to-tag",!0),function(l){e=e||{data:{}},e.data.replaces_to_tag=l},"early-only",p("early-only",!0),function(){e=e||{data:{}},e.data.early_only=!0},function(l,b){return b},function(l,b){return zi(l,b)},function(l){e=e||{data:{}},e.startRule==="Require"&&(e.data=l||[])},function(l){e=e||{data:{}},e.data.value=parseInt(l.join(""))},"active",p("active",!0),"pending",p("pending",!0),"terminated",p("terminated",!0),function(){e=e||{data:{}},e.data.state=C()},"reason",p("reason",!0),function(l){e=e||{data:{}},typeof l<"u"&&(e.data.reason=l)},function(l){e=e||{data:{}},typeof l<"u"&&(e.data.expires=l)},"retry_after",p("retry_after",!0),function(l){e=e||{data:{}},typeof l<"u"&&(e.data.retry_after=l)},"deactivated",p("deactivated",!0),"probation",p("probation",!0),"rejected",p("rejected",!0),"timeout",p("timeout",!0),"giveup",p("giveup",!0),"noresource",p("noresource",!0),"invariant",p("invariant",!0),function(l){e=e||{data:{}},e.startRule==="Supported"&&(e.data=l||[])},function(){e=e||{data:{}};var l=e.data.tag;e.data=new N(e.data.uri,e.data.displayName,e.data.params),l&&e.data.setParam("tag",l)},"ttl",p("ttl",!0),function(l){e=e||{data:{}},e.data.ttl=l},"maddr",p("maddr",!0),function(l){e=e||{data:{}},e.data.maddr=l},"received",p("received",!0),function(l){e=e||{data:{}},e.data.received=l},"branch",p("branch",!0),function(l){e=e||{data:{}},e.data.branch=l},"rport",p("rport",!0),function(l){e=e||{data:{}},typeof l<"u"&&(e.data.rport=l.join(""))},function(l){e=e||{data:{}},e.data.protocol=l},p("UDP",!0),p("TCP",!0),p("TLS",!0),p("SCTP",!0),function(l){e=e||{data:{}},e.data.transport=l},function(){e=e||{data:{}},e.data.host=C()},function(l){e=e||{data:{}},e.data.port=parseInt(l.join(""))},function(l){return parseInt(l.join(""))},function(l){e=e||{data:{}},e.startRule==="Session_Expires"&&(e.data.deltaSeconds=l)},"refresher",p("refresher",!1),"uas",p("uas",!1),"uac",p("uac",!1),function(l){e=e||{data:{}},e.startRule==="Session_Expires"&&(e.data.refresher=l)},function(l){e=e||{data:{}},e.startRule==="Min_SE"&&(e.data=l)},"stuns",p("stuns",!0),"stun",p("stun",!0),function(l){e=e||{data:{}},e.data.scheme=l},function(l){e=e||{data:{}},e.data.host=l},"?transport=",p("?transport=",!1),"turns",p("turns",!0),"turn",p("turn",!0),function(l){e=e||{data:{}},e.data.transport=l},function(){e=e||{data:{}},e.data=C()},"Referred-By",p("Referred-By",!1),"b",p("b",!1),"cid",p("cid",!1)],o=[c('2 ""6 7!'),c('4"""5!7#'),c('4$""5!7%'),c(`4&""5!7'`),c(";'.# &;("),c('4(""5!7)'),c('4*""5!7+'),c('2,""6,7-'),c('2.""6.7/'),c('40""5!71'),c('22""6273. &24""6475.} &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'),c(";).# &;,"),c('2F""6F7G.} &2H""6H7I.q &2J""6J7K.e &2L""6L7M.Y &2N""6N7O.M &2P""6P7Q.A &2R""6R7S.5 &2T""6T7U.) &2V""6V7W'),c(`%%2X""6X7Y/5#;#/,$;#/#$+#)(#'#("'#&'#/"!&,)`),c(`%%$;$0#*;$&/,#; /#$+")("'#&'#." &"/=#$;$/�#*;$&&&#/'$8":Z" )("'#&'#`),c(';.." &"'),c(`%$;'.# &;(0)*;'.# &;(&/?#28""6879/0$;//'$8#:[# )(#'#("'#&'#`),c(`%%$;2/�#*;2&&&#/g#$%$;.0#*;.&/,#;2/#$+")("'#&'#0=*%$;.0#*;.&/,#;2/#$+")("'#&'#&/#$+")("'#&'#/"!&,)`),c('4\\""5!7].# &;3'),c('4^""5!7_'),c('4`""5!7a'),c(';!.) &4b""5!7c'),c('%$;). &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&&&#/"!&,)'),c('%$;). &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&&&#/"!&,)'),c(`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.) &;'.# &;(`),c('%$;).ī &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&&&#/"!&,)'),c(`%;//?#2P""6P7Q/0$;//'$8#:t# )(#'#("'#&'#`),c(`%;//?#24""6475/0$;//'$8#:u# )(#'#("'#&'#`),c(`%;//?#2>""6>7?/0$;//'$8#:v# )(#'#("'#&'#`),c(`%;//?#2T""6T7U/0$;//'$8#:w# )(#'#("'#&'#`),c(`%;//?#2V""6V7W/0$;//'$8#:x# )(#'#("'#&'#`),c(`%2h""6h7i/0#;//'$8":y" )("'#&'#`),c(`%;//6#2f""6f7g/'$8":z" )("'#&'#`),c(`%;//?#2D""6D7E/0$;//'$8#:{# )(#'#("'#&'#`),c(`%;//?#22""6273/0$;//'$8#:|# )(#'#("'#&'#`),c(`%;//?#28""6879/0$;//'$8#:}# )(#'#("'#&'#`),c(`%;//0#;&/'$8":~" )("'#&'#`),c(`%;&/0#;//'$8":~" )("'#&'#`),c(`%;=/T#$;G.) &;K.# &;F0/*;G.) &;K.# &;F&/,$;>/#$+#)(#'#("'#&'#`),c('4""5!7.A &4""5!7.5 &4""5!7.) &;3.# &;.'),c(`%%;//Q#;&/H$$;J.# &;K0)*;J.# &;K&/,$;&/#$+$)($'#(#'#("'#&'#/"!&,)`),c(`%;//]#;&/T$%$;J.# &;K0)*;J.# &;K&/"!&,)/1$;&/($8$:
$!!)($'#(#'#("'#&'#`),c(';..G &2L""6L7M.; &4""5!7./ &4""5!7.# &;3'),c(`%2j""6j7k/J#4""5!7.5 &4""5!7.) &4""5!7/#$+")("'#&'#`),c(`%;N/M#28""6879/>$;O." &"/0$;S/'$8$:$ )($'#(#'#("'#&'#`),c(`%;N/d#28""6879/U$;O." &"/G$;S/>$;_/5$;l." &"/'$8&:& )(&'#(%'#($'#(#'#("'#&'#`),c(`%3""5$7.) &3""5#7/' 8!:!! )`),c(`%;P/]#%28""6879/,#;R/#$+")("'#&'#." &"/6$2:""6:7;/'$8#:# )(#'#("'#&'#`),c("$;+.) &;-.# &;Q/2#0/*;+.) &;-.# &;Q&&&#"),c('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'),c('%$;+._ &;-.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!:! )'),c(`%;T/J#%28""6879/,#;^/#$+")("'#&'#." &"/#$+")("'#&'#`),c("%;U.) &;\\.# &;X/& 8!:! )"),c(`%$%;V/2#2J""6J7K/#$+")("'#&'#0<*%;V/2#2J""6J7K/#$+")("'#&'#&/D#;W/;$2J""6J7K." &"/'$8#:# )(#'#("'#&'#`),c('$4""5!7/,#0)*4""5!7&&&#'),c(`%4$""5!7%/?#$4""5!70)*4""5!7&/#$+")("'#&'#`),c(`%2l""6l7m/?#;Y/6$2n""6n7o/'$8#:# )(#'#("'#&'#`),c(`%%;Z/³#28""6879/¤$;Z/$28""6879/$;Z/$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+-)(-'#(,'#(+'#(*'#()'#(('#(''#(&'#(%'#($'#(#'#("'#&'#.ސ &%2""67/¤#;Z/$28""6879/$;Z/$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+,)(,'#(+'#(*'#()'#(('#(''#(&'#(%'#($'#(#'#("'#&'#.۹ &%2""67/#;Z/$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+*)(*'#()'#(('#(''#(&'#(%'#($'#(#'#("'#&'#.ٺ &%2""67/t#;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+()(('#(''#(&'#(%'#($'#(#'#("'#&'#.ؓ &%2""67/\\#;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+&)(&'#(%'#($'#(#'#("'#&'#.ׄ &%2""67/D#;Z/;$28""6879/,$;[/#$+$)($'#(#'#("'#&'#.֍ &%2""67/,#;[/#$+")("'#&'#.ծ &%2""67/,#;Z/#$+")("'#&'#.Տ &%;Z/#2""67/$;Z/$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$++)(+'#(*'#()'#(('#(''#(&'#(%'#($'#(#'#("'#&'#.Ӈ &%;Z/ª#%28""6879/,#;Z/#$+")("'#&'#." &"/$2""67/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+*)(*'#()'#(('#(''#(&'#(%'#($'#(#'#("'#&'#.а &%;Z/¹#%28""6879/,#;Z/#$+")("'#&'#." &"/$%28""6879/,#;Z/#$+")("'#&'#." &"/k$2""67/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+))()'#(('#(''#(&'#(%'#($'#(#'#("'#&'#.Ί &%;Z/È#%28""6879/,#;Z/#$+")("'#&'#." &"/¡$%28""6879/,#;Z/#$+")("'#&'#." &"/z$%28""6879/,#;Z/#$+")("'#&'#." &"/S$2""67/D$;Z/;$28""6879/,$;[/#$+()(('#(''#(&'#(%'#($'#(#'#("'#&'#.˕ &%;Z/×#%28""6879/,#;Z/#$+")("'#&'#." &"/°$%28""6879/,#;Z/#$+")("'#&'#." &"/$%28""6879/,#;Z/#$+")("'#&'#." &"/b$%28""6879/,#;Z/#$+")("'#&'#." &"/;$2""67/,$;[/#$+')(''#(&'#(%'#($'#(#'#("'#&'#.ȑ &%;Z/þ#%28""6879/,#;Z/#$+")("'#&'#." &"/×$%28""6879/,#;Z/#$+")("'#&'#." &"/°$%28""6879/,#;Z/#$+")("'#&'#." &"/$%28""6879/,#;Z/#$+")("'#&'#." &"/b$%28""6879/,#;Z/#$+")("'#&'#." &"/;$2""67/,$;Z/#$+()(('#(''#(&'#(%'#($'#(#'#("'#&'#.Ħ &%;Z/Ĝ#%28""6879/,#;Z/#$+")("'#&'#." &"/õ$%28""6879/,#;Z/#$+")("'#&'#." &"/Î$%28""6879/,#;Z/#$+")("'#&'#." &"/§$%28""6879/,#;Z/#$+")("'#&'#." &"/$%28""6879/,#;Z/#$+")("'#&'#." &"/Y$%28""6879/,#;Z/#$+")("'#&'#." &"/2$2""67/#$+()(('#(''#(&'#(%'#($'#(#'#("'#&'#/& 8!: ! )`),c(`%;#/M#;#." &"/?$;#." &"/1$;#." &"/#$+$)($'#(#'#("'#&'#`),c(`%;Z/;#28""6879/,$;Z/#$+#)(#'#("'#&'#.# &;\\`),c(`%;]/o#2J""6J7K/\`$;]/W$2J""6J7K/H$;]/?$2J""6J7K/0$;]/'$8':¡' )(''#(&'#(%'#($'#(#'#("'#&'#`),c(`%2¢""6¢7£/2#4¤""5!7¥/#$+")("'#&'#. &%2¦""6¦7§/;#4¨""5!7©/,$;!/#$+#)(#'#("'#&'#.j &%2ª""6ª7«/5#;!/,$;!/#$+#)(#'#("'#&'#.B &%4¬""5!7/,#;!/#$+")("'#&'#.# &;!`),c(`%%;!." &"/[#;!." &"/M$;!." &"/?$;!." &"/1$;!." &"/#$+%)(%'#($'#(#'#("'#&'#/' 8!:®!! )`),c(`$%22""6273/,#;\`/#$+")("'#&'#0<*%22""6273/,#;\`/#$+")("'#&'#&`),c(";a.A &;b.; &;c.5 &;d./ &;e.) &;f.# &;g"),c(`%3¯""5*7°/a#3±""5#7².G &3³""5#7´.; &3µ""5$7¶./ &3·""5#7¸.# &;6/($8":¹"! )("'#&'#`),c(`%3º""5%7»/I#3¼""5%7½./ &3¾""5"7¿.# &;6/($8":À"! )("'#&'#`),c(`%3Á""5'7Â/1#;/($8":Ã"! )("'#&'#`),c(`%3Ä""5$7Å/1#;ð/($8":Æ"! )("'#&'#`),c(`%3Ç""5&7È/1#;T/($8":É"! )("'#&'#`),c(`%3Ê""5"7Ë/N#%2>""6>7?/,#;6/#$+")("'#&'#." &"/'$8":Ì" )("'#&'#`),c(`%;h/P#%2>""6>7?/,#;i/#$+")("'#&'#." &"/)$8":Í""! )("'#&'#`),c('%$;j/�#*;j&&&#/"!&,)'),c('%$;j/�#*;j&&&#/"!&,)'),c(";k.) &;+.# &;-"),c('2l""6l7m.e &2n""6n7o.Y &24""6475.M &28""6879.A &2<""6<7=.5 &2@""6@7A.) &2B""6B7C'),c(`%26""6677/n#;m/e$$%2<""6<7=/,#;m/#$+")("'#&'#0<*%2<""6<7=/,#;m/#$+")("'#&'#&/#$+#)(#'#("'#&'#`),c(`%;n/A#2>""6>7?/2$;o/)$8#:Î#"" )(#'#("'#&'#`),c("$;p.) &;+.# &;-/2#0/*;p.) &;+.# &;-&&&#"),c("$;p.) &;+.# &;-0/*;p.) &;+.# &;-&"),c('2l""6l7m.e &2n""6n7o.Y &24""6475.M &26""6677.A &28""6879.5 &2@""6@7A.) &2B""6B7C'),c(";.# &;r"),c(`%;/G#;'/>$;s/5$;'/,$;/#$+%)(%'#($'#(#'#("'#&'#`),c(";M.# &;t"),c(`%;/E#28""6879/6$;u.# &;x/'$8#:Ï# )(#'#("'#&'#`),c(`%;v.# &;w/J#%26""6677/,#;/#$+")("'#&'#." &"/#$+")("'#&'#`),c(`%2Ð""6Ð7Ñ/:#;/1$;w." &"/#$+#)(#'#("'#&'#`),c(`%24""6475/,#;{/#$+")("'#&'#`),c(`%;z/3#$;y0#*;y&/#$+")("'#&'#`),c(";*.) &;+.# &;-"),c(';+. &;-. &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'),c(`%;|/e#$%24""6475/,#;|/#$+")("'#&'#0<*%24""6475/,#;|/#$+")("'#&'#&/#$+")("'#&'#`),c(`%$;~0#*;~&/e#$%22""6273/,#;}/#$+")("'#&'#0<*%22""6273/,#;}/#$+")("'#&'#&/#$+")("'#&'#`),c("$;~0#*;~&"),c(';+.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'),c(`%%;"/#$;".G &;!.A &2@""6@7A.5 &2F""6F7G.) &2J""6J7K0M*;".G &;!.A &2@""6@7A.5 &2F""6F7G.) &2J""6J7K&/#$+")("'#&'#/& 8!:Ò! )`),c(";.# &;"),c(`%%;O/2#2:""6:7;/#$+")("'#&'#." &"/,#;S/#$+")("'#&'#." &"`),c('$;+. &;-.} &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&&&#'),c("$;y0#*;y&"),c(`%3""5#7Ó/q#24""6475/b$$;!/�#*;!&&&#/L$2J""6J7K/=$$;!/�#*;!&&&#/'$8%:Ô% )(%'#($'#(#'#("'#&'#`),c('2Õ""6Õ7Ö'),c('2×""6×7Ø'),c('2Ù""6Ù7Ú'),c('2Û""6Û7Ü'),c('2Ý""6Ý7Þ'),c('2ß""6ß7à'),c('2á""6á7â'),c('2ã""6ã7ä'),c('2å""6å7æ'),c('2ç""6ç7è'),c('2é""6é7ê'),c("%;
.Y &;.S &;.M &;.G &;.A &;.; &;.5 &;./ &;.) &;.# &;6/& 8!:ë! )"),c(`%;/G#;'/>$;/5$;'/,$;/#$+%)(%'#($'#(#'#("'#&'#`),c("%;/' 8!:ì!! )"),c(`%;!/5#;!/,$;!/#$+#)(#'#("'#&'#`),c("%$;*.A &;+.; &;-.5 &;3./ &;4.) &;'.# &;(0G*;*.A &;+.; &;-.5 &;3./ &;4.) &;'.# &;(&/& 8!:í! )"),c(`%;¶/Y#$%;A/,#;¶/#$+")("'#&'#06*%;A/,#;¶/#$+")("'#&'#&/#$+")("'#&'#`),c(`%;9/N#%2:""6:7;/,#;9/#$+")("'#&'#." &"/'$8":î" )("'#&'#`),c(`%;:.c &%;/Y#$%;A/,#;/#$+")("'#&'#06*%;A/,#;/#$+")("'#&'#&/#$+")("'#&'#/& 8!:ï! )`),c(`%;L.# &;/]#$%;B/,#;/#$+")("'#&'#06*%;B/,#;/#$+")("'#&'#&/'$8":ð" )("'#&'#`),c(`%;." &"/>#;@/5$;M/,$;?/#$+$)($'#(#'#("'#&'#`),c(`%%;6/Y#$%;./,#;6/#$+")("'#&'#06*%;./,#;6/#$+")("'#&'#&/#$+")("'#&'#.# &;H/' 8!:ñ!! )`),c(";.) &;.# &; "),c(`%3ò""5!7ó/:#;</1$;/($8#:ô#! )(#'#("'#&'#`),c(`%3õ""5'7ö/:#;</1$;/($8#:÷#! )(#'#("'#&'#`),c("%$;!/�#*;!&&&#/' 8!:ø!! )"),c(`%2ù""6ù7ú/o#%2J""6J7K/M#;!." &"/?$;!." &"/1$;!." &"/#$+$)($'#(#'#("'#&'#." &"/'$8":û" )("'#&'#`),c(`%;6/J#%;</,#;¡/#$+")("'#&'#." &"/)$8":ü""! )("'#&'#`),c(";6.) &;T.# &;H"),c(`%;£/Y#$%;B/,#;¤/#$+")("'#&'#06*%;B/,#;¤/#$+")("'#&'#&/#$+")("'#&'#`),c(`%3ý""5&7þ.G &3ÿ""5'7Ā.; &3ā""5$7Ă./ &3ă""5%7Ą.# &;6/& 8!:ą! )`),c(";¥.# &; "),c(`%3Ć""5(7ć/M#;</D$3Ĉ""5(7ĉ./ &3Ċ""5(7ċ.# &;6/#$+#)(#'#("'#&'#`),c(`%;6/Y#$%;A/,#;6/#$+")("'#&'#06*%;A/,#;6/#$+")("'#&'#&/#$+")("'#&'#`),c("%$;!/�#*;!&&&#/' 8!:Č!! )"),c("%;©/& 8!:č! )"),c(`%;ª/k#;;/b$;¯/Y$$%;B/,#;°/#$+")("'#&'#06*%;B/,#;°/#$+")("'#&'#&/#$+$)($'#(#'#("'#&'#`),c(";«.# &;¬"),c('3Ď""5$7ď.S &3Đ""5%7đ.G &3Ē""5%7ē.; &3Ĕ""5%7ĕ./ &3Ė""5+7ė.# &;'),c(`3Ę""5'7ę./ &3Ě""5)7ě.# &;`),c(";6.# &;®"),c(`%3Ĝ""5"7ĝ/,#;6/#$+")("'#&'#`),c(";.# &;6"),c(`%;6/5#;</,$;±/#$+#)(#'#("'#&'#`),c(";6.# &;H"),c(`%;³/5#;./,$;/#$+#)(#'#("'#&'#`),c("%$;!/�#*;!&&&#/' 8!:Ğ!! )"),c("%;/' 8!:ğ!! )"),c(`%;¶/^#$%;B/,#; /#$+")("'#&'#06*%;B/,#; /#$+")("'#&'#&/($8":Ġ"!!)("'#&'#`),c(`%%;7/e#$%2J""6J7K/,#;7/#$+")("'#&'#0<*%2J""6J7K/,#;7/#$+")("'#&'#&/#$+")("'#&'#/"!&,)`),c(`%;L.# &;/]#$%;B/,#;¸/#$+")("'#&'#06*%;B/,#;¸/#$+")("'#&'#&/'$8":ġ" )("'#&'#`),c(";¹.# &; "),c(`%3Ģ""5#7ģ/:#;</1$;6/($8#:Ĥ#! )(#'#("'#&'#`),c("%$;!/�#*;!&&&#/' 8!:ĥ!! )"),c("%;/' 8!:Ħ!! )"),c(`%$;0#*;&/x#;@/o$;M/f$;?/]$$%;B/,#; /#$+")("'#&'#06*%;B/,#; /#$+")("'#&'#&/'$8%:ħ% )(%'#($'#(#'#("'#&'#`),c(";¾"),c(`%3Ĩ""5&7ĩ/k#;./b$;Á/Y$$%;A/,#;Á/#$+")("'#&'#06*%;A/,#;Á/#$+")("'#&'#&/#$+$)($'#(#'#("'#&'#.# &;¿`),c(`%;6/k#;./b$;À/Y$$%;A/,#;À/#$+")("'#&'#06*%;A/,#;À/#$+")("'#&'#&/#$+$)($'#(#'#("'#&'#`),c(`%;6/;#;</2$;6.# &;H/#$+#)(#'#("'#&'#`),c(";Â.G &;Ä.A &;Æ.; &;È.5 &;É./ &;Ê.) &;Ë.# &;À"),c(`%3Ī""5%7ī/5#;</,$;Ã/#$+#)(#'#("'#&'#`),c("%;I/' 8!:Ĭ!! )"),c(`%3ĭ""5&7Į/#;</$;D/
$;Å/|$$%$;'/�#*;'&&&#/,#;Å/#$+")("'#&'#0C*%$;'/�#*;'&&&#/,#;Å/#$+")("'#&'#&/,$;E/#$+&)(&'#(%'#($'#(#'#("'#&'#`),c(";t.# &;w"),c(`%3į""5%7İ/5#;</,$;Ç/#$+#)(#'#("'#&'#`),c("%;I/' 8!:ı!! )"),c(`%3IJ""5&7ij/:#;</1$;I/($8#:Ĵ#! )(#'#("'#&'#`),c(`%3ĵ""5%7Ķ/]#;</T$%3ķ""5$7ĸ/& 8!:Ĺ! ).4 &%3ĺ""5%7Ļ/& 8!:ļ! )/#$+#)(#'#("'#&'#`),c(`%3Ľ""5)7ľ/R#;</I$3Ŀ""5#7ŀ./ &3Ł""5(7ł.# &;6/($8#:Ń#! )(#'#("'#&'#`),c(`%3ń""5#7Ņ/#;</$;D/$%;Ì/e#$%2D""6D7E/,#;Ì/#$+")("'#&'#0<*%2D""6D7E/,#;Ì/#$+")("'#&'#&/#$+")("'#&'#/,$;E/#$+%)(%'#($'#(#'#("'#&'#`),c(`%3ņ""5(7Ň./ &3ň""5$7ʼn.# &;6/' 8!:Ŋ!! )`),c(`%;6/Y#$%;A/,#;6/#$+")("'#&'#06*%;A/,#;6/#$+")("'#&'#&/#$+")("'#&'#`),c(`%;Ï/G#;./>$;Ï/5$;./,$;/#$+%)(%'#($'#(#'#("'#&'#`),c("%$;!/�#*;!&&&#/' 8!:ŋ!! )"),c(`%;Ñ/]#$%;A/,#;Ñ/#$+")("'#&'#06*%;A/,#;Ñ/#$+")("'#&'#&/'$8":Ō" )("'#&'#`),c(`%;/]#$%;B/,#; /#$+")("'#&'#06*%;B/,#; /#$+")("'#&'#&/'$8":ō" )("'#&'#`),c(`%;L.O &;.I &%;@." &"/:#;t/1$;?." &"/#$+#)(#'#("'#&'#/]#$%;B/,#; /#$+")("'#&'#06*%;B/,#; /#$+")("'#&'#&/'$8":Ŏ" )("'#&'#`),c(`%;Ô/]#$%;B/,#;Õ/#$+")("'#&'#06*%;B/,#;Õ/#$+")("'#&'#&/'$8":ŏ" )("'#&'#`),c("%;/& 8!:Ő! )"),c(`%3ő""5(7Œ/:#;</1$;6/($8#:œ#! )(#'#("'#&'#.g &%3Ŕ""5&7ŕ/:#;</1$;6/($8#:Ŗ#! )(#'#("'#&'#.: &%3ŗ""5*7Ř/& 8!:ř! ).# &; `),c(`%%;6/k#$%;A/2#;6/)$8":Ś""$ )("'#&'#0<*%;A/2#;6/)$8":Ś""$ )("'#&'#&/)$8":ś""! )("'#&'#." &"/' 8!:Ŝ!! )`),c(`%;Ø/Y#$%;A/,#;Ø/#$+")("'#&'#06*%;A/,#;Ø/#$+")("'#&'#&/#$+")("'#&'#`),c(`%;/Y#$%;B/,#; /#$+")("'#&'#06*%;B/,#; /#$+")("'#&'#&/#$+")("'#&'#`),c("%$;!/�#*;!&&&#/' 8!:ŝ!! )"),c(`%;Û/Y#$%;B/,#;Ü/#$+")("'#&'#06*%;B/,#;Ü/#$+")("'#&'#&/#$+")("'#&'#`),c(`%3Ş""5&7ş.; &3Š""5'7š./ &3Ţ""5*7ţ.# &;6/& 8!:Ť! )`),c(`%3ť""5&7Ŧ/:#;</1$;Ý/($8#:ŧ#! )(#'#("'#&'#.} &%3õ""5'7ö/:#;</1$;/($8#:Ũ#! )(#'#("'#&'#.P &%3ũ""5+7Ū/:#;</1$;/($8#:ū#! )(#'#("'#&'#.# &; `),c(`3Ŭ""5+7ŭ.k &3Ů""5)7ů._ &3Ű""5(7ű.S &3Ų""5'7ų.G &3Ŵ""5&7ŵ.; &3Ŷ""5*7ŷ./ &3Ÿ""5)7Ź.# &;6`),c(';1." &"'),c(`%%;6/k#$%;A/2#;6/)$8":Ś""$ )("'#&'#0<*%;A/2#;6/)$8":Ś""$ )("'#&'#&/)$8":ś""! )("'#&'#." &"/' 8!:ź!! )`),c(`%;L.# &;/]#$%;B/,#;á/#$+")("'#&'#06*%;B/,#;á/#$+")("'#&'#&/'$8":Ż" )("'#&'#`),c(";¹.# &; "),c(`%;ã/Y#$%;A/,#;ã/#$+")("'#&'#06*%;A/,#;ã/#$+")("'#&'#&/#$+")("'#&'#`),c(`%;ê/k#;./b$;í/Y$$%;B/,#;ä/#$+")("'#&'#06*%;B/,#;ä/#$+")("'#&'#&/#$+$)($'#(#'#("'#&'#`),c(";å.; &;æ.5 &;ç./ &;è.) &;é.# &; "),c(`%3ż""5#7Ž/:#;</1$;ð/($8#:ž#! )(#'#("'#&'#`),c(`%3ſ""5%7ƀ/:#;</1$;T/($8#:Ɓ#! )(#'#("'#&'#`),c(`%3Ƃ""5(7ƃ/F#;</=$;\\.) &;Y.# &;X/($8#:Ƅ#! )(#'#("'#&'#`),c(`%3ƅ""5&7Ɔ/:#;</1$;6/($8#:Ƈ#! )(#'#("'#&'#`),c(`%3ƈ""5%7Ɖ/A#;</8$$;!0#*;!&/($8#:Ɗ#! )(#'#("'#&'#`),c(`%;ë/G#;;/>$;6/5$;;/,$;ì/#$+%)(%'#($'#(#'#("'#&'#`),c(`%3""5#7Ó.# &;6/' 8!:Ƌ!! )`),c(`%3±""5#7ƌ.G &3³""5#7ƍ.; &3·""5#7Ǝ./ &3µ""5$7Ə.# &;6/' 8!:Ɛ!! )`),c(`%;î/D#%;C/,#;ï/#$+")("'#&'#." &"/#$+")("'#&'#`),c("%;U.) &;\\.# &;X/& 8!:Ƒ! )"),c(`%%;!." &"/[#;!." &"/M$;!." &"/?$;!." &"/1$;!." &"/#$+%)(%'#($'#(#'#("'#&'#/' 8!:ƒ!! )`),c(`%%;!/?#;!." &"/1$;!." &"/#$+#)(#'#("'#&'#/' 8!:Ɠ!! )`),c(";¾"),c(`%;/^#$%;B/,#;ó/#$+")("'#&'#06*%;B/,#;ó/#$+")("'#&'#&/($8":Ɣ"!!)("'#&'#`),c(";ô.# &; "),c(`%2ƕ""6ƕ7Ɩ/L#;</C$2Ɨ""6Ɨ7Ƙ.) &2ƙ""6ƙ7ƚ/($8#:ƛ#! )(#'#("'#&'#`),c(`%;/^#$%;B/,#; /#$+")("'#&'#06*%;B/,#; /#$+")("'#&'#&/($8":Ɯ"!!)("'#&'#`),c(`%;6/5#;0/,$;÷/#$+#)(#'#("'#&'#`),c("$;2.) &;4.# &;.0/*;2.) &;4.# &;.&"),c("$;%0#*;%&"),c(`%;ú/;#28""6879/,$;û/#$+#)(#'#("'#&'#`),c(`%3Ɲ""5%7ƞ.) &3Ɵ""5$7Ơ/' 8!:ơ!! )`),c(`%;ü/J#%28""6879/,#;^/#$+")("'#&'#." &"/#$+")("'#&'#`),c("%;\\.) &;X.# &;/' 8!:Ƣ!! )"),c(';".S &;!.M &2F""6F7G.A &2J""6J7K.5 &2H""6H7I.) &2N""6N7O'),c('2L""6L7M. &2B""6B7C. &2<""6<7=.} &2R""6R7S.q &2T""6T7U.e &2V""6V7W.Y &2P""6P7Q.M &2@""6@7A.A &2D""6D7E.5 &22""6273.) &2>""6>7?'),c(`%;Ā/b#28""6879/S$;û/J$%2ƣ""6ƣ7Ƥ/,#;ì/#$+")("'#&'#." &"/#$+$)($'#(#'#("'#&'#`),c(`%3ƥ""5%7Ʀ.) &3Ƨ""5$7ƨ/' 8!:ơ!! )`),c(`%3±""5#7².6 &3³""5#7´.* &$;+0#*;+&/' 8!:Ʃ!! )`),c(`%;Ą/#2F""6F7G/x$;ă/o$2F""6F7G/\`$;ă/W$2F""6F7G/H$;ă/?$2F""6F7G/0$;ą/'$8):ƪ) )()'#(('#(''#(&'#(%'#($'#(#'#("'#&'#`),c(`%;#/>#;#/5$;#/,$;#/#$+$)($'#(#'#("'#&'#`),c(`%;ă/,#;ă/#$+")("'#&'#`),c(`%;ă/5#;ă/,$;ă/#$+#)(#'#("'#&'#`),c(`%;q/T#$;m0#*;m&/D$%; /,#;ø/#$+")("'#&'#." &"/#$+#)(#'#("'#&'#`),c(`%2ƫ""6ƫ7Ƭ.) &2ƭ""6ƭ7Ʈ/w#;0/n$;Ĉ/e$$%;B/2#;ĉ.# &; /#$+")("'#&'#0<*%;B/2#;ĉ.# &; /#$+")("'#&'#&/#$+$)($'#(#'#("'#&'#`),c(";.# &;L"),c(`%2Ư""6Ư7ư/5#;</,$;Ċ/#$+#)(#'#("'#&'#`),c(`%;D/S#;,/J$2:""6:7;/;$;,.# &;T/,$;E/#$+%)(%'#($'#(#'#("'#&'#`)];let d=0,u=0;const h=[{line:1,column:1}];let m=0,S=[],x=0,_;if(e.startRule!==void 0){if(!(e.startRule in s))throw new Error(`Can't start parsing from rule "`+e.startRule+'".');r=s[e.startRule]}function C(){return a.substring(u,d)}function ee(){return tt(u,d)}function p(l,b){return{type:"literal",text:l,ignoreCase:b}}function $(l,b,g){return{type:"class",parts:l,inverted:b,ignoreCase:g}}function et(){return{type:"end"}}function It(l){let b=h[l],g;if(b)return b;for(g=l-1;!h[g];)g--;for(b=h[g],b={line:b.line,column:b.column};g<l;)a.charCodeAt(g)===10?(b.line++,b.column=1):b.column++,g++;return h[l]=b,b}function tt(l,b){const g=It(l),G=It(b);return{source:i,start:{offset:l,line:g.line,column:g.column},end:{offset:b,line:G.line,column:G.column}}}function At(l){d<m||(d>m&&(m=d,S=[]),S.push(l))}function Ki(l,b,g){return new pe(pe.buildMessage(l,b),l,b,g)}function c(l){return l.split("").map(b=>b.charCodeAt(0)-32)}function $t(l){const b=o[l];let g=0;const G=[];let D=b.length;const te=[],E=[];let Dt;for(;;){for(;g<D;)switch(b[g]){case 0:E.push(n[b[g+1]]),g+=2;break;case 1:E.push(void 0),g++;break;case 2:E.push(null),g++;break;case 3:E.push(t),g++;break;case 4:E.push([]),g++;break;case 5:E.push(d),g++;break;case 6:E.pop(),g++;break;case 7:d=E.pop(),g++;break;case 8:E.length-=b[g+1],g+=2;break;case 9:E.splice(-2,1),g++;break;case 10:E[E.length-2].push(E.pop()),g++;break;case 11:E.push(E.splice(E.length-b[g+1],b[g+1])),g+=2;break;case 12:E.push(a.substring(E.pop(),d)),g++;break;case 13:te.push(D),G.push(g+3+b[g+1]+b[g+2]),E[E.length-1]?(D=g+3+b[g+1],g+=3):(D=g+3+b[g+1]+b[g+2],g+=3+b[g+1]);break;case 14:te.push(D),G.push(g+3+b[g+1]+b[g+2]),E[E.length-1]===t?(D=g+3+b[g+1],g+=3):(D=g+3+b[g+1]+b[g+2],g+=3+b[g+1]);break;case 15:te.push(D),G.push(g+3+b[g+1]+b[g+2]),E[E.length-1]!==t?(D=g+3+b[g+1],g+=3):(D=g+3+b[g+1]+b[g+2],g+=3+b[g+1]);break;case 16:E[E.length-1]!==t?(te.push(D),G.push(g),D=g+2+b[g+1],g+=2):g+=2+b[g+1];break;case 17:te.push(D),G.push(g+3+b[g+1]+b[g+2]),a.length>d?(D=g+3+b[g+1],g+=3):(D=g+3+b[g+1]+b[g+2],g+=3+b[g+1]);break;case 18:te.push(D),G.push(g+4+b[g+2]+b[g+3]),a.substr(d,n[b[g+1]].length)===n[b[g+1]]?(D=g+4+b[g+2],g+=4):(D=g+4+b[g+2]+b[g+3],g+=4+b[g+2]);break;case 19:te.push(D),G.push(g+4+b[g+2]+b[g+3]),a.substr(d,n[b[g+1]].length).toLowerCase()===n[b[g+1]]?(D=g+4+b[g+2],g+=4):(D=g+4+b[g+2]+b[g+3],g+=4+b[g+2]);break;case 20:te.push(D),G.push(g+4+b[g+2]+b[g+3]),n[b[g+1]].test(a.charAt(d))?(D=g+4+b[g+2],g+=4):(D=g+4+b[g+2]+b[g+3],g+=4+b[g+2]);break;case 21:E.push(a.substr(d,b[g+1])),d+=b[g+1],g+=2;break;case 22:E.push(n[b[g+1]]),d+=n[b[g+1]].length,g+=2;break;case 23:E.push(t),x===0&&At(n[b[g+1]]),g+=2;break;case 24:u=E[E.length-1-b[g+1]],g+=2;break;case 25:u=d,g++;break;case 26:Dt=b.slice(g+4,g+4+b[g+3]).map(function(Yi){return E[E.length-1-Yi]}),E.splice(E.length-b[g+2],b[g+2],n[b[g+1]].apply(null,Dt)),g+=4+b[g+3];break;case 27:E.push($t(b[g+1])),g+=2;break;case 28:x++,g++;break;case 29:x--,g++;break;default:throw new Error("Invalid opcode: "+b[g]+".")}if(te.length>0)D=te.pop(),g=G.pop();else break}return E[0]}e.data={};function zi(l,b){return[l].concat(b)}if(_=$t(r),_!==t&&d===a.length)return _;throw _!==t&&d<a.length&&At(et()),Ki(S,m<a.length?a.charAt(m):null,m<a.length?tt(m,m+1):tt(m,m))}const Nt=Ft;var P;(function(a){function e(s,r){const n={startRule:r};try{Nt(s,n)}catch{n.data=-1}return n.data}a.parse=e;function t(s){const r=a.parse(s,"Name_Addr_Header");return r!==-1?r:void 0}a.nameAddrHeaderParse=t;function i(s){const r=a.parse(s,"SIP_URI");return r!==-1?r:void 0}a.URIParse=i})(P=P||(P={}));const Ut={100:"Trying",180:"Ringing",181:"Call Is Being Forwarded",182:"Queued",183:"Session Progress",199:"Early Dialog Terminated",200:"OK",202:"Accepted",204:"No Notification",300:"Multiple Choices",301:"Moved Permanently",302:"Moved Temporarily",305:"Use Proxy",380:"Alternative Service",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",410:"Gone",412:"Conditional Request Failed",413:"Request Entity Too Large",414:"Request-URI Too Long",415:"Unsupported Media Type",416:"Unsupported URI Scheme",417:"Unknown Resource-Priority",420:"Bad Extension",421:"Extension Required",422:"Session Interval Too Small",423:"Interval Too Brief",428:"Use Identity Header",429:"Provide Referrer Identity",430:"Flow Failed",433:"Anonymity Disallowed",436:"Bad Identity-Info",437:"Unsupported Certificate",438:"Invalid Identity Header",439:"First Hop Lacks Outbound Support",440:"Max-Breadth Exceeded",469:"Bad Info Package",470:"Consent Needed",478:"Unresolvable Destination",480:"Temporarily Unavailable",481:"Call/Transaction Does Not Exist",482:"Loop Detected",483:"Too Many Hops",484:"Address Incomplete",485:"Ambiguous",486:"Busy Here",487:"Request Terminated",488:"Not Acceptable Here",489:"Bad Event",491:"Request Pending",493:"Undecipherable",494:"Security Agreement Required",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Server Time-out",505:"Version Not Supported",513:"Message Too Large",580:"Precondition Failure",600:"Busy Everywhere",603:"Decline",604:"Does Not Exist Anywhere",606:"Not Acceptable"};function ue(a,e=32){let t="";for(let i=0;i<a;i++){const s=Math.floor(Math.random()*e);t+=s.toString(e)}return t}function Ae(a){return Ut[a]||""}function $e(){return ue(10)}function Y(a){const e={"Call-Id":"Call-ID",Cseq:"CSeq","Min-Se":"Min-SE",Rack:"RAck",Rseq:"RSeq","Www-Authenticate":"WWW-Authenticate"},t=a.toLowerCase().replace(/_/g,"-").split("-"),i=t.length;let s="";for(let r=0;r<i;r++)r!==0&&(s+="-"),s+=t[r].charAt(0).toUpperCase()+t[r].substring(1);return e[s]&&(s=e[s]),s}function Ce(a){return encodeURIComponent(a).replace(/%[A-F\d]{2}/g,"U").length}class rt{constructor(){this.headers={}}addHeader(e,t){const i={raw:t};e=Y(e),this.headers[e]?this.headers[e].push(i):this.headers[e]=[i]}getHeader(e){const t=this.headers[Y(e)];if(t){if(t[0])return t[0].raw}else return}getHeaders(e){const t=this.headers[Y(e)],i=[];if(!t)return[];for(const s of t)i.push(s.raw);return i}hasHeader(e){return!!this.headers[Y(e)]}parseHeader(e,t=0){if(e=Y(e),this.headers[e]){if(t>=this.headers[e].length)return}else return;const i=this.headers[e][t],s=i.raw;if(i.parsed)return i.parsed;const r=P.parse(s,e.replace(/-/g,"_"));if(r===-1){this.headers[e].splice(t,1);return}else return i.parsed=r,r}s(e,t=0){return this.parseHeader(e,t)}setHeader(e,t){this.headers[Y(e)]=[{raw:t}]}toString(){return this.data}}class me extends rt{constructor(){super()}}class re extends rt{constructor(){super()}}class ge{constructor(e,t,i,s,r,n,o){this.headers={},this.extraHeaders=[],this.options=ge.getDefaultOptions(),r&&(this.options=Object.assign(Object.assign({},this.options),r),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())),n&&n.length&&(this.extraHeaders=n.slice()),o&&(this.body={body:o.content,contentType:o.contentType}),this.method=e,this.ruri=t.clone(),this.fromURI=i.clone(),this.fromTag=this.options.fromTag?this.options.fromTag:$e(),this.from=ge.makeNameAddrHeader(this.fromURI,this.options.fromDisplayName,this.fromTag),this.toURI=s.clone(),this.toTag=this.options.toTag,this.to=ge.makeNameAddrHeader(this.toURI,this.options.toDisplayName,this.toTag),this.callId=this.options.callId?this.options.callId:this.options.callIdPrefix+ue(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,i){const s={};return i&&(s.tag=i),new N(e,t,s)}getHeader(e){const t=this.headers[Y(e)];if(t){if(t[0])return t[0]}else{const i=new RegExp("^\\s*"+e+"\\s*:","i");for(const s of this.extraHeaders)if(i.test(s))return s.substring(s.indexOf(":")+1).trim()}}getHeaders(e){const t=[],i=this.headers[Y(e)];if(i)for(const s of i)t.push(s);else{const s=new RegExp("^\\s*"+e+"\\s*:","i");for(const r of this.extraHeaders)s.test(r)&&t.push(r.substring(r.indexOf(":")+1).trim())}return t}hasHeader(e){if(this.headers[Y(e)])return!0;{const t=new RegExp("^\\s*"+e+"\\s*:","i");for(const i of this.extraHeaders)if(t.test(i))return!0}return!1}setHeader(e,t){this.headers[Y(e)]=t instanceof Array?t:[t]}setViaHeader(e,t){this.options.hackViaTcp&&(t="TCP");let i="SIP/2.0/"+t;i+=" "+this.options.viaHost+";branch="+e,this.options.forceRport&&(i+=";rport"),this.setHeader("via",i),this.branch=e}toString(){let e="";e+=this.method+" "+this.ruri.toRaw()+` SIP/2.0\r
|
|
9
9
|
`;for(const t in this.headers)if(this.headers[t])for(const i of this.headers[t])e+=t+": "+i+`\r
|
|
10
10
|
`;for(const t of this.extraHeaders)e+=t.trim()+`\r
|
|
11
11
|
`;return e+="Supported: "+this.options.optionTags.join(", ")+`\r
|
|
@@ -19,7 +19,7 @@ var EmbeddedCallWidgetRuntimeBundle=(function(Fe){"use strict";const Pt="0.21.1"
|
|
|
19
19
|
\r
|
|
20
20
|
`:e+=`Content-Length: 0\r
|
|
21
21
|
\r
|
|
22
|
-
`,e}}function nt(a){return a==="application/sdp"?"session":"render"}function De(a){const e=typeof a=="string"?a:a.body,t=typeof a=="string"?"application/sdp":a.contentType;return{contentDisposition:nt(t),contentType:t,content:e}}function at(a){return a&&typeof a.content=="string"&&typeof a.contentType=="string"&&a.contentDisposition===void 0?!0:typeof a.contentDisposition=="string"}function Ee(a){let e,t,i;if(a instanceof me&&a.body){const s=a.parseHeader("Content-Disposition");e=s?s.type:void 0,t=a.parseHeader("Content-Type"),i=a.body}if(a instanceof re&&a.body){const s=a.parseHeader("Content-Disposition");e=s?s.type:void 0,t=a.parseHeader("Content-Type"),i=a.body}if(a instanceof ge&&a.body)if(e=a.getHeader("Content-Disposition"),t=a.getHeader("Content-Type"),typeof a.body=="string"){if(!t)throw new Error("Header content type header does not equal body content type.");i=a.body}else{if(t&&t!==a.body.contentType)throw new Error("Header content type header does not equal body content type.");t=a.body.contentType,i=a.body.body}if(at(a)&&(e=a.contentDisposition,t=a.contentType,i=a.content),!!i){if(t&&!e&&(e=nt(t)),!e)throw new Error("Content disposition undefined.");if(!t)throw new Error("Content type undefined.");return{contentDisposition:e,contentType:t,content:i}}}var V;(function(a){a.Initial="Initial",a.Early="Early",a.AckWait="AckWait",a.Confirmed="Confirmed",a.Terminated="Terminated"})(V=V||(V={}));var y;(function(a){a.Initial="Initial",a.HaveLocalOffer="HaveLocalOffer",a.HaveRemoteOffer="HaveRemoteOffer",a.Stable="Stable",a.Closed="Closed"})(y=y||(y={}));const te=500,Lt=4e3,ot=5e3,M={T1:te,T2:Lt,TIMER_B:64*te,TIMER_D:0*te,TIMER_F:64*te,TIMER_H:64*te,TIMER_I:0*ot,TIMER_J:0*te,TIMER_K:0*ot,TIMER_L:64*te,TIMER_M:64*te,TIMER_N:64*te,PROVISIONAL_RESPONSE_INTERVAL:6e4};class ne extends he{constructor(e){super(e||"Transaction state error.")}}var v;(function(a){a.ACK="ACK",a.BYE="BYE",a.CANCEL="CANCEL",a.INFO="INFO",a.INVITE="INVITE",a.MESSAGE="MESSAGE",a.NOTIFY="NOTIFY",a.OPTIONS="OPTIONS",a.REGISTER="REGISTER",a.UPDATE="UPDATE",a.SUBSCRIBE="SUBSCRIBE",a.PUBLISH="PUBLISH",a.REFER="REFER",a.PRACK="PRACK"})(v=v||(v={}));const ae=[v.ACK,v.BYE,v.CANCEL,v.INFO,v.INVITE,v.MESSAGE,v.NOTIFY,v.OPTIONS,v.PRACK,v.REFER,v.REGISTER,v.SUBSCRIBE];class ct{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 Be{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 Bt{constructor(e,t){this.incomingReferRequest=e,this.session=t}get referTo(){const e=this.incomingReferRequest.message.parseHeader("refer-to");if(!(e instanceof N))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(),e=e||{};const i=(e.extraHeaders||[]).slice(),s=this.replaces;s&&i.push("Replaces: "+decodeURIComponent(s));const r=this.referredBy;return r&&i.push("Referred-By: "+r),e.extraHeaders=i,this.inviter=this.session.userAgent._makeInviter(t,e),this.inviter._referred=this.session,this.session._referral=this.inviter,this.inviter}}var w;(function(a){a.Initial="Initial",a.Establishing="Establishing",a.Established="Established",a.Terminating="Terminating",a.Terminated="Terminated"})(w=w||(w={}));class we{constructor(e,t={}){this.pendingReinvite=!1,this.pendingReinviteAck=!1,this._state=w.Initial,this.delegate=t.delegate,this._stateEventEmitter=new Te,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 w.Initial:break;case w.Establishing:break;case w.Established:return new Promise(e=>{this._bye({onAccept:()=>e(),onRedirect:()=>e(),onReject:()=>e()})});case w.Terminating:break;case w.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 w.Initial:typeof this.cancel=="function"?(t+=" However Inviter.invite() has not yet been called.",t+=" Perhaps you should have called Inviter.cancel()?"):typeof this.reject=="function"&&(t+=" However Invitation.accept() has not yet been called.",t+=" Perhaps you should have called Invitation.reject()?");break;case w.Establishing:typeof this.cancel=="function"?(t+=" However a dialog does not yet exist.",t+=" Perhaps you should have called Inviter.cancel()?"):typeof this.reject=="function"&&(t+=" However Invitation.accept() has not yet been called (or not yet resolved).",t+=" Perhaps you should have called Invitation.reject()?");break;case w.Established:{const i=e.requestDelegate,s=this.copyRequestOptions(e.requestOptions);return this._bye(i,s)}case w.Terminating:t+=" However this session is already terminating.",typeof this.cancel=="function"?t+=" Perhaps you have already called Inviter.cancel()?":typeof this.reject=="function"&&(t+=" Perhaps you have already called Session.bye()?");break;case w.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!==w.Established)return this.logger.error("Session.info() may only be called if established session."),Promise.reject(new Error(`Invalid session state ${this.state}`));const t=e.requestDelegate,i=this.copyRequestOptions(e.requestOptions);return this._info(t,i)}invite(e={}){if(this.logger.log("Session.invite"),this.state!==w.Established)return Promise.reject(new Error(`Invalid session state ${this.state}`));if(this.pendingReinvite)return Promise.reject(new ve("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:r=>{const n=Ee(r.message);if(!n){this.logger.error("Received 2xx response to re-INVITE without a session description"),this.ackAndBye(r,400,"Missing session description"),this.stateTransition(w.Terminated),this.pendingReinvite=!1;return}if(e.withoutSdp){const o={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};this.setOfferAndGetAnswer(n,o).then(d=>{r.ack({body:d})}).catch(d=>{this.logger.error("Failed to handle offer in 2xx response to re-INVITE"),this.logger.error(d.message),this.state===w.Terminated?r.ack():(this.ackAndBye(r,488,"Bad Media Description"),this.stateTransition(w.Terminated))}).then(()=>{this.pendingReinvite=!1,e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(r)})}else{const o={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};this.setAnswer(n,o).then(()=>{r.ack()}).catch(d=>{this.logger.error("Failed to handle answer in 2xx response to re-INVITE"),this.logger.error(d.message),this.state!==w.Terminated?(this.ackAndBye(r,488,"Bad Media Description"),this.stateTransition(w.Terminated)):r.ack()}).then(()=>{this.pendingReinvite=!1,e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(r)})}},onProgress:r=>{},onRedirect:r=>{},onReject:r=>{this.logger.warn("Received a non-2xx response to re-INVITE"),this.pendingReinvite=!1,e.withoutSdp?e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(r):this.rollbackOffer().catch(n=>{if(this.logger.error("Failed to rollback offer on non-2xx response to re-INVITE"),this.logger.error(n.message),this.state!==w.Terminated){if(!this.dialog)throw new Error("Dialog undefined.");const o=[];o.push("Reason: "+this.getReasonHeaderValue(500,"Internal Server Error")),this.dialog.bye(void 0,{extraHeaders:o}),this.stateTransition(w.Terminated)}}).then(()=>{e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(r)})},onTrying:r=>{}},i=e.requestOptions||{};if(i.extraHeaders=(i.extraHeaders||[]).slice(),i.extraHeaders.push("Allow: "+ae.toString()),i.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,i))}const s={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};return this.getOffer(s).then(r=>{if(!this.dialog)throw this.pendingReinvite=!1,new Error("Dialog undefined.");return i.body=r,this.dialog.invite(t,i)}).catch(r=>{throw this.logger.error(r.message),this.logger.error("Failed to send re-INVITE"),this.pendingReinvite=!1,r})}message(e={}){if(this.state!==w.Established)return this.logger.error("Session.message() may only be called if established session."),Promise.reject(new Error(`Invalid session state ${this.state}`));const t=e.requestDelegate,i=this.copyRequestOptions(e.requestOptions);return this._message(t,i)}refer(e,t={}){if(this.state!==w.Established)return this.logger.error("Session.refer() may only be called if established session."),Promise.reject(new Error(`Invalid session state ${this.state}`));if(e instanceof we&&!e.dialog)return this.logger.error("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)."),Promise.reject(new Error(`Invalid session state ${this.state}`));const i=t.requestDelegate,s=this.copyRequestOptions(t.requestOptions);return s.extraHeaders=s.extraHeaders?s.extraHeaders.concat(this.referExtraHeaders(this.referToString(e))):this.referExtraHeaders(this.referToString(e)),this._refer(t.onNotify,i,s)}_bye(e,t){if(!this.dialog)return Promise.reject(new Error("Session dialog undefined."));const i=this.dialog;switch(i.sessionState){case V.Initial:throw new Error(`Invalid dialog state ${i.sessionState}`);case V.Early:throw new Error(`Invalid dialog state ${i.sessionState}`);case V.AckWait:return this.stateTransition(w.Terminating),new Promise(s=>{i.delegate={onAck:()=>{const r=i.bye(e,t);return this.stateTransition(w.Terminated),s(r),Promise.resolve()},onAckTimeout:()=>{const r=i.bye(e,t);this.stateTransition(w.Terminated),s(r)}}});case V.Confirmed:{const s=i.bye(e,t);return this.stateTransition(w.Terminated),Promise.resolve(s)}case V.Terminated:throw new Error(`Invalid dialog state ${i.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,i){return this.dialog?(this.onNotify=e,Promise.resolve(this.dialog.refer(t,i))):Promise.reject(new Error("Session dialog undefined."))}ackAndBye(e,t,i){e.ack();const s=[];t&&s.push("Reason: "+this.getReasonHeaderValue(t,i)),e.session.bye(void 0,{extraHeaders:s})}onAckRequest(e){if(this.logger.log("Session.onAckRequest"),this.state!==w.Established&&this.state!==w.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 i={sessionDescriptionHandlerOptions:this.pendingReinviteAck?this.sessionDescriptionHandlerOptionsReInvite:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.pendingReinviteAck?this._sessionDescriptionHandlerModifiersReInvite:this._sessionDescriptionHandlerModifiers};if(this.delegate&&this.delegate.onAck){const s=new Ht(e);this.delegate.onAck(s)}switch(this.pendingReinviteAck=!1,t.signalingState){case y.Initial:{this.logger.error(`Invalid signaling state ${t.signalingState}.`);const s=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];return t.bye(void 0,{extraHeaders:s}),this.stateTransition(w.Terminated),Promise.resolve()}case y.Stable:{const s=Ee(e.message);return s?s.contentDisposition==="render"?(this._renderbody=s.content,this._rendertype=s.contentType,Promise.resolve()):s.contentDisposition!=="session"?Promise.resolve():this.setAnswer(s,i).catch(r=>{this.logger.error(r.message);const n=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];t.bye(void 0,{extraHeaders:n}),this.stateTransition(w.Terminated)}):Promise.resolve()}case y.HaveLocalOffer:{this.logger.error(`Invalid signaling state ${t.signalingState}.`);const s=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];return t.bye(void 0,{extraHeaders:s}),this.stateTransition(w.Terminated),Promise.resolve()}case y.HaveRemoteOffer:{this.logger.error(`Invalid signaling state ${t.signalingState}.`);const s=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];return t.bye(void 0,{extraHeaders:s}),this.stateTransition(w.Terminated),Promise.resolve()}case y.Closed:throw new Error(`Invalid signaling state ${t.signalingState}.`);default:throw new Error(`Invalid signaling state ${t.signalingState}.`)}}onByeRequest(e){if(this.logger.log("Session.onByeRequest"),this.state!==w.Established){this.logger.error(`BYE received while in state ${this.state}, dropping request`);return}if(this.delegate&&this.delegate.onBye){const t=new Mt(e);this.delegate.onBye(t)}else e.accept();this.stateTransition(w.Terminated)}onInfoRequest(e){if(this.logger.log("Session.onInfoRequest"),this.state!==w.Established){this.logger.error(`INFO received while in state ${this.state}, dropping request`);return}if(this.delegate&&this.delegate.onInfo){const t=new Ot(e);this.delegate.onInfo(t)}else e.accept()}onInviteRequest(e){if(this.logger.log("Session.onInviteRequest"),this.state!==w.Established){this.logger.error(`INVITE received while in state ${this.state}, dropping request`);return}this.pendingReinviteAck=!0;const t=["Contact: "+this._contact];if(e.message.hasHeader("P-Asserted-Identity")){const s=e.message.getHeader("P-Asserted-Identity");if(!s)throw new Error("Header undefined.");this._assertedIdentity=P.nameAddrHeaderParse(s)}const i={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};this.generateResponseOfferAnswerInDialog(i).then(s=>{const r=e.accept({statusCode:200,extraHeaders:t,body:s});this.delegate&&this.delegate.onInvite&&this.delegate.onInvite(e.message,r.message,200)}).catch(s=>{if(this.logger.error(s.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===y.Stable){const r=e.reject({statusCode:488});this.delegate&&this.delegate.onInvite&&this.delegate.onInvite(e.message,r.message,488);return}this.rollbackOffer().then(()=>{const r=e.reject({statusCode:488});this.delegate&&this.delegate.onInvite&&this.delegate.onInvite(e.message,r.message,488)}).catch(r=>{this.logger.error(r.message),this.logger.error("Failed to rollback offer on re-INVITE request");const n=e.reject({statusCode:488});if(this.state!==w.Terminated){if(!this.dialog)throw new Error("Dialog undefined.");const o=[];o.push("Reason: "+this.getReasonHeaderValue(500,"Internal Server Error")),this.dialog.bye(void 0,{extraHeaders:o}),this.stateTransition(w.Terminated)}this.delegate&&this.delegate.onInvite&&this.delegate.onInvite(e.message,n.message,488)})})}onMessageRequest(e){if(this.logger.log("Session.onMessageRequest"),this.state!==w.Established){this.logger.error(`MESSAGE received while in state ${this.state}, dropping request`);return}if(this.delegate&&this.delegate.onMessage){const t=new ct(e);this.delegate.onMessage(t)}else e.accept()}onNotifyRequest(e){if(this.logger.log("Session.onNotifyRequest"),this.state!==w.Established){this.logger.error(`NOTIFY received while in state ${this.state}, dropping request`);return}if(this.onNotify){const t=new Be(e);this.onNotify(t);return}if(this.delegate&&this.delegate.onNotify){const t=new Be(e);this.delegate.onNotify(t)}else e.accept()}onPrackRequest(e){if(this.logger.log("Session.onPrackRequest"),this.state!==w.Established){this.logger.error(`PRACK received while in state ${this.state}, dropping request`);return}throw new Error("Unimplemented.")}onReferRequest(e){if(this.logger.log("Session.onReferRequest"),this.state!==w.Established){this.logger.error(`REFER received while in state ${this.state}, dropping request`);return}if(!e.message.hasHeader("refer-to")){this.logger.warn("Invalid REFER packet. A refer-to header is required. Rejecting."),e.reject();return}const t=new Bt(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(i=>{this.logger.error(i.message)}))}generateResponseOfferAnswer(e,t){if(this.dialog)return this.generateResponseOfferAnswerInDialog(t);const i=Ee(e.message);return!i||i.contentDisposition!=="session"?this.getOffer(t):this.setOfferAndGetAnswer(i,t)}generateResponseOfferAnswerInDialog(e){if(!this.dialog)throw new Error("Dialog undefined.");switch(this.dialog.signalingState){case y.Initial:return this.getOffer(e);case y.HaveLocalOffer:return Promise.resolve(void 0);case y.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 y.Stable:return this.state!==w.Established?Promise.resolve(void 0):this.getOffer(e);case y.Closed:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`);default:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`)}}getOffer(e){const t=this.setupSessionDescriptionHandler(),i=e.sessionDescriptionHandlerOptions,s=e.sessionDescriptionHandlerModifiers;try{return t.getDescription(i,s).then(r=>De(r)).catch(r=>{this.logger.error("Session.getOffer: SDH getDescription rejected...");const n=r instanceof Error?r:new Error("Session.getOffer unknown error.");throw this.logger.error(n.message),n})}catch(r){this.logger.error("Session.getOffer: SDH getDescription threw...");const n=r instanceof Error?r:new Error(r);return this.logger.error(n.message),Promise.reject(n)}}rollbackOffer(){const e=this.setupSessionDescriptionHandler();if(e.rollbackDescription===void 0)return Promise.resolve();try{return e.rollbackDescription().catch(t=>{this.logger.error("Session.rollbackOffer: SDH rollbackDescription rejected...");const i=t instanceof Error?t:new Error("Session.rollbackOffer unknown error.");throw this.logger.error(i.message),i})}catch(t){this.logger.error("Session.rollbackOffer: SDH rollbackDescription threw...");const i=t instanceof Error?t:new Error(t);return this.logger.error(i.message),Promise.reject(i)}}setAnswer(e,t){const i=this.setupSessionDescriptionHandler(),s=t.sessionDescriptionHandlerOptions,r=t.sessionDescriptionHandlerModifiers;try{if(!i.hasDescription(e.contentType))return Promise.reject(new Ne)}catch(n){this.logger.error("Session.setAnswer: SDH hasDescription threw...");const o=n instanceof Error?n:new Error(n);return this.logger.error(o.message),Promise.reject(o)}try{return i.setDescription(e.content,s,r).catch(n=>{this.logger.error("Session.setAnswer: SDH setDescription rejected...");const o=n instanceof Error?n:new Error("Session.setAnswer unknown error.");throw this.logger.error(o.message),o})}catch(n){this.logger.error("Session.setAnswer: SDH setDescription threw...");const o=n instanceof Error?n:new Error(n);return this.logger.error(o.message),Promise.reject(o)}}setOfferAndGetAnswer(e,t){const i=this.setupSessionDescriptionHandler(),s=t.sessionDescriptionHandlerOptions,r=t.sessionDescriptionHandlerModifiers;try{if(!i.hasDescription(e.contentType))return Promise.reject(new Ne)}catch(n){this.logger.error("Session.setOfferAndGetAnswer: SDH hasDescription threw...");const o=n instanceof Error?n:new Error(n);return this.logger.error(o.message),Promise.reject(o)}try{return i.setDescription(e.content,s,r).then(()=>i.getDescription(s,r)).then(n=>De(n)).catch(n=>{this.logger.error("Session.setOfferAndGetAnswer: SDH setDescription or getDescription rejected...");const o=n instanceof Error?n:new Error("Session.setOfferAndGetAnswer unknown error.");throw this.logger.error(o.message),o})}catch(n){this.logger.error("Session.setOfferAndGetAnswer: SDH setDescription or getDescription threw...");const o=n instanceof Error?n:new Error(n);return this.logger.error(o.message),Promise.reject(o)}}setSessionDescriptionHandler(e){if(this._sessionDescriptionHandler)throw new Error("Session description handler defined.");this._sessionDescriptionHandler=e}setupSessionDescriptionHandler(){var e;return this._sessionDescriptionHandler?this._sessionDescriptionHandler:(this._sessionDescriptionHandler=this.sessionDescriptionHandlerFactory(this,this.userAgent.configuration.sessionDescriptionHandlerFactoryOptions),!((e=this.delegate)===null||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 w.Initial:e!==w.Establishing&&e!==w.Established&&e!==w.Terminating&&e!==w.Terminated&&t();break;case w.Establishing:e!==w.Established&&e!==w.Terminating&&e!==w.Terminated&&t();break;case w.Established:e!==w.Terminating&&e!==w.Terminated&&t();break;case w.Terminating:e!==w.Terminated&&t();break;case w.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===w.Terminated&&this.dispose()}copyRequestOptions(e={}){const t=e.extraHeaders?e.extraHeaders.slice():void 0,i=e.body?{contentDisposition:e.body.contentDisposition||"render",contentType:e.body.contentType||"text/plain",content:e.body.content||""}:void 0;return{extraHeaders:t,body:i}}getReasonHeaderValue(e,t){const i=e;let s=Ae(e);return!s&&t&&(s=t),"SIP;cause="+i+';text="'+s+'"'}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 z)t=e.toString();else{if(!e.dialog)throw new Error("Dialog undefined.");const i=e.remoteIdentity.friendlyName,s=e.dialog.remoteTarget.toString(),r=e.dialog.callId,n=e.dialog.remoteTag,o=e.dialog.localTag,d=encodeURIComponent(`${r};to-tag=${n};from-tag=${o}`);t=`"${i}" <${s}?Replaces=${d}>`}return t}}var W;(function(a){a.Required="Required",a.Supported="Supported",a.Unsupported="Unsupported"})(W=W||(W={}));const jt={"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 fe extends we{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(Math.random()*1e4),this.userNoAnswerTimer=void 0,this.waitingForPrack=!1,this.logger=e.getLogger("sip.Invitation");const i=this.incomingInviteRequest.message,s=i.getHeader("require");s&&s.toLowerCase().includes("100rel")&&(this.rel100="required");const r=i.getHeader("supported");if(r&&r.toLowerCase().includes("100rel")&&(this.rel100="supported"),i.toTag=t.toTag,typeof i.toTag!="string")throw new TypeError("toTag should have been a string.");if(this.userNoAnswerTimer=setTimeout(()=>{t.reject({statusCode:480}),this.stateTransition(w.Terminated)},this.userAgent.configuration.noAnswerTimeout?this.userAgent.configuration.noAnswerTimeout*1e3:6e4),i.hasHeader("expires")){const d=Number(i.getHeader("expires")||0)*1e3;this.expiresTimer=setTimeout(()=>{this.state===w.Initial&&(t.reject({statusCode:487}),this.stateTransition(w.Terminated))},d)}const n=this.request.getHeader("P-Asserted-Identity");n&&(this._assertedIdentity=P.nameAddrHeaderParse(n)),this._contact=this.userAgent.contact.toString();const o=i.parseHeader("Content-Disposition");o&&o.type==="render"&&(this._renderbody=i.body,this._rendertype=i.getHeader("Content-Type")),this._id=i.callId+i.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 w.Initial:return this.reject().then(()=>super.dispose());case w.Establishing:return this.reject().then(()=>super.dispose());case w.Established:return super.dispose();case w.Terminating:return super.dispose();case w.Terminated:return super.dispose();default:throw new Error("Unknown state.")}}get autoSendAnInitialProvisionalResponse(){return this.rel100!=="required"&&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!==w.Initial){const t=new Error(`Invalid session state ${this.state}`);return this.logger.error(t.message),Promise.reject(t)}return e.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiers=e.sessionDescriptionHandlerModifiers),e.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptions=e.sessionDescriptionHandlerOptions),this.stateTransition(w.Establishing),this.sendAccept(e).then(({message:t,session:i})=>{i.delegate={onAck:s=>this.onAckRequest(s),onAckTimeout:()=>this.onAckTimeout(),onBye:s=>this.onByeRequest(s),onInfo:s=>this.onInfoRequest(s),onInvite:s=>this.onInviteRequest(s),onMessage:s=>this.onMessageRequest(s),onNotify:s=>this.onNotifyRequest(s),onPrack:s=>this.onPrackRequest(s),onRefer:s=>this.onReferRequest(s)},this._dialog=i,this.stateTransition(w.Established),this._replacee&&this._replacee._bye()}).catch(t=>this.handleResponseError(t))}progress(e={}){if(this.logger.log("Invitation.progress"),this.state!==w.Initial){const i=new Error(`Invalid session state ${this.state}`);return this.logger.error(i.message),Promise.reject(i)}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()):e.statusCode===100?this.sendProgressTrying().then(()=>{}).catch(i=>this.handleResponseError(i)):this.rel100!=="required"&&!(this.rel100==="supported"&&e.rel100)&&!(this.rel100==="supported"&&this.userAgent.configuration.sipExtension100rel===W.Required)?this.sendProgress(e).then(()=>{}).catch(i=>this.handleResponseError(i)):this.sendProgressReliableWaitForPrack(e).then(()=>{}).catch(i=>this.handleResponseError(i))}reject(e={}){if(this.logger.log("Invitation.reject"),this.state!==w.Initial&&this.state!==w.Establishing){const n=new Error(`Invalid session state ${this.state}`);return this.logger.error(n.message),Promise.reject(n)}const t=e.statusCode||480,i=e.reasonPhrase?e.reasonPhrase:Ae(t),s=e.extraHeaders||[];if(t<300||t>699)throw new TypeError("Invalid statusCode: "+t);const r=e.body?De(e.body):void 0;return t<400?this.incomingInviteRequest.redirect([],{statusCode:t,reasonPhrase:i,extraHeaders:s,body:r}):this.incomingInviteRequest.reject({statusCode:t,reasonPhrase:i,extraHeaders:s,body:r}),this.stateTransition(w.Terminated),Promise.resolve()}_onCancel(e){if(this.logger.log("Invitation._onCancel"),this.state!==w.Initial&&this.state!==w.Establishing){this.logger.error(`CANCEL received while in state ${this.state}, dropping request`);return}if(this.delegate&&this.delegate.onCancel){const t=new qt(e);this.delegate.onCancel(t)}this.isCanceled=!0,this.incomingInviteRequest.reject({statusCode:487}),this.stateTransition(w.Terminated)}handlePrackOfferAnswer(e){if(!this.dialog)throw new Error("Dialog undefined.");const t=Ee(e.message);if(!t||t.contentDisposition!=="session")return Promise.resolve(void 0);const i={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers};switch(this.dialog.signalingState){case y.Initial:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`);case y.Stable:return this.setAnswer(t,i).then(()=>{});case y.HaveLocalOffer:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`);case y.HaveRemoteOffer:return this.setOfferAndGetAnswer(t,i);case y.Closed:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`);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 Ne?(this.logger.error("A session description handler occurred while sending response (content type unsupported"),t=415):e instanceof kt?this.logger.error("A session description handler occurred while sending response"):e instanceof Ue?this.logger.error("Session ended before response could be formulated and sent (while waiting for PRACK)"):e instanceof ne&&this.logger.error("Session changed state before response could be formulated and sent"),this.state===w.Initial||this.state===w.Establishing)try{this.incomingInviteRequest.reject({statusCode:t}),this.stateTransition(w.Terminated)}catch(i){throw this.logger.error("An error occurred attempting to reject the request while handling another error"),i}if(this.isCanceled){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.");return}throw e}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(w.Terminated)}sendAccept(e={}){const t={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers},i=e.extraHeaders||[];return this.waitingForPrack?this.waitForArrivalOfPrack().then(()=>clearTimeout(this.userNoAnswerTimer)).then(()=>this.generateResponseOfferAnswer(this.incomingInviteRequest,t)).then(s=>this.incomingInviteRequest.accept({statusCode:200,body:s,extraHeaders:i})):(clearTimeout(this.userNoAnswerTimer),this.generateResponseOfferAnswer(this.incomingInviteRequest,t).then(s=>this.incomingInviteRequest.accept({statusCode:200,body:s,extraHeaders:i})))}sendProgress(e={}){const t=e.statusCode||180,i=e.reasonPhrase,s=(e.extraHeaders||[]).slice(),r=e.body?De(e.body):void 0;if(t===183&&!r)return this.sendProgressWithSDP(e);try{const n=this.incomingInviteRequest.progress({statusCode:t,reasonPhrase:i,extraHeaders:s,body:r});return this._dialog=n.session,Promise.resolve(n)}catch(n){return Promise.reject(n)}}sendProgressWithSDP(e={}){const t={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers},i=e.statusCode||183,s=e.reasonPhrase,r=(e.extraHeaders||[]).slice();return this.generateResponseOfferAnswer(this.incomingInviteRequest,t).then(n=>this.incomingInviteRequest.progress({statusCode:i,reasonPhrase:s,extraHeaders:r,body:n})).then(n=>(this._dialog=n.session,n))}sendProgressReliable(e={}){return e.extraHeaders=(e.extraHeaders||[]).slice(),e.extraHeaders.push("Require: 100rel"),e.extraHeaders.push("RSeq: "+Math.floor(Math.random()*1e4)),this.sendProgressWithSDP(e)}sendProgressReliableWaitForPrack(e={}){const t={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers},i=e.statusCode||183,s=e.reasonPhrase,r=(e.extraHeaders||[]).slice();r.push("Require: 100rel"),r.push("RSeq: "+this.rseq++);let n;return new Promise((o,d)=>{this.waitingForPrack=!0,this.generateResponseOfferAnswer(this.incomingInviteRequest,t).then(u=>(n=u,this.incomingInviteRequest.progress({statusCode:i,reasonPhrase:s,extraHeaders:r,body:n}))).then(u=>{this._dialog=u.session;let h,m;u.session.delegate={onPrack:p=>{h=p,clearTimeout(x),clearTimeout(Q),this.waitingForPrack&&(this.waitingForPrack=!1,this.handlePrackOfferAnswer(h).then($=>{try{m=h.accept({statusCode:200,body:$}),this.prackArrived(),o({prackRequest:h,prackResponse:m,progressResponse:u})}catch(et){d(et)}}).catch($=>d($)))}};const x=setTimeout(()=>{this.waitingForPrack&&(this.waitingForPrack=!1,this.logger.warn("No PRACK received, rejecting INVITE."),clearTimeout(Q),this.reject({statusCode:504}).then(()=>d(new Ue)).catch(p=>d(p)))},M.T1*64),_=()=>{try{this.incomingInviteRequest.progress({statusCode:i,reasonPhrase:s,extraHeaders:r,body:n})}catch(p){this.waitingForPrack=!1,d(p);return}Q=setTimeout(_,C*=2)};let C=M.T1,Q=setTimeout(_,C)}).catch(u=>{this.waitingForPrack=!1,d(u)})})}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 Ue),this.waitingForPrackPromise=void 0,this.waitingForPrackResolve=void 0,this.waitingForPrackReject=void 0}}class Pe extends we{constructor(e,t,i={}){super(e,i),this.disposed=!1,this.earlyMedia=!1,this.earlyMediaSessionDescriptionHandlers=new Map,this.isCanceled=!1,this.inviteWithoutSdp=!1,this.logger=e.getLogger("sip.Inviter"),this.earlyMedia=i.earlyMedia!==void 0?i.earlyMedia:this.earlyMedia,this.fromTag=$e(),this.inviteWithoutSdp=i.inviteWithoutSdp!==void 0?i.inviteWithoutSdp:this.inviteWithoutSdp;const s=Object.assign({},i);s.params=Object.assign({},i.params);const r=i.anonymous||!1,n=e.contact.toString({anonymous:r,outbound:r?!e.contact.tempGruu:!e.contact.pubGruu});r&&e.configuration.uri&&(s.params.fromDisplayName="Anonymous",s.params.fromUri="sip:anonymous@anonymous.invalid");let o=e.userAgentCore.configuration.aor;if(s.params.fromUri&&(o=typeof s.params.fromUri=="string"?P.URIParse(s.params.fromUri):s.params.fromUri),!o)throw new TypeError("Invalid from URI: "+s.params.fromUri);let d=t;if(s.params.toUri&&(d=typeof s.params.toUri=="string"?P.URIParse(s.params.toUri):s.params.toUri),!d)throw new TypeError("Invalid to URI: "+s.params.toUri);const u=Object.assign({},s.params);u.fromTag=this.fromTag;const h=(s.extraHeaders||[]).slice();r&&e.configuration.uri&&(h.push("P-Preferred-Identity: "+e.configuration.uri.toString()),h.push("Privacy: id")),h.push("Contact: "+n),h.push("Allow: "+["ACK","CANCEL","INVITE","MESSAGE","BYE","OPTIONS","INFO","NOTIFY","REFER"].toString()),e.configuration.sipExtension100rel===W.Required&&h.push("Require: 100rel"),e.configuration.sipExtensionReplaces===W.Required&&h.push("Require: replaces"),s.extraHeaders=h;const m=void 0;this.outgoingRequestMessage=e.userAgentCore.makeOutgoingRequestMessage(v.INVITE,t,o,d,u,h,m),this._contact=n,this._referralInviterOptions=s,this._renderbody=i.renderbody,this._rendertype=i.rendertype,i.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiers=i.sessionDescriptionHandlerModifiers),i.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptions=i.sessionDescriptionHandlerOptions),i.sessionDescriptionHandlerModifiersReInvite&&(this.sessionDescriptionHandlerModifiersReInvite=i.sessionDescriptionHandlerModifiersReInvite),i.sessionDescriptionHandlerOptionsReInvite&&(this.sessionDescriptionHandlerOptionsReInvite=i.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 w.Initial:return this.cancel().then(()=>super.dispose());case w.Establishing:return this.cancel().then(()=>super.dispose());case w.Established:return super.dispose();case w.Terminating:return super.dispose();case w.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!==w.Initial&&this.state!==w.Establishing){const i=new Error(`Invalid session state ${this.state}`);return this.logger.error(i.message),Promise.reject(i)}this.isCanceled=!0,this.stateTransition(w.Terminating);function t(i,s){if(i&&i<200||i>699)throw new TypeError("Invalid statusCode: "+i);if(i){const r=i,n=Ae(i)||s;return"SIP;cause="+r+';text="'+n+'"'}}if(this.outgoingInviteRequest){let i;e.statusCode&&e.reasonPhrase&&(i=t(e.statusCode,e.reasonPhrase)),this.outgoingInviteRequest.cancel(i,e)}else this.logger.warn("Canceled session before INVITE was sent"),this.stateTransition(w.Terminated);return Promise.resolve()}invite(e={}){if(this.logger.log("Inviter.invite"),this.state!==w.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(w.Establishing),Promise.resolve(this.sendInvite(e));const t={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.getOffer(t).then(i=>(this.outgoingRequestMessage.body={body:i.content,contentType:i.contentType},this.stateTransition(w.Establishing),this.sendInvite(e))).catch(i=>{throw this.logger.log(i.message),this.state!==w.Terminated&&this.stateTransition(w.Terminated),i})}sendInvite(e={}){return this.outgoingInviteRequest=this.userAgent.userAgentCore.invite(this.outgoingRequestMessage,{onAccept:t=>{if(this.dialog){this.logger.log("Additional confirmed dialog, sending ACK and BYE"),this.ackAndBye(t);return}if(this.isCanceled){this.logger.log("Canceled session accepted, sending ACK and BYE"),this.ackAndBye(t),this.stateTransition(w.Terminated);return}this.notifyReferer(t),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 we))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=e.message.statusCode,i=e.message.reasonPhrase,s=`SIP/2.0 ${t} ${i}`.trim(),r=this._referred.dialog.notify(void 0,{extraHeaders:["Event: refer","Subscription-State: terminated"],body:{contentDisposition:"render",contentType:"message/sipfrag",content:s}});r.delegate={onReject:()=>{this._referred=void 0}}}onAccept(e){if(this.logger.log("Inviter.onAccept"),this.state!==w.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,i=e.session;switch(t.hasHeader("P-Asserted-Identity")&&(this._assertedIdentity=P.nameAddrHeaderParse(t.getHeader("P-Asserted-Identity"))),i.delegate={onAck:s=>this.onAckRequest(s),onBye:s=>this.onByeRequest(s),onInfo:s=>this.onInfoRequest(s),onInvite:s=>this.onInviteRequest(s),onMessage:s=>this.onMessageRequest(s),onNotify:s=>this.onNotifyRequest(s),onPrack:s=>this.onPrackRequest(s),onRefer:s=>this.onReferRequest(s)},this._dialog=i,i.signalingState){case y.Initial:return this.logger.error("Received 2xx response to INVITE without a session description"),this.ackAndBye(e,400,"Missing session description"),this.stateTransition(w.Terminated),Promise.reject(new Error("Bad Media Description"));case y.HaveLocalOffer:return this.logger.error("Received 2xx response to INVITE without a session description"),this.ackAndBye(e,400,"Missing session description"),this.stateTransition(w.Terminated),Promise.reject(new Error("Bad Media Description"));case y.HaveRemoteOffer:{if(!this._dialog.offer)throw new Error(`Session offer undefined in signaling state ${this._dialog.signalingState}.`);const s={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.setOfferAndGetAnswer(this._dialog.offer,s).then(r=>{e.ack({body:r}),this.stateTransition(w.Established)}).catch(r=>{throw this.ackAndBye(e,488,"Invalid session description"),this.stateTransition(w.Terminated),r})}case y.Stable:{if(this.earlyMediaSessionDescriptionHandlers.size>0){const n=this.earlyMediaSessionDescriptionHandlers.get(i.id);if(!n)throw new Error("Session description handler undefined.");return this.setSessionDescriptionHandler(n),this.earlyMediaSessionDescriptionHandlers.delete(i.id),e.ack(),this.stateTransition(w.Established),Promise.resolve()}if(this.earlyMediaDialog){if(this.earlyMediaDialog!==i){this.earlyMedia&&this.logger.error("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.");const n=new Error("Early media dialog does not equal confirmed dialog, terminating session");return this.logger.error(n.message),this.ackAndBye(e,488,"Not Acceptable Here"),this.stateTransition(w.Terminated),Promise.reject(n)}return e.ack(),this.stateTransition(w.Established),Promise.resolve()}const s=i.answer;if(!s)throw new Error("Answer is undefined.");const r={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.setAnswer(s,r).then(()=>{let n;this._renderbody&&this._rendertype&&(n={body:{contentDisposition:"render",contentType:this._rendertype,content:this._renderbody}}),e.ack(n),this.stateTransition(w.Established)}).catch(n=>{throw this.logger.error(n.message),this.ackAndBye(e,488,"Not Acceptable Here"),this.stateTransition(w.Terminated),n})}case y.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!==w.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 i=e.message,s=e.session;i.hasHeader("P-Asserted-Identity")&&(this._assertedIdentity=P.nameAddrHeaderParse(i.getHeader("P-Asserted-Identity")));const r=i.getHeader("require"),n=i.getHeader("rseq"),d=!!(r&&r.includes("100rel")&&n?Number(n):void 0),u=[];switch(d&&u.push("RAck: "+i.getHeader("rseq")+" "+i.getHeader("cseq")),s.signalingState){case y.Initial:return d&&(this.logger.warn("First reliable provisional response received MUST contain an offer when INVITE does not contain an offer."),e.prack({extraHeaders:u})),Promise.resolve();case y.HaveLocalOffer:return d&&e.prack({extraHeaders:u}),Promise.resolve();case y.HaveRemoteOffer:if(!d)return this.logger.warn("Non-reliable provisional response MUST NOT contain an initial offer, discarding response."),Promise.resolve();{const h=this.sessionDescriptionHandlerFactory(this,this.userAgent.configuration.sessionDescriptionHandlerFactoryOptions||{});return!((t=this.delegate)===null||t===void 0)&&t.onSessionDescriptionHandler&&this.delegate.onSessionDescriptionHandler(h,!0),this.earlyMediaSessionDescriptionHandlers.set(s.id,h),h.setDescription(i.body,this.sessionDescriptionHandlerOptions,this.sessionDescriptionHandlerModifiers).then(()=>h.getDescription(this.sessionDescriptionHandlerOptions,this.sessionDescriptionHandlerModifiers)).then(m=>{const S={contentDisposition:"session",contentType:m.contentType,content:m.body};e.prack({extraHeaders:u,body:S})}).catch(m=>{throw this.stateTransition(w.Terminated),m})}case y.Stable:if(d&&e.prack({extraHeaders:u}),this.earlyMedia&&!this.earlyMediaDialog){this.earlyMediaDialog=s;const h=s.answer;if(!h)throw new Error("Answer is undefined.");const m={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.setAnswer(h,m).catch(S=>{throw this.stateTransition(w.Terminated),S})}return Promise.resolve();case y.Closed:return Promise.reject(new Error("Terminated."));default:throw new Error("Unknown session signaling state.")}}onRedirect(e){if(this.logger.log("Inviter.onRedirect"),this.state!==w.Establishing&&this.state!==w.Terminating){this.logger.error(`Redirect received while in state ${this.state}, dropping response`);return}this.stateTransition(w.Terminated)}onReject(e){if(this.logger.log("Inviter.onReject"),this.state!==w.Establishing&&this.state!==w.Terminating){this.logger.error(`Reject received while in state ${this.state}, dropping response`);return}this.stateTransition(w.Terminated)}onTrying(e){if(this.logger.log("Inviter.onTrying"),this.state!==w.Establishing){this.logger.error(`Trying received while in state ${this.state}, dropping response`);return}}}class Vt{constructor(e,t,i,s="text/plain",r={}){this.logger=e.getLogger("sip.Messager"),r.params=r.params||{};let n=e.userAgentCore.configuration.aor;if(r.params.fromUri&&(n=typeof r.params.fromUri=="string"?P.URIParse(r.params.fromUri):r.params.fromUri),!n)throw new TypeError("Invalid from URI: "+r.params.fromUri);let o=t;if(r.params.toUri&&(o=typeof r.params.toUri=="string"?P.URIParse(r.params.toUri):r.params.toUri),!o)throw new TypeError("Invalid to URI: "+r.params.toUri);const d=r.params?Object.assign({},r.params):{},u=(r.extraHeaders||[]).slice(),m={contentDisposition:"render",contentType:s,content:i};this.request=e.userAgentCore.makeOutgoingRequestMessage(v.MESSAGE,t,n,o,d,u,m),this.userAgent=e}message(e={}){return this.userAgent.userAgentCore.request(this.request,e.requestDelegate),Promise.resolve()}}var R;(function(a){a.Initial="Initial",a.Registered="Registered",a.Unregistered="Unregistered",a.Terminated="Terminated"})(R=R||(R={}));class J{constructor(e,t={}){this.disposed=!1,this._contacts=[],this._retryAfter=void 0,this._state=R.Initial,this._waiting=!1,this._stateEventEmitter=new Te,this._waitingEventEmitter=new Te,this.userAgent=e;const i=e.configuration.uri.clone();if(i.user=void 0,this.options=Object.assign(Object.assign(Object.assign({},J.defaultOptions()),{registrar:i}),J.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&&P.parse(this.options.instanceId,"uuid")===-1)throw new Error("Invalid instanceId.");if(this.options.regId&&this.options.regId<0)throw new Error("Invalid regId.");const s=this.options.registrar,r=this.options.params&&this.options.params.fromUri||e.userAgentCore.configuration.aor,n=this.options.params&&this.options.params.toUri||e.configuration.uri,o=this.options.params||{},d=(t.extraHeaders||[]).slice();if(this.request=e.userAgentCore.makeOutgoingRequestMessage(v.REGISTER,s,r,n,o,d,void 0),this.expires=this.options.expires||J.defaultExpires,this.expires<0)throw new Error("Invalid expires.");if(this.refreshFrequency=this.options.refreshFrequency||J.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(u=>{const h=this.options[u];u==="registrar"?this.logger.log("· "+u+": "+h):this.logger.log("· "+u+": "+JSON.stringify(h))})),this.id=this.request.callId+this.request.from.parameters.tag,this.userAgent._registerers[this.id]=this}static defaultOptions(){return{expires:J.defaultExpires,extraContactHeaderParams:[],extraHeaders:[],logConfiguration:!0,instanceId:"",params:{},regId:0,registrar:new z("sip","anonymous","anonymous.invalid"),refreshFrequency:J.defaultRefreshFrequency}}static stripUndefinedProperties(e){return Object.keys(e).reduce((t,i)=>(e[i]!==void 0&&(t[i]=e[i]),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===R.Registered){this.stateChange.addListener(()=>{this.terminated(),e()},{once:!0}),this.unregister();return}this.terminated(),e()};this.waiting?this.waitingChange.addListener(()=>{t()},{once:!0}):t()}))}register(e={}){if(this.state===R.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 s=new ve("REGISTER request already in progress, waiting for final response");return Promise.reject(s)}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 i=this.userAgent.userAgentCore.register(this.request,{onAccept:s=>{let r;s.message.hasHeader("expires")&&(r=Number(s.message.getHeader("expires"))),this._contacts=s.message.getHeaders("contact");let n=this._contacts.length;if(!n){this.logger.error("No Contact header in response to REGISTER, dropping response."),this.unregistered();return}let o;for(;n--;){if(o=s.message.parseHeader("contact",n),!o)throw new Error("Contact undefined");if(this.userAgent.contact.pubGruu&&st(o.uri,this.userAgent.contact.pubGruu)){r=Number(o.getParam("expires"));break}if(this.userAgent.configuration.contactName===""){if(o.uri.user===this.userAgent.contact.uri.user){r=Number(o.getParam("expires"));break}}else if(st(o.uri,this.userAgent.contact.uri)){r=Number(o.getParam("expires"));break}o=void 0}if(o===void 0){this.logger.error("No Contact header pointing to us, dropping response"),this.unregistered(),this.waitingToggle(!1);return}if(r===void 0){this.logger.error("Contact pointing to us is missing expires parameter, dropping response"),this.unregistered(),this.waitingToggle(!1);return}if(o.hasParam("temp-gruu")){const d=o.getParam("temp-gruu");d&&(this.userAgent.contact.tempGruu=P.URIParse(d.replace(/"/g,"")))}if(o.hasParam("pub-gruu")){const d=o.getParam("pub-gruu");d&&(this.userAgent.contact.pubGruu=P.URIParse(d.replace(/"/g,"")))}this.registered(r),e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(s),this.waitingToggle(!1)},onProgress:s=>{e.requestDelegate&&e.requestDelegate.onProgress&&e.requestDelegate.onProgress(s)},onRedirect:s=>{this.logger.error("Redirect received. Not supported."),this.unregistered(),e.requestDelegate&&e.requestDelegate.onRedirect&&e.requestDelegate.onRedirect(s),this.waitingToggle(!1)},onReject:s=>{if(s.message.statusCode===423){if(!s.message.hasHeader("min-expires")){this.logger.error("423 response received for REGISTER without Min-Expires, dropping response"),this.unregistered(),this.waitingToggle(!1);return}this.expires=Number(s.message.getHeader("min-expires")),this.waitingToggle(!1),this.register();return}this.logger.warn(`Failed to register, status code ${s.message.statusCode}`);let r=NaN;if(s.message.statusCode===500||s.message.statusCode===503){const n=s.message.getHeader("retry-after");n&&(r=Number.parseInt(n,void 0))}this._retryAfter=isNaN(r)?void 0:r,this.unregistered(),e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(s),this._retryAfter=void 0,this.waitingToggle(!1)},onTrying:s=>{e.requestDelegate&&e.requestDelegate.onTrying&&e.requestDelegate.onTrying(s)}});return Promise.resolve(i)}unregister(e={}){if(this.state===R.Terminated)throw this.stateError(),new Error("Registerer terminated. Unable to register.");if(this.disposed&&this.state!==R.Registered)throw this.stateError(),new Error("Registerer disposed. Unable to register.");if(this.waiting){this.waitingWarning();const s=new ve("REGISTER request already in progress, waiting for final response");return Promise.reject(s)}this._state!==R.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"),this.registrationTimer!==void 0&&(clearTimeout(this.registrationTimer),this.registrationTimer=void 0),this.waitingToggle(!0);const i=this.userAgent.userAgentCore.register(this.request,{onAccept:s=>{this._contacts=s.message.getHeaders("contact"),this.unregistered(),e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(s),this.waitingToggle(!1)},onProgress:s=>{e.requestDelegate&&e.requestDelegate.onProgress&&e.requestDelegate.onProgress(s)},onRedirect:s=>{this.logger.error("Unregister redirected. Not currently supported."),this.unregistered(),e.requestDelegate&&e.requestDelegate.onRedirect&&e.requestDelegate.onRedirect(s),this.waitingToggle(!1)},onReject:s=>{this.logger.error(`Unregister rejected with status code ${s.message.statusCode}`),this.unregistered(),e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(s),this.waitingToggle(!1)},onTrying:s=>{e.requestDelegate&&e.requestDelegate.onTrying&&e.requestDelegate.onTrying(s)}});return Promise.resolve(i)}clearTimers(){this.registrationTimer!==void 0&&(clearTimeout(this.registrationTimer),this.registrationTimer=void 0),this.registrationExpiredTimer!==void 0&&(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="<urn:uuid:'+this.options.instanceId+'>"'),this.options.extraContactHeaderParams&&this.options.extraContactHeaderParams.forEach(i=>{t+=";"+i}),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()},e*1e3),this._state!==R.Registered&&this.stateTransition(R.Registered)}unregistered(){this.clearTimers(),this._state!==R.Unregistered&&this.stateTransition(R.Unregistered)}terminated(){this.clearTimers(),this._state!==R.Terminated&&this.stateTransition(R.Terminated)}stateTransition(e){const t=()=>{throw new Error(`Invalid state transition from ${this._state} to ${e}`)};switch(this._state){case R.Initial:e!==R.Registered&&e!==R.Unregistered&&e!==R.Terminated&&t();break;case R.Registered:e!==R.Unregistered&&e!==R.Terminated&&t();break;case R.Unregistered:e!==R.Registered&&e!==R.Terminated&&t();break;case R.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===R.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(e)}stateError(){let t=`An attempt was made to send a REGISTER request when the Registerer ${this.state===R.Terminated?"is in 'Terminated' state":"has been disposed"}.`;t+=" The Registerer transitions to 'Terminated' when Registerer.dispose() is called.",t+=" Perhaps you called UserAgent.stop() which dipsoses of all Registerers?",this.logger.error(t)}}J.defaultExpires=600,J.defaultRefreshFrequency=99;var I;(function(a){a.Initial="Initial",a.NotifyWait="NotifyWait",a.Pending="Pending",a.Active="Active",a.Terminated="Terminated"})(I=I||(I={}));var T;(function(a){a.Connecting="Connecting",a.Connected="Connected",a.Disconnecting="Disconnecting",a.Disconnected="Disconnected"})(T=T||(T={}));var k;(function(a){a.Started="Started",a.Stopped="Stopped"})(k=k||(k={}));class H{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=H.hexChars,i=H.hexOut;let s,r,n,o;for(o=0;o<4;o+=1)for(r=o*8,s=e[o],n=0;n<8;n+=2)i[r+1+n]=t.charAt(s&15),s>>>=4,i[r+0+n]=t.charAt(s&15),s>>>=4;return i.join("")}static _md5cycle(e,t){let i=e[0],s=e[1],r=e[2],n=e[3];i+=(s&r|~s&n)+t[0]-680876936|0,i=(i<<7|i>>>25)+s|0,n+=(i&s|~i&r)+t[1]-389564586|0,n=(n<<12|n>>>20)+i|0,r+=(n&i|~n&s)+t[2]+606105819|0,r=(r<<17|r>>>15)+n|0,s+=(r&n|~r&i)+t[3]-1044525330|0,s=(s<<22|s>>>10)+r|0,i+=(s&r|~s&n)+t[4]-176418897|0,i=(i<<7|i>>>25)+s|0,n+=(i&s|~i&r)+t[5]+1200080426|0,n=(n<<12|n>>>20)+i|0,r+=(n&i|~n&s)+t[6]-1473231341|0,r=(r<<17|r>>>15)+n|0,s+=(r&n|~r&i)+t[7]-45705983|0,s=(s<<22|s>>>10)+r|0,i+=(s&r|~s&n)+t[8]+1770035416|0,i=(i<<7|i>>>25)+s|0,n+=(i&s|~i&r)+t[9]-1958414417|0,n=(n<<12|n>>>20)+i|0,r+=(n&i|~n&s)+t[10]-42063|0,r=(r<<17|r>>>15)+n|0,s+=(r&n|~r&i)+t[11]-1990404162|0,s=(s<<22|s>>>10)+r|0,i+=(s&r|~s&n)+t[12]+1804603682|0,i=(i<<7|i>>>25)+s|0,n+=(i&s|~i&r)+t[13]-40341101|0,n=(n<<12|n>>>20)+i|0,r+=(n&i|~n&s)+t[14]-1502002290|0,r=(r<<17|r>>>15)+n|0,s+=(r&n|~r&i)+t[15]+1236535329|0,s=(s<<22|s>>>10)+r|0,i+=(s&n|r&~n)+t[1]-165796510|0,i=(i<<5|i>>>27)+s|0,n+=(i&r|s&~r)+t[6]-1069501632|0,n=(n<<9|n>>>23)+i|0,r+=(n&s|i&~s)+t[11]+643717713|0,r=(r<<14|r>>>18)+n|0,s+=(r&i|n&~i)+t[0]-373897302|0,s=(s<<20|s>>>12)+r|0,i+=(s&n|r&~n)+t[5]-701558691|0,i=(i<<5|i>>>27)+s|0,n+=(i&r|s&~r)+t[10]+38016083|0,n=(n<<9|n>>>23)+i|0,r+=(n&s|i&~s)+t[15]-660478335|0,r=(r<<14|r>>>18)+n|0,s+=(r&i|n&~i)+t[4]-405537848|0,s=(s<<20|s>>>12)+r|0,i+=(s&n|r&~n)+t[9]+568446438|0,i=(i<<5|i>>>27)+s|0,n+=(i&r|s&~r)+t[14]-1019803690|0,n=(n<<9|n>>>23)+i|0,r+=(n&s|i&~s)+t[3]-187363961|0,r=(r<<14|r>>>18)+n|0,s+=(r&i|n&~i)+t[8]+1163531501|0,s=(s<<20|s>>>12)+r|0,i+=(s&n|r&~n)+t[13]-1444681467|0,i=(i<<5|i>>>27)+s|0,n+=(i&r|s&~r)+t[2]-51403784|0,n=(n<<9|n>>>23)+i|0,r+=(n&s|i&~s)+t[7]+1735328473|0,r=(r<<14|r>>>18)+n|0,s+=(r&i|n&~i)+t[12]-1926607734|0,s=(s<<20|s>>>12)+r|0,i+=(s^r^n)+t[5]-378558|0,i=(i<<4|i>>>28)+s|0,n+=(i^s^r)+t[8]-2022574463|0,n=(n<<11|n>>>21)+i|0,r+=(n^i^s)+t[11]+1839030562|0,r=(r<<16|r>>>16)+n|0,s+=(r^n^i)+t[14]-35309556|0,s=(s<<23|s>>>9)+r|0,i+=(s^r^n)+t[1]-1530992060|0,i=(i<<4|i>>>28)+s|0,n+=(i^s^r)+t[4]+1272893353|0,n=(n<<11|n>>>21)+i|0,r+=(n^i^s)+t[7]-155497632|0,r=(r<<16|r>>>16)+n|0,s+=(r^n^i)+t[10]-1094730640|0,s=(s<<23|s>>>9)+r|0,i+=(s^r^n)+t[13]+681279174|0,i=(i<<4|i>>>28)+s|0,n+=(i^s^r)+t[0]-358537222|0,n=(n<<11|n>>>21)+i|0,r+=(n^i^s)+t[3]-722521979|0,r=(r<<16|r>>>16)+n|0,s+=(r^n^i)+t[6]+76029189|0,s=(s<<23|s>>>9)+r|0,i+=(s^r^n)+t[9]-640364487|0,i=(i<<4|i>>>28)+s|0,n+=(i^s^r)+t[12]-421815835|0,n=(n<<11|n>>>21)+i|0,r+=(n^i^s)+t[15]+530742520|0,r=(r<<16|r>>>16)+n|0,s+=(r^n^i)+t[2]-995338651|0,s=(s<<23|s>>>9)+r|0,i+=(r^(s|~n))+t[0]-198630844|0,i=(i<<6|i>>>26)+s|0,n+=(s^(i|~r))+t[7]+1126891415|0,n=(n<<10|n>>>22)+i|0,r+=(i^(n|~s))+t[14]-1416354905|0,r=(r<<15|r>>>17)+n|0,s+=(n^(r|~i))+t[5]-57434055|0,s=(s<<21|s>>>11)+r|0,i+=(r^(s|~n))+t[12]+1700485571|0,i=(i<<6|i>>>26)+s|0,n+=(s^(i|~r))+t[3]-1894986606|0,n=(n<<10|n>>>22)+i|0,r+=(i^(n|~s))+t[10]-1051523|0,r=(r<<15|r>>>17)+n|0,s+=(n^(r|~i))+t[1]-2054922799|0,s=(s<<21|s>>>11)+r|0,i+=(r^(s|~n))+t[8]+1873313359|0,i=(i<<6|i>>>26)+s|0,n+=(s^(i|~r))+t[15]-30611744|0,n=(n<<10|n>>>22)+i|0,r+=(i^(n|~s))+t[6]-1560198380|0,r=(r<<15|r>>>17)+n|0,s+=(n^(r|~i))+t[13]+1309151649|0,s=(s<<21|s>>>11)+r|0,i+=(r^(s|~n))+t[4]-145523070|0,i=(i<<6|i>>>26)+s|0,n+=(s^(i|~r))+t[11]-1120210379|0,n=(n<<10|n>>>22)+i|0,r+=(i^(n|~s))+t[2]+718787259|0,r=(r<<15|r>>>17)+n|0,s+=(n^(r|~i))+t[9]-343485551|0,s=(s<<21|s>>>11)+r|0,e[0]=i+e[0]|0,e[1]=s+e[1]|0,e[2]=r+e[2]|0,e[3]=n+e[3]|0}start(){return this._dataLength=0,this._bufferLength=0,this._state.set(H.stateIdentity),this}appendStr(e){const t=this._buffer8,i=this._buffer32;let s=this._bufferLength,r,n;for(n=0;n<e.length;n+=1){if(r=e.charCodeAt(n),r<128)t[s++]=r;else if(r<2048)t[s++]=(r>>>6)+192,t[s++]=r&63|128;else if(r<55296||r>56319)t[s++]=(r>>>12)+224,t[s++]=r>>>6&63|128,t[s++]=r&63|128;else{if(r=(r-55296)*1024+(e.charCodeAt(++n)-56320)+65536,r>1114111)throw new Error("Unicode standard supports code points up to U+10FFFF");t[s++]=(r>>>18)+240,t[s++]=r>>>12&63|128,t[s++]=r>>>6&63|128,t[s++]=r&63|128}s>=64&&(this._dataLength+=64,H._md5cycle(this._state,i),s-=64,i[0]=i[16])}return this._bufferLength=s,this}appendAsciiStr(e){const t=this._buffer8,i=this._buffer32;let s=this._bufferLength,r,n=0;for(;;){for(r=Math.min(e.length-n,64-s);r--;)t[s++]=e.charCodeAt(n++);if(s<64)break;this._dataLength+=64,H._md5cycle(this._state,i),s=0}return this._bufferLength=s,this}appendByteArray(e){const t=this._buffer8,i=this._buffer32;let s=this._bufferLength,r,n=0;for(;;){for(r=Math.min(e.length-n,64-s);r--;)t[s++]=e[n++];if(s<64)break;this._dataLength+=64,H._md5cycle(this._state,i),s=0}return this._bufferLength=s,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,i=e.state,s=this._state;let r;for(this._dataLength=e.length,this._bufferLength=e.buflen,s[0]=i[0],s[1]=i[1],s[2]=i[2],s[3]=i[3],r=0;r<t.length;r+=1)this._buffer8[r]=t.charCodeAt(r)}end(e=!1){const t=this._bufferLength,i=this._buffer8,s=this._buffer32,r=(t>>2)+1;let n;if(this._dataLength+=t,i[t]=128,i[t+1]=i[t+2]=i[t+3]=0,s.set(H.buffer32Identity.subarray(r),r),t>55&&(H._md5cycle(this._state,s),s.set(H.buffer32Identity)),n=this._dataLength*8,n<=4294967295)s[14]=n;else{const o=n.toString(16).match(/(.*?)(.{0,8})$/);if(o===null)return;const d=parseInt(o[2],16),u=parseInt(o[1],16)||0;s[14]=d,s[15]=u}return H._md5cycle(this._state,s),e?this._state:H._hex(this._state)}}H.stateIdentity=new Int32Array([1732584193,-271733879,-1732584194,271733878]),H.buffer32Identity=new Int32Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]),H.hexChars="0123456789abcdef",H.hexOut=[],H.onePassHasher=new H,H.hashStr("hello")!=="5d41402abc4b2a76b9719d911017c592"&&console.error("Md5 self test failed.");function oe(a){return H.hashStr(a)}class Gt{constructor(e,t,i,s){this.logger=e.getLogger("sipjs.digestauthentication"),this.username=i,this.password=s,this.ha1=t,this.nc=0,this.ncHex="00000000"}authenticate(e,t,i){if(this.algorithm=t.algorithm,this.realm=t.realm,this.nonce=t.nonce,this.opaque=t.opaque,this.stale=t.stale,this.algorithm){if(this.algorithm!=="MD5")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)this.qop="auth-int";else return this.logger.warn("challenge without Digest qop different than 'auth' or 'auth-int', authentication aborted"),!1;else this.qop=void 0;return this.method=e.method,this.uri=e.ruri,this.cnonce=ue(12),this.nc+=1,this.updateNcHex(),this.nc===4294967296&&(this.nc=1,this.ncHex="00000001"),this.calculateResponse(i),!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,i;t=this.ha1,(t===""||t===void 0)&&(t=oe(this.username+":"+this.realm+":"+this.password)),this.qop==="auth"?(i=oe(this.method+":"+this.uri),this.response=oe(t+":"+this.nonce+":"+this.ncHex+":"+this.cnonce+":auth:"+i)):this.qop==="auth-int"?(i=oe(this.method+":"+this.uri+":"+oe(e||"")),this.response=oe(t+":"+this.nonce+":"+this.ncHex+":"+this.cnonce+":auth-int:"+i)):this.qop===void 0&&(i=oe(this.method+":"+this.uri),this.response=oe(t+":"+this.nonce+":"+i))}}var q;(function(a){a[a.error=0]="error",a[a.warn=1]="warn",a[a.log=2]="log",a[a.debug=3]="debug"})(q=q||(q={}));class dt{constructor(e,t,i){this.logger=e,this.category=t,this.label=i}error(e){this.genericLog(q.error,e)}warn(e){this.genericLog(q.warn,e)}log(e){this.genericLog(q.log,e)}debug(e){this.genericLog(q.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 Wt{constructor(){this.builtinEnabled=!0,this._level=q.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:q.hasOwnProperty(e)?this._level=e:this.logger.error("invalid 'level' parameter value: "+JSON.stringify(e))}get connector(){return this._connector}set connector(e){e?typeof e=="function"?this._connector=e:this.logger.error("invalid 'connector' parameter value: "+JSON.stringify(e)):this._connector=void 0}getLogger(e,t){if(t&&this.level===3)return new dt(this,e,t);if(this.loggers[e])return this.loggers[e];{const i=new dt(this,e);return this.loggers[e]=i,i}}genericLog(e,t,i,s){this.level>=e&&this.builtinEnabled&&this.print(e,t,i,s),this.connector&&this.connector(q[e],t,i,s)}print(e,t,i,s){if(typeof s=="string"){const r=[new Date,t];i&&r.push(i),s=r.concat(s).join(" | ")}switch(e){case q.error:console.error(s);break;case q.warn:console.warn(s);break;case q.log:console.log(s);break;case q.debug:console.debug(s);break}}}var ke;(function(a){function e(s,r){let n=r,o=0,d=0;if(s.substring(n,n+2).match(/(^\r\n)/))return-2;for(;o===0;){if(d=s.indexOf(`\r
|
|
22
|
+
`,e}}function nt(a){return a==="application/sdp"?"session":"render"}function De(a){const e=typeof a=="string"?a:a.body,t=typeof a=="string"?"application/sdp":a.contentType;return{contentDisposition:nt(t),contentType:t,content:e}}function at(a){return a&&typeof a.content=="string"&&typeof a.contentType=="string"&&a.contentDisposition===void 0?!0:typeof a.contentDisposition=="string"}function Ee(a){let e,t,i;if(a instanceof me&&a.body){const s=a.parseHeader("Content-Disposition");e=s?s.type:void 0,t=a.parseHeader("Content-Type"),i=a.body}if(a instanceof re&&a.body){const s=a.parseHeader("Content-Disposition");e=s?s.type:void 0,t=a.parseHeader("Content-Type"),i=a.body}if(a instanceof ge&&a.body)if(e=a.getHeader("Content-Disposition"),t=a.getHeader("Content-Type"),typeof a.body=="string"){if(!t)throw new Error("Header content type header does not equal body content type.");i=a.body}else{if(t&&t!==a.body.contentType)throw new Error("Header content type header does not equal body content type.");t=a.body.contentType,i=a.body.body}if(at(a)&&(e=a.contentDisposition,t=a.contentType,i=a.content),!!i){if(t&&!e&&(e=nt(t)),!e)throw new Error("Content disposition undefined.");if(!t)throw new Error("Content type undefined.");return{contentDisposition:e,contentType:t,content:i}}}var V;(function(a){a.Initial="Initial",a.Early="Early",a.AckWait="AckWait",a.Confirmed="Confirmed",a.Terminated="Terminated"})(V=V||(V={}));var y;(function(a){a.Initial="Initial",a.HaveLocalOffer="HaveLocalOffer",a.HaveRemoteOffer="HaveRemoteOffer",a.Stable="Stable",a.Closed="Closed"})(y=y||(y={}));const ie=500,Lt=4e3,ot=5e3,M={T1:ie,T2:Lt,TIMER_B:64*ie,TIMER_D:0*ie,TIMER_F:64*ie,TIMER_H:64*ie,TIMER_I:0*ot,TIMER_J:0*ie,TIMER_K:0*ot,TIMER_L:64*ie,TIMER_M:64*ie,TIMER_N:64*ie,PROVISIONAL_RESPONSE_INTERVAL:6e4};class ne extends he{constructor(e){super(e||"Transaction state error.")}}var v;(function(a){a.ACK="ACK",a.BYE="BYE",a.CANCEL="CANCEL",a.INFO="INFO",a.INVITE="INVITE",a.MESSAGE="MESSAGE",a.NOTIFY="NOTIFY",a.OPTIONS="OPTIONS",a.REGISTER="REGISTER",a.UPDATE="UPDATE",a.SUBSCRIBE="SUBSCRIBE",a.PUBLISH="PUBLISH",a.REFER="REFER",a.PRACK="PRACK"})(v=v||(v={}));const ae=[v.ACK,v.BYE,v.CANCEL,v.INFO,v.INVITE,v.MESSAGE,v.NOTIFY,v.OPTIONS,v.PRACK,v.REFER,v.REGISTER,v.SUBSCRIBE];class ct{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 Be{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 Bt{constructor(e,t){this.incomingReferRequest=e,this.session=t}get referTo(){const e=this.incomingReferRequest.message.parseHeader("refer-to");if(!(e instanceof N))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(),e=e||{};const i=(e.extraHeaders||[]).slice(),s=this.replaces;s&&i.push("Replaces: "+decodeURIComponent(s));const r=this.referredBy;return r&&i.push("Referred-By: "+r),e.extraHeaders=i,this.inviter=this.session.userAgent._makeInviter(t,e),this.inviter._referred=this.session,this.session._referral=this.inviter,this.inviter}}var w;(function(a){a.Initial="Initial",a.Establishing="Establishing",a.Established="Established",a.Terminating="Terminating",a.Terminated="Terminated"})(w=w||(w={}));class we{constructor(e,t={}){this.pendingReinvite=!1,this.pendingReinviteAck=!1,this._state=w.Initial,this.delegate=t.delegate,this._stateEventEmitter=new Te,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 w.Initial:break;case w.Establishing:break;case w.Established:return new Promise(e=>{this._bye({onAccept:()=>e(),onRedirect:()=>e(),onReject:()=>e()})});case w.Terminating:break;case w.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 w.Initial:typeof this.cancel=="function"?(t+=" However Inviter.invite() has not yet been called.",t+=" Perhaps you should have called Inviter.cancel()?"):typeof this.reject=="function"&&(t+=" However Invitation.accept() has not yet been called.",t+=" Perhaps you should have called Invitation.reject()?");break;case w.Establishing:typeof this.cancel=="function"?(t+=" However a dialog does not yet exist.",t+=" Perhaps you should have called Inviter.cancel()?"):typeof this.reject=="function"&&(t+=" However Invitation.accept() has not yet been called (or not yet resolved).",t+=" Perhaps you should have called Invitation.reject()?");break;case w.Established:{const i=e.requestDelegate,s=this.copyRequestOptions(e.requestOptions);return this._bye(i,s)}case w.Terminating:t+=" However this session is already terminating.",typeof this.cancel=="function"?t+=" Perhaps you have already called Inviter.cancel()?":typeof this.reject=="function"&&(t+=" Perhaps you have already called Session.bye()?");break;case w.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!==w.Established)return this.logger.error("Session.info() may only be called if established session."),Promise.reject(new Error(`Invalid session state ${this.state}`));const t=e.requestDelegate,i=this.copyRequestOptions(e.requestOptions);return this._info(t,i)}invite(e={}){if(this.logger.log("Session.invite"),this.state!==w.Established)return Promise.reject(new Error(`Invalid session state ${this.state}`));if(this.pendingReinvite)return Promise.reject(new ve("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:r=>{const n=Ee(r.message);if(!n){this.logger.error("Received 2xx response to re-INVITE without a session description"),this.ackAndBye(r,400,"Missing session description"),this.stateTransition(w.Terminated),this.pendingReinvite=!1;return}if(e.withoutSdp){const o={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};this.setOfferAndGetAnswer(n,o).then(d=>{r.ack({body:d})}).catch(d=>{this.logger.error("Failed to handle offer in 2xx response to re-INVITE"),this.logger.error(d.message),this.state===w.Terminated?r.ack():(this.ackAndBye(r,488,"Bad Media Description"),this.stateTransition(w.Terminated))}).then(()=>{this.pendingReinvite=!1,e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(r)})}else{const o={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};this.setAnswer(n,o).then(()=>{r.ack()}).catch(d=>{this.logger.error("Failed to handle answer in 2xx response to re-INVITE"),this.logger.error(d.message),this.state!==w.Terminated?(this.ackAndBye(r,488,"Bad Media Description"),this.stateTransition(w.Terminated)):r.ack()}).then(()=>{this.pendingReinvite=!1,e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(r)})}},onProgress:r=>{},onRedirect:r=>{},onReject:r=>{this.logger.warn("Received a non-2xx response to re-INVITE"),this.pendingReinvite=!1,e.withoutSdp?e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(r):this.rollbackOffer().catch(n=>{if(this.logger.error("Failed to rollback offer on non-2xx response to re-INVITE"),this.logger.error(n.message),this.state!==w.Terminated){if(!this.dialog)throw new Error("Dialog undefined.");const o=[];o.push("Reason: "+this.getReasonHeaderValue(500,"Internal Server Error")),this.dialog.bye(void 0,{extraHeaders:o}),this.stateTransition(w.Terminated)}}).then(()=>{e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(r)})},onTrying:r=>{}},i=e.requestOptions||{};if(i.extraHeaders=(i.extraHeaders||[]).slice(),i.extraHeaders.push("Allow: "+ae.toString()),i.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,i))}const s={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};return this.getOffer(s).then(r=>{if(!this.dialog)throw this.pendingReinvite=!1,new Error("Dialog undefined.");return i.body=r,this.dialog.invite(t,i)}).catch(r=>{throw this.logger.error(r.message),this.logger.error("Failed to send re-INVITE"),this.pendingReinvite=!1,r})}message(e={}){if(this.state!==w.Established)return this.logger.error("Session.message() may only be called if established session."),Promise.reject(new Error(`Invalid session state ${this.state}`));const t=e.requestDelegate,i=this.copyRequestOptions(e.requestOptions);return this._message(t,i)}refer(e,t={}){if(this.state!==w.Established)return this.logger.error("Session.refer() may only be called if established session."),Promise.reject(new Error(`Invalid session state ${this.state}`));if(e instanceof we&&!e.dialog)return this.logger.error("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)."),Promise.reject(new Error(`Invalid session state ${this.state}`));const i=t.requestDelegate,s=this.copyRequestOptions(t.requestOptions);return s.extraHeaders=s.extraHeaders?s.extraHeaders.concat(this.referExtraHeaders(this.referToString(e))):this.referExtraHeaders(this.referToString(e)),this._refer(t.onNotify,i,s)}_bye(e,t){if(!this.dialog)return Promise.reject(new Error("Session dialog undefined."));const i=this.dialog;switch(i.sessionState){case V.Initial:throw new Error(`Invalid dialog state ${i.sessionState}`);case V.Early:throw new Error(`Invalid dialog state ${i.sessionState}`);case V.AckWait:return this.stateTransition(w.Terminating),new Promise(s=>{i.delegate={onAck:()=>{const r=i.bye(e,t);return this.stateTransition(w.Terminated),s(r),Promise.resolve()},onAckTimeout:()=>{const r=i.bye(e,t);this.stateTransition(w.Terminated),s(r)}}});case V.Confirmed:{const s=i.bye(e,t);return this.stateTransition(w.Terminated),Promise.resolve(s)}case V.Terminated:throw new Error(`Invalid dialog state ${i.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,i){return this.dialog?(this.onNotify=e,Promise.resolve(this.dialog.refer(t,i))):Promise.reject(new Error("Session dialog undefined."))}ackAndBye(e,t,i){e.ack();const s=[];t&&s.push("Reason: "+this.getReasonHeaderValue(t,i)),e.session.bye(void 0,{extraHeaders:s})}onAckRequest(e){if(this.logger.log("Session.onAckRequest"),this.state!==w.Established&&this.state!==w.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 i={sessionDescriptionHandlerOptions:this.pendingReinviteAck?this.sessionDescriptionHandlerOptionsReInvite:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.pendingReinviteAck?this._sessionDescriptionHandlerModifiersReInvite:this._sessionDescriptionHandlerModifiers};if(this.delegate&&this.delegate.onAck){const s=new Ht(e);this.delegate.onAck(s)}switch(this.pendingReinviteAck=!1,t.signalingState){case y.Initial:{this.logger.error(`Invalid signaling state ${t.signalingState}.`);const s=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];return t.bye(void 0,{extraHeaders:s}),this.stateTransition(w.Terminated),Promise.resolve()}case y.Stable:{const s=Ee(e.message);return s?s.contentDisposition==="render"?(this._renderbody=s.content,this._rendertype=s.contentType,Promise.resolve()):s.contentDisposition!=="session"?Promise.resolve():this.setAnswer(s,i).catch(r=>{this.logger.error(r.message);const n=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];t.bye(void 0,{extraHeaders:n}),this.stateTransition(w.Terminated)}):Promise.resolve()}case y.HaveLocalOffer:{this.logger.error(`Invalid signaling state ${t.signalingState}.`);const s=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];return t.bye(void 0,{extraHeaders:s}),this.stateTransition(w.Terminated),Promise.resolve()}case y.HaveRemoteOffer:{this.logger.error(`Invalid signaling state ${t.signalingState}.`);const s=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];return t.bye(void 0,{extraHeaders:s}),this.stateTransition(w.Terminated),Promise.resolve()}case y.Closed:throw new Error(`Invalid signaling state ${t.signalingState}.`);default:throw new Error(`Invalid signaling state ${t.signalingState}.`)}}onByeRequest(e){if(this.logger.log("Session.onByeRequest"),this.state!==w.Established){this.logger.error(`BYE received while in state ${this.state}, dropping request`);return}if(this.delegate&&this.delegate.onBye){const t=new Mt(e);this.delegate.onBye(t)}else e.accept();this.stateTransition(w.Terminated)}onInfoRequest(e){if(this.logger.log("Session.onInfoRequest"),this.state!==w.Established){this.logger.error(`INFO received while in state ${this.state}, dropping request`);return}if(this.delegate&&this.delegate.onInfo){const t=new Ot(e);this.delegate.onInfo(t)}else e.accept()}onInviteRequest(e){if(this.logger.log("Session.onInviteRequest"),this.state!==w.Established){this.logger.error(`INVITE received while in state ${this.state}, dropping request`);return}this.pendingReinviteAck=!0;const t=["Contact: "+this._contact];if(e.message.hasHeader("P-Asserted-Identity")){const s=e.message.getHeader("P-Asserted-Identity");if(!s)throw new Error("Header undefined.");this._assertedIdentity=P.nameAddrHeaderParse(s)}const i={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};this.generateResponseOfferAnswerInDialog(i).then(s=>{const r=e.accept({statusCode:200,extraHeaders:t,body:s});this.delegate&&this.delegate.onInvite&&this.delegate.onInvite(e.message,r.message,200)}).catch(s=>{if(this.logger.error(s.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===y.Stable){const r=e.reject({statusCode:488});this.delegate&&this.delegate.onInvite&&this.delegate.onInvite(e.message,r.message,488);return}this.rollbackOffer().then(()=>{const r=e.reject({statusCode:488});this.delegate&&this.delegate.onInvite&&this.delegate.onInvite(e.message,r.message,488)}).catch(r=>{this.logger.error(r.message),this.logger.error("Failed to rollback offer on re-INVITE request");const n=e.reject({statusCode:488});if(this.state!==w.Terminated){if(!this.dialog)throw new Error("Dialog undefined.");const o=[];o.push("Reason: "+this.getReasonHeaderValue(500,"Internal Server Error")),this.dialog.bye(void 0,{extraHeaders:o}),this.stateTransition(w.Terminated)}this.delegate&&this.delegate.onInvite&&this.delegate.onInvite(e.message,n.message,488)})})}onMessageRequest(e){if(this.logger.log("Session.onMessageRequest"),this.state!==w.Established){this.logger.error(`MESSAGE received while in state ${this.state}, dropping request`);return}if(this.delegate&&this.delegate.onMessage){const t=new ct(e);this.delegate.onMessage(t)}else e.accept()}onNotifyRequest(e){if(this.logger.log("Session.onNotifyRequest"),this.state!==w.Established){this.logger.error(`NOTIFY received while in state ${this.state}, dropping request`);return}if(this.onNotify){const t=new Be(e);this.onNotify(t);return}if(this.delegate&&this.delegate.onNotify){const t=new Be(e);this.delegate.onNotify(t)}else e.accept()}onPrackRequest(e){if(this.logger.log("Session.onPrackRequest"),this.state!==w.Established){this.logger.error(`PRACK received while in state ${this.state}, dropping request`);return}throw new Error("Unimplemented.")}onReferRequest(e){if(this.logger.log("Session.onReferRequest"),this.state!==w.Established){this.logger.error(`REFER received while in state ${this.state}, dropping request`);return}if(!e.message.hasHeader("refer-to")){this.logger.warn("Invalid REFER packet. A refer-to header is required. Rejecting."),e.reject();return}const t=new Bt(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(i=>{this.logger.error(i.message)}))}generateResponseOfferAnswer(e,t){if(this.dialog)return this.generateResponseOfferAnswerInDialog(t);const i=Ee(e.message);return!i||i.contentDisposition!=="session"?this.getOffer(t):this.setOfferAndGetAnswer(i,t)}generateResponseOfferAnswerInDialog(e){if(!this.dialog)throw new Error("Dialog undefined.");switch(this.dialog.signalingState){case y.Initial:return this.getOffer(e);case y.HaveLocalOffer:return Promise.resolve(void 0);case y.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 y.Stable:return this.state!==w.Established?Promise.resolve(void 0):this.getOffer(e);case y.Closed:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`);default:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`)}}getOffer(e){const t=this.setupSessionDescriptionHandler(),i=e.sessionDescriptionHandlerOptions,s=e.sessionDescriptionHandlerModifiers;try{return t.getDescription(i,s).then(r=>De(r)).catch(r=>{this.logger.error("Session.getOffer: SDH getDescription rejected...");const n=r instanceof Error?r:new Error("Session.getOffer unknown error.");throw this.logger.error(n.message),n})}catch(r){this.logger.error("Session.getOffer: SDH getDescription threw...");const n=r instanceof Error?r:new Error(r);return this.logger.error(n.message),Promise.reject(n)}}rollbackOffer(){const e=this.setupSessionDescriptionHandler();if(e.rollbackDescription===void 0)return Promise.resolve();try{return e.rollbackDescription().catch(t=>{this.logger.error("Session.rollbackOffer: SDH rollbackDescription rejected...");const i=t instanceof Error?t:new Error("Session.rollbackOffer unknown error.");throw this.logger.error(i.message),i})}catch(t){this.logger.error("Session.rollbackOffer: SDH rollbackDescription threw...");const i=t instanceof Error?t:new Error(t);return this.logger.error(i.message),Promise.reject(i)}}setAnswer(e,t){const i=this.setupSessionDescriptionHandler(),s=t.sessionDescriptionHandlerOptions,r=t.sessionDescriptionHandlerModifiers;try{if(!i.hasDescription(e.contentType))return Promise.reject(new Ne)}catch(n){this.logger.error("Session.setAnswer: SDH hasDescription threw...");const o=n instanceof Error?n:new Error(n);return this.logger.error(o.message),Promise.reject(o)}try{return i.setDescription(e.content,s,r).catch(n=>{this.logger.error("Session.setAnswer: SDH setDescription rejected...");const o=n instanceof Error?n:new Error("Session.setAnswer unknown error.");throw this.logger.error(o.message),o})}catch(n){this.logger.error("Session.setAnswer: SDH setDescription threw...");const o=n instanceof Error?n:new Error(n);return this.logger.error(o.message),Promise.reject(o)}}setOfferAndGetAnswer(e,t){const i=this.setupSessionDescriptionHandler(),s=t.sessionDescriptionHandlerOptions,r=t.sessionDescriptionHandlerModifiers;try{if(!i.hasDescription(e.contentType))return Promise.reject(new Ne)}catch(n){this.logger.error("Session.setOfferAndGetAnswer: SDH hasDescription threw...");const o=n instanceof Error?n:new Error(n);return this.logger.error(o.message),Promise.reject(o)}try{return i.setDescription(e.content,s,r).then(()=>i.getDescription(s,r)).then(n=>De(n)).catch(n=>{this.logger.error("Session.setOfferAndGetAnswer: SDH setDescription or getDescription rejected...");const o=n instanceof Error?n:new Error("Session.setOfferAndGetAnswer unknown error.");throw this.logger.error(o.message),o})}catch(n){this.logger.error("Session.setOfferAndGetAnswer: SDH setDescription or getDescription threw...");const o=n instanceof Error?n:new Error(n);return this.logger.error(o.message),Promise.reject(o)}}setSessionDescriptionHandler(e){if(this._sessionDescriptionHandler)throw new Error("Session description handler defined.");this._sessionDescriptionHandler=e}setupSessionDescriptionHandler(){var e;return this._sessionDescriptionHandler?this._sessionDescriptionHandler:(this._sessionDescriptionHandler=this.sessionDescriptionHandlerFactory(this,this.userAgent.configuration.sessionDescriptionHandlerFactoryOptions),!((e=this.delegate)===null||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 w.Initial:e!==w.Establishing&&e!==w.Established&&e!==w.Terminating&&e!==w.Terminated&&t();break;case w.Establishing:e!==w.Established&&e!==w.Terminating&&e!==w.Terminated&&t();break;case w.Established:e!==w.Terminating&&e!==w.Terminated&&t();break;case w.Terminating:e!==w.Terminated&&t();break;case w.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===w.Terminated&&this.dispose()}copyRequestOptions(e={}){const t=e.extraHeaders?e.extraHeaders.slice():void 0,i=e.body?{contentDisposition:e.body.contentDisposition||"render",contentType:e.body.contentType||"text/plain",content:e.body.content||""}:void 0;return{extraHeaders:t,body:i}}getReasonHeaderValue(e,t){const i=e;let s=Ae(e);return!s&&t&&(s=t),"SIP;cause="+i+';text="'+s+'"'}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 z)t=e.toString();else{if(!e.dialog)throw new Error("Dialog undefined.");const i=e.remoteIdentity.friendlyName,s=e.dialog.remoteTarget.toString(),r=e.dialog.callId,n=e.dialog.remoteTag,o=e.dialog.localTag,d=encodeURIComponent(`${r};to-tag=${n};from-tag=${o}`);t=`"${i}" <${s}?Replaces=${d}>`}return t}}var W;(function(a){a.Required="Required",a.Supported="Supported",a.Unsupported="Unsupported"})(W=W||(W={}));const jt={"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 fe extends we{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(Math.random()*1e4),this.userNoAnswerTimer=void 0,this.waitingForPrack=!1,this.logger=e.getLogger("sip.Invitation");const i=this.incomingInviteRequest.message,s=i.getHeader("require");s&&s.toLowerCase().includes("100rel")&&(this.rel100="required");const r=i.getHeader("supported");if(r&&r.toLowerCase().includes("100rel")&&(this.rel100="supported"),i.toTag=t.toTag,typeof i.toTag!="string")throw new TypeError("toTag should have been a string.");if(this.userNoAnswerTimer=setTimeout(()=>{t.reject({statusCode:480}),this.stateTransition(w.Terminated)},this.userAgent.configuration.noAnswerTimeout?this.userAgent.configuration.noAnswerTimeout*1e3:6e4),i.hasHeader("expires")){const d=Number(i.getHeader("expires")||0)*1e3;this.expiresTimer=setTimeout(()=>{this.state===w.Initial&&(t.reject({statusCode:487}),this.stateTransition(w.Terminated))},d)}const n=this.request.getHeader("P-Asserted-Identity");n&&(this._assertedIdentity=P.nameAddrHeaderParse(n)),this._contact=this.userAgent.contact.toString();const o=i.parseHeader("Content-Disposition");o&&o.type==="render"&&(this._renderbody=i.body,this._rendertype=i.getHeader("Content-Type")),this._id=i.callId+i.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 w.Initial:return this.reject().then(()=>super.dispose());case w.Establishing:return this.reject().then(()=>super.dispose());case w.Established:return super.dispose();case w.Terminating:return super.dispose();case w.Terminated:return super.dispose();default:throw new Error("Unknown state.")}}get autoSendAnInitialProvisionalResponse(){return this.rel100!=="required"&&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!==w.Initial){const t=new Error(`Invalid session state ${this.state}`);return this.logger.error(t.message),Promise.reject(t)}return e.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiers=e.sessionDescriptionHandlerModifiers),e.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptions=e.sessionDescriptionHandlerOptions),this.stateTransition(w.Establishing),this.sendAccept(e).then(({message:t,session:i})=>{i.delegate={onAck:s=>this.onAckRequest(s),onAckTimeout:()=>this.onAckTimeout(),onBye:s=>this.onByeRequest(s),onInfo:s=>this.onInfoRequest(s),onInvite:s=>this.onInviteRequest(s),onMessage:s=>this.onMessageRequest(s),onNotify:s=>this.onNotifyRequest(s),onPrack:s=>this.onPrackRequest(s),onRefer:s=>this.onReferRequest(s)},this._dialog=i,this.stateTransition(w.Established),this._replacee&&this._replacee._bye()}).catch(t=>this.handleResponseError(t))}progress(e={}){if(this.logger.log("Invitation.progress"),this.state!==w.Initial){const i=new Error(`Invalid session state ${this.state}`);return this.logger.error(i.message),Promise.reject(i)}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()):e.statusCode===100?this.sendProgressTrying().then(()=>{}).catch(i=>this.handleResponseError(i)):this.rel100!=="required"&&!(this.rel100==="supported"&&e.rel100)&&!(this.rel100==="supported"&&this.userAgent.configuration.sipExtension100rel===W.Required)?this.sendProgress(e).then(()=>{}).catch(i=>this.handleResponseError(i)):this.sendProgressReliableWaitForPrack(e).then(()=>{}).catch(i=>this.handleResponseError(i))}reject(e={}){if(this.logger.log("Invitation.reject"),this.state!==w.Initial&&this.state!==w.Establishing){const n=new Error(`Invalid session state ${this.state}`);return this.logger.error(n.message),Promise.reject(n)}const t=e.statusCode||480,i=e.reasonPhrase?e.reasonPhrase:Ae(t),s=e.extraHeaders||[];if(t<300||t>699)throw new TypeError("Invalid statusCode: "+t);const r=e.body?De(e.body):void 0;return t<400?this.incomingInviteRequest.redirect([],{statusCode:t,reasonPhrase:i,extraHeaders:s,body:r}):this.incomingInviteRequest.reject({statusCode:t,reasonPhrase:i,extraHeaders:s,body:r}),this.stateTransition(w.Terminated),Promise.resolve()}_onCancel(e){if(this.logger.log("Invitation._onCancel"),this.state!==w.Initial&&this.state!==w.Establishing){this.logger.error(`CANCEL received while in state ${this.state}, dropping request`);return}if(this.delegate&&this.delegate.onCancel){const t=new qt(e);this.delegate.onCancel(t)}this.isCanceled=!0,this.incomingInviteRequest.reject({statusCode:487}),this.stateTransition(w.Terminated)}handlePrackOfferAnswer(e){if(!this.dialog)throw new Error("Dialog undefined.");const t=Ee(e.message);if(!t||t.contentDisposition!=="session")return Promise.resolve(void 0);const i={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers};switch(this.dialog.signalingState){case y.Initial:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`);case y.Stable:return this.setAnswer(t,i).then(()=>{});case y.HaveLocalOffer:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`);case y.HaveRemoteOffer:return this.setOfferAndGetAnswer(t,i);case y.Closed:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`);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 Ne?(this.logger.error("A session description handler occurred while sending response (content type unsupported"),t=415):e instanceof kt?this.logger.error("A session description handler occurred while sending response"):e instanceof Ue?this.logger.error("Session ended before response could be formulated and sent (while waiting for PRACK)"):e instanceof ne&&this.logger.error("Session changed state before response could be formulated and sent"),this.state===w.Initial||this.state===w.Establishing)try{this.incomingInviteRequest.reject({statusCode:t}),this.stateTransition(w.Terminated)}catch(i){throw this.logger.error("An error occurred attempting to reject the request while handling another error"),i}if(this.isCanceled){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.");return}throw e}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(w.Terminated)}sendAccept(e={}){const t={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers},i=e.extraHeaders||[];return this.waitingForPrack?this.waitForArrivalOfPrack().then(()=>clearTimeout(this.userNoAnswerTimer)).then(()=>this.generateResponseOfferAnswer(this.incomingInviteRequest,t)).then(s=>this.incomingInviteRequest.accept({statusCode:200,body:s,extraHeaders:i})):(clearTimeout(this.userNoAnswerTimer),this.generateResponseOfferAnswer(this.incomingInviteRequest,t).then(s=>this.incomingInviteRequest.accept({statusCode:200,body:s,extraHeaders:i})))}sendProgress(e={}){const t=e.statusCode||180,i=e.reasonPhrase,s=(e.extraHeaders||[]).slice(),r=e.body?De(e.body):void 0;if(t===183&&!r)return this.sendProgressWithSDP(e);try{const n=this.incomingInviteRequest.progress({statusCode:t,reasonPhrase:i,extraHeaders:s,body:r});return this._dialog=n.session,Promise.resolve(n)}catch(n){return Promise.reject(n)}}sendProgressWithSDP(e={}){const t={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers},i=e.statusCode||183,s=e.reasonPhrase,r=(e.extraHeaders||[]).slice();return this.generateResponseOfferAnswer(this.incomingInviteRequest,t).then(n=>this.incomingInviteRequest.progress({statusCode:i,reasonPhrase:s,extraHeaders:r,body:n})).then(n=>(this._dialog=n.session,n))}sendProgressReliable(e={}){return e.extraHeaders=(e.extraHeaders||[]).slice(),e.extraHeaders.push("Require: 100rel"),e.extraHeaders.push("RSeq: "+Math.floor(Math.random()*1e4)),this.sendProgressWithSDP(e)}sendProgressReliableWaitForPrack(e={}){const t={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers},i=e.statusCode||183,s=e.reasonPhrase,r=(e.extraHeaders||[]).slice();r.push("Require: 100rel"),r.push("RSeq: "+this.rseq++);let n;return new Promise((o,d)=>{this.waitingForPrack=!0,this.generateResponseOfferAnswer(this.incomingInviteRequest,t).then(u=>(n=u,this.incomingInviteRequest.progress({statusCode:i,reasonPhrase:s,extraHeaders:r,body:n}))).then(u=>{this._dialog=u.session;let h,m;u.session.delegate={onPrack:p=>{h=p,clearTimeout(x),clearTimeout(ee),this.waitingForPrack&&(this.waitingForPrack=!1,this.handlePrackOfferAnswer(h).then($=>{try{m=h.accept({statusCode:200,body:$}),this.prackArrived(),o({prackRequest:h,prackResponse:m,progressResponse:u})}catch(et){d(et)}}).catch($=>d($)))}};const x=setTimeout(()=>{this.waitingForPrack&&(this.waitingForPrack=!1,this.logger.warn("No PRACK received, rejecting INVITE."),clearTimeout(ee),this.reject({statusCode:504}).then(()=>d(new Ue)).catch(p=>d(p)))},M.T1*64),_=()=>{try{this.incomingInviteRequest.progress({statusCode:i,reasonPhrase:s,extraHeaders:r,body:n})}catch(p){this.waitingForPrack=!1,d(p);return}ee=setTimeout(_,C*=2)};let C=M.T1,ee=setTimeout(_,C)}).catch(u=>{this.waitingForPrack=!1,d(u)})})}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 Ue),this.waitingForPrackPromise=void 0,this.waitingForPrackResolve=void 0,this.waitingForPrackReject=void 0}}class Pe extends we{constructor(e,t,i={}){super(e,i),this.disposed=!1,this.earlyMedia=!1,this.earlyMediaSessionDescriptionHandlers=new Map,this.isCanceled=!1,this.inviteWithoutSdp=!1,this.logger=e.getLogger("sip.Inviter"),this.earlyMedia=i.earlyMedia!==void 0?i.earlyMedia:this.earlyMedia,this.fromTag=$e(),this.inviteWithoutSdp=i.inviteWithoutSdp!==void 0?i.inviteWithoutSdp:this.inviteWithoutSdp;const s=Object.assign({},i);s.params=Object.assign({},i.params);const r=i.anonymous||!1,n=e.contact.toString({anonymous:r,outbound:r?!e.contact.tempGruu:!e.contact.pubGruu});r&&e.configuration.uri&&(s.params.fromDisplayName="Anonymous",s.params.fromUri="sip:anonymous@anonymous.invalid");let o=e.userAgentCore.configuration.aor;if(s.params.fromUri&&(o=typeof s.params.fromUri=="string"?P.URIParse(s.params.fromUri):s.params.fromUri),!o)throw new TypeError("Invalid from URI: "+s.params.fromUri);let d=t;if(s.params.toUri&&(d=typeof s.params.toUri=="string"?P.URIParse(s.params.toUri):s.params.toUri),!d)throw new TypeError("Invalid to URI: "+s.params.toUri);const u=Object.assign({},s.params);u.fromTag=this.fromTag;const h=(s.extraHeaders||[]).slice();r&&e.configuration.uri&&(h.push("P-Preferred-Identity: "+e.configuration.uri.toString()),h.push("Privacy: id")),h.push("Contact: "+n),h.push("Allow: "+["ACK","CANCEL","INVITE","MESSAGE","BYE","OPTIONS","INFO","NOTIFY","REFER"].toString()),e.configuration.sipExtension100rel===W.Required&&h.push("Require: 100rel"),e.configuration.sipExtensionReplaces===W.Required&&h.push("Require: replaces"),s.extraHeaders=h;const m=void 0;this.outgoingRequestMessage=e.userAgentCore.makeOutgoingRequestMessage(v.INVITE,t,o,d,u,h,m),this._contact=n,this._referralInviterOptions=s,this._renderbody=i.renderbody,this._rendertype=i.rendertype,i.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiers=i.sessionDescriptionHandlerModifiers),i.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptions=i.sessionDescriptionHandlerOptions),i.sessionDescriptionHandlerModifiersReInvite&&(this.sessionDescriptionHandlerModifiersReInvite=i.sessionDescriptionHandlerModifiersReInvite),i.sessionDescriptionHandlerOptionsReInvite&&(this.sessionDescriptionHandlerOptionsReInvite=i.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 w.Initial:return this.cancel().then(()=>super.dispose());case w.Establishing:return this.cancel().then(()=>super.dispose());case w.Established:return super.dispose();case w.Terminating:return super.dispose();case w.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!==w.Initial&&this.state!==w.Establishing){const i=new Error(`Invalid session state ${this.state}`);return this.logger.error(i.message),Promise.reject(i)}this.isCanceled=!0,this.stateTransition(w.Terminating);function t(i,s){if(i&&i<200||i>699)throw new TypeError("Invalid statusCode: "+i);if(i){const r=i,n=Ae(i)||s;return"SIP;cause="+r+';text="'+n+'"'}}if(this.outgoingInviteRequest){let i;e.statusCode&&e.reasonPhrase&&(i=t(e.statusCode,e.reasonPhrase)),this.outgoingInviteRequest.cancel(i,e)}else this.logger.warn("Canceled session before INVITE was sent"),this.stateTransition(w.Terminated);return Promise.resolve()}invite(e={}){if(this.logger.log("Inviter.invite"),this.state!==w.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(w.Establishing),Promise.resolve(this.sendInvite(e));const t={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.getOffer(t).then(i=>(this.outgoingRequestMessage.body={body:i.content,contentType:i.contentType},this.stateTransition(w.Establishing),this.sendInvite(e))).catch(i=>{throw this.logger.log(i.message),this.state!==w.Terminated&&this.stateTransition(w.Terminated),i})}sendInvite(e={}){return this.outgoingInviteRequest=this.userAgent.userAgentCore.invite(this.outgoingRequestMessage,{onAccept:t=>{if(this.dialog){this.logger.log("Additional confirmed dialog, sending ACK and BYE"),this.ackAndBye(t);return}if(this.isCanceled){this.logger.log("Canceled session accepted, sending ACK and BYE"),this.ackAndBye(t),this.stateTransition(w.Terminated);return}this.notifyReferer(t),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 we))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=e.message.statusCode,i=e.message.reasonPhrase,s=`SIP/2.0 ${t} ${i}`.trim(),r=this._referred.dialog.notify(void 0,{extraHeaders:["Event: refer","Subscription-State: terminated"],body:{contentDisposition:"render",contentType:"message/sipfrag",content:s}});r.delegate={onReject:()=>{this._referred=void 0}}}onAccept(e){if(this.logger.log("Inviter.onAccept"),this.state!==w.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,i=e.session;switch(t.hasHeader("P-Asserted-Identity")&&(this._assertedIdentity=P.nameAddrHeaderParse(t.getHeader("P-Asserted-Identity"))),i.delegate={onAck:s=>this.onAckRequest(s),onBye:s=>this.onByeRequest(s),onInfo:s=>this.onInfoRequest(s),onInvite:s=>this.onInviteRequest(s),onMessage:s=>this.onMessageRequest(s),onNotify:s=>this.onNotifyRequest(s),onPrack:s=>this.onPrackRequest(s),onRefer:s=>this.onReferRequest(s)},this._dialog=i,i.signalingState){case y.Initial:return this.logger.error("Received 2xx response to INVITE without a session description"),this.ackAndBye(e,400,"Missing session description"),this.stateTransition(w.Terminated),Promise.reject(new Error("Bad Media Description"));case y.HaveLocalOffer:return this.logger.error("Received 2xx response to INVITE without a session description"),this.ackAndBye(e,400,"Missing session description"),this.stateTransition(w.Terminated),Promise.reject(new Error("Bad Media Description"));case y.HaveRemoteOffer:{if(!this._dialog.offer)throw new Error(`Session offer undefined in signaling state ${this._dialog.signalingState}.`);const s={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.setOfferAndGetAnswer(this._dialog.offer,s).then(r=>{e.ack({body:r}),this.stateTransition(w.Established)}).catch(r=>{throw this.ackAndBye(e,488,"Invalid session description"),this.stateTransition(w.Terminated),r})}case y.Stable:{if(this.earlyMediaSessionDescriptionHandlers.size>0){const n=this.earlyMediaSessionDescriptionHandlers.get(i.id);if(!n)throw new Error("Session description handler undefined.");return this.setSessionDescriptionHandler(n),this.earlyMediaSessionDescriptionHandlers.delete(i.id),e.ack(),this.stateTransition(w.Established),Promise.resolve()}if(this.earlyMediaDialog){if(this.earlyMediaDialog!==i){this.earlyMedia&&this.logger.error("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.");const n=new Error("Early media dialog does not equal confirmed dialog, terminating session");return this.logger.error(n.message),this.ackAndBye(e,488,"Not Acceptable Here"),this.stateTransition(w.Terminated),Promise.reject(n)}return e.ack(),this.stateTransition(w.Established),Promise.resolve()}const s=i.answer;if(!s)throw new Error("Answer is undefined.");const r={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.setAnswer(s,r).then(()=>{let n;this._renderbody&&this._rendertype&&(n={body:{contentDisposition:"render",contentType:this._rendertype,content:this._renderbody}}),e.ack(n),this.stateTransition(w.Established)}).catch(n=>{throw this.logger.error(n.message),this.ackAndBye(e,488,"Not Acceptable Here"),this.stateTransition(w.Terminated),n})}case y.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!==w.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 i=e.message,s=e.session;i.hasHeader("P-Asserted-Identity")&&(this._assertedIdentity=P.nameAddrHeaderParse(i.getHeader("P-Asserted-Identity")));const r=i.getHeader("require"),n=i.getHeader("rseq"),d=!!(r&&r.includes("100rel")&&n?Number(n):void 0),u=[];switch(d&&u.push("RAck: "+i.getHeader("rseq")+" "+i.getHeader("cseq")),s.signalingState){case y.Initial:return d&&(this.logger.warn("First reliable provisional response received MUST contain an offer when INVITE does not contain an offer."),e.prack({extraHeaders:u})),Promise.resolve();case y.HaveLocalOffer:return d&&e.prack({extraHeaders:u}),Promise.resolve();case y.HaveRemoteOffer:if(!d)return this.logger.warn("Non-reliable provisional response MUST NOT contain an initial offer, discarding response."),Promise.resolve();{const h=this.sessionDescriptionHandlerFactory(this,this.userAgent.configuration.sessionDescriptionHandlerFactoryOptions||{});return!((t=this.delegate)===null||t===void 0)&&t.onSessionDescriptionHandler&&this.delegate.onSessionDescriptionHandler(h,!0),this.earlyMediaSessionDescriptionHandlers.set(s.id,h),h.setDescription(i.body,this.sessionDescriptionHandlerOptions,this.sessionDescriptionHandlerModifiers).then(()=>h.getDescription(this.sessionDescriptionHandlerOptions,this.sessionDescriptionHandlerModifiers)).then(m=>{const S={contentDisposition:"session",contentType:m.contentType,content:m.body};e.prack({extraHeaders:u,body:S})}).catch(m=>{throw this.stateTransition(w.Terminated),m})}case y.Stable:if(d&&e.prack({extraHeaders:u}),this.earlyMedia&&!this.earlyMediaDialog){this.earlyMediaDialog=s;const h=s.answer;if(!h)throw new Error("Answer is undefined.");const m={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.setAnswer(h,m).catch(S=>{throw this.stateTransition(w.Terminated),S})}return Promise.resolve();case y.Closed:return Promise.reject(new Error("Terminated."));default:throw new Error("Unknown session signaling state.")}}onRedirect(e){if(this.logger.log("Inviter.onRedirect"),this.state!==w.Establishing&&this.state!==w.Terminating){this.logger.error(`Redirect received while in state ${this.state}, dropping response`);return}this.stateTransition(w.Terminated)}onReject(e){if(this.logger.log("Inviter.onReject"),this.state!==w.Establishing&&this.state!==w.Terminating){this.logger.error(`Reject received while in state ${this.state}, dropping response`);return}this.stateTransition(w.Terminated)}onTrying(e){if(this.logger.log("Inviter.onTrying"),this.state!==w.Establishing){this.logger.error(`Trying received while in state ${this.state}, dropping response`);return}}}class Vt{constructor(e,t,i,s="text/plain",r={}){this.logger=e.getLogger("sip.Messager"),r.params=r.params||{};let n=e.userAgentCore.configuration.aor;if(r.params.fromUri&&(n=typeof r.params.fromUri=="string"?P.URIParse(r.params.fromUri):r.params.fromUri),!n)throw new TypeError("Invalid from URI: "+r.params.fromUri);let o=t;if(r.params.toUri&&(o=typeof r.params.toUri=="string"?P.URIParse(r.params.toUri):r.params.toUri),!o)throw new TypeError("Invalid to URI: "+r.params.toUri);const d=r.params?Object.assign({},r.params):{},u=(r.extraHeaders||[]).slice(),m={contentDisposition:"render",contentType:s,content:i};this.request=e.userAgentCore.makeOutgoingRequestMessage(v.MESSAGE,t,n,o,d,u,m),this.userAgent=e}message(e={}){return this.userAgent.userAgentCore.request(this.request,e.requestDelegate),Promise.resolve()}}var R;(function(a){a.Initial="Initial",a.Registered="Registered",a.Unregistered="Unregistered",a.Terminated="Terminated"})(R=R||(R={}));class J{constructor(e,t={}){this.disposed=!1,this._contacts=[],this._retryAfter=void 0,this._state=R.Initial,this._waiting=!1,this._stateEventEmitter=new Te,this._waitingEventEmitter=new Te,this.userAgent=e;const i=e.configuration.uri.clone();if(i.user=void 0,this.options=Object.assign(Object.assign(Object.assign({},J.defaultOptions()),{registrar:i}),J.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&&P.parse(this.options.instanceId,"uuid")===-1)throw new Error("Invalid instanceId.");if(this.options.regId&&this.options.regId<0)throw new Error("Invalid regId.");const s=this.options.registrar,r=this.options.params&&this.options.params.fromUri||e.userAgentCore.configuration.aor,n=this.options.params&&this.options.params.toUri||e.configuration.uri,o=this.options.params||{},d=(t.extraHeaders||[]).slice();if(this.request=e.userAgentCore.makeOutgoingRequestMessage(v.REGISTER,s,r,n,o,d,void 0),this.expires=this.options.expires||J.defaultExpires,this.expires<0)throw new Error("Invalid expires.");if(this.refreshFrequency=this.options.refreshFrequency||J.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(u=>{const h=this.options[u];u==="registrar"?this.logger.log("· "+u+": "+h):this.logger.log("· "+u+": "+JSON.stringify(h))})),this.id=this.request.callId+this.request.from.parameters.tag,this.userAgent._registerers[this.id]=this}static defaultOptions(){return{expires:J.defaultExpires,extraContactHeaderParams:[],extraHeaders:[],logConfiguration:!0,instanceId:"",params:{},regId:0,registrar:new z("sip","anonymous","anonymous.invalid"),refreshFrequency:J.defaultRefreshFrequency}}static stripUndefinedProperties(e){return Object.keys(e).reduce((t,i)=>(e[i]!==void 0&&(t[i]=e[i]),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===R.Registered){this.stateChange.addListener(()=>{this.terminated(),e()},{once:!0}),this.unregister();return}this.terminated(),e()};this.waiting?this.waitingChange.addListener(()=>{t()},{once:!0}):t()}))}register(e={}){if(this.state===R.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 s=new ve("REGISTER request already in progress, waiting for final response");return Promise.reject(s)}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 i=this.userAgent.userAgentCore.register(this.request,{onAccept:s=>{let r;s.message.hasHeader("expires")&&(r=Number(s.message.getHeader("expires"))),this._contacts=s.message.getHeaders("contact");let n=this._contacts.length;if(!n){this.logger.error("No Contact header in response to REGISTER, dropping response."),this.unregistered();return}let o;for(;n--;){if(o=s.message.parseHeader("contact",n),!o)throw new Error("Contact undefined");if(this.userAgent.contact.pubGruu&&st(o.uri,this.userAgent.contact.pubGruu)){r=Number(o.getParam("expires"));break}if(this.userAgent.configuration.contactName===""){if(o.uri.user===this.userAgent.contact.uri.user){r=Number(o.getParam("expires"));break}}else if(st(o.uri,this.userAgent.contact.uri)){r=Number(o.getParam("expires"));break}o=void 0}if(o===void 0){this.logger.error("No Contact header pointing to us, dropping response"),this.unregistered(),this.waitingToggle(!1);return}if(r===void 0){this.logger.error("Contact pointing to us is missing expires parameter, dropping response"),this.unregistered(),this.waitingToggle(!1);return}if(o.hasParam("temp-gruu")){const d=o.getParam("temp-gruu");d&&(this.userAgent.contact.tempGruu=P.URIParse(d.replace(/"/g,"")))}if(o.hasParam("pub-gruu")){const d=o.getParam("pub-gruu");d&&(this.userAgent.contact.pubGruu=P.URIParse(d.replace(/"/g,"")))}this.registered(r),e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(s),this.waitingToggle(!1)},onProgress:s=>{e.requestDelegate&&e.requestDelegate.onProgress&&e.requestDelegate.onProgress(s)},onRedirect:s=>{this.logger.error("Redirect received. Not supported."),this.unregistered(),e.requestDelegate&&e.requestDelegate.onRedirect&&e.requestDelegate.onRedirect(s),this.waitingToggle(!1)},onReject:s=>{if(s.message.statusCode===423){if(!s.message.hasHeader("min-expires")){this.logger.error("423 response received for REGISTER without Min-Expires, dropping response"),this.unregistered(),this.waitingToggle(!1);return}this.expires=Number(s.message.getHeader("min-expires")),this.waitingToggle(!1),this.register();return}this.logger.warn(`Failed to register, status code ${s.message.statusCode}`);let r=NaN;if(s.message.statusCode===500||s.message.statusCode===503){const n=s.message.getHeader("retry-after");n&&(r=Number.parseInt(n,void 0))}this._retryAfter=isNaN(r)?void 0:r,this.unregistered(),e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(s),this._retryAfter=void 0,this.waitingToggle(!1)},onTrying:s=>{e.requestDelegate&&e.requestDelegate.onTrying&&e.requestDelegate.onTrying(s)}});return Promise.resolve(i)}unregister(e={}){if(this.state===R.Terminated)throw this.stateError(),new Error("Registerer terminated. Unable to register.");if(this.disposed&&this.state!==R.Registered)throw this.stateError(),new Error("Registerer disposed. Unable to register.");if(this.waiting){this.waitingWarning();const s=new ve("REGISTER request already in progress, waiting for final response");return Promise.reject(s)}this._state!==R.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"),this.registrationTimer!==void 0&&(clearTimeout(this.registrationTimer),this.registrationTimer=void 0),this.waitingToggle(!0);const i=this.userAgent.userAgentCore.register(this.request,{onAccept:s=>{this._contacts=s.message.getHeaders("contact"),this.unregistered(),e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(s),this.waitingToggle(!1)},onProgress:s=>{e.requestDelegate&&e.requestDelegate.onProgress&&e.requestDelegate.onProgress(s)},onRedirect:s=>{this.logger.error("Unregister redirected. Not currently supported."),this.unregistered(),e.requestDelegate&&e.requestDelegate.onRedirect&&e.requestDelegate.onRedirect(s),this.waitingToggle(!1)},onReject:s=>{this.logger.error(`Unregister rejected with status code ${s.message.statusCode}`),this.unregistered(),e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(s),this.waitingToggle(!1)},onTrying:s=>{e.requestDelegate&&e.requestDelegate.onTrying&&e.requestDelegate.onTrying(s)}});return Promise.resolve(i)}clearTimers(){this.registrationTimer!==void 0&&(clearTimeout(this.registrationTimer),this.registrationTimer=void 0),this.registrationExpiredTimer!==void 0&&(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="<urn:uuid:'+this.options.instanceId+'>"'),this.options.extraContactHeaderParams&&this.options.extraContactHeaderParams.forEach(i=>{t+=";"+i}),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()},e*1e3),this._state!==R.Registered&&this.stateTransition(R.Registered)}unregistered(){this.clearTimers(),this._state!==R.Unregistered&&this.stateTransition(R.Unregistered)}terminated(){this.clearTimers(),this._state!==R.Terminated&&this.stateTransition(R.Terminated)}stateTransition(e){const t=()=>{throw new Error(`Invalid state transition from ${this._state} to ${e}`)};switch(this._state){case R.Initial:e!==R.Registered&&e!==R.Unregistered&&e!==R.Terminated&&t();break;case R.Registered:e!==R.Unregistered&&e!==R.Terminated&&t();break;case R.Unregistered:e!==R.Registered&&e!==R.Terminated&&t();break;case R.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===R.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(e)}stateError(){let t=`An attempt was made to send a REGISTER request when the Registerer ${this.state===R.Terminated?"is in 'Terminated' state":"has been disposed"}.`;t+=" The Registerer transitions to 'Terminated' when Registerer.dispose() is called.",t+=" Perhaps you called UserAgent.stop() which dipsoses of all Registerers?",this.logger.error(t)}}J.defaultExpires=600,J.defaultRefreshFrequency=99;var I;(function(a){a.Initial="Initial",a.NotifyWait="NotifyWait",a.Pending="Pending",a.Active="Active",a.Terminated="Terminated"})(I=I||(I={}));var T;(function(a){a.Connecting="Connecting",a.Connected="Connected",a.Disconnecting="Disconnecting",a.Disconnected="Disconnected"})(T=T||(T={}));var k;(function(a){a.Started="Started",a.Stopped="Stopped"})(k=k||(k={}));class H{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=H.hexChars,i=H.hexOut;let s,r,n,o;for(o=0;o<4;o+=1)for(r=o*8,s=e[o],n=0;n<8;n+=2)i[r+1+n]=t.charAt(s&15),s>>>=4,i[r+0+n]=t.charAt(s&15),s>>>=4;return i.join("")}static _md5cycle(e,t){let i=e[0],s=e[1],r=e[2],n=e[3];i+=(s&r|~s&n)+t[0]-680876936|0,i=(i<<7|i>>>25)+s|0,n+=(i&s|~i&r)+t[1]-389564586|0,n=(n<<12|n>>>20)+i|0,r+=(n&i|~n&s)+t[2]+606105819|0,r=(r<<17|r>>>15)+n|0,s+=(r&n|~r&i)+t[3]-1044525330|0,s=(s<<22|s>>>10)+r|0,i+=(s&r|~s&n)+t[4]-176418897|0,i=(i<<7|i>>>25)+s|0,n+=(i&s|~i&r)+t[5]+1200080426|0,n=(n<<12|n>>>20)+i|0,r+=(n&i|~n&s)+t[6]-1473231341|0,r=(r<<17|r>>>15)+n|0,s+=(r&n|~r&i)+t[7]-45705983|0,s=(s<<22|s>>>10)+r|0,i+=(s&r|~s&n)+t[8]+1770035416|0,i=(i<<7|i>>>25)+s|0,n+=(i&s|~i&r)+t[9]-1958414417|0,n=(n<<12|n>>>20)+i|0,r+=(n&i|~n&s)+t[10]-42063|0,r=(r<<17|r>>>15)+n|0,s+=(r&n|~r&i)+t[11]-1990404162|0,s=(s<<22|s>>>10)+r|0,i+=(s&r|~s&n)+t[12]+1804603682|0,i=(i<<7|i>>>25)+s|0,n+=(i&s|~i&r)+t[13]-40341101|0,n=(n<<12|n>>>20)+i|0,r+=(n&i|~n&s)+t[14]-1502002290|0,r=(r<<17|r>>>15)+n|0,s+=(r&n|~r&i)+t[15]+1236535329|0,s=(s<<22|s>>>10)+r|0,i+=(s&n|r&~n)+t[1]-165796510|0,i=(i<<5|i>>>27)+s|0,n+=(i&r|s&~r)+t[6]-1069501632|0,n=(n<<9|n>>>23)+i|0,r+=(n&s|i&~s)+t[11]+643717713|0,r=(r<<14|r>>>18)+n|0,s+=(r&i|n&~i)+t[0]-373897302|0,s=(s<<20|s>>>12)+r|0,i+=(s&n|r&~n)+t[5]-701558691|0,i=(i<<5|i>>>27)+s|0,n+=(i&r|s&~r)+t[10]+38016083|0,n=(n<<9|n>>>23)+i|0,r+=(n&s|i&~s)+t[15]-660478335|0,r=(r<<14|r>>>18)+n|0,s+=(r&i|n&~i)+t[4]-405537848|0,s=(s<<20|s>>>12)+r|0,i+=(s&n|r&~n)+t[9]+568446438|0,i=(i<<5|i>>>27)+s|0,n+=(i&r|s&~r)+t[14]-1019803690|0,n=(n<<9|n>>>23)+i|0,r+=(n&s|i&~s)+t[3]-187363961|0,r=(r<<14|r>>>18)+n|0,s+=(r&i|n&~i)+t[8]+1163531501|0,s=(s<<20|s>>>12)+r|0,i+=(s&n|r&~n)+t[13]-1444681467|0,i=(i<<5|i>>>27)+s|0,n+=(i&r|s&~r)+t[2]-51403784|0,n=(n<<9|n>>>23)+i|0,r+=(n&s|i&~s)+t[7]+1735328473|0,r=(r<<14|r>>>18)+n|0,s+=(r&i|n&~i)+t[12]-1926607734|0,s=(s<<20|s>>>12)+r|0,i+=(s^r^n)+t[5]-378558|0,i=(i<<4|i>>>28)+s|0,n+=(i^s^r)+t[8]-2022574463|0,n=(n<<11|n>>>21)+i|0,r+=(n^i^s)+t[11]+1839030562|0,r=(r<<16|r>>>16)+n|0,s+=(r^n^i)+t[14]-35309556|0,s=(s<<23|s>>>9)+r|0,i+=(s^r^n)+t[1]-1530992060|0,i=(i<<4|i>>>28)+s|0,n+=(i^s^r)+t[4]+1272893353|0,n=(n<<11|n>>>21)+i|0,r+=(n^i^s)+t[7]-155497632|0,r=(r<<16|r>>>16)+n|0,s+=(r^n^i)+t[10]-1094730640|0,s=(s<<23|s>>>9)+r|0,i+=(s^r^n)+t[13]+681279174|0,i=(i<<4|i>>>28)+s|0,n+=(i^s^r)+t[0]-358537222|0,n=(n<<11|n>>>21)+i|0,r+=(n^i^s)+t[3]-722521979|0,r=(r<<16|r>>>16)+n|0,s+=(r^n^i)+t[6]+76029189|0,s=(s<<23|s>>>9)+r|0,i+=(s^r^n)+t[9]-640364487|0,i=(i<<4|i>>>28)+s|0,n+=(i^s^r)+t[12]-421815835|0,n=(n<<11|n>>>21)+i|0,r+=(n^i^s)+t[15]+530742520|0,r=(r<<16|r>>>16)+n|0,s+=(r^n^i)+t[2]-995338651|0,s=(s<<23|s>>>9)+r|0,i+=(r^(s|~n))+t[0]-198630844|0,i=(i<<6|i>>>26)+s|0,n+=(s^(i|~r))+t[7]+1126891415|0,n=(n<<10|n>>>22)+i|0,r+=(i^(n|~s))+t[14]-1416354905|0,r=(r<<15|r>>>17)+n|0,s+=(n^(r|~i))+t[5]-57434055|0,s=(s<<21|s>>>11)+r|0,i+=(r^(s|~n))+t[12]+1700485571|0,i=(i<<6|i>>>26)+s|0,n+=(s^(i|~r))+t[3]-1894986606|0,n=(n<<10|n>>>22)+i|0,r+=(i^(n|~s))+t[10]-1051523|0,r=(r<<15|r>>>17)+n|0,s+=(n^(r|~i))+t[1]-2054922799|0,s=(s<<21|s>>>11)+r|0,i+=(r^(s|~n))+t[8]+1873313359|0,i=(i<<6|i>>>26)+s|0,n+=(s^(i|~r))+t[15]-30611744|0,n=(n<<10|n>>>22)+i|0,r+=(i^(n|~s))+t[6]-1560198380|0,r=(r<<15|r>>>17)+n|0,s+=(n^(r|~i))+t[13]+1309151649|0,s=(s<<21|s>>>11)+r|0,i+=(r^(s|~n))+t[4]-145523070|0,i=(i<<6|i>>>26)+s|0,n+=(s^(i|~r))+t[11]-1120210379|0,n=(n<<10|n>>>22)+i|0,r+=(i^(n|~s))+t[2]+718787259|0,r=(r<<15|r>>>17)+n|0,s+=(n^(r|~i))+t[9]-343485551|0,s=(s<<21|s>>>11)+r|0,e[0]=i+e[0]|0,e[1]=s+e[1]|0,e[2]=r+e[2]|0,e[3]=n+e[3]|0}start(){return this._dataLength=0,this._bufferLength=0,this._state.set(H.stateIdentity),this}appendStr(e){const t=this._buffer8,i=this._buffer32;let s=this._bufferLength,r,n;for(n=0;n<e.length;n+=1){if(r=e.charCodeAt(n),r<128)t[s++]=r;else if(r<2048)t[s++]=(r>>>6)+192,t[s++]=r&63|128;else if(r<55296||r>56319)t[s++]=(r>>>12)+224,t[s++]=r>>>6&63|128,t[s++]=r&63|128;else{if(r=(r-55296)*1024+(e.charCodeAt(++n)-56320)+65536,r>1114111)throw new Error("Unicode standard supports code points up to U+10FFFF");t[s++]=(r>>>18)+240,t[s++]=r>>>12&63|128,t[s++]=r>>>6&63|128,t[s++]=r&63|128}s>=64&&(this._dataLength+=64,H._md5cycle(this._state,i),s-=64,i[0]=i[16])}return this._bufferLength=s,this}appendAsciiStr(e){const t=this._buffer8,i=this._buffer32;let s=this._bufferLength,r,n=0;for(;;){for(r=Math.min(e.length-n,64-s);r--;)t[s++]=e.charCodeAt(n++);if(s<64)break;this._dataLength+=64,H._md5cycle(this._state,i),s=0}return this._bufferLength=s,this}appendByteArray(e){const t=this._buffer8,i=this._buffer32;let s=this._bufferLength,r,n=0;for(;;){for(r=Math.min(e.length-n,64-s);r--;)t[s++]=e[n++];if(s<64)break;this._dataLength+=64,H._md5cycle(this._state,i),s=0}return this._bufferLength=s,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,i=e.state,s=this._state;let r;for(this._dataLength=e.length,this._bufferLength=e.buflen,s[0]=i[0],s[1]=i[1],s[2]=i[2],s[3]=i[3],r=0;r<t.length;r+=1)this._buffer8[r]=t.charCodeAt(r)}end(e=!1){const t=this._bufferLength,i=this._buffer8,s=this._buffer32,r=(t>>2)+1;let n;if(this._dataLength+=t,i[t]=128,i[t+1]=i[t+2]=i[t+3]=0,s.set(H.buffer32Identity.subarray(r),r),t>55&&(H._md5cycle(this._state,s),s.set(H.buffer32Identity)),n=this._dataLength*8,n<=4294967295)s[14]=n;else{const o=n.toString(16).match(/(.*?)(.{0,8})$/);if(o===null)return;const d=parseInt(o[2],16),u=parseInt(o[1],16)||0;s[14]=d,s[15]=u}return H._md5cycle(this._state,s),e?this._state:H._hex(this._state)}}H.stateIdentity=new Int32Array([1732584193,-271733879,-1732584194,271733878]),H.buffer32Identity=new Int32Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]),H.hexChars="0123456789abcdef",H.hexOut=[],H.onePassHasher=new H,H.hashStr("hello")!=="5d41402abc4b2a76b9719d911017c592"&&console.error("Md5 self test failed.");function oe(a){return H.hashStr(a)}class Gt{constructor(e,t,i,s){this.logger=e.getLogger("sipjs.digestauthentication"),this.username=i,this.password=s,this.ha1=t,this.nc=0,this.ncHex="00000000"}authenticate(e,t,i){if(this.algorithm=t.algorithm,this.realm=t.realm,this.nonce=t.nonce,this.opaque=t.opaque,this.stale=t.stale,this.algorithm){if(this.algorithm!=="MD5")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)this.qop="auth-int";else return this.logger.warn("challenge without Digest qop different than 'auth' or 'auth-int', authentication aborted"),!1;else this.qop=void 0;return this.method=e.method,this.uri=e.ruri,this.cnonce=ue(12),this.nc+=1,this.updateNcHex(),this.nc===4294967296&&(this.nc=1,this.ncHex="00000001"),this.calculateResponse(i),!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,i;t=this.ha1,(t===""||t===void 0)&&(t=oe(this.username+":"+this.realm+":"+this.password)),this.qop==="auth"?(i=oe(this.method+":"+this.uri),this.response=oe(t+":"+this.nonce+":"+this.ncHex+":"+this.cnonce+":auth:"+i)):this.qop==="auth-int"?(i=oe(this.method+":"+this.uri+":"+oe(e||"")),this.response=oe(t+":"+this.nonce+":"+this.ncHex+":"+this.cnonce+":auth-int:"+i)):this.qop===void 0&&(i=oe(this.method+":"+this.uri),this.response=oe(t+":"+this.nonce+":"+i))}}var q;(function(a){a[a.error=0]="error",a[a.warn=1]="warn",a[a.log=2]="log",a[a.debug=3]="debug"})(q=q||(q={}));class dt{constructor(e,t,i){this.logger=e,this.category=t,this.label=i}error(e){this.genericLog(q.error,e)}warn(e){this.genericLog(q.warn,e)}log(e){this.genericLog(q.log,e)}debug(e){this.genericLog(q.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 Wt{constructor(){this.builtinEnabled=!0,this._level=q.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:q.hasOwnProperty(e)?this._level=e:this.logger.error("invalid 'level' parameter value: "+JSON.stringify(e))}get connector(){return this._connector}set connector(e){e?typeof e=="function"?this._connector=e:this.logger.error("invalid 'connector' parameter value: "+JSON.stringify(e)):this._connector=void 0}getLogger(e,t){if(t&&this.level===3)return new dt(this,e,t);if(this.loggers[e])return this.loggers[e];{const i=new dt(this,e);return this.loggers[e]=i,i}}genericLog(e,t,i,s){this.level>=e&&this.builtinEnabled&&this.print(e,t,i,s),this.connector&&this.connector(q[e],t,i,s)}print(e,t,i,s){if(typeof s=="string"){const r=[new Date,t];i&&r.push(i),s=r.concat(s).join(" | ")}switch(e){case q.error:console.error(s);break;case q.warn:console.warn(s);break;case q.log:console.log(s);break;case q.debug:console.debug(s);break}}}var ke;(function(a){function e(s,r){let n=r,o=0,d=0;if(s.substring(n,n+2).match(/(^\r\n)/))return-2;for(;o===0;){if(d=s.indexOf(`\r
|
|
23
23
|
`,n),d===-1)return d;!s.substring(d+2,d+4).match(/(^\r\n)/)&&s.charAt(d+2).match(/(^\s+)/)?n=d+2:o=d}return o}a.getHeader=e;function t(s,r,n,o){const d=r.indexOf(":",n),u=r.substring(n,d).trim(),h=r.substring(d+1,o).trim();let m;switch(u.toLowerCase()){case"via":case"v":s.addHeader("via",h),s.getHeaders("via").length===1?(m=s.parseHeader("Via"),m&&(s.via=m,s.viaBranch=m.branch)):m=0;break;case"from":case"f":s.setHeader("from",h),m=s.parseHeader("from"),m&&(s.from=m,s.fromTag=m.getParam("tag"));break;case"to":case"t":s.setHeader("to",h),m=s.parseHeader("to"),m&&(s.to=m,s.toTag=m.getParam("tag"));break;case"record-route":if(m=P.parse(h,"Record_Route"),m===-1){m=void 0;break}if(!(m instanceof Array)){m=void 0;break}m.forEach(S=>{s.addHeader("record-route",h.substring(S.position,S.offset)),s.headers["Record-Route"][s.getHeaders("record-route").length-1].parsed=S.parsed});break;case"call-id":case"i":s.setHeader("call-id",h),m=s.parseHeader("call-id"),m&&(s.callId=h);break;case"contact":case"m":if(m=P.parse(h,"Contact"),m===-1){m=void 0;break}if(!(m instanceof Array)){m=void 0;break}m.forEach(S=>{s.addHeader("contact",h.substring(S.position,S.offset)),s.headers.Contact[s.getHeaders("contact").length-1].parsed=S.parsed});break;case"content-length":case"l":s.setHeader("content-length",h),m=s.parseHeader("content-length");break;case"content-type":case"c":s.setHeader("content-type",h),m=s.parseHeader("content-type");break;case"cseq":s.setHeader("cseq",h),m=s.parseHeader("cseq"),m&&(s.cseq=m.value),s instanceof re&&(s.method=m.method);break;case"max-forwards":s.setHeader("max-forwards",h),m=s.parseHeader("max-forwards");break;case"www-authenticate":s.setHeader("www-authenticate",h),m=s.parseHeader("www-authenticate");break;case"proxy-authenticate":s.setHeader("proxy-authenticate",h),m=s.parseHeader("proxy-authenticate");break;case"refer-to":case"r":s.setHeader("refer-to",h),m=s.parseHeader("refer-to"),m&&(s.referTo=m);break;default:s.addHeader(u.toLowerCase(),h),m=0}return m===void 0?{error:"error parsing header '"+u+"'"}:!0}a.parseHeader=t;function i(s,r){let n=0,o=s.indexOf(`\r
|
|
24
24
|
`);if(o===-1){r.warn("no CRLF found, not a SIP message, discarded");return}const d=s.substring(0,o),u=P.parse(d,"Request_Response");let h;if(u===-1){r.warn('error parsing first line of SIP message: "'+d+'"');return}else u.status_code?(h=new re,h.statusCode=u.status_code,h.reasonPhrase=u.reason_phrase):(h=new me,h.method=u.method,h.ruri=u.uri);h.data=s,n=o+2;let m;for(;;){if(o=e(s,n),o===-2){m=n+2;break}else if(o===-1){r.error("malformed message");return}const S=t(h,s,n,o);if(S&&S!==!0){r.error(S.error);return}n=o+2}return h.hasHeader("content-length")?h.body=s.substr(m,Number(h.getHeader("content-length"))):h.body=s.substring(m),h}a.parseMessage=i})(ke=ke||(ke={}));function lt(a,e){if(e.statusCode<100||e.statusCode>699)throw new TypeError("Invalid statusCode: "+e.statusCode);const i=e.reasonPhrase?e.reasonPhrase:Ae(e.statusCode);let s="SIP/2.0 "+e.statusCode+" "+i+`\r
|
|
25
25
|
`;e.statusCode>=100&&e.statusCode<200,e.statusCode;const r="From: "+a.getHeader("From")+`\r
|
|
@@ -282,12 +282,12 @@ Duration=`+2e3}};return e.info({requestOptions:n}).then(()=>{})}}async transfer(
|
|
|
282
282
|
.meta { padding: 12px 16px 0; font-size: 12px; }
|
|
283
283
|
.logs { max-height: 150px; padding: 12px 16px 16px; }
|
|
284
284
|
}
|
|
285
|
-
`,
|
|
285
|
+
`,se={idle:"网页电话已加载,正在准备待机能力。",requesting:"正在向服务端申请网页通话会话。",standbyRequesting:"正在向服务端申请 widget 待机会话。",registering:"临时账号已拿到,正在连接并执行 REGISTER。",standby:"REGISTER 已完成,widget 正在等待来电。",incoming:"收到新的来电,请选择接听或拒接。",calling:"已发起呼叫,正在等待对端振铃或接听。",connected:"通话已接通,媒体链路正在运行。",ended:"通话已结束,网页电话正在返回待机。",rejected:"本次来电已拒接,widget 仍保持待机。",missed:"本次来电未接听,widget 仍保持待机。",failed:"本次呼叫失败,请先看下方日志。"},Ze={idle:"准备通话",ringing:"来电中",dialing:"拨打中",connected:"通话中",ended:"已结束",failed:"当前暂时无法接通"},Ri="手机网页首次接入时,请允许麦克风权限;若切到后台后再回来,先确认页面仍保持前台活跃。",Ii=1500,Ai=5e3,$i=15e3,Ct=2,Re=3e4,Di=1200,Pi=3e4,ki=4e3,Hi="embedded-call-widget:first-hint-dismissed:",de={ready:"线路可用",preparing:"正在准备",working:"通话处理中",recovering:"正在恢复",offline:"当前离线",conflicted:"协议冲突"},Ie=Object.freeze({standby:"widget_standby",outbound:"outbound"}),Et=Object.freeze({standby:"standby",outbound:"outbound"}),Xe=Object.freeze({keep:"keep",restartStandby:"restart_standby"}),Mi=new Set(["session_missing_or_terminal","session_binding_changed","session_anchor_changed","browser_lease_lost","anchor_or_browser_conflict"]);function qi(a,e){return e?`${a}
|
|
286
286
|
${JSON.stringify(e,null,2)}`:a}function Oi(a){if(typeof window>"u"||!a)return!1;try{return window.localStorage.getItem(a)==="1"}catch{return!1}}function Fi(a,e){if(!(typeof window>"u"||!a))try{e&&window.localStorage.setItem(a,"1")}catch{}}const Ni=`
|
|
287
287
|
<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
288
288
|
<path d="M6.84 4.28c.3-.72 1.15-1.1 1.89-.85l2.24.75c.77.26 1.18 1.09.91 1.85l-.64 1.82a1.6 1.6 0 0 1-1.9.99l-.63-.16a12.8 12.8 0 0 0 6.62 6.62l-.16-.63a1.6 1.6 0 0 1 .99-1.9l1.82-.64c.76-.27 1.59.14 1.85.91l.75 2.24c.25.74-.13 1.59-.85 1.89l-1.74.72c-.72.3-1.54.26-2.23-.1A17.94 17.94 0 0 1 4.48 7.23c-.36-.69-.4-1.51-.1-2.23z" fill="currentColor"/>
|
|
289
289
|
</svg>
|
|
290
|
-
`;function A(a,e,t){t!=null&&(typeof t=="string"&&t.trim()===""||(a[e]=t))}function
|
|
290
|
+
`;function A(a,e,t){t!=null&&(typeof t=="string"&&t.trim()===""||(a[e]=t))}function Q(a){return typeof a=="string"?a.trim():""}function xt(a,e,t){const i=Q(a?.session_mode);if(!i)throw L(`${t} 缺少必填字段 session_mode。`,{source:t,session_id:a?.session_id||null,expected_session_mode:e,received_session_mode:null});if(!Object.values(Ie).includes(i))throw L(`${t} 返回了未登记的 session_mode。`,{source:t,session_id:a?.session_id||null,expected_session_mode:e,received_session_mode:i});if(i!==e)throw L(`${t} 返回的 session_mode 与当前流程不匹配。`,{source:t,session_id:a?.session_id||null,expected_session_mode:e,received_session_mode:i});return i}function Ui(a,e={}){const t=Q(e?.session_action).toLowerCase(),i=Q(e?.session_action_reason)||null,s=Q(e?.session_action_detail)||null,r=Q(e?.resolved_session_id)||null,n=Q(e?.resolved_widget_anchor_number)||null,o=Q(e?.resolved_browser_sip_username)||null,d={source:a,session_action:t||null,session_action_reason:i,session_action_detail:s,resolved_session_id:r,resolved_widget_anchor_number:n,resolved_browser_sip_username:o};if(!t)throw L("服务端缺少必填字段 session_action。",d);if(!Object.values(Xe).includes(t))throw L("服务端返回了未登记的 session_action。",d);if(t===Xe.keep){if(i||s)throw L("session_action=keep 时不得携带 session_action_reason 或 session_action_detail。",d);return{action:t,reason:null,detail:null,resolvedSessionId:r,resolvedWidgetAnchorNumber:n,resolvedBrowserSipUsername:o}}if(!i)throw L("session_action=restart_standby 时必须携带 session_action_reason。",d);if(!Mi.has(i))throw L("服务端返回了未登记的 session_action_reason。",d);if(!s)throw L("session_action=restart_standby 时必须携带非空的 session_action_detail。",d);if(i==="session_missing_or_terminal"){if(r||n||o)throw L("session_missing_or_terminal 不得返回非空 resolved_* 字段。",d)}else if(i==="session_binding_changed"||i==="browser_lease_lost"){if(!r||!o)throw L(`${i} 必须返回 resolved_session_id 和 resolved_browser_sip_username。`,d)}else if(i==="session_anchor_changed"){if(!r||!n)throw L("session_anchor_changed 必须返回 resolved_session_id 和 resolved_widget_anchor_number。",d)}else if(i==="anchor_or_browser_conflict"&&(!r||!n&&!o))throw L("anchor_or_browser_conflict 必须返回 resolved_session_id 及至少一个冲突定位字段。",d);return{action:t,reason:i,detail:s,resolvedSessionId:r,resolvedWidgetAnchorNumber:n,resolvedBrowserSipUsername:o}}function Li(a){return a==="outbound"?"outbound":"terminal"}function Bi(a){return typeof a=="function"}function ji(){return typeof window>"u"?!1:new URLSearchParams(window.location.search).get("embeddedCallWidgetE2E")==="1"}function Vi(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`widget-${Date.now()}-${Math.random().toString(16).slice(2,10)}`}function Qe(a){const e=String(a?.message||a||"");return/Failed to fetch|NetworkError|Load failed|network/i.test(e)}function le(a={},e=null){const t=a?.advanced&&typeof a.advanced=="object"?a.advanced:{},i=String(t.visitorBusinessKey??"").trim();if(i)return i;const s=String(a?.businessKey??"").trim();return s||""}function Gi(a){const e=new Error(a);return e.name="EmbeddedCallWidgetLifecycleCancelledError",e.code="widget_runtime_run_stale",e}function _t(a){return a?.code==="sip_client_replaced"||a?.code==="widget_runtime_run_stale"}function L(a,e={}){const t=new Error(a);return t.name="EmbeddedCallWidgetProtocolViolationError",t.code="widget_protocol_violation",t.detail=e,t}function Oe(a){return a?.code==="widget_protocol_violation"}class Wi{constructor({mount:e,shadowRoot:t,options:i}){this.mountNode=e,this.shadowRoot=t,this.options=i,this.mode=Li(i.mode),this.legacyOutboundOnly=this.mode==="outbound",this.apiBaseUrl=_e(i.apiBaseUrl||window.location.origin).href,this.client=null,this.issuedSession=null,this.bootstrap=null,this.turnIceServers=[],this.state="idle",this.stateDetail=se.idle,this.finalizing=!1,this.isMobileViewport=!1,this.pendingIncomingCall=null,this.visibilityHandler=null,this.sessionTouchTimer=null,this.sessionRecoveryInFlight=null,this.transportDisconnectTimer=null,this.transportDisconnectContext=null,this.e2eBridgeEnabled=ji(),this.terminalFailureOverride="",this.presenceId=Vi(),this.presenceTouchTimer=null,this.presenceFailureCount=0,this.availabilityState="preparing",this.availabilityDetail="正在连接后台并准备网页电话待机。",this.connectivityRecoveryInFlight=null,this.lifecycleRunId=0,this.pendingLifecycleMode=null,this.expectedClientTeardown=null,this.expectedTermination=null,this.autoStandbyRecoveryTimer=null,this.recentlyReleasedSessions=new Map,this.networkOnline=typeof navigator>"u"?!0:navigator.onLine!==!1,this.pageVisible=typeof document>"u"?!0:document.visibilityState==="visible",this.onlineHandler=null,this.offlineHandler=null,this.beforeUnloadHandler=null,this.pageHideHandler=null,this.unloadCleanupStarted=!1,this.panelAutoCloseTimer=null,this.transientPanelState=null,this.transientPanelDetail="",this.missedIncomingCount=0,this.debugRequested=i.debug===!0,this.debugPanelEnabled=!1,this.hasAccessToken=!!String(i.accessToken||"").trim(),this.triggerHintStorageKey=`${Hi}${String(i.siteKey||"default").trim()||"default"}`,this.triggerHintDismissed=Oi(this.triggerHintStorageKey),this.refs={}}async mount(){this.isMobileViewport=typeof window<"u"&&window.matchMedia("(max-width: 480px)").matches,this.shadowRoot.innerHTML=`
|
|
291
291
|
<style>${_i}</style>
|
|
292
292
|
<section class="widget">
|
|
293
293
|
<button class="trigger" data-role="trigger" type="button" aria-label="${this.options.text||"联系管理员"}">
|
|
@@ -318,4 +318,4 @@ ${JSON.stringify(e,null,2)}`:a}function Oi(a){if(typeof window>"u"||!a)return!1;
|
|
|
318
318
|
</section>
|
|
319
319
|
<audio class="audio" data-role="audio" autoplay playsinline></audio>
|
|
320
320
|
</section>
|
|
321
|
-
`,this.refs.trigger=this.shadowRoot.querySelector('[data-role="trigger"]'),this.refs.triggerBadge=this.shadowRoot.querySelector('[data-role="trigger-badge"]'),this.refs.panelShell=this.shadowRoot.querySelector('[data-role="panel-shell"]'),this.refs.panel=this.shadowRoot.querySelector('[data-role="panel"]'),this.refs.panelEyebrow=this.shadowRoot.querySelector('[data-role="panel-eyebrow"]'),this.refs.panelTitle=this.shadowRoot.querySelector('[data-role="panel-title"]'),this.refs.panelDetail=this.shadowRoot.querySelector('[data-role="panel-detail"]'),this.refs.actions=this.shadowRoot.querySelector('[data-role="actions"]'),this.refs.status=this.shadowRoot.querySelector('[data-role="status"]'),this.refs.debugPanel=this.shadowRoot.querySelector('[data-role="debug-panel"]'),this.refs.availability=this.shadowRoot.querySelector('[data-role="availability"]'),this.refs.hint=this.shadowRoot.querySelector('[data-role="hint"]'),this.refs.meta=this.shadowRoot.querySelector('[data-role="meta"]'),this.refs.primary=this.shadowRoot.querySelector('[data-role="primary"]'),this.refs.secondary=this.shadowRoot.querySelector('[data-role="secondary"]'),this.refs.logs=this.shadowRoot.querySelector('[data-role="logs"]'),this.refs.audio=this.shadowRoot.querySelector('[data-role="audio"]'),this.refs.trigger.addEventListener("click",()=>{this.handleTriggerClick()}),this.refs.primary.addEventListener("click",()=>{this.handlePrimaryAction()}),this.refs.secondary.addEventListener("click",()=>{this.handleSecondaryAction()}),this.bindPageLifecycle(),this.registerE2EBridge(),this.startPresenceTouch(),this.render()}bindPageLifecycle(){typeof document>"u"||(this.visibilityHandler=()=>{if(this.pageVisible=document.visibilityState==="visible",document.visibilityState==="hidden"){this.reportIssuedSessionEvent("visibility-hidden",{visible:!1}),this.touchWidgetPresence("visibility-hidden"),this.issuedSession?.session_id&&this.touchIssuedSession(this.state,{trigger:"visibility-hidden"}),this.appendLog("页面已切到后台",{state:this.state,advice:"系统会继续自动保活;回到前台后请确认页面仍保持活动。"}),this.isMobileViewport&&["requesting","registering","calling","connected"].includes(this.state)&&(this.stateDetail="页面已切到后台;手机网页回到前台后请确认通话仍在继续。",this.render());return}if(this.isMobileViewport&&(this.appendLog("页面已回到前台",{state:this.state}),["requesting","registering","calling","connected"].includes(this.state)&&(this.stateDetail=ie[this.state]||ie.idle,this.render())),this.touchWidgetPresence("visibility-visible"),!this.legacyOutboundOnly&&["standby","registering","standbyRequesting","failed","idle","missed","rejected","ended"].includes(this.state)){const e=this.client?.getConnectionSnapshot?.()||null,t=!!(e?.connected&&(this.state!=="standby"||e?.registered));this.issuedSession?.session_id&&t?this.touchIssuedSession(this.state,{trigger:"visibility-visible"}):(this.appendLog("页面回到前台后检测到待机链路未处于健康状态,准备自动重建。",{state:this.state,has_session:!!this.issuedSession?.session_id,client_snapshot:e}),this.client||this.issuedSession?.session_id?this.disconnectAndCleanup("visibility-visible-unhealthy-client"):this.startStandby({force:!0}))}this.reportIssuedSessionEvent("visibility-visible",{visible:!0}),this.render()},document.addEventListener("visibilitychange",this.visibilityHandler),typeof window<"u"&&(this.onlineHandler=()=>{this.networkOnline=!0,this.setAvailabilityState("recovering","网络已恢复,正在重新连接网页电话。"),this.touchWidgetPresence("browser-online"),this.legacyOutboundOnly||this.restartStandbyAfterConnectivity("browser-online")},this.offlineHandler=()=>{this.networkOnline=!1,this.setAvailabilityState("offline","当前网络连接已断开,正在等待恢复。"),["incoming","connected"].includes(this.state)?this.render():this.setState("failed","当前网络连接已断开,正在等待恢复。")},window.addEventListener("online",this.onlineHandler),window.addEventListener("offline",this.offlineHandler),this.beforeUnloadHandler=()=>{this.flushUnloadCleanup("beforeunload")},this.pageHideHandler=e=>{e?.persisted||this.flushUnloadCleanup("pagehide")},window.addEventListener("beforeunload",this.beforeUnloadHandler),window.addEventListener("pagehide",this.pageHideHandler)))}open(){this.mountNode.scrollIntoView({block:"nearest",inline:"nearest"})}beginLifecycleRun(){return this.lifecycleRunId+=1,this.lifecycleRunId}assertLifecycleRunCurrent(e){if(e!==this.lifecycleRunId)throw Gi("网页电话已切换到新的连接流程,旧流程不再继续。")}emitHostCallback(e,t){const i=this.options?.[e];if(Bi(i))try{i(t)}catch(s){this.appendLog("宿主回调执行失败",{callback:e,message:s?.message||String(s)})}}getSnapshot(){const e=this.getVisibleState();return{mode:this.mode,state:this.state,stateDetail:this.stateDetail,visibleState:e,panelOpen:this.isPanelVisible(),sessionMode:this.issuedSession?.session_mode||null,sessionId:this.issuedSession?.session_id||null,siteKey:this.options.siteKey||this.bootstrap?.default_site_key||null,businessKey:this.issuedSession?.resolved_business_key||le(this.options,this.bootstrap)||null,standbyMode:this.issuedSession?.standby_mode||null,standbyState:this.issuedSession?.standby_state||this.options.standbyState||null,widgetSipNumber:this.issuedSession?.widget_anchor_number||null,browserSipUsername:this.issuedSession?.browser_sip_username||this.issuedSession?.sip_username||null,routeNote:this.issuedSession?.route_note||null,incomingAnchors:Array.isArray(this.issuedSession?.incoming_anchors)?this.issuedSession.incoming_anchors:[],hasClient:!!this.client,hasIssuedSession:!!this.issuedSession?.session_id,primaryText:this.refs.primary?.textContent?.trim()||"",secondaryText:this.refs.secondary?.textContent?.trim()||"",statusText:this.refs.status?.textContent?.trim()||"",availabilityState:this.availabilityState,availabilityLabel:this.refs.availability?.textContent?.trim()||"",triggerBadge:this.refs.triggerBadge?.textContent?.trim()||"",missedIncomingCount:this.missedIncomingCount,triggerHintDismissed:this.triggerHintDismissed,debugRequested:this.debugRequested,debugPanelEnabled:this.debugPanelEnabled,presenceId:this.presenceId,networkOnline:this.networkOnline,pendingIncomingCall:this.pendingIncomingCall}}getVisibleState(){return this.transientPanelState?this.transientPanelState:this.state==="incoming"?"ringing":["requesting","registering","calling"].includes(this.state)?"dialing":this.state==="connected"?"connected":"idle"}isPanelVisible(){return this.getVisibleState()!=="idle"}clearPanelAutoClose(){this.panelAutoCloseTimer&&(window.clearTimeout(this.panelAutoCloseTimer),this.panelAutoCloseTimer=null)}clearTransientPanelState(){this.clearPanelAutoClose(),this.transientPanelState=null,this.transientPanelDetail="",this.render()}setTransientPanelState(e,t="",i=Ii){this.clearPanelAutoClose(),this.transientPanelState=e,this.transientPanelDetail=t,this.render(),i>0&&(this.panelAutoCloseTimer=window.setTimeout(()=>{this.panelAutoCloseTimer=null,this.transientPanelState=null,this.transientPanelDetail="",this.render()},i))}markDebugPanelEnabled(e,t){!this.debugRequested||!this.hasAccessToken||!t||this.debugPanelEnabled||(this.debugPanelEnabled=!0,this.appendLog("调试模式门禁已成立,开始展示调试面板。",{source:e}),this.render())}dismissTriggerHint(){this.triggerHintDismissed||(this.triggerHintDismissed=!0,Fi(this.triggerHintStorageKey,!0))}clearMissedIncomingCount(){this.missedIncomingCount&&(this.missedIncomingCount=0)}incrementMissedIncomingCount(){this.missedIncomingCount+=1}async handleTriggerClick(){if(this.dismissTriggerHint(),this.clearMissedIncomingCount(),this.clearTransientPanelState(),this.open(),["requesting","registering","calling","connected","incoming"].includes(this.state)){this.render();return}await this.connectAndCall()}registerE2EBridge(){if(!this.e2eBridgeEnabled||typeof window>"u")return;const e=window.location.hostname||"example.invalid";window.__embeddedCallWidgetE2E__={getSnapshot:()=>this.getSnapshot(),simulateIncomingCall:(t={})=>{const i=t.host||e,s=t.user||"2001";return this.pendingIncomingCall={displayName:t.displayName||"测试来电",user:s,host:i,direction:"inbound",uri:t.uri||`sip:${s}@${i}`,e2eSimulated:!0},this.clearPanelAutoClose(),this.transientPanelState=null,this.transientPanelDetail="",this.setAvailabilityState("working","已有新来电,请直接接听或挂断。"),this.setState("incoming"),this.emitHostCallback("onIncomingCall",this.pendingIncomingCall),this.getSnapshot()},simulateOutboundDialing:(t={})=>(this.dismissTriggerHint(),this.clearMissedIncomingCount(),this.clearPanelAutoClose(),this.transientPanelState=null,this.transientPanelDetail="",this.pendingIncomingCall=t&&typeof t=="object"?{...t,direction:"outbound",e2eSimulated:!0}:null,this.setAvailabilityState("working","测试桥已模拟发起外呼。"),this.setState("calling",t?.message||"测试桥已模拟拨打管理员。"),this.getSnapshot()),simulateOutboundConnected:(t={})=>(this.clearPanelAutoClose(),this.transientPanelState=null,this.transientPanelDetail="",t&&typeof t=="object"&&(this.pendingIncomingCall={...this.pendingIncomingCall||{},...t,direction:"outbound",e2eSimulated:!0}),this.setAvailabilityState("working","测试桥已模拟外呼接通。"),this.setState("connected",t?.message||"测试桥已模拟通话接通。"),this.getSnapshot()),answerIncomingCall:async()=>(await this.answerIncomingCall(),this.getSnapshot()),declineIncomingCall:async()=>(await this.declineIncomingCall(),this.getSnapshot()),hangupCall:async()=>(await this.hangupCall(),this.getSnapshot()),destroyWidget:async()=>(await this.destroy(),null)}}async handlePrimaryAction(){if(this.state==="incoming"){await this.answerIncomingCall();return}["calling","connected"].includes(this.state)||await this.handleTriggerClick()}async handleSecondaryAction(){if(this.state==="incoming"){await this.declineIncomingCall();return}if(["calling","connected"].includes(this.state)&&this.client){await this.hangupCall();return}await this.disconnectAndCleanup("manual-disconnect")}async connectAndCall(){if(["requesting","registering","calling","connected"].includes(this.state))return;const e=this.beginLifecycleRun();try{this.terminalFailureOverride="",this.clearAutoStandbyRecovery(),this.pendingLifecycleMode="outbound",this.setAvailabilityState("working","正在建立呼叫链路。");const t=this.issuedSession?.session_mode==="widget_standby"&&(this.issuedSession?.browser_sip_username||this.issuedSession?.sip_username)||null;!this.legacyOutboundOnly&&this.issuedSession?.session_mode==="widget_standby"&&(this.appendLog("访客主动呼叫前,先释放当前待机会话并切换到呼叫链路。",{widget_anchor_number:this.issuedSession?.widget_anchor_number||null,resolved_business_key:this.issuedSession?.resolved_business_key||le(this.options)||null}),await this.disconnectAndCleanup("switch-to-outbound-call",{preserveLifecycleRun:!0,suppressStateReset:!0,suppressClientTeardownState:"switch-to-outbound-call"}),this.assertLifecycleRunCurrent(e)),this.setState("requesting"),await this.loadBootstrap(),this.assertLifecycleRunCurrent(e),this.turnIceServers=await this.fetchTurnIceServers(),this.assertLifecycleRunCurrent(e);const i=await this.fetchIssuedSession({preferredBrowserSipUsername:t});this.assertLifecycleRunCurrent(e),await this.ensureClient(i),this.assertLifecycleRunCurrent(e),this.setState("registering"),await this.client.ensureReady(),this.assertLifecycleRunCurrent(e),this.setState("calling"),this.syncAvailabilityState(),await this.client.call(i.target),this.assertLifecycleRunCurrent(e),this.appendLog("已发起呼叫",{target:i.target,route_note:i.routeNote||null})}catch(t){if(this.pendingLifecycleMode=null,_t(t)){this.appendLog("已忽略过期的网页电话呼叫流程",{message:t?.message||String(t)});return}if(Oe(t)){await this.handleProtocolViolation(t);return}const i=t?.message||String(t);if(this.terminalFailureOverride=i,this.setState("failed",i),this.setTransientPanelState("failed","当前暂时无法接通,请稍后再试。"),Qe(t)||this.networkOnline===!1?this.setAvailabilityState("offline",this.networkOnline===!1?"当前网络连接已断开,正在等待恢复。":"当前无法连接通话服务,正在自动尝试恢复。"):this.setAvailabilityState("recovering","呼叫失败,正在准备恢复网页电话待机。"),this.appendLog("连接并呼叫失败",{message:i}),await this.releaseIssuedSession("failed","connect-and-call-failed"),!this.legacyOutboundOnly){this.appendLog("呼叫失败后,网页电话将恢复待机。",{message:i}),await this.startStandby({force:!0});return}this.setState("failed",i)}}async startStandby(e={}){if(this.legacyOutboundOnly)throw new Error("当前 widget 仍处于 legacy outbound 兼容模式");const{force:t=!1}=e;if(!t&&["standbyRequesting","registering","incoming","connected"].includes(this.state))return;const i=this.beginLifecycleRun();try{this.clearAutoStandbyRecovery(),this.pendingLifecycleMode="standby",this.terminalFailureOverride="",this.setState("standbyRequesting"),this.setAvailabilityState("preparing","正在申请新的待机会话。"),await this.loadBootstrap(),this.assertLifecycleRunCurrent(i),this.turnIceServers=await this.fetchTurnIceServers(),this.assertLifecycleRunCurrent(i);const s=await this.fetchStandbySession();this.assertLifecycleRunCurrent(i),await this.ensureClient(s),this.assertLifecycleRunCurrent(i),this.setState("registering","待机会话已拿到,正在连接并执行 REGISTER。"),await this.client.ensureReady(),this.assertLifecycleRunCurrent(i),this.pendingLifecycleMode=null,this.setState("standby"),this.setAvailabilityState("ready","当前可被呼叫,也可由访客主动发起呼叫。"),this.appendLog("widget 已进入待机",{session_id:this.issuedSession?.session_id||null,route_business_key:this.issuedSession?.resolved_business_key||le(this.options)||null,standby_mode:this.issuedSession?.standby_mode||null,widget_anchor_number:this.issuedSession?.widget_anchor_number||null,browser_sip_username:this.issuedSession?.browser_sip_username||this.issuedSession?.sip_username||null}),this.emitHostCallback("onStandbyReady",this.getSnapshot())}catch(s){if(_t(s)){this.appendLog("已忽略过期的网页电话待机流程",{message:s?.message||String(s)});return}if(this.pendingLifecycleMode=null,Oe(s)){await this.handleProtocolViolation(s);return}const r=s?.message||String(s);this.terminalFailureOverride=r,this.setState("failed",r),Qe(s)||this.networkOnline===!1?this.setAvailabilityState("offline",this.networkOnline===!1?"当前网络连接已断开,正在等待恢复。":"当前无法连接通话服务,正在自动尝试恢复。"):this.setAvailabilityState("recovering","当前未能完成待机注册,系统会继续自动恢复。"),this.appendLog("进入待机失败",{message:r}),await this.releaseIssuedSession("failed","standby-start-failed"),this.setState("failed",r),!this.legacyOutboundOnly&&this.networkOnline!==!1&&this.scheduleAutoStandbyRecovery("standby-start-failed")}}async ensureClient(e){const t={sip_username:e.sipUsername,sip_password:e.password,sip_domain:e.sipDomain,webrtc_url:e.transport,ice_servers:this.turnIceServers};this.client?.matchesAccount(t)||(this.client&&await this.client.destroy(),this.client=new Si(t,{remoteAudioElement:this.refs.audio,onStateChange:(i,s)=>{this.handleClientState(i,s)},onError:i=>this.appendLog("SIP 客户端错误",{message:i?.message||String(i)})}))}async handleClientState(e,t={}){if(this.syncSessionTouch(e),this.reportIssuedSessionEvent(e,t,e),(e==="connected"||e==="registered"||e==="ringing"||e==="dialing"||e==="answered")&&await this.clearTransportDisconnectGrace(!0),e==="registered"){this.pendingLifecycleMode=null,this.issuedSession?.session_mode==="widget_standby"?(this.setState("standby"),this.setAvailabilityState("ready","当前可被呼叫,也可由访客主动发起呼叫。")):this.setState("registering","REGISTER 已完成,正在准备发起呼叫。");return}if(e==="incoming"){this.pendingLifecycleMode=null,this.pendingIncomingCall=t&&typeof t=="object"?{...t}:null,this.clearPanelAutoClose(),this.transientPanelState=null,this.transientPanelDetail="",this.setState("incoming"),this.setAvailabilityState("working","已有新来电,请直接接听或拒接。"),this.appendLog("收到新的来电",this.pendingIncomingCall),this.emitHostCallback("onIncomingCall",this.pendingIncomingCall);return}if(e==="ringing"||e==="dialing"){this.setState("calling",t?.message||ie.calling);return}if(e==="answered"){this.pendingLifecycleMode=null,this.terminalFailureOverride="";const i=this.pendingIncomingCall||t||null;this.clearPanelAutoClose(),this.transientPanelState=null,this.transientPanelDetail="",this.setState("connected"),this.setAvailabilityState("working","当前通话已接通。"),this.emitHostCallback("onCallAnswered",i);return}if(e==="terminated"){if(this.issuedSession?.session_mode==="widget_standby"){await this.handleStandbyTermination(t);return}t&&typeof t=="object"&&(t.source==="invite-response"||t.source==="invite-exception"||t.code||t.status||t.stage)&&(this.terminalFailureOverride=t?.message||ie.failed,this.setState("failed",this.terminalFailureOverride)),await this.finalizeAfterTermination(t?.hangupSource||"terminated");return}if(e==="failed"){if(this.isExpectedClientTeardown())return;this.pendingLifecycleMode=null,await this.clearTransportDisconnectGrace(!1),this.stopSessionTouch(),this.terminalFailureOverride=t?.message||ie.failed,this.setState("failed",this.terminalFailureOverride),this.setTransientPanelState("failed","当前暂时无法接通,请稍后再试。"),this.setAvailabilityState("recovering","通话链路异常断开,系统会继续自动恢复。"),await this.releaseIssuedSession("failed","sip-client-failed");return}if(e==="disconnected"||e==="unregistered"){if(this.isExpectedClientTeardown()||this.isExpectedTermination()||!this.issuedSession?.session_id&&this.pendingLifecycleMode==="standby")return;if(this.stopSessionTouch(),["calling","connected"].includes(this.state)){this.setState("connected","SIP 信令短暂中断,正在等待恢复。"),this.setAvailabilityState("recovering","通话信令短暂中断,正在等待恢复。"),this.scheduleTransportDisconnectGrace(e);return}const s=this.terminalFailureOverride||this.client?.lastFailureMeta?.message||null;if(s){this.terminalFailureOverride=s,this.setState("failed",s),this.setTransientPanelState("failed","当前暂时无法接通,请稍后再试。");return}if(this.state==="failed")return;this.state!=="idle"&&this.state!=="ended"&&(this.pendingLifecycleMode=null,this.setState("ended"),this.setAvailabilityState("preparing","通话已结束,正在自动返回网页电话待机。"),this.scheduleAutoStandbyRecovery(`client-${e}`))}}stopTransportDisconnectGrace(){this.transportDisconnectTimer&&(window.clearTimeout(this.transportDisconnectTimer),this.transportDisconnectTimer=null),this.transportDisconnectContext=null}sameTransportDisconnectContext(e){return!e||!this.issuedSession?.session_id?!1:e.sessionId===this.issuedSession.session_id}async clearTransportDisconnectGrace(e){const t=this.transportDisconnectContext,i=!!(e&&t?.reported&&this.sameTransportDisconnectContext(t));this.stopTransportDisconnectGrace(),i&&(await this.reportIssuedSessionEvent("transport-restored",{disconnectDurationMs:Date.now()-(t.startedAt||Date.now()),graceMs:Re},this.state),this.appendLog("网页通话信令已恢复",{disconnectDurationMs:Date.now()-(t.startedAt||Date.now()),graceMs:Re}))}scheduleTransportDisconnectGrace(e){if(!this.issuedSession?.session_id)return;this.stopTransportDisconnectGrace();const t={sessionId:this.issuedSession.session_id,startedAt:Date.now(),reported:!1,state:e};this.transportDisconnectContext=t,this.transportDisconnectTimer=window.setTimeout(()=>{this.transportDisconnectTimer=null,this.sameTransportDisconnectContext(t)&&(t.reported=!0,this.reportIssuedSessionEvent("transport-disconnected",{state:e,graceMs:Re},this.state),this.appendLog("网页通话信令断开超过宽限窗口",{graceMs:Re,state:e}))},Re)}async finalizeAfterTermination(e){if(!this.finalizing){this.beginLifecycleRun(),this.finalizing=!0;try{this.pendingLifecycleMode=null,this.stopSessionTouch(),this.stopTransportDisconnectGrace(),await this.releaseIssuedSession("released",e),this.client&&(await this.client.destroy(),this.client=null);const t=this.terminalFailureOverride||(this.state==="failed"?this.stateDetail||ie.failed:"");if(this.setTransientPanelState(t?"failed":"ended",t?"当前暂时无法接通,请稍后再试。":"本次通话已结束。"),!this.legacyOutboundOnly){t?this.setState("failed",t):this.setState("ended"),this.setAvailabilityState("preparing","页面仍在线,正在自动回到待机。"),this.appendLog("通话已结束,网页电话正在自动回到待机。",{reason:e}),await this.startStandby({force:!0});return}t?this.setState("failed",t):this.setState("ended"),this.appendLog("通话已结束并完成清理",{reason:e})}finally{this.finalizing=!1}}}async handleStandbyTermination(e={}){this.stopTransportDisconnectGrace();const t=this.state,i=e?.hangupSource||"terminated";t==="incoming"?(this.incrementMissedIncomingCount(),i==="local"?(this.setState("standby","当前来电已拒接,widget 仍保持可用。"),this.setAvailabilityState("ready","当前来电已拒接,widget 仍保持可用。"),this.emitHostCallback("onCallRejected",this.pendingIncomingCall||e||null)):(this.setState("standby","当前来电未接听,widget 仍保持可用。"),this.setAvailabilityState("ready","当前来电未接听,widget 仍保持可用。"),this.emitHostCallback("onCallMissed",this.pendingIncomingCall||e||null)),this.setTransientPanelState("ended","本次来电已结束。")):(this.setState("standby","上一通来电已结束,继续等待下一通来电。"),this.setAvailabilityState("ready","当前可被呼叫,也可由访客主动发起呼叫。"),this.setTransientPanelState("ended","本次通话已结束。")),this.appendLog("待机会话中的来电已结束",{hangupSource:i,previousState:t}),this.pendingIncomingCall=null}async answerIncomingCall(){if(this.state==="incoming"){if(this.clearPanelAutoClose(),this.transientPanelState=null,this.transientPanelDetail="",this.e2eBridgeEnabled&&this.pendingIncomingCall?.e2eSimulated){this.setState("connected","测试桥已模拟接听当前来电。"),this.emitHostCallback("onCallAnswered",this.pendingIncomingCall);return}if(!this.client&&this.e2eBridgeEnabled){this.setState("connected","测试桥已模拟接听当前来电。"),this.emitHostCallback("onCallAnswered",this.pendingIncomingCall);return}if(!this.client)throw new Error("当前没有可接听的 SIP 会话");await this.client.answer()}}async declineIncomingCall(){if(this.state==="incoming"){if(this.e2eBridgeEnabled&&this.pendingIncomingCall?.e2eSimulated){this.incrementMissedIncomingCount(),this.setState("standby","测试桥已模拟拒接当前来电,网页电话已恢复待机。"),this.setTransientPanelState("ended","本次来电已结束。"),this.setAvailabilityState("ready","当前可被呼叫,也可由访客主动发起呼叫。"),this.emitHostCallback("onCallRejected",this.pendingIncomingCall),this.pendingIncomingCall=null;return}if(!this.client&&this.e2eBridgeEnabled){this.incrementMissedIncomingCount(),this.setState("standby","测试桥已模拟拒接当前来电,网页电话已恢复待机。"),this.setTransientPanelState("ended","本次来电已结束。"),this.setAvailabilityState("ready","当前可被呼叫,也可由访客主动发起呼叫。"),this.emitHostCallback("onCallRejected",this.pendingIncomingCall),this.pendingIncomingCall=null;return}if(!this.client)throw new Error("当前没有可拒接的 SIP 会话");await this.client.decline()}}async hangupCall(){if(this.e2eBridgeEnabled&&this.pendingIncomingCall?.e2eSimulated){this.legacyOutboundOnly?(this.setState("ended"),this.setTransientPanelState("ended","本次通话已结束。")):(this.setState("standby","测试桥已模拟挂断,网页电话已恢复待机。"),this.setTransientPanelState("ended","本次通话已结束。")),this.pendingIncomingCall=null;return}if(!this.client&&this.e2eBridgeEnabled){this.legacyOutboundOnly?(this.setState("ended"),this.setTransientPanelState("ended","本次通话已结束。")):(this.setState("standby","测试桥已模拟挂断,网页电话已恢复待机。"),this.setTransientPanelState("ended","本次通话已结束。")),this.pendingIncomingCall=null;return}this.client&&(this.expectTermination("hangup-call"),this.suppressExpectedClientTeardown("hangup-call"),await this.client.hangup())}async disconnectAndCleanup(e,t={}){const{preserveLifecycleRun:i=!1,suppressStateReset:s=!1,suppressClientTeardownState:r=null}=t;i||this.beginLifecycleRun(),r&&this.suppressExpectedClientTeardown(r),this.stopSessionTouch(),this.stopTransportDisconnectGrace(),this.reportIssuedSessionEvent("manual-disconnect",{reason:e},this.state),this.pendingIncomingCall=null,this.terminalFailureOverride="",this.client&&(await this.client.destroy(),this.client=null),await this.releaseIssuedSession("released",e),s||(this.pendingLifecycleMode=null,this.setState("idle"),this.setAvailabilityState("preparing","网页电话已断开,系统正在自动返回待机。"),this.appendLog("连接已断开",{reason:e}),!this.legacyOutboundOnly&&this.networkOnline!==!1&&this.scheduleAutoStandbyRecovery(e))}async loadBootstrap(){if(this.bootstrap)return this.bootstrap;const e=await fetch(X(this.apiBaseUrl,"api/sip/embedded-call-demo-bootstrap"),{credentials:"include",cache:"no-store"});if(!e.ok)throw new Error(`默认模式读取失败:${e.status}`);return this.bootstrap=await e.json(),this.bootstrap}async fetchTurnIceServers(){const e=await fetch(X(this.apiBaseUrl,"api/sip/webrtc-turn-credentials"),{credentials:"include",cache:"no-store"});if(!e.ok)return this.appendLog("TURN 凭证获取失败,继续尝试直连",{status:e.status}),[];const t=await e.json();return Array.isArray(t?.ice_servers)?t.ice_servers:[]}async fetchIssuedSession(e={}){const{preferredBrowserSipUsername:t=null}=e,i=le(this.options),s={page_url:window.location.href};A(s,"site_key",this.options.siteKey),A(s,"standby_state",this.options.standbyState),A(s,"selected_primary_account",this.options.selectedPrimaryAccount),A(s,"selected_middle_layer_account",this.options.selectedMiddleLayerAccount),A(s,"preferred_browser_sip_username",t),A(s,"display_name",this.options.displayName),A(s,"access_token",this.options.accessToken),i&&(s.business_key=i);const r=await fetch(X(this.apiBaseUrl,"api/sip/issue-call-session"),{method:"POST",credentials:"include",cache:"no-store",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!r.ok){const d=await r.json().catch(()=>({}));throw new Error(d?.detail||`会话签发失败:${r.status}`)}const n=await r.json(),o=xt(n,Ie.outbound,"issue-call-session");return this.markDebugPanelEnabled("issue-call-session",n?.debug_access_granted===!0),this.issuedSession=n,this.reportIssuedSessionEvent("issued-session-fetched",{sessionId:n.session_id,targetExtension:n.target_extension,dialTargetExtension:n.dial_target_extension||n.target_extension,resolvedTargetInternalNumbers:n.resolved_target_internal_numbers||[],resolvedBusinessKey:n.resolved_business_key||null},"requesting"),this.appendLog("已获取服务端签发会话",{session_id:n.session_id,target_extension:n.target_extension,dial_target_extension:n.dial_target_extension||n.target_extension||null,resolved_target_internal_numbers:n.resolved_target_internal_numbers||[],resolved_business_key:n.resolved_business_key||null,resolved_route_mode:n.resolved_route_mode||null,route_note:n.route_note||null}),{sessionMode:o,sipUsername:n.sip_username,sipDomain:n.sip_domain,password:n.sip_password,transport:Tt({apiBaseUrl:this.apiBaseUrl,transportBaseUrl:this.options.transportBaseUrl||"",transportUrl:n.ws_server}),target:n.dial_target_extension||n.target_extension,routeNote:n.route_note||""}}async fetchStandbySession(){const e=le(this.options)||null,t={page_url:window.location.href};A(t,"site_key",this.options.siteKey),A(t,"standby_state",this.options.standbyState),A(t,"selected_primary_account",this.options.selectedPrimaryAccount),A(t,"selected_middle_layer_account",this.options.selectedMiddleLayerAccount),A(t,"display_name",this.options.displayName),A(t,"access_token",this.options.accessToken),e&&(t.business_key=e);const i=await fetch(X(this.apiBaseUrl,"api/sip/issue-widget-standby-session"),{method:"POST",credentials:"include",cache:"no-store",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!i.ok){const n=await i.json().catch(()=>({}));throw new Error(n?.detail||`待机会话签发失败:${i.status}`)}const s=await i.json(),r=xt(s,Ie.standby,"issue-widget-standby-session");return this.markDebugPanelEnabled("issue-widget-standby-session",s?.debug_access_granted===!0),this.issuedSession=s,this.reportIssuedSessionEvent("standby-session-fetched",{sessionId:s.session_id,resolvedBusinessKey:s.resolved_business_key||null,standbyMode:s.standby_mode||null},"standbyRequesting"),this.appendLog("已获取 widget 待机会话",{session_id:s.session_id,resolved_business_key:s.resolved_business_key||null,standby_mode:s.standby_mode||null,standby_state:s.standby_state||null,widget_anchor_number:s.widget_anchor_number||null,browser_sip_username:s.browser_sip_username||s.sip_username||null,route_note:s.route_note||null}),{sessionMode:r,sipUsername:s.sip_username,sipDomain:s.sip_domain,password:s.sip_password,transport:Tt({apiBaseUrl:this.apiBaseUrl,transportBaseUrl:this.options.transportBaseUrl||"",transportUrl:s.ws_server}),target:null,routeNote:s.route_note||""}}async releaseIssuedSession(e,t){if(!this.issuedSession?.session_id)return;const i=this.issuedSession.session_id;this.markRecentlyReleasedSession(i,t),this.issuedSession=null,await fetch(X(this.apiBaseUrl,"api/sip/release-call-session"),{method:"POST",credentials:"include",cache:"no-store",headers:{"Content-Type":"application/json"},body:JSON.stringify({session_id:i,status:e,reason:t,client_summary:this.buildClientEvidenceSummary(e,{releaseReason:t})})}).catch(()=>{})}postLifecycleBeacon(e,t){const i=JSON.stringify(t),s=X(this.apiBaseUrl,e);if(typeof navigator<"u"&&typeof navigator.sendBeacon=="function")try{const r=new Blob([i],{type:"application/json"});if(navigator.sendBeacon(s,r))return!0}catch{}return fetch(s,{method:"POST",credentials:"include",cache:"no-store",keepalive:!0,headers:{"Content-Type":"application/json"},body:i}).catch(()=>{}),!0}flushUnloadCleanup(e){if(this.unloadCleanupStarted||(this.unloadCleanupStarted=!0,this.stopSessionTouch(),this.stopPresenceTouch(),this.stopTransportDisconnectGrace(),!this.issuedSession?.session_id))return;const t=this.issuedSession.session_id;this.markRecentlyReleasedSession(t,e),this.postLifecycleBeacon("api/sip/release-call-session",{session_id:t,status:"released",reason:e,client_summary:this.buildClientEvidenceSummary("released",{releaseReason:e})}),this.issuedSession=null}buildClientEvidenceSummary(e=null,t=null){const i={runtimeMode:"embedded-widget-runtime",widgetVersion:"2026-03-29-runtime-evidence",widgetMode:this.mode,sessionMode:this.issuedSession?.session_mode||null,state:e||this.state,visible:typeof document>"u"?!0:document.visibilityState==="visible",pageUrl:typeof window>"u"?null:window.location.href,connectionSnapshot:this.client?.getConnectionSnapshot?.()||null};return t&&typeof t=="object"&&(i.eventDetail=t),i}buildPresenceEvidenceSummary(e=null,t=null){return{...this.buildClientEvidenceSummary(e,t),presenceId:this.presenceId,availabilityState:this.availabilityState,availabilityDetail:this.availabilityDetail,networkOnline:this.networkOnline,pageVisible:this.pageVisible}}setAvailabilityState(e,t=""){this.availabilityState=e,this.availabilityDetail=t||this.availabilityDetail,this.refs.availability&&(this.refs.availability.textContent=t?`${de[e]||de.recovering} · ${t}`:de[e]||de.recovering,this.refs.availability.className=`availability availability--${e}`),this.render()}suppressExpectedClientTeardown(e,t=ki){this.expectedClientTeardown={reason:e,expiresAt:Date.now()+t}}expectTermination(e,t=1e4){this.expectedTermination={reason:e,expiresAt:Date.now()+t}}clearExpectedTermination(){this.expectedTermination=null}isExpectedTermination(){const e=this.expectedTermination;return e?e.expiresAt<=Date.now()?(this.expectedTermination=null,!1):!0:!1}isExpectedClientTeardown(){const e=this.expectedClientTeardown;return e?e.expiresAt<=Date.now()?(this.expectedClientTeardown=null,!1):!0:!1}clearAutoStandbyRecovery(){this.autoStandbyRecoveryTimer&&(window.clearTimeout(this.autoStandbyRecoveryTimer),this.autoStandbyRecoveryTimer=null)}scheduleAutoStandbyRecovery(e,t=Di){this.legacyOutboundOnly||this.networkOnline===!1||this.autoStandbyRecoveryTimer||this.client||this.issuedSession?.session_id||this.finalizing||this.pendingLifecycleMode==="outbound"||this.sessionRecoveryInFlight||this.connectivityRecoveryInFlight||["requesting","standbyRequesting","registering","calling","incoming","connected"].includes(this.state)||(this.autoStandbyRecoveryTimer=window.setTimeout(()=>{this.autoStandbyRecoveryTimer=null,!(this.legacyOutboundOnly||this.networkOnline===!1)&&(this.client||this.issuedSession?.session_id||this.finalizing||this.pendingLifecycleMode==="outbound"||(this.appendLog("检测到页面当前不在通话中,开始自动进入待机。",{reason:e}),this.startStandby({force:!0})))},t))}pruneRecentlyReleasedSessions(){const e=Date.now();for(const[t,i]of this.recentlyReleasedSessions.entries())(i?.expiresAt||0)<=e&&this.recentlyReleasedSessions.delete(t)}markRecentlyReleasedSession(e,t){e&&(this.pruneRecentlyReleasedSessions(),this.recentlyReleasedSessions.set(e,{reason:t,expiresAt:Date.now()+Pi}))}wasSessionRecentlyReleased(e){return e?(this.pruneRecentlyReleasedSessions(),this.recentlyReleasedSessions.has(e)):!1}syncAvailabilityState(){if(this.networkOnline===!1){this.setAvailabilityState("offline","当前网络连接已断开,正在等待恢复。");return}if(this.state==="incoming"){this.setAvailabilityState("working","已有新来电,请直接接听或拒接。");return}if(this.state==="connected"){this.setAvailabilityState("working","当前通话已接通。");return}if(this.state==="calling"){this.setAvailabilityState("working","正在等待对端振铃或接听。");return}if(this.pendingLifecycleMode==="outbound"&&["requesting","registering"].includes(this.state)){this.setAvailabilityState("working","正在建立呼叫链路。");return}if(["requesting","standbyRequesting","registering"].includes(this.state)){this.setAvailabilityState("preparing","页面仍在线,正在建立网页电话连接。");return}if(!this.legacyOutboundOnly&&!this.issuedSession?.session_id&&!this.pendingLifecycleMode&&["idle","ended","missed","rejected"].includes(this.state)){this.setAvailabilityState("preparing","页面仍在线,正在自动进入网页电话待机。"),this.scheduleAutoStandbyRecovery("missing-issued-session");return}if(!this.legacyOutboundOnly&&!this.issuedSession?.session_id&&!this.pendingLifecycleMode&&!["calling","connected","incoming"].includes(this.state)){this.setAvailabilityState("preparing","页面仍在线,正在重新建立网页电话待机。"),this.scheduleAutoStandbyRecovery("missing-issued-session");return}this.setAvailabilityState("ready","当前可被呼叫,也可由访客主动发起呼叫。")}stopPresenceTouch(){this.presenceTouchTimer&&(window.clearInterval(this.presenceTouchTimer),this.presenceTouchTimer=null)}async restartStandbyAfterConnectivity(e){if(!(this.legacyOutboundOnly||this.connectivityRecoveryInFlight)&&!["connected","incoming","calling","requesting","standbyRequesting","registering"].includes(this.state)){this.connectivityRecoveryInFlight=(async()=>{this.appendLog("检测到连通性已恢复,准备重建网页电话待机。",{trigger:e,state:this.state,hasSession:!!this.issuedSession?.session_id}),(this.client||this.issuedSession?.session_id)&&await this.disconnectAndCleanup(`connectivity-restored-${e}`),await this.startStandby({force:!0})})();try{await this.connectivityRecoveryInFlight}finally{this.connectivityRecoveryInFlight=null}}}async handleServerSessionAction(e,t={}){if(this.legacyOutboundOnly)return!1;const i=Ui(e,t);if(i.action!==Xe.restartStandby)return!1;const s=se(this.issuedSession?.session_mode),r=se(this.pendingLifecycleMode),n=s===Ie.outbound||r===Et.outbound,o=s===Ie.standby||r===Et.standby;if(n||!o)throw L("非待机协议上下文收到了非法的 restart_standby 指令。",{source:e,state:this.state,local_session_mode:s||null,local_lifecycle_mode:r||null,session_action:i.action,session_action_reason:i.reason,session_action_detail:i.detail,resolved_session_id:i.resolvedSessionId,resolved_widget_anchor_number:i.resolvedWidgetAnchorNumber,resolved_browser_sip_username:i.resolvedBrowserSipUsername});if(this.sessionRecoveryInFlight||this.connectivityRecoveryInFlight)return!1;this.sessionRecoveryInFlight=(async()=>{this.appendLog("服务端要求当前页面立即放弃旧锚点并重建待机。",{source:e,state:this.state,local_session_mode:s||null,local_lifecycle_mode:r||null,session_action_reason:i.reason,session_action_detail:i.detail,resolved_session_id:i.resolvedSessionId,resolved_widget_anchor_number:i.resolvedWidgetAnchorNumber,resolved_browser_sip_username:i.resolvedBrowserSipUsername}),this.setAvailabilityState("recovering",i.detail||"当前锚点已失效,正在自动切换到新的待机线路。"),(this.client||this.issuedSession?.session_id)&&await this.disconnectAndCleanup(`server-session-action-${i.reason||e}`,{preserveLifecycleRun:!0,suppressStateReset:!0}),await this.startStandby({force:!0})})();try{await this.sessionRecoveryInFlight}finally{this.sessionRecoveryInFlight=null}return!0}async handleProtocolViolation(e){const t=e?.detail&&typeof e.detail=="object"?e.detail:{},i={violation_code:e?.code||"widget_protocol_violation",violation_name:e?.name||"EmbeddedCallWidgetProtocolViolationError",violation_message:e?.message||String(e),...t};this.appendLog("协议错误:当前页面收到了非法的运行态指令,已拒绝执行并保留现有通话状态。",i),typeof console<"u"&&typeof console.error=="function"&&console.error("[embedded-call-widget] protocol violation",i),await this.reportIssuedSessionEvent("protocol-violation",i),!["calling","connected","incoming"].includes(this.state)&&(this.pendingLifecycleMode=null,this.clearAutoStandbyRecovery(),this.stopSessionTouch(),this.stopPresenceTouch(),this.terminalFailureOverride=i.violation_message,this.setState("failed",i.violation_message),this.setAvailabilityState("conflicted","检测到前后端协议不一致,已停止自动恢复,请尽快排查。"))}async touchWidgetPresence(e="interval"){if(this.legacyOutboundOnly)return;this.networkOnline=typeof navigator>"u"?!0:navigator.onLine!==!1,this.pageVisible=typeof document>"u"?!0:document.visibilityState==="visible";const t=this.availabilityState==="offline";try{const i=await fetch(X(this.apiBaseUrl,"api/sip/touch-widget-presence"),{method:"POST",credentials:"include",cache:"no-store",keepalive:!0,headers:{"Content-Type":"application/json"},body:JSON.stringify((()=>{const n={presence_id:this.presenceId,state:this.state,page_url:typeof window>"u"?void 0:window.location.href,visible:this.pageVisible,network_online:this.networkOnline,client_summary:this.buildPresenceEvidenceSummary(this.state,{trigger:e})};return A(n,"site_key",this.options.siteKey),A(n,"requested_business_key",le(this.options)),A(n,"resolved_business_key",this.issuedSession?.resolved_business_key),A(n,"display_name",this.options.displayName),A(n,"session_id",this.issuedSession?.session_id),A(n,"session_mode",this.issuedSession?.session_mode),A(n,"widget_anchor_number",this.issuedSession?.widget_anchor_number),A(n,"browser_sip_username",this.issuedSession?.browser_sip_username||this.issuedSession?.sip_username),A(n,"standby_mode",this.issuedSession?.standby_mode),A(n,"standby_state",this.issuedSession?.standby_state||this.options.standbyState),A(n,"selected_primary_account",this.options.selectedPrimaryAccount),A(n,"selected_middle_layer_account",this.options.selectedMiddleLayerAccount),A(n,"route_note",this.issuedSession?.route_note),n})())});if(!i.ok)throw new Error(`运行态心跳失败:${i.status}`);const s=await i.json().catch(()=>({}));this.presenceFailureCount=0,await this.handleServerSessionAction("touch-widget-presence",s)||this.syncAvailabilityState(),t&&await this.restartStandbyAfterConnectivity(`presence-${e}`)}catch(i){if(Oe(i)){await this.handleProtocolViolation(i),this.syncAvailabilityState();return}if(this.presenceFailureCount+=1,this.networkOnline===!1||Qe(i)||this.presenceFailureCount>=Ct){const r=this.networkOnline===!1?"当前网络连接已断开,正在等待恢复。":"当前无法连接通话服务,正在自动尝试恢复。";this.setAvailabilityState("offline",r)}else this.setAvailabilityState("recovering","正在确认后台连接状态。");this.presenceFailureCount<=Ct&&this.appendLog("widget 运行态心跳失败",{trigger:e,failure_count:this.presenceFailureCount,message:i?.message||String(i)})}}startPresenceTouch(){this.legacyOutboundOnly||(this.touchWidgetPresence("mount"),this.presenceTouchTimer||(this.presenceTouchTimer=window.setInterval(()=>{this.touchWidgetPresence("interval")},$i)))}async touchIssuedSession(e,t=null){if(!this.issuedSession?.session_id)return;const i=this.issuedSession.session_id;try{const s=await fetch(X(this.apiBaseUrl,"api/sip/touch-call-session"),{method:"POST",credentials:"include",cache:"no-store",keepalive:!0,headers:{"Content-Type":"application/json"},body:JSON.stringify({session_id:i,state:e,client_summary:this.buildClientEvidenceSummary(e,t)})});if(!s.ok){const n=new Error(`会话心跳失败:${s.status}`);throw n.status=s.status,n}const r=await s.json().catch(()=>({}));await this.handleServerSessionAction("touch-call-session",r)}catch(s){if(Oe(s)){await this.handleProtocolViolation(s);return}if(s?.status===404&&this.wasSessionRecentlyReleased(i))return;this.appendLog("网页通话会话心跳失败",{session_id:i,state:e,message:s?.message||String(s)}),s?.status===404&&this.handleMissingIssuedSession(i,e)}}async handleMissingIssuedSession(e,t){if(!(this.sessionRecoveryInFlight||this.issuedSession?.session_id!==e)){this.sessionRecoveryInFlight=(async()=>{this.stopSessionTouch(),this.appendLog("网页电话待机会话已失效,准备自动恢复。",{session_id:e,state:t}),this.setAvailabilityState("recovering","原待机会话已失效,正在自动恢复。"),this.issuedSession?.session_id===e&&(this.issuedSession=null),!this.legacyOutboundOnly&&["standby","registering","standbyRequesting","failed","idle","missed","rejected","ended"].includes(this.state)&&(this.setState("standbyRequesting","待机会话已失效,正在自动重新进入待机。"),await this.startStandby({force:!0}))})();try{await this.sessionRecoveryInFlight}finally{this.sessionRecoveryInFlight=null}}}async reportIssuedSessionEvent(e,t=null,i=null){if(!this.issuedSession?.session_id)return;const s=this.issuedSession.session_id,r=i||this.state;let n=null,o="";try{const d=await fetch(X(this.apiBaseUrl,"api/sip/report-call-session-event"),{method:"POST",credentials:"include",cache:"no-store",keepalive:!0,headers:{"Content-Type":"application/json"},body:JSON.stringify({session_id:s,source:"widget-runtime",event:e,state:r,detail:this.buildClientEvidenceSummary(r,t)})});if(!d.ok){n=d.status;const u=await d.json().catch(()=>({}));throw o=u?.detail?String(u.detail):"",new Error(o||`事件留证失败:${d.status}`)}}catch(d){await fetch(X(this.apiBaseUrl,"api/sip/report-call-session-event-delivery-failure"),{method:"POST",credentials:"include",cache:"no-store",keepalive:!0,headers:{"Content-Type":"application/json"},body:JSON.stringify({session_id:s,source:"widget-runtime",event:e,state:r,detail:this.buildClientEvidenceSummary(r,t),delivery_error:{status:typeof n=="number"?n:null,detail:o||"",message:d?.message||String(d)}})}).catch(()=>{}),this.appendLog("网页通话事件留证失败",{session_id:s,event:e,state:r,message:d?.message||String(d)})}}stopSessionTouch(){this.sessionTouchTimer&&(window.clearInterval(this.sessionTouchTimer),this.sessionTouchTimer=null)}syncSessionTouch(e){if(!(!!this.issuedSession?.session_id&&["connected","registered","dialing","ringing","answered","standby","incoming"].includes(e))){this.stopSessionTouch();return}this.touchIssuedSession(e),this.sessionTouchTimer||(this.sessionTouchTimer=window.setInterval(()=>{this.touchIssuedSession(this.state)},Ai))}setState(e,t=""){this.state=e,this.stateDetail=t||ie[e]||ie.idle,this.syncAvailabilityState(),this.render(),this.emitHostCallback("onStateChange",this.getSnapshot())}appendLog(e,t){if(!this.refs.logs)return;const i=document.createElement("div");for(i.className="log",i.textContent=qi(e,t),this.refs.logs.prepend(i);this.refs.logs.children.length>8;)this.refs.logs.lastElementChild?.remove()}render(){const e=this.getVisibleState(),t=e!=="idle",i=this.pendingIncomingCall?.displayName||this.pendingIncomingCall?.user||"管理员",s=["requesting","registering","calling","connected","incoming"].includes(this.state);let r="网页通话",n=this.options.text||"联系管理员",o=this.transientPanelDetail||"",d=null,u=null;e==="ringing"?(r="网页来电",n=i,o=o||"对方正在呼叫你,请选择接听或挂断。",d={text:"接听",className:"btn btn-primary",disabled:!1},u={text:"挂断",className:"btn btn-danger",disabled:!1}):e==="dialing"?(r="正在呼叫",o=o||"正在为你接通管理员,请稍候。",u={text:"挂断",className:"btn btn-danger",disabled:!1}):e==="connected"?(r="通话进行中",n=this.pendingIncomingCall?.displayName||n,o=o||"通话已接通,如需结束请点击挂断。",u={text:"挂断",className:"btn btn-danger",disabled:!1}):e==="ended"?(r="通话已结束",o=o||"本次通话已结束。"):e==="failed"&&(r="暂未接通",o=o||"当前暂时无法接通,请稍后再试。");const h=this.missedIncomingCount>0?String(this.missedIncomingCount):this.triggerHintDismissed?"":" ";this.refs.trigger.disabled=s,this.refs.triggerBadge.hidden=!h,this.refs.triggerBadge.textContent=h,this.refs.triggerBadge.className=this.missedIncomingCount>0?"trigger-badge":"trigger-badge trigger-badge--dot",this.refs.panelShell.className=t?"panel-shell panel-shell--visible":"panel-shell",this.refs.panel.setAttribute("aria-hidden",t?"false":"true"),this.refs.panelEyebrow.textContent=r,this.refs.panelTitle.textContent=n,this.refs.status.textContent=Ze[e]||Ze.idle,this.refs.status.className=e==="failed"?"status status--failed":"status",this.refs.panelDetail.textContent=o,this.refs.primary.hidden=!d,d?(this.refs.primary.textContent=d.text,this.refs.primary.className=d.className,this.refs.primary.disabled=d.disabled):this.refs.primary.textContent="",this.refs.secondary.hidden=!u,u?(this.refs.secondary.textContent=u.text,this.refs.secondary.className=u.className,this.refs.secondary.disabled=u.disabled):this.refs.secondary.textContent="";const m=+!!d+ +!!u;this.refs.actions.className=m<=1?"actions actions--single":"actions";const S=String(this.options.siteKey||"").trim(),x=String(this.bootstrap?.default_site_key||"").trim(),_=String(le(this.options)||"").trim(),C=String(this.bootstrap?.default_business_key||"").trim(),Q=S||(x?`${x}(服务端默认站点)`:"等待服务端解析"),p=this.issuedSession?.resolved_business_key||_||(C?`${C}(服务端默认规则)`:"等待服务端解析");this.legacyOutboundOnly?this.refs.meta.textContent=`入站规则:${p};站点键:${Q}`:this.refs.meta.textContent=`站点键:${Q};网页电话会先进入可被叫待机;访客主动呼叫默认规则:${p}`,this.refs.availability.textContent=this.availabilityDetail?`${de[this.availabilityState]||de.recovering} · ${this.availabilityDetail}`:de[this.availabilityState]||de.recovering,this.refs.availability.className=`availability availability--${this.availabilityState}`,this.availabilityState==="offline"?this.refs.hint.textContent=this.networkOnline===!1?"当前浏览器网络已断开。系统会在网络恢复后自动尝试重连网页电话。":"当前无法连接通话服务。系统会继续自动恢复,暂时不要重复点击。":this.availabilityState==="preparing"?this.refs.hint.textContent="当前正在准备待机能力。只要页面在线,系统会自动进入可呼入、可呼出的网页电话状态。":this.availabilityState==="working"?this.state==="incoming"?this.refs.hint.textContent="当前已有来电,直接接听或拒接即可;处理完成后会自动回到待机。":this.state==="connected"?this.refs.hint.textContent="当前通话已接通,挂断后会自动回到待机,不需要额外刷新页面。":this.refs.hint.textContent="当前正在切换到外呼链路,请等待振铃、接通或自动回到待机。":this.availabilityState==="recovering"?this.refs.hint.textContent="当前页面仍在线,系统正在自动恢复可被叫待机,不需要刷新页面或手动切换模式。":this.availabilityState==="conflicted"?this.refs.hint.textContent="检测到前后端协议不一致,当前已停止自动恢复。请先排查版本和协议口径,再继续使用。":this.refs.hint.textContent=this.isMobileViewport?Ri:"桌面网页可直接使用;若宿主站点启用了来源白名单或接入令牌,请按站点配置提供对应参数。",this.refs.debugPanel.hidden=!this.debugPanelEnabled}async destroy(){this.clearAutoStandbyRecovery(),this.clearPanelAutoClose(),await this.disconnectAndCleanup("destroy-widget",{suppressStateReset:!0}),typeof document<"u"&&this.visibilityHandler&&(document.removeEventListener("visibilitychange",this.visibilityHandler),this.visibilityHandler=null),this.stopSessionTouch(),this.stopPresenceTouch(),this.stopTransportDisconnectGrace(),this.pendingLifecycleMode=null,this.pendingIncomingCall=null,typeof window<"u"&&(this.onlineHandler&&(window.removeEventListener("online",this.onlineHandler),this.onlineHandler=null),this.offlineHandler&&(window.removeEventListener("offline",this.offlineHandler),this.offlineHandler=null),this.beforeUnloadHandler&&(window.removeEventListener("beforeunload",this.beforeUnloadHandler),this.beforeUnloadHandler=null),this.pageHideHandler&&(window.removeEventListener("pagehide",this.pageHideHandler),this.pageHideHandler=null)),this.e2eBridgeEnabled&&typeof window<"u"&&window.__embeddedCallWidgetE2E__&&delete window.__embeddedCallWidgetE2E__,this.shadowRoot.innerHTML=""}}function Rt(a){return new Wi(a)}return typeof window<"u"&&(window.__EmbeddedCallWidgetRuntime__={createEmbeddedCallWidgetRuntime:Rt}),Fe.createEmbeddedCallWidgetRuntime=Rt,Object.defineProperty(Fe,Symbol.toStringTag,{value:"Module"}),Fe})({});
|
|
321
|
+
`,this.refs.trigger=this.shadowRoot.querySelector('[data-role="trigger"]'),this.refs.triggerBadge=this.shadowRoot.querySelector('[data-role="trigger-badge"]'),this.refs.panelShell=this.shadowRoot.querySelector('[data-role="panel-shell"]'),this.refs.panel=this.shadowRoot.querySelector('[data-role="panel"]'),this.refs.panelEyebrow=this.shadowRoot.querySelector('[data-role="panel-eyebrow"]'),this.refs.panelTitle=this.shadowRoot.querySelector('[data-role="panel-title"]'),this.refs.panelDetail=this.shadowRoot.querySelector('[data-role="panel-detail"]'),this.refs.actions=this.shadowRoot.querySelector('[data-role="actions"]'),this.refs.status=this.shadowRoot.querySelector('[data-role="status"]'),this.refs.debugPanel=this.shadowRoot.querySelector('[data-role="debug-panel"]'),this.refs.availability=this.shadowRoot.querySelector('[data-role="availability"]'),this.refs.hint=this.shadowRoot.querySelector('[data-role="hint"]'),this.refs.meta=this.shadowRoot.querySelector('[data-role="meta"]'),this.refs.primary=this.shadowRoot.querySelector('[data-role="primary"]'),this.refs.secondary=this.shadowRoot.querySelector('[data-role="secondary"]'),this.refs.logs=this.shadowRoot.querySelector('[data-role="logs"]'),this.refs.audio=this.shadowRoot.querySelector('[data-role="audio"]'),this.refs.trigger.addEventListener("click",()=>{this.handleTriggerClick()}),this.refs.primary.addEventListener("click",()=>{this.handlePrimaryAction()}),this.refs.secondary.addEventListener("click",()=>{this.handleSecondaryAction()}),this.bindPageLifecycle(),this.registerE2EBridge(),this.startPresenceTouch(),this.render()}bindPageLifecycle(){typeof document>"u"||(this.visibilityHandler=()=>{if(this.pageVisible=document.visibilityState==="visible",document.visibilityState==="hidden"){this.reportIssuedSessionEvent("visibility-hidden",{visible:!1}),this.touchWidgetPresence("visibility-hidden"),this.issuedSession?.session_id&&this.touchIssuedSession(this.state,{trigger:"visibility-hidden"}),this.appendLog("页面已切到后台",{state:this.state,advice:"系统会继续自动保活;回到前台后请确认页面仍保持活动。"}),this.isMobileViewport&&["requesting","registering","calling","connected"].includes(this.state)&&(this.stateDetail="页面已切到后台;手机网页回到前台后请确认通话仍在继续。",this.render());return}if(this.isMobileViewport&&(this.appendLog("页面已回到前台",{state:this.state}),["requesting","registering","calling","connected"].includes(this.state)&&(this.stateDetail=se[this.state]||se.idle,this.render())),this.touchWidgetPresence("visibility-visible"),!this.legacyOutboundOnly&&["standby","registering","standbyRequesting","failed","idle","missed","rejected","ended"].includes(this.state)){const e=this.client?.getConnectionSnapshot?.()||null,t=!!(e?.connected&&(this.state!=="standby"||e?.registered));this.issuedSession?.session_id&&t?this.touchIssuedSession(this.state,{trigger:"visibility-visible"}):(this.appendLog("页面回到前台后检测到待机链路未处于健康状态,准备自动重建。",{state:this.state,has_session:!!this.issuedSession?.session_id,client_snapshot:e}),this.client||this.issuedSession?.session_id?this.disconnectAndCleanup("visibility-visible-unhealthy-client"):this.startStandby({force:!0}))}this.reportIssuedSessionEvent("visibility-visible",{visible:!0}),this.render()},document.addEventListener("visibilitychange",this.visibilityHandler),typeof window<"u"&&(this.onlineHandler=()=>{this.networkOnline=!0,this.setAvailabilityState("recovering","网络已恢复,正在重新连接网页电话。"),this.touchWidgetPresence("browser-online"),this.legacyOutboundOnly||this.restartStandbyAfterConnectivity("browser-online")},this.offlineHandler=()=>{this.networkOnline=!1,this.setAvailabilityState("offline","当前网络连接已断开,正在等待恢复。"),["incoming","connected"].includes(this.state)?this.render():this.setState("failed","当前网络连接已断开,正在等待恢复。")},window.addEventListener("online",this.onlineHandler),window.addEventListener("offline",this.offlineHandler),this.beforeUnloadHandler=()=>{this.flushUnloadCleanup("beforeunload")},this.pageHideHandler=e=>{e?.persisted||this.flushUnloadCleanup("pagehide")},window.addEventListener("beforeunload",this.beforeUnloadHandler),window.addEventListener("pagehide",this.pageHideHandler)))}open(){this.mountNode.scrollIntoView({block:"nearest",inline:"nearest"})}beginLifecycleRun(){return this.lifecycleRunId+=1,this.lifecycleRunId}assertLifecycleRunCurrent(e){if(e!==this.lifecycleRunId)throw Gi("网页电话已切换到新的连接流程,旧流程不再继续。")}emitHostCallback(e,t){const i=this.options?.[e];if(Bi(i))try{i(t)}catch(s){this.appendLog("宿主回调执行失败",{callback:e,message:s?.message||String(s)})}}getSnapshot(){const e=this.getVisibleState();return{mode:this.mode,state:this.state,stateDetail:this.stateDetail,visibleState:e,panelOpen:this.isPanelVisible(),sessionMode:this.issuedSession?.session_mode||null,sessionId:this.issuedSession?.session_id||null,siteKey:this.options.siteKey||this.bootstrap?.default_site_key||null,businessKey:this.issuedSession?.resolved_business_key||le(this.options,this.bootstrap)||null,standbyMode:this.issuedSession?.standby_mode||null,standbyState:this.issuedSession?.standby_state||this.options.standbyState||null,widgetSipNumber:this.issuedSession?.widget_anchor_number||null,browserSipUsername:this.issuedSession?.browser_sip_username||this.issuedSession?.sip_username||null,routeNote:this.issuedSession?.route_note||null,incomingAnchors:Array.isArray(this.issuedSession?.incoming_anchors)?this.issuedSession.incoming_anchors:[],hasClient:!!this.client,hasIssuedSession:!!this.issuedSession?.session_id,primaryText:this.refs.primary?.textContent?.trim()||"",secondaryText:this.refs.secondary?.textContent?.trim()||"",statusText:this.refs.status?.textContent?.trim()||"",availabilityState:this.availabilityState,availabilityLabel:this.refs.availability?.textContent?.trim()||"",triggerBadge:this.refs.triggerBadge?.textContent?.trim()||"",missedIncomingCount:this.missedIncomingCount,triggerHintDismissed:this.triggerHintDismissed,debugRequested:this.debugRequested,debugPanelEnabled:this.debugPanelEnabled,presenceId:this.presenceId,networkOnline:this.networkOnline,pendingIncomingCall:this.pendingIncomingCall}}getVisibleState(){if(this.transientPanelState)return this.transientPanelState;if(this.state==="incoming")return"ringing";const e=Q(this.issuedSession?.session_mode),t=this.pendingLifecycleMode==="outbound",i=this.state==="registering"&&e==="outbound";return this.state==="calling"||i||t&&["requesting","registering"].includes(this.state)?"dialing":this.state==="connected"?"connected":"idle"}isPanelVisible(){return this.getVisibleState()!=="idle"}clearPanelAutoClose(){this.panelAutoCloseTimer&&(window.clearTimeout(this.panelAutoCloseTimer),this.panelAutoCloseTimer=null)}clearTransientPanelState(){this.clearPanelAutoClose(),this.transientPanelState=null,this.transientPanelDetail="",this.render()}setTransientPanelState(e,t="",i=Ii){this.clearPanelAutoClose(),this.transientPanelState=e,this.transientPanelDetail=t,this.render(),i>0&&(this.panelAutoCloseTimer=window.setTimeout(()=>{this.panelAutoCloseTimer=null,this.transientPanelState=null,this.transientPanelDetail="",this.render()},i))}markDebugPanelEnabled(e,t){!this.debugRequested||!this.hasAccessToken||!t||this.debugPanelEnabled||(this.debugPanelEnabled=!0,this.appendLog("调试模式门禁已成立,开始展示调试面板。",{source:e}),this.render())}dismissTriggerHint(){this.triggerHintDismissed||(this.triggerHintDismissed=!0,Fi(this.triggerHintStorageKey,!0))}clearMissedIncomingCount(){this.missedIncomingCount&&(this.missedIncomingCount=0)}incrementMissedIncomingCount(){this.missedIncomingCount+=1}async handleTriggerClick(){if(this.dismissTriggerHint(),this.clearMissedIncomingCount(),this.clearTransientPanelState(),this.open(),["requesting","registering","calling","connected","incoming"].includes(this.state)){this.render();return}await this.connectAndCall()}registerE2EBridge(){if(!this.e2eBridgeEnabled||typeof window>"u")return;const e=window.location.hostname||"example.invalid";window.__embeddedCallWidgetE2E__={getSnapshot:()=>this.getSnapshot(),simulateIncomingCall:(t={})=>{const i=t.host||e,s=t.user||"2001";return this.pendingIncomingCall={displayName:t.displayName||"测试来电",user:s,host:i,direction:"inbound",uri:t.uri||`sip:${s}@${i}`,e2eSimulated:!0},this.clearPanelAutoClose(),this.transientPanelState=null,this.transientPanelDetail="",this.setAvailabilityState("working","已有新来电,请直接接听或挂断。"),this.setState("incoming"),this.emitHostCallback("onIncomingCall",this.pendingIncomingCall),this.getSnapshot()},simulateOutboundDialing:(t={})=>(this.dismissTriggerHint(),this.clearMissedIncomingCount(),this.clearPanelAutoClose(),this.transientPanelState=null,this.transientPanelDetail="",this.pendingIncomingCall=t&&typeof t=="object"?{...t,direction:"outbound",e2eSimulated:!0}:null,this.setAvailabilityState("working","测试桥已模拟发起外呼。"),this.setState("calling",t?.message||"测试桥已模拟拨打管理员。"),this.getSnapshot()),simulateOutboundConnected:(t={})=>(this.clearPanelAutoClose(),this.transientPanelState=null,this.transientPanelDetail="",t&&typeof t=="object"&&(this.pendingIncomingCall={...this.pendingIncomingCall||{},...t,direction:"outbound",e2eSimulated:!0}),this.setAvailabilityState("working","测试桥已模拟外呼接通。"),this.setState("connected",t?.message||"测试桥已模拟通话接通。"),this.getSnapshot()),answerIncomingCall:async()=>(await this.answerIncomingCall(),this.getSnapshot()),declineIncomingCall:async()=>(await this.declineIncomingCall(),this.getSnapshot()),hangupCall:async()=>(await this.hangupCall(),this.getSnapshot()),destroyWidget:async()=>(await this.destroy(),null)}}async handlePrimaryAction(){if(this.state==="incoming"){await this.answerIncomingCall();return}["calling","connected"].includes(this.state)||await this.handleTriggerClick()}async handleSecondaryAction(){if(this.state==="incoming"){await this.declineIncomingCall();return}if(["calling","connected"].includes(this.state)&&this.client){await this.hangupCall();return}await this.disconnectAndCleanup("manual-disconnect")}async connectAndCall(){if(["requesting","registering","calling","connected"].includes(this.state))return;const e=this.beginLifecycleRun();try{this.terminalFailureOverride="",this.clearAutoStandbyRecovery(),this.pendingLifecycleMode="outbound",this.setAvailabilityState("working","正在建立呼叫链路。");const t=this.issuedSession?.session_mode==="widget_standby"&&(this.issuedSession?.browser_sip_username||this.issuedSession?.sip_username)||null;!this.legacyOutboundOnly&&this.issuedSession?.session_mode==="widget_standby"&&(this.appendLog("访客主动呼叫前,先释放当前待机会话并切换到呼叫链路。",{widget_anchor_number:this.issuedSession?.widget_anchor_number||null,resolved_business_key:this.issuedSession?.resolved_business_key||le(this.options)||null}),await this.disconnectAndCleanup("switch-to-outbound-call",{preserveLifecycleRun:!0,suppressStateReset:!0,suppressClientTeardownState:"switch-to-outbound-call"}),this.assertLifecycleRunCurrent(e)),this.setState("requesting"),await this.loadBootstrap(),this.assertLifecycleRunCurrent(e),this.turnIceServers=await this.fetchTurnIceServers(),this.assertLifecycleRunCurrent(e);const i=await this.fetchIssuedSession({preferredBrowserSipUsername:t});this.assertLifecycleRunCurrent(e),await this.ensureClient(i),this.assertLifecycleRunCurrent(e),this.setState("registering"),await this.client.ensureReady(),this.assertLifecycleRunCurrent(e),this.setState("calling"),this.syncAvailabilityState(),await this.client.call(i.target),this.assertLifecycleRunCurrent(e),this.appendLog("已发起呼叫",{target:i.target,route_note:i.routeNote||null})}catch(t){if(this.pendingLifecycleMode=null,_t(t)){this.appendLog("已忽略过期的网页电话呼叫流程",{message:t?.message||String(t)});return}if(Oe(t)){await this.handleProtocolViolation(t);return}const i=t?.message||String(t);if(this.terminalFailureOverride=i,this.setState("failed",i),this.setTransientPanelState("failed","当前暂时无法接通,请稍后再试。"),Qe(t)||this.networkOnline===!1?this.setAvailabilityState("offline",this.networkOnline===!1?"当前网络连接已断开,正在等待恢复。":"当前无法连接通话服务,正在自动尝试恢复。"):this.setAvailabilityState("recovering","呼叫失败,正在准备恢复网页电话待机。"),this.appendLog("连接并呼叫失败",{message:i}),await this.releaseIssuedSession("failed","connect-and-call-failed"),!this.legacyOutboundOnly){this.appendLog("呼叫失败后,网页电话将恢复待机。",{message:i}),await this.startStandby({force:!0});return}this.setState("failed",i)}}async startStandby(e={}){if(this.legacyOutboundOnly)throw new Error("当前 widget 仍处于 legacy outbound 兼容模式");const{force:t=!1}=e;if(!t&&["standbyRequesting","registering","incoming","connected"].includes(this.state))return;const i=this.beginLifecycleRun();try{this.clearAutoStandbyRecovery(),this.pendingLifecycleMode="standby",this.terminalFailureOverride="",this.setState("standbyRequesting"),this.setAvailabilityState("preparing","正在申请新的待机会话。"),await this.loadBootstrap(),this.assertLifecycleRunCurrent(i),this.turnIceServers=await this.fetchTurnIceServers(),this.assertLifecycleRunCurrent(i);const s=await this.fetchStandbySession();this.assertLifecycleRunCurrent(i),await this.ensureClient(s),this.assertLifecycleRunCurrent(i),this.setState("registering","待机会话已拿到,正在连接并执行 REGISTER。"),await this.client.ensureReady(),this.assertLifecycleRunCurrent(i),this.pendingLifecycleMode=null,this.setState("standby"),this.setAvailabilityState("ready","当前可被呼叫,也可由访客主动发起呼叫。"),this.appendLog("widget 已进入待机",{session_id:this.issuedSession?.session_id||null,route_business_key:this.issuedSession?.resolved_business_key||le(this.options)||null,standby_mode:this.issuedSession?.standby_mode||null,widget_anchor_number:this.issuedSession?.widget_anchor_number||null,browser_sip_username:this.issuedSession?.browser_sip_username||this.issuedSession?.sip_username||null}),this.emitHostCallback("onStandbyReady",this.getSnapshot())}catch(s){if(_t(s)){this.appendLog("已忽略过期的网页电话待机流程",{message:s?.message||String(s)});return}if(this.pendingLifecycleMode=null,Oe(s)){await this.handleProtocolViolation(s);return}const r=s?.message||String(s);this.terminalFailureOverride=r,this.setState("failed",r),Qe(s)||this.networkOnline===!1?this.setAvailabilityState("offline",this.networkOnline===!1?"当前网络连接已断开,正在等待恢复。":"当前无法连接通话服务,正在自动尝试恢复。"):this.setAvailabilityState("recovering","当前未能完成待机注册,系统会继续自动恢复。"),this.appendLog("进入待机失败",{message:r}),await this.releaseIssuedSession("failed","standby-start-failed"),this.setState("failed",r),!this.legacyOutboundOnly&&this.networkOnline!==!1&&this.scheduleAutoStandbyRecovery("standby-start-failed")}}async ensureClient(e){const t={sip_username:e.sipUsername,sip_password:e.password,sip_domain:e.sipDomain,webrtc_url:e.transport,ice_servers:this.turnIceServers};this.client?.matchesAccount(t)||(this.client&&await this.client.destroy(),this.client=new Si(t,{remoteAudioElement:this.refs.audio,onStateChange:(i,s)=>{this.handleClientState(i,s)},onError:i=>this.appendLog("SIP 客户端错误",{message:i?.message||String(i)})}))}async handleClientState(e,t={}){if(this.syncSessionTouch(e),this.reportIssuedSessionEvent(e,t,e),(e==="connected"||e==="registered"||e==="ringing"||e==="dialing"||e==="answered")&&await this.clearTransportDisconnectGrace(!0),e==="registered"){this.pendingLifecycleMode=null,this.issuedSession?.session_mode==="widget_standby"?(this.setState("standby"),this.setAvailabilityState("ready","当前可被呼叫,也可由访客主动发起呼叫。")):this.setState("registering","REGISTER 已完成,正在准备发起呼叫。");return}if(e==="incoming"){this.pendingLifecycleMode=null,this.pendingIncomingCall=t&&typeof t=="object"?{...t}:null,this.clearPanelAutoClose(),this.transientPanelState=null,this.transientPanelDetail="",this.setState("incoming"),this.setAvailabilityState("working","已有新来电,请直接接听或拒接。"),this.appendLog("收到新的来电",this.pendingIncomingCall),this.emitHostCallback("onIncomingCall",this.pendingIncomingCall);return}if(e==="ringing"||e==="dialing"){this.setState("calling",t?.message||se.calling);return}if(e==="answered"){this.pendingLifecycleMode=null,this.terminalFailureOverride="";const i=this.pendingIncomingCall||t||null;this.clearPanelAutoClose(),this.transientPanelState=null,this.transientPanelDetail="",this.setState("connected"),this.setAvailabilityState("working","当前通话已接通。"),this.emitHostCallback("onCallAnswered",i);return}if(e==="terminated"){if(this.issuedSession?.session_mode==="widget_standby"){await this.handleStandbyTermination(t);return}t&&typeof t=="object"&&(t.source==="invite-response"||t.source==="invite-exception"||t.code||t.status||t.stage)&&(this.terminalFailureOverride=t?.message||se.failed,this.setState("failed",this.terminalFailureOverride)),await this.finalizeAfterTermination(t?.hangupSource||"terminated");return}if(e==="failed"){if(this.isExpectedClientTeardown())return;this.pendingLifecycleMode=null,await this.clearTransportDisconnectGrace(!1),this.stopSessionTouch(),this.terminalFailureOverride=t?.message||se.failed,this.setState("failed",this.terminalFailureOverride),this.setTransientPanelState("failed","当前暂时无法接通,请稍后再试。"),this.setAvailabilityState("recovering","通话链路异常断开,系统会继续自动恢复。"),await this.releaseIssuedSession("failed","sip-client-failed");return}if(e==="disconnected"||e==="unregistered"){if(this.isExpectedClientTeardown()||this.isExpectedTermination()||!this.issuedSession?.session_id&&this.pendingLifecycleMode==="standby")return;if(this.stopSessionTouch(),["calling","connected"].includes(this.state)){this.setState("connected","SIP 信令短暂中断,正在等待恢复。"),this.setAvailabilityState("recovering","通话信令短暂中断,正在等待恢复。"),this.scheduleTransportDisconnectGrace(e);return}const s=this.terminalFailureOverride||this.client?.lastFailureMeta?.message||null;if(s){this.terminalFailureOverride=s,this.setState("failed",s),this.setTransientPanelState("failed","当前暂时无法接通,请稍后再试。");return}if(this.state==="failed")return;this.state!=="idle"&&this.state!=="ended"&&(this.pendingLifecycleMode=null,this.setState("ended"),this.setAvailabilityState("preparing","通话已结束,正在自动返回网页电话待机。"),this.scheduleAutoStandbyRecovery(`client-${e}`))}}stopTransportDisconnectGrace(){this.transportDisconnectTimer&&(window.clearTimeout(this.transportDisconnectTimer),this.transportDisconnectTimer=null),this.transportDisconnectContext=null}sameTransportDisconnectContext(e){return!e||!this.issuedSession?.session_id?!1:e.sessionId===this.issuedSession.session_id}async clearTransportDisconnectGrace(e){const t=this.transportDisconnectContext,i=!!(e&&t?.reported&&this.sameTransportDisconnectContext(t));this.stopTransportDisconnectGrace(),i&&(await this.reportIssuedSessionEvent("transport-restored",{disconnectDurationMs:Date.now()-(t.startedAt||Date.now()),graceMs:Re},this.state),this.appendLog("网页通话信令已恢复",{disconnectDurationMs:Date.now()-(t.startedAt||Date.now()),graceMs:Re}))}scheduleTransportDisconnectGrace(e){if(!this.issuedSession?.session_id)return;this.stopTransportDisconnectGrace();const t={sessionId:this.issuedSession.session_id,startedAt:Date.now(),reported:!1,state:e};this.transportDisconnectContext=t,this.transportDisconnectTimer=window.setTimeout(()=>{this.transportDisconnectTimer=null,this.sameTransportDisconnectContext(t)&&(t.reported=!0,this.reportIssuedSessionEvent("transport-disconnected",{state:e,graceMs:Re},this.state),this.appendLog("网页通话信令断开超过宽限窗口",{graceMs:Re,state:e}))},Re)}async finalizeAfterTermination(e){if(!this.finalizing){this.beginLifecycleRun(),this.finalizing=!0;try{this.pendingLifecycleMode=null,this.stopSessionTouch(),this.stopTransportDisconnectGrace(),await this.releaseIssuedSession("released",e),this.client&&(await this.client.destroy(),this.client=null);const t=this.terminalFailureOverride||(this.state==="failed"?this.stateDetail||se.failed:"");if(this.setTransientPanelState(t?"failed":"ended",t?"当前暂时无法接通,请稍后再试。":"本次通话已结束。"),!this.legacyOutboundOnly){t?this.setState("failed",t):this.setState("ended"),this.setAvailabilityState("preparing","页面仍在线,正在自动回到待机。"),this.appendLog("通话已结束,网页电话正在自动回到待机。",{reason:e}),await this.startStandby({force:!0});return}t?this.setState("failed",t):this.setState("ended"),this.appendLog("通话已结束并完成清理",{reason:e})}finally{this.finalizing=!1}}}async handleStandbyTermination(e={}){this.stopTransportDisconnectGrace();const t=this.state,i=e?.hangupSource||"terminated";t==="incoming"?(this.incrementMissedIncomingCount(),i==="local"?(this.setState("standby","当前来电已拒接,widget 仍保持可用。"),this.setAvailabilityState("ready","当前来电已拒接,widget 仍保持可用。"),this.emitHostCallback("onCallRejected",this.pendingIncomingCall||e||null)):(this.setState("standby","当前来电未接听,widget 仍保持可用。"),this.setAvailabilityState("ready","当前来电未接听,widget 仍保持可用。"),this.emitHostCallback("onCallMissed",this.pendingIncomingCall||e||null)),this.setTransientPanelState("ended","本次来电已结束。")):(this.setState("standby","上一通来电已结束,继续等待下一通来电。"),this.setAvailabilityState("ready","当前可被呼叫,也可由访客主动发起呼叫。"),this.setTransientPanelState("ended","本次通话已结束。")),this.appendLog("待机会话中的来电已结束",{hangupSource:i,previousState:t}),this.pendingIncomingCall=null}async answerIncomingCall(){if(this.state==="incoming"){if(this.clearPanelAutoClose(),this.transientPanelState=null,this.transientPanelDetail="",this.e2eBridgeEnabled&&this.pendingIncomingCall?.e2eSimulated){this.setState("connected","测试桥已模拟接听当前来电。"),this.emitHostCallback("onCallAnswered",this.pendingIncomingCall);return}if(!this.client&&this.e2eBridgeEnabled){this.setState("connected","测试桥已模拟接听当前来电。"),this.emitHostCallback("onCallAnswered",this.pendingIncomingCall);return}if(!this.client)throw new Error("当前没有可接听的 SIP 会话");await this.client.answer()}}async declineIncomingCall(){if(this.state==="incoming"){if(this.e2eBridgeEnabled&&this.pendingIncomingCall?.e2eSimulated){this.incrementMissedIncomingCount(),this.setState("standby","测试桥已模拟拒接当前来电,网页电话已恢复待机。"),this.setTransientPanelState("ended","本次来电已结束。"),this.setAvailabilityState("ready","当前可被呼叫,也可由访客主动发起呼叫。"),this.emitHostCallback("onCallRejected",this.pendingIncomingCall),this.pendingIncomingCall=null;return}if(!this.client&&this.e2eBridgeEnabled){this.incrementMissedIncomingCount(),this.setState("standby","测试桥已模拟拒接当前来电,网页电话已恢复待机。"),this.setTransientPanelState("ended","本次来电已结束。"),this.setAvailabilityState("ready","当前可被呼叫,也可由访客主动发起呼叫。"),this.emitHostCallback("onCallRejected",this.pendingIncomingCall),this.pendingIncomingCall=null;return}if(!this.client)throw new Error("当前没有可拒接的 SIP 会话");await this.client.decline()}}async hangupCall(){if(this.e2eBridgeEnabled&&this.pendingIncomingCall?.e2eSimulated){this.legacyOutboundOnly?(this.setState("ended"),this.setTransientPanelState("ended","本次通话已结束。")):(this.setState("standby","测试桥已模拟挂断,网页电话已恢复待机。"),this.setTransientPanelState("ended","本次通话已结束。")),this.pendingIncomingCall=null;return}if(!this.client&&this.e2eBridgeEnabled){this.legacyOutboundOnly?(this.setState("ended"),this.setTransientPanelState("ended","本次通话已结束。")):(this.setState("standby","测试桥已模拟挂断,网页电话已恢复待机。"),this.setTransientPanelState("ended","本次通话已结束。")),this.pendingIncomingCall=null;return}this.client&&(this.expectTermination("hangup-call"),this.suppressExpectedClientTeardown("hangup-call"),await this.client.hangup())}async disconnectAndCleanup(e,t={}){const{preserveLifecycleRun:i=!1,suppressStateReset:s=!1,suppressClientTeardownState:r=null}=t;i||this.beginLifecycleRun(),r&&this.suppressExpectedClientTeardown(r),this.stopSessionTouch(),this.stopTransportDisconnectGrace(),this.reportIssuedSessionEvent("manual-disconnect",{reason:e},this.state),this.pendingIncomingCall=null,this.terminalFailureOverride="",this.client&&(await this.client.destroy(),this.client=null),await this.releaseIssuedSession("released",e),s||(this.pendingLifecycleMode=null,this.setState("idle"),this.setAvailabilityState("preparing","网页电话已断开,系统正在自动返回待机。"),this.appendLog("连接已断开",{reason:e}),!this.legacyOutboundOnly&&this.networkOnline!==!1&&this.scheduleAutoStandbyRecovery(e))}async loadBootstrap(){if(this.bootstrap)return this.bootstrap;const e=await fetch(X(this.apiBaseUrl,"api/sip/embedded-call-demo-bootstrap"),{credentials:"include",cache:"no-store"});if(!e.ok)throw new Error(`默认模式读取失败:${e.status}`);return this.bootstrap=await e.json(),this.bootstrap}async fetchTurnIceServers(){const e=await fetch(X(this.apiBaseUrl,"api/sip/webrtc-turn-credentials"),{credentials:"include",cache:"no-store"});if(!e.ok)return this.appendLog("TURN 凭证获取失败,继续尝试直连",{status:e.status}),[];const t=await e.json();return Array.isArray(t?.ice_servers)?t.ice_servers:[]}async fetchIssuedSession(e={}){const{preferredBrowserSipUsername:t=null}=e,i=le(this.options),s={page_url:window.location.href};A(s,"site_key",this.options.siteKey),A(s,"standby_state",this.options.standbyState),A(s,"selected_primary_account",this.options.selectedPrimaryAccount),A(s,"selected_middle_layer_account",this.options.selectedMiddleLayerAccount),A(s,"preferred_browser_sip_username",t),A(s,"display_name",this.options.displayName),A(s,"access_token",this.options.accessToken),i&&(s.business_key=i);const r=await fetch(X(this.apiBaseUrl,"api/sip/issue-call-session"),{method:"POST",credentials:"include",cache:"no-store",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!r.ok){const d=await r.json().catch(()=>({}));throw new Error(d?.detail||`会话签发失败:${r.status}`)}const n=await r.json(),o=xt(n,Ie.outbound,"issue-call-session");return this.markDebugPanelEnabled("issue-call-session",n?.debug_access_granted===!0),this.issuedSession=n,this.reportIssuedSessionEvent("issued-session-fetched",{sessionId:n.session_id,targetExtension:n.target_extension,dialTargetExtension:n.dial_target_extension||n.target_extension,resolvedTargetInternalNumbers:n.resolved_target_internal_numbers||[],resolvedBusinessKey:n.resolved_business_key||null},"requesting"),this.appendLog("已获取服务端签发会话",{session_id:n.session_id,target_extension:n.target_extension,dial_target_extension:n.dial_target_extension||n.target_extension||null,resolved_target_internal_numbers:n.resolved_target_internal_numbers||[],resolved_business_key:n.resolved_business_key||null,resolved_route_mode:n.resolved_route_mode||null,route_note:n.route_note||null}),{sessionMode:o,sipUsername:n.sip_username,sipDomain:n.sip_domain,password:n.sip_password,transport:Tt({apiBaseUrl:this.apiBaseUrl,transportBaseUrl:this.options.transportBaseUrl||"",transportUrl:n.ws_server}),target:n.dial_target_extension||n.target_extension,routeNote:n.route_note||""}}async fetchStandbySession(){const e=le(this.options)||null,t={page_url:window.location.href};A(t,"site_key",this.options.siteKey),A(t,"standby_state",this.options.standbyState),A(t,"selected_primary_account",this.options.selectedPrimaryAccount),A(t,"selected_middle_layer_account",this.options.selectedMiddleLayerAccount),A(t,"display_name",this.options.displayName),A(t,"access_token",this.options.accessToken),e&&(t.business_key=e);const i=await fetch(X(this.apiBaseUrl,"api/sip/issue-widget-standby-session"),{method:"POST",credentials:"include",cache:"no-store",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!i.ok){const n=await i.json().catch(()=>({}));throw new Error(n?.detail||`待机会话签发失败:${i.status}`)}const s=await i.json(),r=xt(s,Ie.standby,"issue-widget-standby-session");return this.markDebugPanelEnabled("issue-widget-standby-session",s?.debug_access_granted===!0),this.issuedSession=s,this.reportIssuedSessionEvent("standby-session-fetched",{sessionId:s.session_id,resolvedBusinessKey:s.resolved_business_key||null,standbyMode:s.standby_mode||null},"standbyRequesting"),this.appendLog("已获取 widget 待机会话",{session_id:s.session_id,resolved_business_key:s.resolved_business_key||null,standby_mode:s.standby_mode||null,standby_state:s.standby_state||null,widget_anchor_number:s.widget_anchor_number||null,browser_sip_username:s.browser_sip_username||s.sip_username||null,route_note:s.route_note||null}),{sessionMode:r,sipUsername:s.sip_username,sipDomain:s.sip_domain,password:s.sip_password,transport:Tt({apiBaseUrl:this.apiBaseUrl,transportBaseUrl:this.options.transportBaseUrl||"",transportUrl:s.ws_server}),target:null,routeNote:s.route_note||""}}async releaseIssuedSession(e,t){if(!this.issuedSession?.session_id)return;const i=this.issuedSession.session_id;this.markRecentlyReleasedSession(i,t),this.issuedSession=null,await fetch(X(this.apiBaseUrl,"api/sip/release-call-session"),{method:"POST",credentials:"include",cache:"no-store",headers:{"Content-Type":"application/json"},body:JSON.stringify({session_id:i,status:e,reason:t,client_summary:this.buildClientEvidenceSummary(e,{releaseReason:t})})}).catch(()=>{})}postLifecycleBeacon(e,t){const i=JSON.stringify(t),s=X(this.apiBaseUrl,e);if(typeof navigator<"u"&&typeof navigator.sendBeacon=="function")try{const r=new Blob([i],{type:"application/json"});if(navigator.sendBeacon(s,r))return!0}catch{}return fetch(s,{method:"POST",credentials:"include",cache:"no-store",keepalive:!0,headers:{"Content-Type":"application/json"},body:i}).catch(()=>{}),!0}flushUnloadCleanup(e){if(this.unloadCleanupStarted||(this.unloadCleanupStarted=!0,this.stopSessionTouch(),this.stopPresenceTouch(),this.stopTransportDisconnectGrace(),!this.issuedSession?.session_id))return;const t=this.issuedSession.session_id;this.markRecentlyReleasedSession(t,e),this.postLifecycleBeacon("api/sip/release-call-session",{session_id:t,status:"released",reason:e,client_summary:this.buildClientEvidenceSummary("released",{releaseReason:e})}),this.issuedSession=null}buildClientEvidenceSummary(e=null,t=null){const i={runtimeMode:"embedded-widget-runtime",widgetVersion:"2026-03-29-runtime-evidence",widgetMode:this.mode,sessionMode:this.issuedSession?.session_mode||null,state:e||this.state,visible:typeof document>"u"?!0:document.visibilityState==="visible",pageUrl:typeof window>"u"?null:window.location.href,connectionSnapshot:this.client?.getConnectionSnapshot?.()||null};return t&&typeof t=="object"&&(i.eventDetail=t),i}buildPresenceEvidenceSummary(e=null,t=null){return{...this.buildClientEvidenceSummary(e,t),presenceId:this.presenceId,availabilityState:this.availabilityState,availabilityDetail:this.availabilityDetail,networkOnline:this.networkOnline,pageVisible:this.pageVisible}}setAvailabilityState(e,t=""){this.availabilityState=e,this.availabilityDetail=t||this.availabilityDetail,this.refs.availability&&(this.refs.availability.textContent=t?`${de[e]||de.recovering} · ${t}`:de[e]||de.recovering,this.refs.availability.className=`availability availability--${e}`),this.render()}suppressExpectedClientTeardown(e,t=ki){this.expectedClientTeardown={reason:e,expiresAt:Date.now()+t}}expectTermination(e,t=1e4){this.expectedTermination={reason:e,expiresAt:Date.now()+t}}clearExpectedTermination(){this.expectedTermination=null}isExpectedTermination(){const e=this.expectedTermination;return e?e.expiresAt<=Date.now()?(this.expectedTermination=null,!1):!0:!1}isExpectedClientTeardown(){const e=this.expectedClientTeardown;return e?e.expiresAt<=Date.now()?(this.expectedClientTeardown=null,!1):!0:!1}clearAutoStandbyRecovery(){this.autoStandbyRecoveryTimer&&(window.clearTimeout(this.autoStandbyRecoveryTimer),this.autoStandbyRecoveryTimer=null)}scheduleAutoStandbyRecovery(e,t=Di){this.legacyOutboundOnly||this.networkOnline===!1||this.autoStandbyRecoveryTimer||this.client||this.issuedSession?.session_id||this.finalizing||this.pendingLifecycleMode==="outbound"||this.sessionRecoveryInFlight||this.connectivityRecoveryInFlight||["requesting","standbyRequesting","registering","calling","incoming","connected"].includes(this.state)||(this.autoStandbyRecoveryTimer=window.setTimeout(()=>{this.autoStandbyRecoveryTimer=null,!(this.legacyOutboundOnly||this.networkOnline===!1)&&(this.client||this.issuedSession?.session_id||this.finalizing||this.pendingLifecycleMode==="outbound"||(this.appendLog("检测到页面当前不在通话中,开始自动进入待机。",{reason:e}),this.startStandby({force:!0})))},t))}pruneRecentlyReleasedSessions(){const e=Date.now();for(const[t,i]of this.recentlyReleasedSessions.entries())(i?.expiresAt||0)<=e&&this.recentlyReleasedSessions.delete(t)}markRecentlyReleasedSession(e,t){e&&(this.pruneRecentlyReleasedSessions(),this.recentlyReleasedSessions.set(e,{reason:t,expiresAt:Date.now()+Pi}))}wasSessionRecentlyReleased(e){return e?(this.pruneRecentlyReleasedSessions(),this.recentlyReleasedSessions.has(e)):!1}syncAvailabilityState(){if(this.networkOnline===!1){this.setAvailabilityState("offline","当前网络连接已断开,正在等待恢复。");return}if(this.state==="incoming"){this.setAvailabilityState("working","已有新来电,请直接接听或拒接。");return}if(this.state==="connected"){this.setAvailabilityState("working","当前通话已接通。");return}if(this.state==="calling"){this.setAvailabilityState("working","正在等待对端振铃或接听。");return}if(this.pendingLifecycleMode==="outbound"&&["requesting","registering"].includes(this.state)){this.setAvailabilityState("working","正在建立呼叫链路。");return}if(["requesting","standbyRequesting","registering"].includes(this.state)){this.setAvailabilityState("preparing","页面仍在线,正在建立网页电话连接。");return}if(!this.legacyOutboundOnly&&!this.issuedSession?.session_id&&!this.pendingLifecycleMode&&["idle","ended","missed","rejected"].includes(this.state)){this.setAvailabilityState("preparing","页面仍在线,正在自动进入网页电话待机。"),this.scheduleAutoStandbyRecovery("missing-issued-session");return}if(!this.legacyOutboundOnly&&!this.issuedSession?.session_id&&!this.pendingLifecycleMode&&!["calling","connected","incoming"].includes(this.state)){this.setAvailabilityState("preparing","页面仍在线,正在重新建立网页电话待机。"),this.scheduleAutoStandbyRecovery("missing-issued-session");return}this.setAvailabilityState("ready","当前可被呼叫,也可由访客主动发起呼叫。")}stopPresenceTouch(){this.presenceTouchTimer&&(window.clearInterval(this.presenceTouchTimer),this.presenceTouchTimer=null)}async restartStandbyAfterConnectivity(e){if(!(this.legacyOutboundOnly||this.connectivityRecoveryInFlight)&&!["connected","incoming","calling","requesting","standbyRequesting","registering"].includes(this.state)){this.connectivityRecoveryInFlight=(async()=>{this.appendLog("检测到连通性已恢复,准备重建网页电话待机。",{trigger:e,state:this.state,hasSession:!!this.issuedSession?.session_id}),(this.client||this.issuedSession?.session_id)&&await this.disconnectAndCleanup(`connectivity-restored-${e}`),await this.startStandby({force:!0})})();try{await this.connectivityRecoveryInFlight}finally{this.connectivityRecoveryInFlight=null}}}async handleServerSessionAction(e,t={}){if(this.legacyOutboundOnly)return!1;const i=Ui(e,t);if(i.action!==Xe.restartStandby)return!1;const s=Q(this.issuedSession?.session_mode),r=Q(this.pendingLifecycleMode),n=s===Ie.outbound||r===Et.outbound,o=s===Ie.standby||r===Et.standby;if(n||!o)throw L("非待机协议上下文收到了非法的 restart_standby 指令。",{source:e,state:this.state,local_session_mode:s||null,local_lifecycle_mode:r||null,session_action:i.action,session_action_reason:i.reason,session_action_detail:i.detail,resolved_session_id:i.resolvedSessionId,resolved_widget_anchor_number:i.resolvedWidgetAnchorNumber,resolved_browser_sip_username:i.resolvedBrowserSipUsername});if(this.sessionRecoveryInFlight||this.connectivityRecoveryInFlight)return!1;this.sessionRecoveryInFlight=(async()=>{this.appendLog("服务端要求当前页面立即放弃旧锚点并重建待机。",{source:e,state:this.state,local_session_mode:s||null,local_lifecycle_mode:r||null,session_action_reason:i.reason,session_action_detail:i.detail,resolved_session_id:i.resolvedSessionId,resolved_widget_anchor_number:i.resolvedWidgetAnchorNumber,resolved_browser_sip_username:i.resolvedBrowserSipUsername}),this.setAvailabilityState("recovering",i.detail||"当前锚点已失效,正在自动切换到新的待机线路。"),(this.client||this.issuedSession?.session_id)&&await this.disconnectAndCleanup(`server-session-action-${i.reason||e}`,{preserveLifecycleRun:!0,suppressStateReset:!0}),await this.startStandby({force:!0})})();try{await this.sessionRecoveryInFlight}finally{this.sessionRecoveryInFlight=null}return!0}async handleProtocolViolation(e){const t=e?.detail&&typeof e.detail=="object"?e.detail:{},i={violation_code:e?.code||"widget_protocol_violation",violation_name:e?.name||"EmbeddedCallWidgetProtocolViolationError",violation_message:e?.message||String(e),...t};this.appendLog("协议错误:当前页面收到了非法的运行态指令,已拒绝执行并保留现有通话状态。",i),typeof console<"u"&&typeof console.error=="function"&&console.error("[embedded-call-widget] protocol violation",i),await this.reportIssuedSessionEvent("protocol-violation",i),!["calling","connected","incoming"].includes(this.state)&&(this.pendingLifecycleMode=null,this.clearAutoStandbyRecovery(),this.stopSessionTouch(),this.stopPresenceTouch(),this.terminalFailureOverride=i.violation_message,this.setState("failed",i.violation_message),this.setAvailabilityState("conflicted","检测到前后端协议不一致,已停止自动恢复,请尽快排查。"))}async touchWidgetPresence(e="interval"){if(this.legacyOutboundOnly)return;this.networkOnline=typeof navigator>"u"?!0:navigator.onLine!==!1,this.pageVisible=typeof document>"u"?!0:document.visibilityState==="visible";const t=this.availabilityState==="offline";try{const i=await fetch(X(this.apiBaseUrl,"api/sip/touch-widget-presence"),{method:"POST",credentials:"include",cache:"no-store",keepalive:!0,headers:{"Content-Type":"application/json"},body:JSON.stringify((()=>{const n={presence_id:this.presenceId,state:this.state,page_url:typeof window>"u"?void 0:window.location.href,visible:this.pageVisible,network_online:this.networkOnline,client_summary:this.buildPresenceEvidenceSummary(this.state,{trigger:e})};return A(n,"site_key",this.options.siteKey),A(n,"requested_business_key",le(this.options)),A(n,"resolved_business_key",this.issuedSession?.resolved_business_key),A(n,"display_name",this.options.displayName),A(n,"session_id",this.issuedSession?.session_id),A(n,"session_mode",this.issuedSession?.session_mode),A(n,"widget_anchor_number",this.issuedSession?.widget_anchor_number),A(n,"browser_sip_username",this.issuedSession?.browser_sip_username||this.issuedSession?.sip_username),A(n,"standby_mode",this.issuedSession?.standby_mode),A(n,"standby_state",this.issuedSession?.standby_state||this.options.standbyState),A(n,"selected_primary_account",this.options.selectedPrimaryAccount),A(n,"selected_middle_layer_account",this.options.selectedMiddleLayerAccount),A(n,"route_note",this.issuedSession?.route_note),n})())});if(!i.ok)throw new Error(`运行态心跳失败:${i.status}`);const s=await i.json().catch(()=>({}));this.presenceFailureCount=0,await this.handleServerSessionAction("touch-widget-presence",s)||this.syncAvailabilityState(),t&&await this.restartStandbyAfterConnectivity(`presence-${e}`)}catch(i){if(Oe(i)){await this.handleProtocolViolation(i),this.syncAvailabilityState();return}if(this.presenceFailureCount+=1,this.networkOnline===!1||Qe(i)||this.presenceFailureCount>=Ct){const r=this.networkOnline===!1?"当前网络连接已断开,正在等待恢复。":"当前无法连接通话服务,正在自动尝试恢复。";this.setAvailabilityState("offline",r)}else this.setAvailabilityState("recovering","正在确认后台连接状态。");this.presenceFailureCount<=Ct&&this.appendLog("widget 运行态心跳失败",{trigger:e,failure_count:this.presenceFailureCount,message:i?.message||String(i)})}}startPresenceTouch(){this.legacyOutboundOnly||(this.touchWidgetPresence("mount"),this.presenceTouchTimer||(this.presenceTouchTimer=window.setInterval(()=>{this.touchWidgetPresence("interval")},$i)))}async touchIssuedSession(e,t=null){if(!this.issuedSession?.session_id)return;const i=this.issuedSession.session_id;try{const s=await fetch(X(this.apiBaseUrl,"api/sip/touch-call-session"),{method:"POST",credentials:"include",cache:"no-store",keepalive:!0,headers:{"Content-Type":"application/json"},body:JSON.stringify({session_id:i,state:e,client_summary:this.buildClientEvidenceSummary(e,t)})});if(!s.ok){const n=new Error(`会话心跳失败:${s.status}`);throw n.status=s.status,n}const r=await s.json().catch(()=>({}));await this.handleServerSessionAction("touch-call-session",r)}catch(s){if(Oe(s)){await this.handleProtocolViolation(s);return}if(s?.status===404&&this.wasSessionRecentlyReleased(i))return;this.appendLog("网页通话会话心跳失败",{session_id:i,state:e,message:s?.message||String(s)}),s?.status===404&&this.handleMissingIssuedSession(i,e)}}async handleMissingIssuedSession(e,t){if(!(this.sessionRecoveryInFlight||this.issuedSession?.session_id!==e)){this.sessionRecoveryInFlight=(async()=>{this.stopSessionTouch(),this.appendLog("网页电话待机会话已失效,准备自动恢复。",{session_id:e,state:t}),this.setAvailabilityState("recovering","原待机会话已失效,正在自动恢复。"),this.issuedSession?.session_id===e&&(this.issuedSession=null),!this.legacyOutboundOnly&&["standby","registering","standbyRequesting","failed","idle","missed","rejected","ended"].includes(this.state)&&(this.setState("standbyRequesting","待机会话已失效,正在自动重新进入待机。"),await this.startStandby({force:!0}))})();try{await this.sessionRecoveryInFlight}finally{this.sessionRecoveryInFlight=null}}}async reportIssuedSessionEvent(e,t=null,i=null){if(!this.issuedSession?.session_id)return;const s=this.issuedSession.session_id,r=i||this.state;let n=null,o="";try{const d=await fetch(X(this.apiBaseUrl,"api/sip/report-call-session-event"),{method:"POST",credentials:"include",cache:"no-store",keepalive:!0,headers:{"Content-Type":"application/json"},body:JSON.stringify({session_id:s,source:"widget-runtime",event:e,state:r,detail:this.buildClientEvidenceSummary(r,t)})});if(!d.ok){n=d.status;const u=await d.json().catch(()=>({}));throw o=u?.detail?String(u.detail):"",new Error(o||`事件留证失败:${d.status}`)}}catch(d){await fetch(X(this.apiBaseUrl,"api/sip/report-call-session-event-delivery-failure"),{method:"POST",credentials:"include",cache:"no-store",keepalive:!0,headers:{"Content-Type":"application/json"},body:JSON.stringify({session_id:s,source:"widget-runtime",event:e,state:r,detail:this.buildClientEvidenceSummary(r,t),delivery_error:{status:typeof n=="number"?n:null,detail:o||"",message:d?.message||String(d)}})}).catch(()=>{}),this.appendLog("网页通话事件留证失败",{session_id:s,event:e,state:r,message:d?.message||String(d)})}}stopSessionTouch(){this.sessionTouchTimer&&(window.clearInterval(this.sessionTouchTimer),this.sessionTouchTimer=null)}syncSessionTouch(e){if(!(!!this.issuedSession?.session_id&&["connected","registered","dialing","ringing","answered","standby","incoming"].includes(e))){this.stopSessionTouch();return}this.touchIssuedSession(e),this.sessionTouchTimer||(this.sessionTouchTimer=window.setInterval(()=>{this.touchIssuedSession(this.state)},Ai))}setState(e,t=""){this.state=e,this.stateDetail=t||se[e]||se.idle,this.syncAvailabilityState(),this.render(),this.emitHostCallback("onStateChange",this.getSnapshot())}appendLog(e,t){if(!this.refs.logs)return;const i=document.createElement("div");for(i.className="log",i.textContent=qi(e,t),this.refs.logs.prepend(i);this.refs.logs.children.length>8;)this.refs.logs.lastElementChild?.remove()}render(){const e=this.getVisibleState(),t=e!=="idle",i=this.pendingIncomingCall?.displayName||this.pendingIncomingCall?.user||"管理员",s=["requesting","registering","calling","connected","incoming"].includes(this.state);let r="网页通话",n=this.options.text||"联系管理员",o=this.transientPanelDetail||"",d=null,u=null;e==="ringing"?(r="网页来电",n=i,o=o||"对方正在呼叫你,请选择接听或挂断。",d={text:"接听",className:"btn btn-primary",disabled:!1},u={text:"挂断",className:"btn btn-danger",disabled:!1}):e==="dialing"?(r="正在呼叫",o=o||"正在为你接通管理员,请稍候。",u={text:"挂断",className:"btn btn-danger",disabled:!1}):e==="connected"?(r="通话进行中",n=this.pendingIncomingCall?.displayName||n,o=o||"通话已接通,如需结束请点击挂断。",u={text:"挂断",className:"btn btn-danger",disabled:!1}):e==="ended"?(r="通话已结束",o=o||"本次通话已结束。"):e==="failed"&&(r="暂未接通",o=o||"当前暂时无法接通,请稍后再试。");const h=this.missedIncomingCount>0?String(this.missedIncomingCount):this.triggerHintDismissed?"":" ";this.refs.trigger.disabled=s,this.refs.triggerBadge.hidden=!h,this.refs.triggerBadge.textContent=h,this.refs.triggerBadge.className=this.missedIncomingCount>0?"trigger-badge":"trigger-badge trigger-badge--dot",this.refs.panelShell.className=t?"panel-shell panel-shell--visible":"panel-shell",this.refs.panel.setAttribute("aria-hidden",t?"false":"true"),this.refs.panelEyebrow.textContent=r,this.refs.panelTitle.textContent=n,this.refs.status.textContent=Ze[e]||Ze.idle,this.refs.status.className=e==="failed"?"status status--failed":"status",this.refs.panelDetail.textContent=o,this.refs.primary.hidden=!d,d?(this.refs.primary.textContent=d.text,this.refs.primary.className=d.className,this.refs.primary.disabled=d.disabled):this.refs.primary.textContent="",this.refs.secondary.hidden=!u,u?(this.refs.secondary.textContent=u.text,this.refs.secondary.className=u.className,this.refs.secondary.disabled=u.disabled):this.refs.secondary.textContent="";const m=+!!d+ +!!u;this.refs.actions.className=m<=1?"actions actions--single":"actions";const S=String(this.options.siteKey||"").trim(),x=String(this.bootstrap?.default_site_key||"").trim(),_=String(le(this.options)||"").trim(),C=String(this.bootstrap?.default_business_key||"").trim(),ee=S||(x?`${x}(服务端默认站点)`:"等待服务端解析"),p=this.issuedSession?.resolved_business_key||_||(C?`${C}(服务端默认规则)`:"等待服务端解析");this.legacyOutboundOnly?this.refs.meta.textContent=`入站规则:${p};站点键:${ee}`:this.refs.meta.textContent=`站点键:${ee};网页电话会先进入可被叫待机;访客主动呼叫默认规则:${p}`,this.refs.availability.textContent=this.availabilityDetail?`${de[this.availabilityState]||de.recovering} · ${this.availabilityDetail}`:de[this.availabilityState]||de.recovering,this.refs.availability.className=`availability availability--${this.availabilityState}`,this.availabilityState==="offline"?this.refs.hint.textContent=this.networkOnline===!1?"当前浏览器网络已断开。系统会在网络恢复后自动尝试重连网页电话。":"当前无法连接通话服务。系统会继续自动恢复,暂时不要重复点击。":this.availabilityState==="preparing"?this.refs.hint.textContent="当前正在准备待机能力。只要页面在线,系统会自动进入可呼入、可呼出的网页电话状态。":this.availabilityState==="working"?this.state==="incoming"?this.refs.hint.textContent="当前已有来电,直接接听或拒接即可;处理完成后会自动回到待机。":this.state==="connected"?this.refs.hint.textContent="当前通话已接通,挂断后会自动回到待机,不需要额外刷新页面。":this.refs.hint.textContent="当前正在切换到外呼链路,请等待振铃、接通或自动回到待机。":this.availabilityState==="recovering"?this.refs.hint.textContent="当前页面仍在线,系统正在自动恢复可被叫待机,不需要刷新页面或手动切换模式。":this.availabilityState==="conflicted"?this.refs.hint.textContent="检测到前后端协议不一致,当前已停止自动恢复。请先排查版本和协议口径,再继续使用。":this.refs.hint.textContent=this.isMobileViewport?Ri:"桌面网页可直接使用;若宿主站点启用了来源白名单或接入令牌,请按站点配置提供对应参数。",this.refs.debugPanel.hidden=!this.debugPanelEnabled}async destroy(){this.clearAutoStandbyRecovery(),this.clearPanelAutoClose(),await this.disconnectAndCleanup("destroy-widget",{suppressStateReset:!0}),typeof document<"u"&&this.visibilityHandler&&(document.removeEventListener("visibilitychange",this.visibilityHandler),this.visibilityHandler=null),this.stopSessionTouch(),this.stopPresenceTouch(),this.stopTransportDisconnectGrace(),this.pendingLifecycleMode=null,this.pendingIncomingCall=null,typeof window<"u"&&(this.onlineHandler&&(window.removeEventListener("online",this.onlineHandler),this.onlineHandler=null),this.offlineHandler&&(window.removeEventListener("offline",this.offlineHandler),this.offlineHandler=null),this.beforeUnloadHandler&&(window.removeEventListener("beforeunload",this.beforeUnloadHandler),this.beforeUnloadHandler=null),this.pageHideHandler&&(window.removeEventListener("pagehide",this.pageHideHandler),this.pageHideHandler=null)),this.e2eBridgeEnabled&&typeof window<"u"&&window.__embeddedCallWidgetE2E__&&delete window.__embeddedCallWidgetE2E__,this.shadowRoot.innerHTML=""}}function Rt(a){return new Wi(a)}return typeof window<"u"&&(window.__EmbeddedCallWidgetRuntime__={createEmbeddedCallWidgetRuntime:Rt}),Fe.createEmbeddedCallWidgetRuntime=Rt,Object.defineProperty(Fe,Symbol.toStringTag,{value:"Module"}),Fe})({});
|