@voicenter-team/opensips-js 1.0.129 → 1.0.130

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.
@@ -157,4 +157,4 @@ a=path:${e.getHeader("Use-Path")} msrp://${this._ua._configuration.authorization
157
157
  `);if(l===-1){jo.warn("parseMessage() | no CRLF found, not a SIP message");return}const s=u.substring(0,l);let i=Kh.parse(s,"Request_Response");if(i===-1){jo.warn(`parseMessage() | error parsing first line of SIP message: "${s}"`);return}else i.status_code?(t=new ki.IncomingResponse,t.status_code=i.status_code,t.reason_phrase=i.reason_phrase):(t=new ki.IncomingRequest(e),t.method=i.method,t.ruri=i.uri);t.data=u;let f=l+2;for(;;){if(l=Wy(u,f),l===-2){r=f+2;break}else if(l===-1){jo.warn("parseMessage() | malformed message");return}if(i=Ky(t,u,f,l),i!==!0){jo.warn("parseMessage() |",i.error);return}f=l+2}if(t.hasHeader("content-length")){const h=t.getHeader("content-length");t.body=u.substr(r,h)}else t.body=u.substring(r);return t};function Wy(u,e){let t=e,r=0,l=0;if(u.substring(t,t+2).match(/(^\r\n)/))return-2;for(;r===0;){if(l=u.indexOf(`\r
158
158
  `,t),l===-1)return l;!u.substring(l+2,l+4).match(/(^\r\n)/)&&u.charAt(l+2).match(/(^\s+)/)?t=l+2:r=l}return r}function Ky(u,e,t,r){let l;const s=e.indexOf(":",t),i=e.substring(t,s).trim(),f=e.substring(s+1,r).trim();switch(i.toLowerCase()){case"via":case"v":u.addHeader("via",f),u.getHeaders("via").length===1?(l=u.parseHeader("Via"),l&&(u.via=l,u.via_branch=l.branch)):l=0;break;case"from":case"f":u.setHeader("from",f),l=u.parseHeader("from"),l&&(u.from=l,u.from_tag=l.getParam("tag"));break;case"to":case"t":u.setHeader("to",f),l=u.parseHeader("to"),l&&(u.to=l,u.to_tag=l.getParam("tag"));break;case"record-route":if(l=Kh.parse(f,"Record_Route"),l===-1)l=void 0;else for(const h of l)u.addHeader("record-route",f.substring(h.possition,h.offset)),u.headers["Record-Route"][u.getHeaders("record-route").length-1].parsed=h.parsed;break;case"call-id":case"i":u.setHeader("call-id",f),l=u.parseHeader("call-id"),l&&(u.call_id=f);break;case"contact":case"m":if(l=Kh.parse(f,"Contact"),l===-1)l=void 0;else for(const h of l)u.addHeader("contact",f.substring(h.possition,h.offset)),u.headers.Contact[u.getHeaders("contact").length-1].parsed=h.parsed;break;case"content-length":case"l":u.setHeader("content-length",f),l=u.parseHeader("content-length");break;case"content-type":case"c":u.setHeader("content-type",f),l=u.parseHeader("content-type");break;case"cseq":u.setHeader("cseq",f),l=u.parseHeader("cseq"),l&&(u.cseq=l.value),u instanceof ki.IncomingResponse&&(u.method=l.method);break;case"max-forwards":u.setHeader("max-forwards",f),l=u.parseHeader("max-forwards");break;case"www-authenticate":u.setHeader("www-authenticate",f),l=u.parseHeader("www-authenticate");break;case"proxy-authenticate":u.setHeader("proxy-authenticate",f),l=u.parseHeader("proxy-authenticate");break;case"session-expires":case"x":u.setHeader("session-expires",f),l=u.parseHeader("session-expires"),l&&(u.session_expires=l.expires,u.session_expires_refresher=l.refresher);break;case"refer-to":case"r":u.setHeader("refer-to",f),l=u.parseHeader("refer-to"),l&&(u.refer_to=l);break;case"replaces":u.setHeader("replaces",f),l=u.parseHeader("replaces"),l&&(u.replaces=l);break;case"event":case"o":u.setHeader("event",f),l=u.parseHeader("event"),l&&(u.event=l);break;default:u.addHeader(i,f),l=0}return l===void 0?{error:`error parsing header "${i}"`}:!0}const Yy={parseMessage:qy},dl=new Ro("Registrator"),qo=10;class zy{constructor(e,t){this._reg_id=1,this._ua=e,this._transport=t,this._registrar=e.configuration.registrar_server,this._expires=e.configuration.register_expires,this._call_id=js.createRandomToken(22),this._cseq=0,this._to_uri=e.configuration.uri,this._registrationTimer=null,this._registering=!1,this._registered=!1,this._contact=this._ua.contact.toString();const r=this._contact.indexOf(">");if(r!==-1){const l=this._contact.slice(0,r)+this._contact.slice(r+1,this._contact.length);this._contact=l}this._extra_contact="",this._extraContactParams="",this._extra_contact+=";+sip.ice",this._extraHeaders=[],this._sipInstance=`"<urn:uuid:${this._ua.configuration.instance_id}>"`,this._extra_contact+=`;reg-id=${this._reg_id}`,this._extra_contact+=`;+sip.instance=${this._sipInstance}`}get registered(){return this._registered}setExtraHeaders(e){Array.isArray(e)||(e=[]),this._extraHeaders=e.slice()}setExtraContactParams(e){e instanceof Object||(e={}),this._extraContactParams="";for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)){const r=e[t];this._extraContactParams+=`;${t}`,r&&(this._extraContactParams+=`=${r}`)}}setExtraContactUriParams(e){e instanceof Object||(e={}),this._extraContactParams="";for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)){const r=e[t];this._extraContactParams+=`;${t}`,r&&(this._extraContactParams+=`=${r}`)}}register(){if(this._registering){dl.debug("Register request in progress...");return}const e=this._extraHeaders.slice();e.push(`Contact: ${this._contact}${this._extraContactParams}>${this._extra_contact};expires=${this._expires}`),e.push(`Expires: ${this._expires}`);const t=new Mt.OutgoingRequest(Z.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},e),r=new nl(this._ua,t,{onRequestTimeout:()=>{this._registrationFailure(null,Z.causes.REQUEST_TIMEOUT)},onTransportError:()=>{this._registrationFailure(null,Z.causes.CONNECTION_ERROR)},onAuthenticated:()=>{this._cseq+=1},onReceiveResponse:l=>{if(l.cseq===this._cseq)switch(this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null),!0){case/^1[0-9]{2}$/.test(l.status_code):break;case/^2[0-9]{2}$/.test(l.status_code):{if(this._registering=!1,!l.hasHeader("Contact")){dl.debug("no Contact header in response to REGISTER, response ignored");break}const s=l.headers.Contact.reduce((d,p)=>d.concat(p.parsed),[]);let i=s.find(d=>this._sipInstance===d.getParam("+sip.instance")&&this._reg_id===parseInt(d.getParam("reg-id")));if(i||(i=s.find(d=>d.uri.user===this._ua.contact.uri.user)),!i){dl.debug("no Contact header pointing to us, response ignored");break}let f=i.getParam("expires");!f&&l.hasHeader("expires")&&(f=l.getHeader("expires")),f||(f=this._expires),f=Number(f),f<qo&&(f=qo);const h=f>64?f*1e3/2+Math.floor((f/2-32)*1e3*Math.random()):f*1e3-5e3;this._registrationTimer=setTimeout(()=>{this._registrationTimer=null,this._ua.listeners("registrationExpiring").length===0?this.register():this._ua.emit("registrationExpiring")},h),i.hasParam("temp-gruu")&&(this._ua.contact.temp_gruu=i.getParam("temp-gruu").replace(/"/g,"")),i.hasParam("pub-gruu")&&(this._ua.contact.pub_gruu=i.getParam("pub-gruu").replace(/"/g,"")),this._registered||(this._registered=!0,this._ua.registered({response:l}));break}case/^423$/.test(l.status_code):{l.hasHeader("min-expires")?(this._expires=Number(l.getHeader("min-expires")),this._expires<qo&&(this._expires=qo),this.register()):(dl.debug("423 response received for REGISTER without Min-Expires"),this._registrationFailure(l,Z.causes.SIP_FAILURE_CODE));break}default:{const s=js.sipErrorCause(l.status_code);this._registrationFailure(l,s)}}}});this._registering=!0,r.send()}unregister(e={}){if(!this._registered){dl.debug("already unregistered");return}this._registered=!1,this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null);const t=this._extraHeaders.slice();e.all?t.push(`Contact: *${this._extraContactParams}`):t.push(`Contact: ${this._contact}${this._extraContactParams}>${this._extra_contact};expires=0`),t.push("Expires: 0");const r=new Mt.OutgoingRequest(Z.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},t);new nl(this._ua,r,{onRequestTimeout:()=>{this._unregistered(null,Z.causes.REQUEST_TIMEOUT)},onTransportError:()=>{this._unregistered(null,Z.causes.CONNECTION_ERROR)},onAuthenticated:()=>{this._cseq+=1},onReceiveResponse:s=>{switch(!0){case/^1[0-9]{2}$/.test(s.status_code):break;case/^2[0-9]{2}$/.test(s.status_code):this._unregistered(s);break;default:{const i=js.sipErrorCause(s.status_code);this._unregistered(s,i)}}}}).send()}close(){this._registered&&this.unregister()}onTransportClosed(){this._registering=!1,this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null),this._registered&&(this._registered=!1,this._ua.unregistered({}))}_registrationFailure(e,t){this._registering=!1,this._ua.registrationFailed({response:e||null,cause:t}),this._registered&&(this._registered=!1,this._ua.unregistered({response:e||null,cause:t}))}_unregistered(e,t){this._registering=!1,this._registered=!1,this._ua.unregistered({response:e||null,cause:t||null})}}const pt=console,_n={STATUS_INIT:0,STATUS_READY:1,STATUS_USER_CLOSED:2,STATUS_NOT_READY:3,CONFIGURATION_ERROR:1,NETWORK_ERROR:2},Xy=Uy;class Jy extends Xy{constructor(e){super(e),this._msrp_sessions=[],this._transactions={nist:{},nict:{},ist:{},ict:{}},this._janus_sessions=[],this.newStreamPlugins=[],this.processStreamPlugins=[],this._registrator=new zy(this)}call(e,t){return super.call(e,t)}joinVideoCall(e,t,r){pt.debug("call()");const l=new Bo(this);return l.configureMedia({audio:!0,video:!0}),l.connect(e,t,r),l}startScreenShare(){pt.debug("startScreenShare()");for(const e in this._janus_sessions)this._janus_sessions[e].connectScreenShare()}changeMediaConstraints(e){for(const t in this._janus_sessions)this._janus_sessions[t].changeMediaConstraints(e)}startBlur(){for(const e in this._janus_sessions)this._janus_sessions[e].connectBlur()}stopBlur(){for(const e in this._janus_sessions)this._janus_sessions[e].stopBlur()}_loadConfig(e){try{fl.load(this._configuration,e)}catch(s){throw s}this._configuration.display_name===0&&(this._configuration.display_name="0"),this._configuration.instance_id||(this._configuration.instance_id=js.newUUID());let t;typeof window<"u"&&typeof window.document<"u"?t=window==null?void 0:window.navigator.userAgent:typeof self<"u"&&self.navigator&&(t=self.navigator.userAgent),t+=" "+Ue.USER_AGENT,this._configuration.user_agent=e.overrideUserAgent&&typeof e.overrideUserAgent=="function"?e.overrideUserAgent(t):t,this._configuration.jssip_id=js.createRandomToken(5);const r=this._configuration.uri.clone();r.user=null,this._configuration.hostport_params=r.toString().replace(/^sip:/i,"");try{this._transport=new oy(this._configuration.sockets,{max_interval:this._configuration.connection_recovery_max_interval,min_interval:this._configuration.connection_recovery_min_interval}),this._transport.onconnecting=Qy.bind(this),this._transport.onconnect=Zy.bind(this),this._transport.ondisconnect=eS.bind(this),this._transport.ondata=tS.bind(this)}catch(s){throw pt.warn(s),new cn.ConfigurationError("sockets",this._configuration.sockets)}if(delete this._configuration.sockets,this._configuration.authorization_user||(this._configuration.authorization_user=this._configuration.uri.user),!this._configuration.registrar_server){const s=this._configuration.uri.clone();s.user=null,s.clearParams(),s.clearHeaders(),this._configuration.registrar_server=s}this._configuration.no_answer_timeout*=1e3,this._configuration.contact_uri?this._configuration.via_host=this._configuration.contact_uri.host:this._configuration.contact_uri=new Kn("sip",js.createRandomToken(8),this._configuration.via_host,null,{transport:"ws"}),this._contact={pub_gruu:null,temp_gruu:null,uri:this._configuration.contact_uri,toString(s={}){const i=s.anonymous||null,f=s.outbound||null;let h="<";return i?h+=this.temp_gruu||"sip:anonymous@anonymous.invalid;transport=ws":h+=this.pub_gruu||this.uri.toString(),f&&(i?!this.temp_gruu:!this.pub_gruu)&&(h+=";ob"),h+=">",h}};const l=["authorization_user","password","realm","ha1","authorization_jwt","display_name","register"];for(const s in this._configuration)Object.prototype.hasOwnProperty.call(this._configuration,s)&&(l.indexOf(s)!==-1?Object.defineProperty(this._configuration,s,{writable:!0,configurable:!1}):Object.defineProperty(this._configuration,s,{writable:!1,configurable:!1}));pt.debug("configuration parameters after validation:");for(const s in this._configuration)if(Object.prototype.hasOwnProperty.call(fl.settings,s))switch(s){case"uri":case"registrar_server":pt.debug(`- ${s}: ${this._configuration[s]}`);break;case"password":case"ha1":case"authorization_jwt":pt.debug(`- ${s}: NOT SHOWN`);break;default:pt.debug(`- ${s}: ${JSON.stringify(this._configuration[s])}`)}}newMSRPSession(e,t){e.on("msgHistoryUpdate",r=>{console.log(r)}),this._msrp_sessions[e.id]=e,this.emit("newMSRPSession",t)}newJanusSession(e,t){this._janus_sessions[e.id]=e,this.newStreamPlugins.forEach(r=>{r.setSession(e)}),this.processStreamPlugins.forEach(r=>{r.setSession(e)}),this.emit("newJanusSession",t)}kill(){}destroyMSRPSession(e){delete this._msrp_sessions[e.id]}destroyJanusSession(e){delete this._janus_sessions[e.id]}receiveRequest(e){var s,i,f,h;const t=e.method;if(e.ruri.user!==this._configuration.uri.user&&e.ruri.user!==this._contact.uri.user){pt.debug("Request-URI does not point to us"),e.method!==Ue.ACK&&e.reply_sl(404);return}if(e.ruri.scheme===Ue.SIPS){e.reply_sl(416);return}if(is.checkTransaction(this,e))return;if(t===Ue.INVITE?new is.InviteServerTransaction(this,this._transport,e):t!==Ue.ACK&&t!==Ue.CANCEL&&new is.NonInviteServerTransaction(this,this._transport,e),t===Ue.OPTIONS){if(this.listeners("newOptions").length===0){e.reply(200);return}new N_.Options(this).init_incoming(e)}else if(t===Ue.MESSAGE){if(this.listeners("newMessage").length===0){e.reply(405);return}new N_.Message(this).init_incoming(e)}else if(t===Ue.INVITE&&!e.to_tag&&this.listeners("newRTCSession").length===0){e.reply(405);return}let r,l;if(e.to_tag)if(r=this._findDialog(e.call_id,e.from_tag,e.to_tag),r)r.receiveRequest(e);else if(t===Ue.NOTIFY)if(l=this._findSession(e),l)l.receiveRequest(e);else{if(e.body)try{const d=JSON.parse(e.body)||{};(i=(s=d.plugindata)==null?void 0:s.data)!=null&&i.publishers&&Object.values(this._janus_sessions)[0].receivePublishers(d),(h=(f=d.plugindata)==null?void 0:f.data)!=null&&h.unpublished&&Object.values(this._janus_sessions)[0].receiveUnpublished(d.plugindata.data.unpublished)}catch(d){console.error(d)}e.reply(200)}else t!==Ue.ACK&&e.reply(481);else switch(t){case Ue.INVITE:if(window.RTCPeerConnection)if(e.hasHeader("replaces")){const d=e.replaces;r=this._findDialog(d.call_id,d.from_tag,d.to_tag),r?(l=r.owner,l.isEnded()?e.reply(603):l.receiveRequest(e)):e.reply(481)}else e.body.search(/MSRP/ig)>-1?(l=new Wh(this),l.init_incoming(e)):e.body.search(/JANUS/ig)>-1||(l=new WT(this),l.init_incoming(e));else pt.warn("INVITE received but WebRTC is not supported"),e.reply(488);break;case Ue.BYE:e.reply(481);break;case Ue.CANCEL:l=this._findSession(e),l?l.receiveRequest(e):pt.debug("received CANCEL request for a non existent session");break;case Ue.ACK:break;case Ue.NOTIFY:this.emit("sipEvent",{event:e.event,request:e}),e.reply(200);break;default:e.reply(405);break}}startMSRP(e,t){pt.debug("startMSRP()",t);const r=new Wh(this);return r.connect(e),r}startJanus(e,t){pt.debug("startJanus()",t);const r=new Wh(this);return r.connect(e),r}terminateMSRPSessions(e){pt.debug("terminateSessions()");for(const t in this._msrp_sessions)this._msrp_sessions[t].isEnded()||this._msrp_sessions[t].terminate(e)}terminateJanusSessions(e){pt.debug("terminateSessions()");for(const t in this._janus_sessions)this._janus_sessions[t].isEnded()||this._janus_sessions[t].terminate(e)}enableJanusAudio(e){pt.debug("enableJanusAudio()");for(const t in this._janus_sessions)this._janus_sessions[t].isEnded()||(e?this._janus_sessions[t].startAudio():this._janus_sessions[t].stopAudio())}enableJanusVideo(e){pt.debug("enableJanusVideo()");for(const t in this._janus_sessions)this._janus_sessions[t].isEnded()||(e?this._janus_sessions[t].startVideo():this._janus_sessions[t].stopVideo())}stop(){if(pt.debug("stop()"),this._dynConfiguration={},this._status===_n.STATUS_USER_CLOSED){pt.debug("UA already closed");return}this._registrator.close();const e=Object.keys(this._sessions).length;for(const r in this._sessions)if(Object.prototype.hasOwnProperty.call(this._sessions,r)){pt.debug(`closing session ${r}`);try{this._sessions[r].terminate()}catch(l){console.error(l)}}for(const r in this._msrp_sessions)if(Object.prototype.hasOwnProperty.call(this._msrp_sessions,r)){pt.debug(`closing session ${r}`);try{this._msrp_sessions[r].terminate()}catch(l){console.error(l)}}for(const r in this._janus_sessions)if(Object.prototype.hasOwnProperty.call(this._janus_sessions,r)){pt.debug(`closing session ${r}`);try{this._janus_sessions[r].terminate()}catch(l){console.error(l)}}for(const r in this._applicants)if(Object.prototype.hasOwnProperty.call(this._applicants,r))try{this._applicants[r].close()}catch(l){console.error(l)}this._status=_n.STATUS_USER_CLOSED,Object.keys(this._transactions.nict).length+Object.keys(this._transactions.nist).length+Object.keys(this._transactions.ict).length+Object.keys(this._transactions.ist).length===0&&e===0?this._transport.disconnect():this._closeTimer=setTimeout(()=>{this._closeTimer=null,this._transport.disconnect()},2e3)}}function Qy(u){this.emit("connecting",u)}function Zy(u){this._status!==_n.STATUS_USER_CLOSED&&(this._status=_n.STATUS_READY,this._error=null,this.emit("connected",u),this._dynConfiguration.register&&this._registrator.register())}function eS(u){const e=["nict","ict","nist","ist"];for(const t of e)for(const r in this._transactions[t])Object.prototype.hasOwnProperty.call(this._transactions[t],r)&&this._transactions[t][r].onTransportError();this.emit("disconnected",u),this._registrator.onTransportClosed(),this._status!==_n.STATUS_USER_CLOSED&&(this._status=_n.STATUS_NOT_READY,this._error=_n.NETWORK_ERROR)}function tS(u){const e=u.transport;let t=u.message;if(t=Yy.parseMessage(t,this),!!t&&!(this._status===_n.STATUS_USER_CLOSED&&t instanceof ki.IncomingRequest)&&Cy(t,this,e)){if(t instanceof ki.IncomingRequest)t.transport=e,this.receiveRequest(t);else if(t instanceof ki.IncomingResponse){let r;switch(t.method){case Ue.INVITE:r=this._transactions.ict[t.via_branch],r&&r.receiveResponse(t);break;case Ue.ACK:break;default:r=this._transactions.nict[t.via_branch],r&&r.receiveResponse(t);break}}}}const sS=["roomId","_audioMuted","_cancel_reason","_contact","direction","_end_time","_eventsCount","_from_tag","_id","_is_canceled","_is_confirmed","_late_sdp","_localHold","_videoMuted","status","start_time","_remote_identity","audioTag","isOnHold","localMuted","autoAnswer","putOnHoldTimestamp"],nS=["_cancel_reason","_contact","direction","_end_time","_eventsCount","_from_tag","_id","_is_canceled","_is_confirmed","_late_sdp","status","start_time","_remote_identity","target_addr"];function Rg(u){const e={};return sS.forEach(t=>{u[t]!==void 0&&(e[t]=u[t])}),e.localHold=u._localHold,e}function wg(u){const e={};return nS.forEach(t=>{u[t]!==void 0&&(e[t]=u[t])}),e}function Ig(u,e){const t=new AudioContext,r=t.createMediaStreamSource(u),l=t.createMediaStreamDestination(),s=t.createGain();return r.connect(s),s.connect(l),s.gain.value=e,l.stream}function iS(u,e,t,r){const l=document.createElement("audio");l.id=e._id,l.className="audioTag",l.srcObject=u,Og()||(l.setSinkId(t),l.volume=r),l.play(),e.audioTag=l}function rS(u){if(u&&typeof u.log=="function"&&typeof u.warn=="function"&&typeof u.error=="function")return!0}function Og(){return/Mobi|Android|iPhone/i.test(navigator.userAgent)}class Dg{constructor(e){this.opensips=null,this.session=null,this.name=null,this.name=e}setOpensips(e){this.opensips=e}setSession(e){this.session=e}kill(){this.opensips.kill(this.name)}}class Wo extends Dg{constructor(e,t){super(e),this._candidates=[],this._subscribeSent=!1,this._configureSent=!1,this._lastTrickleReceived=!1,this.type=t}connect(e={}){this.opaqueId=this.session.generateOpaqueId();const t=je.cloneArray(e.extraHeaders),r={from_tag:this.session._from_tag};e.fromUserName&&(r.from_uri=new Kn("sip",e.fromUserName,this.session._ua.configuration.uri.host),t.push(`P-Preferred-Identity: ${this.session._ua.configuration.uri.toString()}`)),e.fromDisplayName&&(r.from_display_name=e.fromDisplayName),t.push(`Contact: ${this.session._contact}`),t.push("Content-Type: application/json"),this.session._sessionTimers.enabled&&t.push(`Session-Expires: ${this.session._sessionTimers.defaultExpires}${this.session._ua.configuration.session_timers_force_refresher?";refresher=uac":""}`),this._request=new Mt.InitialOutgoingInviteRequest(this.session.target,this.session._ua,r,t),this._createRTCConnection(),this._sendInitialRequest()}getStream(){return this.stream}getConnection(){return this._connection}_createRTCConnection(){this._connection=new RTCPeerConnection({iceServers:[{urls:"stun:turn.voicenter.co",credential:"kxsjahnsdjns3eds23esd",username:"turn2es21e"}]});let e;this._connection.onicecandidate=t=>{this._connection.signalingState!=="stable"&&this._connection.signalingState!=="have-local-offer"||t.candidate&&(this._candidates.push(t.candidate),clearTimeout(e),e=setTimeout(()=>{this._lastTrickleReceived=!0,this._subscribeSent&&!this._configureSent&&this._sendConfigureMessage({audio:!0,video:!0})},500))}}addTracks(e){e.forEach(t=>{this._connection.addTrack(t)})}async _sendInitialRequest(){const e=new nl(this.session._ua,this._request,{onRequestTimeout:()=>{this.session.onRequestTimeout()},onTransportError:()=>{this.session.onTransportError()},onAuthenticated:s=>{this._request=s},onReceiveResponse:s=>{this._receiveInviteResponse(s)}});if(await this.generateStream(),!this.stream||!this.stream.getTracks().length)return;this.addTracks(this.stream.getTracks());const t={audio:!1,video:!0};this.jsep_offer=await this._connection.createOffer(t),await this._connection.setLocalDescription(this.jsep_offer);const r={janus:"attach",plugin:"janus.plugin.videoroom",opaque_id:this.opaqueId},l=JSON.stringify(r);this._request.body=l,e.send()}_receiveInviteResponse(e){if(this._publisherSubscribeSent||!e.body)return;const t=JSON.parse(e.body);this.handleId=t.data.id;const r={janus:"message",body:{request:"join",room:this.session.room_id,ptype:"publisher",display:this.session.display_name+" (Screen Share)",opaque_id:this.opaqueId},handle_id:this.handleId},l=[this.session.getPTypeHeader(Zt.PUBLISHER)];this.session.sendRequest(Z.SUBSCRIBE,{extraHeaders:l,body:JSON.stringify(r),eventHandlers:{onSuccessResponse:async s=>{var i,f,h,d;if(s.status_code===200){if(this._subscribeSent=!0,s.body)try{const p=JSON.parse(s.body)||{};((f=(i=p.plugindata)==null?void 0:i.data)==null?void 0:f.videoroom)==="joined"&&this.session.myFeedList.push(p.plugindata.data.id),(d=(h=p.plugindata)==null?void 0:h.data)!=null&&d.publishers&&this.session.receivePublishers(p)}catch(p){console.error(p)}this._lastTrickleReceived&&!this._configureSent&&this._sendConfigureMessage({audio:!0,video:!0})}}}}),this._publisherSubscribeSent=!0}async _sendConfigureMessage(e){const t=this._candidates.map(i=>({janus:"trickle",candidate:i,handle_id:this.handleId,session_id:this.session.session_id})),l={configure:{janus:"message",body:{request:"configure",record:!0,filename:this.session.getRecordFileName(),...e},jsep:this.jsep_offer,handle_id:this.handleId,session_id:this.session.session_id},trickles:[...t]},s=["Content-Type: application/json",this.session.getPTypeHeader(Zt.ICE)];this.session.sendRequest(Z.INFO,{extraHeaders:s,body:JSON.stringify(l),eventHandlers:{onSuccessResponse:async i=>{this._configureSent=!0;const h=i.data.split(`\r
159
159
  `),d=h[h.length-1],p=JSON.parse(d);await this._connection.setRemoteDescription(p.jsep),this._candidates=[]}}})}_sendDetach(){const e={janus:"detach",handle_id:this.handleId,session_id:this.session.session_id},t=[this.session.getPTypeHeader(Zt.DETACH)];this.session.sendRequest(Z.INFO,{extraHeaders:t,body:JSON.stringify(e)}),this.session._ua.emit("pluginDetach",this.name)}async stopMedia(){this._connection&&(this._connection.close(),this._connection=null),this.stream&&(this.stream=null)}async stop(){await this.session.stopProcessPlugins(this.type);const e=this._connection.getSenders();e.forEach(t=>{const r=t.track;r&&r.stop()}),e.forEach(t=>{this._connection.removeTrack(t)}),await this.stopMedia(),this._sendDetach()}async generateStream(){throw new Error("generateStream method is not implemented")}}class lS extends Wo{constructor(){super("ScreenShare","screen")}async generateStream(){try{this.stream=await navigator.mediaDevices.getDisplayMedia(),this.stream.getVideoTracks()[0].onended=()=>{this.kill()},this.session._ua.emit("startScreenShare",{stream:this.stream,handleId:this.handleId,sender:"me",type:"publisher"})}catch(e){this.kill(),console.error(e)}return this.stream}async kill(){await this.stop(),this.session._ua.emit("stopScreenShare")}}var Yh={exports:{}},Ko={},Ng={},Le={};(function(u){Object.defineProperty(u,"__esModule",{value:!0}),u._registerNode=u.Konva=u.glob=void 0;const e=Math.PI/180;function t(){return typeof window<"u"&&({}.toString.call(window)==="[object Window]"||{}.toString.call(window)==="[object global]")}u.glob=typeof fs<"u"?fs:typeof window<"u"?window:typeof WorkerGlobalScope<"u"?self:{},u.Konva={_global:u.glob,version:"9.3.16",isBrowser:t(),isUnminified:/param/.test((function(l){}).toString()),dblClickWindow:400,getAngle(l){return u.Konva.angleDeg?l*e:l},enableTrace:!1,pointerEventsEnabled:!0,autoDrawEnabled:!0,hitOnDragEnabled:!1,capturePointerEventsEnabled:!1,_mouseListenClick:!1,_touchListenClick:!1,_pointerListenClick:!1,_mouseInDblClickWindow:!1,_touchInDblClickWindow:!1,_pointerInDblClickWindow:!1,_mouseDblClickPointerId:null,_touchDblClickPointerId:null,_pointerDblClickPointerId:null,_fixTextRendering:!1,pixelRatio:typeof window<"u"&&window.devicePixelRatio||1,dragDistance:3,angleDeg:!0,showWarnings:!0,dragButtons:[0,1],isDragging(){return u.Konva.DD.isDragging},isTransforming(){var l;return(l=u.Konva.Transformer)===null||l===void 0?void 0:l.isTransforming()},isDragReady(){return!!u.Konva.DD.node},releaseCanvasOnDestroy:!0,document:u.glob.document,_injectGlobal(l){u.glob.Konva=l}};const r=l=>{u.Konva[l.prototype.getClassName()]=l};u._registerNode=r,u.Konva._injectGlobal(u.Konva)})(Le);var rt={};(function(u){Object.defineProperty(u,"__esModule",{value:!0}),u.Util=u.Transform=void 0;const e=Le;class t{constructor(b=[1,0,0,1,0,0]){this.dirty=!1,this.m=b&&b.slice()||[1,0,0,1,0,0]}reset(){this.m[0]=1,this.m[1]=0,this.m[2]=0,this.m[3]=1,this.m[4]=0,this.m[5]=0}copy(){return new t(this.m)}copyInto(b){b.m[0]=this.m[0],b.m[1]=this.m[1],b.m[2]=this.m[2],b.m[3]=this.m[3],b.m[4]=this.m[4],b.m[5]=this.m[5]}point(b){const w=this.m;return{x:w[0]*b.x+w[2]*b.y+w[4],y:w[1]*b.x+w[3]*b.y+w[5]}}translate(b,w){return this.m[4]+=this.m[0]*b+this.m[2]*w,this.m[5]+=this.m[1]*b+this.m[3]*w,this}scale(b,w){return this.m[0]*=b,this.m[1]*=b,this.m[2]*=w,this.m[3]*=w,this}rotate(b){const w=Math.cos(b),F=Math.sin(b),q=this.m[0]*w+this.m[2]*F,D=this.m[1]*w+this.m[3]*F,P=this.m[0]*-F+this.m[2]*w,I=this.m[1]*-F+this.m[3]*w;return this.m[0]=q,this.m[1]=D,this.m[2]=P,this.m[3]=I,this}getTranslation(){return{x:this.m[4],y:this.m[5]}}skew(b,w){const F=this.m[0]+this.m[2]*w,q=this.m[1]+this.m[3]*w,D=this.m[2]+this.m[0]*b,P=this.m[3]+this.m[1]*b;return this.m[0]=F,this.m[1]=q,this.m[2]=D,this.m[3]=P,this}multiply(b){const w=this.m[0]*b.m[0]+this.m[2]*b.m[1],F=this.m[1]*b.m[0]+this.m[3]*b.m[1],q=this.m[0]*b.m[2]+this.m[2]*b.m[3],D=this.m[1]*b.m[2]+this.m[3]*b.m[3],P=this.m[0]*b.m[4]+this.m[2]*b.m[5]+this.m[4],I=this.m[1]*b.m[4]+this.m[3]*b.m[5]+this.m[5];return this.m[0]=w,this.m[1]=F,this.m[2]=q,this.m[3]=D,this.m[4]=P,this.m[5]=I,this}invert(){const b=1/(this.m[0]*this.m[3]-this.m[1]*this.m[2]),w=this.m[3]*b,F=-this.m[1]*b,q=-this.m[2]*b,D=this.m[0]*b,P=b*(this.m[2]*this.m[5]-this.m[3]*this.m[4]),I=b*(this.m[1]*this.m[4]-this.m[0]*this.m[5]);return this.m[0]=w,this.m[1]=F,this.m[2]=q,this.m[3]=D,this.m[4]=P,this.m[5]=I,this}getMatrix(){return this.m}decompose(){const b=this.m[0],w=this.m[1],F=this.m[2],q=this.m[3],D=this.m[4],P=this.m[5],I=b*q-w*F,x={x:D,y:P,rotation:0,scaleX:0,scaleY:0,skewX:0,skewY:0};if(b!=0||w!=0){const U=Math.sqrt(b*b+w*w);x.rotation=w>0?Math.acos(b/U):-Math.acos(b/U),x.scaleX=U,x.scaleY=I/U,x.skewX=(b*F+w*q)/I,x.skewY=0}else if(F!=0||q!=0){const U=Math.sqrt(F*F+q*q);x.rotation=Math.PI/2-(q>0?Math.acos(-F/U):-Math.acos(F/U)),x.scaleX=I/U,x.scaleY=U,x.skewX=0,x.skewY=(b*F+w*q)/I}return x.rotation=u.Util._getRotation(x.rotation),x}}u.Transform=t;let r="[object Array]",l="[object Number]",s="[object String]",i="[object Boolean]",f=Math.PI/180,h=180/Math.PI,d="#",p="",v="0",T="Konva warning: ",y="Konva error: ",S="rgb(",A={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,132,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,255,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,203],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[119,128,144],slategrey:[119,128,144],snow:[255,255,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],transparent:[255,255,255,0],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,5]},R=/rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)/,O=[];const N=typeof requestAnimationFrame<"u"&&requestAnimationFrame||function(C){setTimeout(C,60)};u.Util={_isElement(C){return!!(C&&C.nodeType==1)},_isFunction(C){return!!(C&&C.constructor&&C.call&&C.apply)},_isPlainObject(C){return!!C&&C.constructor===Object},_isArray(C){return Object.prototype.toString.call(C)===r},_isNumber(C){return Object.prototype.toString.call(C)===l&&!isNaN(C)&&isFinite(C)},_isString(C){return Object.prototype.toString.call(C)===s},_isBoolean(C){return Object.prototype.toString.call(C)===i},isObject(C){return C instanceof Object},isValidSelector(C){if(typeof C!="string")return!1;const b=C[0];return b==="#"||b==="."||b===b.toUpperCase()},_sign(C){return C===0||C>0?1:-1},requestAnimFrame(C){O.push(C),O.length===1&&N(function(){const b=O;O=[],b.forEach(function(w){w()})})},createCanvasElement(){const C=document.createElement("canvas");try{C.style=C.style||{}}catch{}return C},createImageElement(){return document.createElement("img")},_isInDocument(C){for(;C=C.parentNode;)if(C==document)return!0;return!1},_urlToImage(C,b){const w=u.Util.createImageElement();w.onload=function(){b(w)},w.src=C},_rgbToHex(C,b,w){return(16777216+(C<<16)+(b<<8)+w).toString(16).slice(1)},_hexToRgb(C){C=C.replace(d,p);const b=parseInt(C,16);return{r:b>>16&255,g:b>>8&255,b:b&255}},getRandomColor(){let C=(Math.random()*16777215<<0).toString(16);for(;C.length<6;)C=v+C;return d+C},getRGB(C){let b;return C in A?(b=A[C],{r:b[0],g:b[1],b:b[2]}):C[0]===d?this._hexToRgb(C.substring(1)):C.substr(0,4)===S?(b=R.exec(C.replace(/ /g,"")),{r:parseInt(b[1],10),g:parseInt(b[2],10),b:parseInt(b[3],10)}):{r:0,g:0,b:0}},colorToRGBA(C){return C=C||"black",u.Util._namedColorToRBA(C)||u.Util._hex3ColorToRGBA(C)||u.Util._hex4ColorToRGBA(C)||u.Util._hex6ColorToRGBA(C)||u.Util._hex8ColorToRGBA(C)||u.Util._rgbColorToRGBA(C)||u.Util._rgbaColorToRGBA(C)||u.Util._hslColorToRGBA(C)},_namedColorToRBA(C){const b=A[C.toLowerCase()];return b?{r:b[0],g:b[1],b:b[2],a:1}:null},_rgbColorToRGBA(C){if(C.indexOf("rgb(")===0){C=C.match(/rgb\(([^)]+)\)/)[1];const b=C.split(/ *, */).map(Number);return{r:b[0],g:b[1],b:b[2],a:1}}},_rgbaColorToRGBA(C){if(C.indexOf("rgba(")===0){C=C.match(/rgba\(([^)]+)\)/)[1];const b=C.split(/ *, */).map((w,F)=>w.slice(-1)==="%"?F===3?parseInt(w)/100:parseInt(w)/100*255:Number(w));return{r:b[0],g:b[1],b:b[2],a:b[3]}}},_hex8ColorToRGBA(C){if(C[0]==="#"&&C.length===9)return{r:parseInt(C.slice(1,3),16),g:parseInt(C.slice(3,5),16),b:parseInt(C.slice(5,7),16),a:parseInt(C.slice(7,9),16)/255}},_hex6ColorToRGBA(C){if(C[0]==="#"&&C.length===7)return{r:parseInt(C.slice(1,3),16),g:parseInt(C.slice(3,5),16),b:parseInt(C.slice(5,7),16),a:1}},_hex4ColorToRGBA(C){if(C[0]==="#"&&C.length===5)return{r:parseInt(C[1]+C[1],16),g:parseInt(C[2]+C[2],16),b:parseInt(C[3]+C[3],16),a:parseInt(C[4]+C[4],16)/255}},_hex3ColorToRGBA(C){if(C[0]==="#"&&C.length===4)return{r:parseInt(C[1]+C[1],16),g:parseInt(C[2]+C[2],16),b:parseInt(C[3]+C[3],16),a:1}},_hslColorToRGBA(C){if(/hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)/g.test(C)){const[b,...w]=/hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)/g.exec(C),F=Number(w[0])/360,q=Number(w[1])/100,D=Number(w[2])/100;let P,I,x;if(q===0)return x=D*255,{r:Math.round(x),g:Math.round(x),b:Math.round(x),a:1};D<.5?P=D*(1+q):P=D+q-D*q;const U=2*D-P,B=[0,0,0];for(let z=0;z<3;z++)I=F+.3333333333333333*-(z-1),I<0&&I++,I>1&&I--,6*I<1?x=U+(P-U)*6*I:2*I<1?x=P:3*I<2?x=U+(P-U)*(.6666666666666666-I)*6:x=U,B[z]=x*255;return{r:Math.round(B[0]),g:Math.round(B[1]),b:Math.round(B[2]),a:1}}},haveIntersection(C,b){return!(b.x>C.x+C.width||b.x+b.width<C.x||b.y>C.y+C.height||b.y+b.height<C.y)},cloneObject(C){const b={};for(const w in C)this._isPlainObject(C[w])?b[w]=this.cloneObject(C[w]):this._isArray(C[w])?b[w]=this.cloneArray(C[w]):b[w]=C[w];return b},cloneArray(C){return C.slice(0)},degToRad(C){return C*f},radToDeg(C){return C*h},_degToRad(C){return u.Util.warn("Util._degToRad is removed. Please use public Util.degToRad instead."),u.Util.degToRad(C)},_radToDeg(C){return u.Util.warn("Util._radToDeg is removed. Please use public Util.radToDeg instead."),u.Util.radToDeg(C)},_getRotation(C){return e.Konva.angleDeg?u.Util.radToDeg(C):C},_capitalize(C){return C.charAt(0).toUpperCase()+C.slice(1)},throw(C){throw new Error(y+C)},error(C){console.error(y+C)},warn(C){e.Konva.showWarnings&&console.warn(T+C)},each(C,b){for(const w in C)b(w,C[w])},_inRange(C,b,w){return b<=C&&C<w},_getProjectionToSegment(C,b,w,F,q,D){let P,I,x;const U=(C-w)*(C-w)+(b-F)*(b-F);if(U==0)P=C,I=b,x=(q-w)*(q-w)+(D-F)*(D-F);else{const B=((q-C)*(w-C)+(D-b)*(F-b))/U;B<0?(P=C,I=b,x=(C-q)*(C-q)+(b-D)*(b-D)):B>1?(P=w,I=F,x=(w-q)*(w-q)+(F-D)*(F-D)):(P=C+B*(w-C),I=b+B*(F-b),x=(P-q)*(P-q)+(I-D)*(I-D))}return[P,I,x]},_getProjectionToLine(C,b,w){const F=u.Util.cloneObject(C);let q=Number.MAX_VALUE;return b.forEach(function(D,P){if(!w&&P===b.length-1)return;const I=b[(P+1)%b.length],x=u.Util._getProjectionToSegment(D.x,D.y,I.x,I.y,C.x,C.y),U=x[0],B=x[1],z=x[2];z<q&&(F.x=U,F.y=B,q=z)}),F},_prepareArrayForTween(C,b,w){let F,q=[],D=[];if(C.length>b.length){const I=b;b=C,C=I}for(F=0;F<C.length;F+=2)q.push({x:C[F],y:C[F+1]});for(F=0;F<b.length;F+=2)D.push({x:b[F],y:b[F+1]});const P=[];return D.forEach(function(I){const x=u.Util._getProjectionToLine(I,q,w);P.push(x.x),P.push(x.y)}),P},_prepareToStringify(C){let b;C.visitedByCircularReferenceRemoval=!0;for(const w in C)if(C.hasOwnProperty(w)&&C[w]&&typeof C[w]=="object"){if(b=Object.getOwnPropertyDescriptor(C,w),C[w].visitedByCircularReferenceRemoval||u.Util._isElement(C[w]))if(b.configurable)delete C[w];else return null;else if(u.Util._prepareToStringify(C[w])===null)if(b.configurable)delete C[w];else return null}return delete C.visitedByCircularReferenceRemoval,C},_assign(C,b){for(const w in b)C[w]=b[w];return C},_getFirstPointerId(C){return C.touches?C.changedTouches[0].identifier:C.pointerId||999},releaseCanvas(...C){e.Konva.releaseCanvasOnDestroy&&C.forEach(b=>{b.width=0,b.height=0})},drawRoundedRectPath(C,b,w,F){let q=0,D=0,P=0,I=0;typeof F=="number"?q=D=P=I=Math.min(F,b/2,w/2):(q=Math.min(F[0]||0,b/2,w/2),D=Math.min(F[1]||0,b/2,w/2),I=Math.min(F[2]||0,b/2,w/2),P=Math.min(F[3]||0,b/2,w/2)),C.moveTo(q,0),C.lineTo(b-D,0),C.arc(b-D,D,D,Math.PI*3/2,0,!1),C.lineTo(b,w-I),C.arc(b-I,w-I,I,0,Math.PI/2,!1),C.lineTo(P,w),C.arc(P,w-P,P,Math.PI/2,Math.PI,!1),C.lineTo(0,q),C.arc(q,q,q,Math.PI,Math.PI*3/2,!1)}}})(rt);var it={},Fe={},Ne={};Object.defineProperty(Ne,"__esModule",{value:!0}),Ne.RGBComponent=aS,Ne.alphaComponent=oS,Ne.getNumberValidator=uS,Ne.getNumberOrArrayOfNumbersValidator=cS,Ne.getNumberOrAutoValidator=hS,Ne.getStringValidator=fS,Ne.getStringOrGradientValidator=dS,Ne.getFunctionValidator=_S,Ne.getNumberArrayValidator=gS,Ne.getBooleanValidator=pS,Ne.getComponentValidator=mS;const qs=Le,ht=rt;function Ws(u){return ht.Util._isString(u)?'"'+u+'"':Object.prototype.toString.call(u)==="[object Number]"||ht.Util._isBoolean(u)?u:Object.prototype.toString.call(u)}function aS(u){return u>255?255:u<0?0:Math.round(u)}function oS(u){return u>1?1:u<1e-4?1e-4:u}function uS(){if(qs.Konva.isUnminified)return function(u,e){return ht.Util._isNumber(u)||ht.Util.warn(Ws(u)+' is a not valid value for "'+e+'" attribute. The value should be a number.'),u}}function cS(u){if(qs.Konva.isUnminified)return function(e,t){const r=ht.Util._isNumber(e),l=ht.Util._isArray(e)&&e.length==u;return!r&&!l&&ht.Util.warn(Ws(e)+' is a not valid value for "'+t+'" attribute. The value should be a number or Array<number>('+u+")"),e}}function hS(){if(qs.Konva.isUnminified)return function(u,e){return ht.Util._isNumber(u)||u==="auto"||ht.Util.warn(Ws(u)+' is a not valid value for "'+e+'" attribute. The value should be a number or "auto".'),u}}function fS(){if(qs.Konva.isUnminified)return function(u,e){return ht.Util._isString(u)||ht.Util.warn(Ws(u)+' is a not valid value for "'+e+'" attribute. The value should be a string.'),u}}function dS(){if(qs.Konva.isUnminified)return function(u,e){const t=ht.Util._isString(u),r=Object.prototype.toString.call(u)==="[object CanvasGradient]"||u&&u.addColorStop;return t||r||ht.Util.warn(Ws(u)+' is a not valid value for "'+e+'" attribute. The value should be a string or a native gradient.'),u}}function _S(){if(qs.Konva.isUnminified)return function(u,e){return ht.Util._isFunction(u)||ht.Util.warn(Ws(u)+' is a not valid value for "'+e+'" attribute. The value should be a function.'),u}}function gS(){if(qs.Konva.isUnminified)return function(u,e){const t=Int8Array?Object.getPrototypeOf(Int8Array):null;return t&&u instanceof t||(ht.Util._isArray(u)?u.forEach(function(r){ht.Util._isNumber(r)||ht.Util.warn('"'+e+'" attribute has non numeric element '+r+". Make sure that all elements are numbers.")}):ht.Util.warn(Ws(u)+' is a not valid value for "'+e+'" attribute. The value should be a array of numbers.')),u}}function pS(){if(qs.Konva.isUnminified)return function(u,e){return u===!0||u===!1||ht.Util.warn(Ws(u)+' is a not valid value for "'+e+'" attribute. The value should be a boolean.'),u}}function mS(u){if(qs.Konva.isUnminified)return function(e,t){return e==null||ht.Util.isObject(e)||ht.Util.warn(Ws(e)+' is a not valid value for "'+t+'" attribute. The value should be an object with properties '+u),e}}(function(u){Object.defineProperty(u,"__esModule",{value:!0}),u.Factory=void 0;const e=rt,t=Ne,r="get",l="set";u.Factory={addGetterSetter(s,i,f,h,d){u.Factory.addGetter(s,i,f),u.Factory.addSetter(s,i,h,d),u.Factory.addOverloadedGetterSetter(s,i)},addGetter(s,i,f){const h=r+e.Util._capitalize(i);s.prototype[h]=s.prototype[h]||function(){const d=this.attrs[i];return d===void 0?f:d}},addSetter(s,i,f,h){const d=l+e.Util._capitalize(i);s.prototype[d]||u.Factory.overWriteSetter(s,i,f,h)},overWriteSetter(s,i,f,h){const d=l+e.Util._capitalize(i);s.prototype[d]=function(p){return f&&p!==void 0&&p!==null&&(p=f.call(this,p,i)),this._setAttr(i,p),h&&h.call(this),this}},addComponentsGetterSetter(s,i,f,h,d){let p=f.length,v=e.Util._capitalize,T=r+v(i),y=l+v(i),S,A;s.prototype[T]=function(){const O={};for(S=0;S<p;S++)A=f[S],O[A]=this.getAttr(i+v(A));return O};const R=(0,t.getComponentValidator)(f);s.prototype[y]=function(O){let N=this.attrs[i],C;h&&(O=h.call(this,O)),R&&R.call(this,O,i);for(C in O)O.hasOwnProperty(C)&&this._setAttr(i+v(C),O[C]);return O||f.forEach(b=>{this._setAttr(i+v(b),void 0)}),this._fireChangeEvent(i,N,O),d&&d.call(this),this},u.Factory.addOverloadedGetterSetter(s,i)},addOverloadedGetterSetter(s,i){const f=e.Util._capitalize(i),h=l+f,d=r+f;s.prototype[i]=function(){return arguments.length?(this[h](arguments[0]),this):this[d]()}},addDeprecatedGetterSetter(s,i,f,h){e.Util.error("Adding deprecated "+i);const d=r+e.Util._capitalize(i),p=i+" property is deprecated and will be removed soon. Look at Konva change log for more information.";s.prototype[d]=function(){e.Util.error(p);const v=this.attrs[i];return v===void 0?f:v},u.Factory.addSetter(s,i,h,function(){e.Util.error(p)}),u.Factory.addOverloadedGetterSetter(s,i)},backCompat(s,i){e.Util.each(i,function(f,h){const d=s.prototype[h],p=r+e.Util._capitalize(f),v=l+e.Util._capitalize(f);function T(){d.apply(this,arguments),e.Util.error('"'+f+'" method is deprecated and will be removed soon. Use ""'+h+'" instead.')}s.prototype[f]=T,s.prototype[p]=T,s.prototype[v]=T})},afterSetFilter(){this._filterUpToDate=!1}}})(Fe);var ms={},Ks={};Object.defineProperty(Ks,"__esModule",{value:!0}),Ks.HitContext=Ks.SceneContext=Ks.Context=void 0;const Pg=rt,vS=Le;function TS(u){let e=[],t=u.length,r=Pg.Util,l,s;for(l=0;l<t;l++)s=u[l],r._isNumber(s)?s=Math.round(s*1e3)/1e3:r._isString(s)||(s=s+""),e.push(s);return e}const xg=",",yS="(",SS=")",ES="([",CS="])",AS=";",bS="()",RS="=",kg=["arc","arcTo","beginPath","bezierCurveTo","clearRect","clip","closePath","createLinearGradient","createPattern","createRadialGradient","drawImage","ellipse","fill","fillText","getImageData","createImageData","lineTo","moveTo","putImageData","quadraticCurveTo","rect","roundRect","restore","rotate","save","scale","setLineDash","setTransform","stroke","strokeText","transform","translate"],wS=["fillStyle","strokeStyle","shadowColor","shadowBlur","shadowOffsetX","shadowOffsetY","letterSpacing","lineCap","lineDashOffset","lineJoin","lineWidth","miterLimit","direction","font","textAlign","textBaseline","globalAlpha","globalCompositeOperation","imageSmoothingEnabled"],IS=100;class Yo{constructor(e){this.canvas=e,vS.Konva.enableTrace&&(this.traceArr=[],this._enableTrace())}fillShape(e){e.fillEnabled()&&this._fill(e)}_fill(e){}strokeShape(e){e.hasStroke()&&this._stroke(e)}_stroke(e){}fillStrokeShape(e){e.attrs.fillAfterStrokeEnabled?(this.strokeShape(e),this.fillShape(e)):(this.fillShape(e),this.strokeShape(e))}getTrace(e,t){let r=this.traceArr,l=r.length,s="",i,f,h,d;for(i=0;i<l;i++)f=r[i],h=f.method,h?(d=f.args,s+=h,e?s+=bS:Pg.Util._isArray(d[0])?s+=ES+d.join(xg)+CS:(t&&(d=d.map(p=>typeof p=="number"?Math.floor(p):p)),s+=yS+d.join(xg)+SS)):(s+=f.property,e||(s+=RS+f.val)),s+=AS;return s}clearTrace(){this.traceArr=[]}_trace(e){let t=this.traceArr,r;t.push(e),r=t.length,r>=IS&&t.shift()}reset(){const e=this.getCanvas().getPixelRatio();this.setTransform(1*e,0,0,1*e,0,0)}getCanvas(){return this.canvas}clear(e){const t=this.getCanvas();e?this.clearRect(e.x||0,e.y||0,e.width||0,e.height||0):this.clearRect(0,0,t.getWidth()/t.pixelRatio,t.getHeight()/t.pixelRatio)}_applyLineCap(e){const t=e.attrs.lineCap;t&&this.setAttr("lineCap",t)}_applyOpacity(e){const t=e.getAbsoluteOpacity();t!==1&&this.setAttr("globalAlpha",t)}_applyLineJoin(e){const t=e.attrs.lineJoin;t&&this.setAttr("lineJoin",t)}setAttr(e,t){this._context[e]=t}arc(e,t,r,l,s,i){this._context.arc(e,t,r,l,s,i)}arcTo(e,t,r,l,s){this._context.arcTo(e,t,r,l,s)}beginPath(){this._context.beginPath()}bezierCurveTo(e,t,r,l,s,i){this._context.bezierCurveTo(e,t,r,l,s,i)}clearRect(e,t,r,l){this._context.clearRect(e,t,r,l)}clip(...e){this._context.clip.apply(this._context,e)}closePath(){this._context.closePath()}createImageData(e,t){const r=arguments;if(r.length===2)return this._context.createImageData(e,t);if(r.length===1)return this._context.createImageData(e)}createLinearGradient(e,t,r,l){return this._context.createLinearGradient(e,t,r,l)}createPattern(e,t){return this._context.createPattern(e,t)}createRadialGradient(e,t,r,l,s,i){return this._context.createRadialGradient(e,t,r,l,s,i)}drawImage(e,t,r,l,s,i,f,h,d){const p=arguments,v=this._context;p.length===3?v.drawImage(e,t,r):p.length===5?v.drawImage(e,t,r,l,s):p.length===9&&v.drawImage(e,t,r,l,s,i,f,h,d)}ellipse(e,t,r,l,s,i,f,h){this._context.ellipse(e,t,r,l,s,i,f,h)}isPointInPath(e,t,r,l){return r?this._context.isPointInPath(r,e,t,l):this._context.isPointInPath(e,t,l)}fill(...e){this._context.fill.apply(this._context,e)}fillRect(e,t,r,l){this._context.fillRect(e,t,r,l)}strokeRect(e,t,r,l){this._context.strokeRect(e,t,r,l)}fillText(e,t,r,l){l?this._context.fillText(e,t,r,l):this._context.fillText(e,t,r)}measureText(e){return this._context.measureText(e)}getImageData(e,t,r,l){return this._context.getImageData(e,t,r,l)}lineTo(e,t){this._context.lineTo(e,t)}moveTo(e,t){this._context.moveTo(e,t)}rect(e,t,r,l){this._context.rect(e,t,r,l)}roundRect(e,t,r,l,s){this._context.roundRect(e,t,r,l,s)}putImageData(e,t,r){this._context.putImageData(e,t,r)}quadraticCurveTo(e,t,r,l){this._context.quadraticCurveTo(e,t,r,l)}restore(){this._context.restore()}rotate(e){this._context.rotate(e)}save(){this._context.save()}scale(e,t){this._context.scale(e,t)}setLineDash(e){this._context.setLineDash?this._context.setLineDash(e):"mozDash"in this._context?this._context.mozDash=e:"webkitLineDash"in this._context&&(this._context.webkitLineDash=e)}getLineDash(){return this._context.getLineDash()}setTransform(e,t,r,l,s,i){this._context.setTransform(e,t,r,l,s,i)}stroke(e){e?this._context.stroke(e):this._context.stroke()}strokeText(e,t,r,l){this._context.strokeText(e,t,r,l)}transform(e,t,r,l,s,i){this._context.transform(e,t,r,l,s,i)}translate(e,t){this._context.translate(e,t)}_enableTrace(){let e=this,t=kg.length,r=this.setAttr,l,s;const i=function(f){let h=e[f],d;e[f]=function(){return s=TS(Array.prototype.slice.call(arguments,0)),d=h.apply(e,arguments),e._trace({method:f,args:s}),d}};for(l=0;l<t;l++)i(kg[l]);e.setAttr=function(){r.apply(e,arguments);const f=arguments[0];let h=arguments[1];(f==="shadowOffsetX"||f==="shadowOffsetY"||f==="shadowBlur")&&(h=h/this.canvas.getPixelRatio()),e._trace({property:f,val:h})}}_applyGlobalCompositeOperation(e){const t=e.attrs.globalCompositeOperation;!t||t==="source-over"||this.setAttr("globalCompositeOperation",t)}}Ks.Context=Yo,wS.forEach(function(u){Object.defineProperty(Yo.prototype,u,{get(){return this._context[u]},set(e){this._context[u]=e}})});class OS extends Yo{constructor(e,{willReadFrequently:t=!1}={}){super(e),this._context=e._canvas.getContext("2d",{willReadFrequently:t})}_fillColor(e){const t=e.fill();this.setAttr("fillStyle",t),e._fillFunc(this)}_fillPattern(e){this.setAttr("fillStyle",e._getFillPattern()),e._fillFunc(this)}_fillLinearGradient(e){const t=e._getLinearGradient();t&&(this.setAttr("fillStyle",t),e._fillFunc(this))}_fillRadialGradient(e){const t=e._getRadialGradient();t&&(this.setAttr("fillStyle",t),e._fillFunc(this))}_fill(e){const t=e.fill(),r=e.getFillPriority();if(t&&r==="color"){this._fillColor(e);return}const l=e.getFillPatternImage();if(l&&r==="pattern"){this._fillPattern(e);return}const s=e.getFillLinearGradientColorStops();if(s&&r==="linear-gradient"){this._fillLinearGradient(e);return}const i=e.getFillRadialGradientColorStops();if(i&&r==="radial-gradient"){this._fillRadialGradient(e);return}t?this._fillColor(e):l?this._fillPattern(e):s?this._fillLinearGradient(e):i&&this._fillRadialGradient(e)}_strokeLinearGradient(e){const t=e.getStrokeLinearGradientStartPoint(),r=e.getStrokeLinearGradientEndPoint(),l=e.getStrokeLinearGradientColorStops(),s=this.createLinearGradient(t.x,t.y,r.x,r.y);if(l){for(let i=0;i<l.length;i+=2)s.addColorStop(l[i],l[i+1]);this.setAttr("strokeStyle",s)}}_stroke(e){const t=e.dash(),r=e.getStrokeScaleEnabled();if(e.hasStroke()){if(!r){this.save();const s=this.getCanvas().getPixelRatio();this.setTransform(s,0,0,s,0,0)}this._applyLineCap(e),t&&e.dashEnabled()&&(this.setLineDash(t),this.setAttr("lineDashOffset",e.dashOffset())),this.setAttr("lineWidth",e.strokeWidth()),e.getShadowForStrokeEnabled()||this.setAttr("shadowColor","rgba(0,0,0,0)"),e.getStrokeLinearGradientColorStops()?this._strokeLinearGradient(e):this.setAttr("strokeStyle",e.stroke()),e._strokeFunc(this),r||this.restore()}}_applyShadow(e){var t,r,l;const s=(t=e.getShadowRGBA())!==null&&t!==void 0?t:"black",i=(r=e.getShadowBlur())!==null&&r!==void 0?r:5,f=(l=e.getShadowOffset())!==null&&l!==void 0?l:{x:0,y:0},h=e.getAbsoluteScale(),d=this.canvas.getPixelRatio(),p=h.x*d,v=h.y*d;this.setAttr("shadowColor",s),this.setAttr("shadowBlur",i*Math.min(Math.abs(p),Math.abs(v))),this.setAttr("shadowOffsetX",f.x*p),this.setAttr("shadowOffsetY",f.y*v)}}Ks.SceneContext=OS;class DS extends Yo{constructor(e){super(e),this._context=e._canvas.getContext("2d",{willReadFrequently:!0})}_fill(e){this.save(),this.setAttr("fillStyle",e.colorKey),e._fillFuncHit(this),this.restore()}strokeShape(e){e.hasHitStroke()&&this._stroke(e)}_stroke(e){if(e.hasHitStroke()){const t=e.getStrokeScaleEnabled();if(!t){this.save();const s=this.getCanvas().getPixelRatio();this.setTransform(s,0,0,s,0,0)}this._applyLineCap(e);const r=e.hitStrokeWidth(),l=r==="auto"?e.strokeWidth():r;this.setAttr("lineWidth",l),this.setAttr("strokeStyle",e.colorKey),e._strokeFuncHit(this),t||this.restore()}}}Ks.HitContext=DS,Object.defineProperty(ms,"__esModule",{value:!0}),ms.HitCanvas=ms.SceneCanvas=ms.Canvas=void 0;const zo=rt,Mg=Ks,Ug=Le,NS=Fe,PS=Ne;let Xo;function xS(){if(Xo)return Xo;const u=zo.Util.createCanvasElement(),e=u.getContext("2d");return Xo=function(){const t=Ug.Konva._global.devicePixelRatio||1,r=e.webkitBackingStorePixelRatio||e.mozBackingStorePixelRatio||e.msBackingStorePixelRatio||e.oBackingStorePixelRatio||e.backingStorePixelRatio||1;return t/r}(),zo.Util.releaseCanvas(u),Xo}class Jo{constructor(e){this.pixelRatio=1,this.width=0,this.height=0,this.isCache=!1;const r=(e||{}).pixelRatio||Ug.Konva.pixelRatio||xS();this.pixelRatio=r,this._canvas=zo.Util.createCanvasElement(),this._canvas.style.padding="0",this._canvas.style.margin="0",this._canvas.style.border="0",this._canvas.style.background="transparent",this._canvas.style.position="absolute",this._canvas.style.top="0",this._canvas.style.left="0"}getContext(){return this.context}getPixelRatio(){return this.pixelRatio}setPixelRatio(e){const t=this.pixelRatio;this.pixelRatio=e,this.setSize(this.getWidth()/t,this.getHeight()/t)}setWidth(e){this.width=this._canvas.width=e*this.pixelRatio,this._canvas.style.width=e+"px";const t=this.pixelRatio;this.getContext()._context.scale(t,t)}setHeight(e){this.height=this._canvas.height=e*this.pixelRatio,this._canvas.style.height=e+"px";const t=this.pixelRatio;this.getContext()._context.scale(t,t)}getWidth(){return this.width}getHeight(){return this.height}setSize(e,t){this.setWidth(e||0),this.setHeight(t||0)}toDataURL(e,t){try{return this._canvas.toDataURL(e,t)}catch{try{return this._canvas.toDataURL()}catch(l){return zo.Util.error("Unable to get data URL. "+l.message+" For more info read https://konvajs.org/docs/posts/Tainted_Canvas.html."),""}}}}ms.Canvas=Jo,NS.Factory.addGetterSetter(Jo,"pixelRatio",void 0,(0,PS.getNumberValidator)());class kS extends Jo{constructor(e={width:0,height:0,willReadFrequently:!1}){super(e),this.context=new Mg.SceneContext(this,{willReadFrequently:e.willReadFrequently}),this.setSize(e.width,e.height)}}ms.SceneCanvas=kS;class MS extends Jo{constructor(e={width:0,height:0}){super(e),this.hitCanvas=!0,this.context=new Mg.HitContext(this),this.setSize(e.width,e.height)}}ms.HitCanvas=MS;var Qo={};(function(u){Object.defineProperty(u,"__esModule",{value:!0}),u.DD=void 0;const e=Le,t=rt;u.DD={get isDragging(){let r=!1;return u.DD._dragElements.forEach(l=>{l.dragStatus==="dragging"&&(r=!0)}),r},justDragged:!1,get node(){let r;return u.DD._dragElements.forEach(l=>{r=l.node}),r},_dragElements:new Map,_drag(r){const l=[];u.DD._dragElements.forEach((s,i)=>{const{node:f}=s,h=f.getStage();h.setPointersPositions(r),s.pointerId===void 0&&(s.pointerId=t.Util._getFirstPointerId(r));const d=h._changedPointerPositions.find(p=>p.id===s.pointerId);if(d){if(s.dragStatus!=="dragging"){const p=f.dragDistance();if(Math.max(Math.abs(d.x-s.startPointerPos.x),Math.abs(d.y-s.startPointerPos.y))<p||(f.startDrag({evt:r}),!f.isDragging()))return}f._setDragPosition(r,s),l.push(f)}}),l.forEach(s=>{s.fire("dragmove",{type:"dragmove",target:s,evt:r},!0)})},_endDragBefore(r){const l=[];u.DD._dragElements.forEach(s=>{const{node:i}=s,f=i.getStage();if(r&&f.setPointersPositions(r),!f._changedPointerPositions.find(p=>p.id===s.pointerId))return;(s.dragStatus==="dragging"||s.dragStatus==="stopped")&&(u.DD.justDragged=!0,e.Konva._mouseListenClick=!1,e.Konva._touchListenClick=!1,e.Konva._pointerListenClick=!1,s.dragStatus="stopped");const d=s.node.getLayer()||s.node instanceof e.Konva.Stage&&s.node;d&&l.indexOf(d)===-1&&l.push(d)}),l.forEach(s=>{s.draw()})},_endDragAfter(r){u.DD._dragElements.forEach((l,s)=>{l.dragStatus==="stopped"&&l.node.fire("dragend",{type:"dragend",target:l.node,evt:r},!0),l.dragStatus!=="dragging"&&u.DD._dragElements.delete(s)})}},e.Konva.isBrowser&&(window.addEventListener("mouseup",u.DD._endDragBefore,!0),window.addEventListener("touchend",u.DD._endDragBefore,!0),window.addEventListener("touchcancel",u.DD._endDragBefore,!0),window.addEventListener("mousemove",u.DD._drag),window.addEventListener("touchmove",u.DD._drag),window.addEventListener("mouseup",u.DD._endDragAfter,!1),window.addEventListener("touchend",u.DD._endDragAfter,!1),window.addEventListener("touchcancel",u.DD._endDragAfter,!1))})(Qo),Object.defineProperty(it,"__esModule",{value:!0}),it.Node=void 0;const $e=rt,_l=Fe,gl=ms,gn=Le,ls=Qo,mt=Ne,Zo="absoluteOpacity",eu="allEventListeners",Ys="absoluteTransform",Lg="absoluteScale",Yn="canvas",US="Change",LS="children",FS="konva",zh="listening",Fg="mouseenter",$g="mouseleave",Hg="set",Gg="Shape",tu=" ",Vg="stage",pn="transform",$S="Stage",Xh="visible",HS=["xChange.konva","yChange.konva","scaleXChange.konva","scaleYChange.konva","skewXChange.konva","skewYChange.konva","rotationChange.konva","offsetXChange.konva","offsetYChange.konva","transformsEnabledChange.konva"].join(tu);let GS=1;class xe{constructor(e){this._id=GS++,this.eventListeners={},this.attrs={},this.index=0,this._allEventListeners=null,this.parent=null,this._cache=new Map,this._attachedDepsListeners=new Map,this._lastPos=null,this._batchingTransformChange=!1,this._needClearTransformCache=!1,this._filterUpToDate=!1,this._isUnderCache=!1,this._dragEventId=null,this._shouldFireChangeEvents=!1,this.setAttrs(e),this._shouldFireChangeEvents=!0}hasChildren(){return!1}_clearCache(e){(e===pn||e===Ys)&&this._cache.get(e)?this._cache.get(e).dirty=!0:e?this._cache.delete(e):this._cache.clear()}_getCache(e,t){let r=this._cache.get(e);return(r===void 0||(e===pn||e===Ys)&&r.dirty===!0)&&(r=t.call(this),this._cache.set(e,r)),r}_calculate(e,t,r){if(!this._attachedDepsListeners.get(e)){const l=t.map(s=>s+"Change.konva").join(tu);this.on(l,()=>{this._clearCache(e)}),this._attachedDepsListeners.set(e,!0)}return this._getCache(e,r)}_getCanvasCache(){return this._cache.get(Yn)}_clearSelfAndDescendantCache(e){this._clearCache(e),e===Ys&&this.fire("absoluteTransformChange")}clearCache(){if(this._cache.has(Yn)){const{scene:e,filter:t,hit:r}=this._cache.get(Yn);$e.Util.releaseCanvas(e,t,r),this._cache.delete(Yn)}return this._clearSelfAndDescendantCache(),this._requestDraw(),this}cache(e){const t=e||{};let r={};(t.x===void 0||t.y===void 0||t.width===void 0||t.height===void 0)&&(r=this.getClientRect({skipTransform:!0,relativeTo:this.getParent()||void 0}));let l=Math.ceil(t.width||r.width),s=Math.ceil(t.height||r.height),i=t.pixelRatio,f=t.x===void 0?Math.floor(r.x):t.x,h=t.y===void 0?Math.floor(r.y):t.y,d=t.offset||0,p=t.drawBorder||!1,v=t.hitCanvasPixelRatio||1;if(!l||!s){$e.Util.error("Can not cache the node. Width or height of the node equals 0. Caching is skipped.");return}const T=Math.abs(Math.round(r.x)-f)>.5?1:0,y=Math.abs(Math.round(r.y)-h)>.5?1:0;l+=d*2+T,s+=d*2+y,f-=d,h-=d;const S=new gl.SceneCanvas({pixelRatio:i,width:l,height:s}),A=new gl.SceneCanvas({pixelRatio:i,width:0,height:0,willReadFrequently:!0}),R=new gl.HitCanvas({pixelRatio:v,width:l,height:s}),O=S.getContext(),N=R.getContext();return R.isCache=!0,S.isCache=!0,this._cache.delete(Yn),this._filterUpToDate=!1,t.imageSmoothingEnabled===!1&&(S.getContext()._context.imageSmoothingEnabled=!1,A.getContext()._context.imageSmoothingEnabled=!1),O.save(),N.save(),O.translate(-f,-h),N.translate(-f,-h),this._isUnderCache=!0,this._clearSelfAndDescendantCache(Zo),this._clearSelfAndDescendantCache(Lg),this.drawScene(S,this),this.drawHit(R,this),this._isUnderCache=!1,O.restore(),N.restore(),p&&(O.save(),O.beginPath(),O.rect(0,0,l,s),O.closePath(),O.setAttr("strokeStyle","red"),O.setAttr("lineWidth",5),O.stroke(),O.restore()),this._cache.set(Yn,{scene:S,filter:A,hit:R,x:f,y:h}),this._requestDraw(),this}isCached(){return this._cache.has(Yn)}getClientRect(e){throw new Error('abstract "getClientRect" method call')}_transformedRect(e,t){const r=[{x:e.x,y:e.y},{x:e.x+e.width,y:e.y},{x:e.x+e.width,y:e.y+e.height},{x:e.x,y:e.y+e.height}];let l=1/0,s=1/0,i=-1/0,f=-1/0;const h=this.getAbsoluteTransform(t);return r.forEach(function(d){const p=h.point(d);l===void 0&&(l=i=p.x,s=f=p.y),l=Math.min(l,p.x),s=Math.min(s,p.y),i=Math.max(i,p.x),f=Math.max(f,p.y)}),{x:l,y:s,width:i-l,height:f-s}}_drawCachedSceneCanvas(e){e.save(),e._applyOpacity(this),e._applyGlobalCompositeOperation(this);const t=this._getCanvasCache();e.translate(t.x,t.y);const r=this._getCachedSceneCanvas(),l=r.pixelRatio;e.drawImage(r._canvas,0,0,r.width/l,r.height/l),e.restore()}_drawCachedHitCanvas(e){const t=this._getCanvasCache(),r=t.hit;e.save(),e.translate(t.x,t.y),e.drawImage(r._canvas,0,0,r.width/r.pixelRatio,r.height/r.pixelRatio),e.restore()}_getCachedSceneCanvas(){let e=this.filters(),t=this._getCanvasCache(),r=t.scene,l=t.filter,s=l.getContext(),i,f,h,d;if(e){if(!this._filterUpToDate){const p=r.pixelRatio;l.setSize(r.width/r.pixelRatio,r.height/r.pixelRatio);try{for(i=e.length,s.clear(),s.drawImage(r._canvas,0,0,r.getWidth()/p,r.getHeight()/p),f=s.getImageData(0,0,l.getWidth(),l.getHeight()),h=0;h<i;h++){if(d=e[h],typeof d!="function"){$e.Util.error("Filter should be type of function, but got "+typeof d+" instead. Please check correct filters");continue}d.call(this,f),s.putImageData(f,0,0)}}catch(v){$e.Util.error("Unable to apply filter. "+v.message+" This post my help you https://konvajs.org/docs/posts/Tainted_Canvas.html.")}this._filterUpToDate=!0}return l}return r}on(e,t){if(this._cache&&this._cache.delete(eu),arguments.length===3)return this._delegate.apply(this,arguments);let r=e.split(tu),l=r.length,s,i,f,h,d;for(s=0;s<l;s++)i=r[s],f=i.split("."),h=f[0],d=f[1]||"",this.eventListeners[h]||(this.eventListeners[h]=[]),this.eventListeners[h].push({name:d,handler:t});return this}off(e,t){let r=(e||"").split(tu),l=r.length,s,i,f,h,d,p;if(this._cache&&this._cache.delete(eu),!e)for(i in this.eventListeners)this._off(i);for(s=0;s<l;s++)if(f=r[s],h=f.split("."),d=h[0],p=h[1],d)this.eventListeners[d]&&this._off(d,p,t);else for(i in this.eventListeners)this._off(i,p,t);return this}dispatchEvent(e){const t={target:this,type:e.type,evt:e};return this.fire(e.type,t),this}addEventListener(e,t){return this.on(e,function(r){t.call(this,r.evt)}),this}removeEventListener(e){return this.off(e),this}_delegate(e,t,r){const l=this;this.on(e,function(s){const i=s.target.findAncestors(t,!0,l);for(let f=0;f<i.length;f++)s=$e.Util.cloneObject(s),s.currentTarget=i[f],r.call(i[f],s)})}remove(){return this.isDragging()&&this.stopDrag(),ls.DD._dragElements.delete(this._id),this._remove(),this}_clearCaches(){this._clearSelfAndDescendantCache(Ys),this._clearSelfAndDescendantCache(Zo),this._clearSelfAndDescendantCache(Lg),this._clearSelfAndDescendantCache(Vg),this._clearSelfAndDescendantCache(Xh),this._clearSelfAndDescendantCache(zh)}_remove(){this._clearCaches();const e=this.getParent();e&&e.children&&(e.children.splice(this.index,1),e._setChildrenIndices(),this.parent=null)}destroy(){return this.remove(),this.clearCache(),this}getAttr(e){const t="get"+$e.Util._capitalize(e);return $e.Util._isFunction(this[t])?this[t]():this.attrs[e]}getAncestors(){let e=this.getParent(),t=[];for(;e;)t.push(e),e=e.getParent();return t}getAttrs(){return this.attrs||{}}setAttrs(e){return this._batchTransformChanges(()=>{let t,r;if(!e)return this;for(t in e)t!==LS&&(r=Hg+$e.Util._capitalize(t),$e.Util._isFunction(this[r])?this[r](e[t]):this._setAttr(t,e[t]))}),this}isListening(){return this._getCache(zh,this._isListening)}_isListening(e){if(!this.listening())return!1;const r=this.getParent();return r&&r!==e&&this!==e?r._isListening(e):!0}isVisible(){return this._getCache(Xh,this._isVisible)}_isVisible(e){if(!this.visible())return!1;const r=this.getParent();return r&&r!==e&&this!==e?r._isVisible(e):!0}shouldDrawHit(e,t=!1){if(e)return this._isVisible(e)&&this._isListening(e);const r=this.getLayer();let l=!1;ls.DD._dragElements.forEach(i=>{i.dragStatus==="dragging"&&(i.node.nodeType==="Stage"||i.node.getLayer()===r)&&(l=!0)});const s=!t&&!gn.Konva.hitOnDragEnabled&&(l||gn.Konva.isTransforming());return this.isListening()&&this.isVisible()&&!s}show(){return this.visible(!0),this}hide(){return this.visible(!1),this}getZIndex(){return this.index||0}getAbsoluteZIndex(){let e=this.getDepth(),t=this,r=0,l,s,i,f;function h(p){for(l=[],s=p.length,i=0;i<s;i++)f=p[i],r++,f.nodeType!==Gg&&(l=l.concat(f.getChildren().slice())),f._id===t._id&&(i=s);l.length>0&&l[0].getDepth()<=e&&h(l)}const d=this.getStage();return t.nodeType!==$S&&d&&h(d.getChildren()),r}getDepth(){let e=0,t=this.parent;for(;t;)e++,t=t.parent;return e}_batchTransformChanges(e){this._batchingTransformChange=!0,e(),this._batchingTransformChange=!1,this._needClearTransformCache&&(this._clearCache(pn),this._clearSelfAndDescendantCache(Ys)),this._needClearTransformCache=!1}setPosition(e){return this._batchTransformChanges(()=>{this.x(e.x),this.y(e.y)}),this}getPosition(){return{x:this.x(),y:this.y()}}getRelativePointerPosition(){const e=this.getStage();if(!e)return null;const t=e.getPointerPosition();if(!t)return null;const r=this.getAbsoluteTransform().copy();return r.invert(),r.point(t)}getAbsolutePosition(e){let t=!1,r=this.parent;for(;r;){if(r.isCached()){t=!0;break}r=r.parent}t&&!e&&(e=!0);const l=this.getAbsoluteTransform(e).getMatrix(),s=new $e.Transform,i=this.offset();return s.m=l.slice(),s.translate(i.x,i.y),s.getTranslation()}setAbsolutePosition(e){const{x:t,y:r,...l}=this._clearTransform();this.attrs.x=t,this.attrs.y=r,this._clearCache(pn);const s=this._getAbsoluteTransform().copy();return s.invert(),s.translate(e.x,e.y),e={x:this.attrs.x+s.getTranslation().x,y:this.attrs.y+s.getTranslation().y},this._setTransform(l),this.setPosition({x:e.x,y:e.y}),this._clearCache(pn),this._clearSelfAndDescendantCache(Ys),this}_setTransform(e){let t;for(t in e)this.attrs[t]=e[t]}_clearTransform(){const e={x:this.x(),y:this.y(),rotation:this.rotation(),scaleX:this.scaleX(),scaleY:this.scaleY(),offsetX:this.offsetX(),offsetY:this.offsetY(),skewX:this.skewX(),skewY:this.skewY()};return this.attrs.x=0,this.attrs.y=0,this.attrs.rotation=0,this.attrs.scaleX=1,this.attrs.scaleY=1,this.attrs.offsetX=0,this.attrs.offsetY=0,this.attrs.skewX=0,this.attrs.skewY=0,e}move(e){let t=e.x,r=e.y,l=this.x(),s=this.y();return t!==void 0&&(l+=t),r!==void 0&&(s+=r),this.setPosition({x:l,y:s}),this}_eachAncestorReverse(e,t){let r=[],l=this.getParent(),s,i;if(!(t&&t._id===this._id)){for(r.unshift(this);l&&(!t||l._id!==t._id);)r.unshift(l),l=l.parent;for(s=r.length,i=0;i<s;i++)e(r[i])}}rotate(e){return this.rotation(this.rotation()+e),this}moveToTop(){if(!this.parent)return $e.Util.warn("Node has no parent. moveToTop function is ignored."),!1;const e=this.index,t=this.parent.getChildren().length;return e<t-1?(this.parent.children.splice(e,1),this.parent.children.push(this),this.parent._setChildrenIndices(),!0):!1}moveUp(){if(!this.parent)return $e.Util.warn("Node has no parent. moveUp function is ignored."),!1;const e=this.index,t=this.parent.getChildren().length;return e<t-1?(this.parent.children.splice(e,1),this.parent.children.splice(e+1,0,this),this.parent._setChildrenIndices(),!0):!1}moveDown(){if(!this.parent)return $e.Util.warn("Node has no parent. moveDown function is ignored."),!1;const e=this.index;return e>0?(this.parent.children.splice(e,1),this.parent.children.splice(e-1,0,this),this.parent._setChildrenIndices(),!0):!1}moveToBottom(){if(!this.parent)return $e.Util.warn("Node has no parent. moveToBottom function is ignored."),!1;const e=this.index;return e>0?(this.parent.children.splice(e,1),this.parent.children.unshift(this),this.parent._setChildrenIndices(),!0):!1}setZIndex(e){if(!this.parent)return $e.Util.warn("Node has no parent. zIndex parameter is ignored."),this;(e<0||e>=this.parent.children.length)&&$e.Util.warn("Unexpected value "+e+" for zIndex property. zIndex is just index of a node in children of its parent. Expected value is from 0 to "+(this.parent.children.length-1)+".");const t=this.index;return this.parent.children.splice(t,1),this.parent.children.splice(e,0,this),this.parent._setChildrenIndices(),this}getAbsoluteOpacity(){return this._getCache(Zo,this._getAbsoluteOpacity)}_getAbsoluteOpacity(){let e=this.opacity();const t=this.getParent();return t&&!t._isUnderCache&&(e*=t.getAbsoluteOpacity()),e}moveTo(e){return this.getParent()!==e&&(this._remove(),e.add(this)),this}toObject(){let e=this.getAttrs(),t,r,l,s,i;const f={attrs:{},className:this.getClassName()};for(t in e)r=e[t],i=$e.Util.isObject(r)&&!$e.Util._isPlainObject(r)&&!$e.Util._isArray(r),!i&&(l=typeof this[t]=="function"&&this[t],delete e[t],s=l?l.call(this):null,e[t]=r,s!==r&&(f.attrs[t]=r));return $e.Util._prepareToStringify(f)}toJSON(){return JSON.stringify(this.toObject())}getParent(){return this.parent}findAncestors(e,t,r){const l=[];t&&this._isMatch(e)&&l.push(this);let s=this.parent;for(;s;){if(s===r)return l;s._isMatch(e)&&l.push(s),s=s.parent}return l}isAncestorOf(e){return!1}findAncestor(e,t,r){return this.findAncestors(e,t,r)[0]}_isMatch(e){if(!e)return!1;if(typeof e=="function")return e(this);let t=e.replace(/ /g,"").split(","),r=t.length,l,s;for(l=0;l<r;l++)if(s=t[l],$e.Util.isValidSelector(s)||($e.Util.warn('Selector "'+s+'" is invalid. Allowed selectors examples are "#foo", ".bar" or "Group".'),$e.Util.warn('If you have a custom shape with such className, please change it to start with upper letter like "Triangle".'),$e.Util.warn("Konva is awesome, right?")),s.charAt(0)==="#"){if(this.id()===s.slice(1))return!0}else if(s.charAt(0)==="."){if(this.hasName(s.slice(1)))return!0}else if(this.className===s||this.nodeType===s)return!0;return!1}getLayer(){const e=this.getParent();return e?e.getLayer():null}getStage(){return this._getCache(Vg,this._getStage)}_getStage(){const e=this.getParent();return e?e.getStage():null}fire(e,t={},r){return t.target=t.target||this,r?this._fireAndBubble(e,t):this._fire(e,t),this}getAbsoluteTransform(e){return e?this._getAbsoluteTransform(e):this._getCache(Ys,this._getAbsoluteTransform)}_getAbsoluteTransform(e){let t;if(e)return t=new $e.Transform,this._eachAncestorReverse(function(r){const l=r.transformsEnabled();l==="all"?t.multiply(r.getTransform()):l==="position"&&t.translate(r.x()-r.offsetX(),r.y()-r.offsetY())},e),t;{t=this._cache.get(Ys)||new $e.Transform,this.parent?this.parent.getAbsoluteTransform().copyInto(t):t.reset();const r=this.transformsEnabled();if(r==="all")t.multiply(this.getTransform());else if(r==="position"){const l=this.attrs.x||0,s=this.attrs.y||0,i=this.attrs.offsetX||0,f=this.attrs.offsetY||0;t.translate(l-i,s-f)}return t.dirty=!1,t}}getAbsoluteScale(e){let t=this;for(;t;)t._isUnderCache&&(e=t),t=t.getParent();const l=this.getAbsoluteTransform(e).decompose();return{x:l.scaleX,y:l.scaleY}}getAbsoluteRotation(){return this.getAbsoluteTransform().decompose().rotation}getTransform(){return this._getCache(pn,this._getTransform)}_getTransform(){var e,t;const r=this._cache.get(pn)||new $e.Transform;r.reset();const l=this.x(),s=this.y(),i=gn.Konva.getAngle(this.rotation()),f=(e=this.attrs.scaleX)!==null&&e!==void 0?e:1,h=(t=this.attrs.scaleY)!==null&&t!==void 0?t:1,d=this.attrs.skewX||0,p=this.attrs.skewY||0,v=this.attrs.offsetX||0,T=this.attrs.offsetY||0;return(l!==0||s!==0)&&r.translate(l,s),i!==0&&r.rotate(i),(d!==0||p!==0)&&r.skew(d,p),(f!==1||h!==1)&&r.scale(f,h),(v!==0||T!==0)&&r.translate(-1*v,-1*T),r.dirty=!1,r}clone(e){let t=$e.Util.cloneObject(this.attrs),r,l,s,i,f;for(r in e)t[r]=e[r];const h=new this.constructor(t);for(r in this.eventListeners)for(l=this.eventListeners[r],s=l.length,i=0;i<s;i++)f=l[i],f.name.indexOf(FS)<0&&(h.eventListeners[r]||(h.eventListeners[r]=[]),h.eventListeners[r].push(f));return h}_toKonvaCanvas(e){e=e||{};const t=this.getClientRect(),r=this.getStage(),l=e.x!==void 0?e.x:Math.floor(t.x),s=e.y!==void 0?e.y:Math.floor(t.y),i=e.pixelRatio||1,f=new gl.SceneCanvas({width:e.width||Math.ceil(t.width)||(r?r.width():0),height:e.height||Math.ceil(t.height)||(r?r.height():0),pixelRatio:i}),h=f.getContext(),d=new gl.SceneCanvas({width:f.width/f.pixelRatio+Math.abs(l),height:f.height/f.pixelRatio+Math.abs(s),pixelRatio:f.pixelRatio});return e.imageSmoothingEnabled===!1&&(h._context.imageSmoothingEnabled=!1),h.save(),(l||s)&&h.translate(-1*l,-1*s),this.drawScene(f,void 0,d),h.restore(),f}toCanvas(e){return this._toKonvaCanvas(e)._canvas}toDataURL(e){e=e||{};const t=e.mimeType||null,r=e.quality||null,l=this._toKonvaCanvas(e).toDataURL(t,r);return e.callback&&e.callback(l),l}toImage(e){return new Promise((t,r)=>{try{const l=e==null?void 0:e.callback;l&&delete e.callback,$e.Util._urlToImage(this.toDataURL(e),function(s){t(s),l==null||l(s)})}catch(l){r(l)}})}toBlob(e){return new Promise((t,r)=>{try{const l=e==null?void 0:e.callback;l&&delete e.callback,this.toCanvas(e).toBlob(s=>{t(s),l==null||l(s)},e==null?void 0:e.mimeType,e==null?void 0:e.quality)}catch(l){r(l)}})}setSize(e){return this.width(e.width),this.height(e.height),this}getSize(){return{width:this.width(),height:this.height()}}getClassName(){return this.className||this.nodeType}getType(){return this.nodeType}getDragDistance(){return this.attrs.dragDistance!==void 0?this.attrs.dragDistance:this.parent?this.parent.getDragDistance():gn.Konva.dragDistance}_off(e,t,r){let l=this.eventListeners[e],s,i,f;for(s=0;s<l.length;s++)if(i=l[s].name,f=l[s].handler,(i!=="konva"||t==="konva")&&(!t||i===t)&&(!r||r===f)){if(l.splice(s,1),l.length===0){delete this.eventListeners[e];break}s--}}_fireChangeEvent(e,t,r){this._fire(e+US,{oldVal:t,newVal:r})}addName(e){if(!this.hasName(e)){const t=this.name(),r=t?t+" "+e:e;this.name(r)}return this}hasName(e){if(!e)return!1;const t=this.name();return t?(t||"").split(/\s/g).indexOf(e)!==-1:!1}removeName(e){const t=(this.name()||"").split(/\s/g),r=t.indexOf(e);return r!==-1&&(t.splice(r,1),this.name(t.join(" "))),this}setAttr(e,t){const r=this[Hg+$e.Util._capitalize(e)];return $e.Util._isFunction(r)?r.call(this,t):this._setAttr(e,t),this}_requestDraw(){if(gn.Konva.autoDrawEnabled){const e=this.getLayer()||this.getStage();e==null||e.batchDraw()}}_setAttr(e,t){const r=this.attrs[e];r===t&&!$e.Util.isObject(t)||(t==null?delete this.attrs[e]:this.attrs[e]=t,this._shouldFireChangeEvents&&this._fireChangeEvent(e,r,t),this._requestDraw())}_setComponentAttr(e,t,r){let l;r!==void 0&&(l=this.attrs[e],l||(this.attrs[e]=this.getAttr(e)),this.attrs[e][t]=r,this._fireChangeEvent(e,l,r))}_fireAndBubble(e,t,r){if(t&&this.nodeType===Gg&&(t.target=this),!((e===Fg||e===$g)&&(r&&(this===r||this.isAncestorOf&&this.isAncestorOf(r))||this.nodeType==="Stage"&&!r))){this._fire(e,t);const s=(e===Fg||e===$g)&&r&&r.isAncestorOf&&r.isAncestorOf(this)&&!r.isAncestorOf(this.parent);(t&&!t.cancelBubble||!t)&&this.parent&&this.parent.isListening()&&!s&&(r&&r.parent?this._fireAndBubble.call(this.parent,e,t,r):this._fireAndBubble.call(this.parent,e,t))}}_getProtoListeners(e){var t,r,l;const s=(t=this._cache.get(eu))!==null&&t!==void 0?t:{};let i=s==null?void 0:s[e];if(i===void 0){i=[];let f=Object.getPrototypeOf(this);for(;f;){const h=(l=(r=f.eventListeners)===null||r===void 0?void 0:r[e])!==null&&l!==void 0?l:[];i.push(...h),f=Object.getPrototypeOf(f)}s[e]=i,this._cache.set(eu,s)}return i}_fire(e,t){t=t||{},t.currentTarget=this,t.type=e;const r=this._getProtoListeners(e);if(r)for(var l=0;l<r.length;l++)r[l].handler.call(this,t);const s=this.eventListeners[e];if(s)for(var l=0;l<s.length;l++)s[l].handler.call(this,t)}draw(){return this.drawScene(),this.drawHit(),this}_createDragElement(e){const t=e?e.pointerId:void 0,r=this.getStage(),l=this.getAbsolutePosition();if(!r)return;const s=r._getPointerById(t)||r._changedPointerPositions[0]||l;ls.DD._dragElements.set(this._id,{node:this,startPointerPos:s,offset:{x:s.x-l.x,y:s.y-l.y},dragStatus:"ready",pointerId:t})}startDrag(e,t=!0){ls.DD._dragElements.has(this._id)||this._createDragElement(e);const r=ls.DD._dragElements.get(this._id);r.dragStatus="dragging",this.fire("dragstart",{type:"dragstart",target:this,evt:e&&e.evt},t)}_setDragPosition(e,t){const r=this.getStage()._getPointerById(t.pointerId);if(!r)return;let l={x:r.x-t.offset.x,y:r.y-t.offset.y};const s=this.dragBoundFunc();if(s!==void 0){const i=s.call(this,l,e);i?l=i:$e.Util.warn("dragBoundFunc did not return any value. That is unexpected behavior. You must return new absolute position from dragBoundFunc.")}(!this._lastPos||this._lastPos.x!==l.x||this._lastPos.y!==l.y)&&(this.setAbsolutePosition(l),this._requestDraw()),this._lastPos=l}stopDrag(e){const t=ls.DD._dragElements.get(this._id);t&&(t.dragStatus="stopped"),ls.DD._endDragBefore(e),ls.DD._endDragAfter(e)}setDraggable(e){this._setAttr("draggable",e),this._dragChange()}isDragging(){const e=ls.DD._dragElements.get(this._id);return e?e.dragStatus==="dragging":!1}_listenDrag(){this._dragCleanup(),this.on("mousedown.konva touchstart.konva",function(e){if(!(!(e.evt.button!==void 0)||gn.Konva.dragButtons.indexOf(e.evt.button)>=0)||this.isDragging())return;let l=!1;ls.DD._dragElements.forEach(s=>{this.isAncestorOf(s.node)&&(l=!0)}),l||this._createDragElement(e)})}_dragChange(){if(this.attrs.draggable)this._listenDrag();else{if(this._dragCleanup(),!this.getStage())return;const t=ls.DD._dragElements.get(this._id),r=t&&t.dragStatus==="dragging",l=t&&t.dragStatus==="ready";r?this.stopDrag():l&&ls.DD._dragElements.delete(this._id)}}_dragCleanup(){this.off("mousedown.konva"),this.off("touchstart.konva")}isClientRectOnScreen(e={x:0,y:0}){const t=this.getStage();if(!t)return!1;const r={x:-e.x,y:-e.y,width:t.width()+2*e.x,height:t.height()+2*e.y};return $e.Util.haveIntersection(r,this.getClientRect())}static create(e,t){return $e.Util._isString(e)&&(e=JSON.parse(e)),this._createNode(e,t)}static _createNode(e,t){let r=xe.prototype.getClassName.call(e),l=e.children,s,i,f;t&&(e.attrs.container=t),gn.Konva[r]||($e.Util.warn('Can not find a node with class name "'+r+'". Fallback to "Shape".'),r="Shape");const h=gn.Konva[r];if(s=new h(e.attrs),l)for(i=l.length,f=0;f<i;f++)s.add(xe._createNode(l[f]));return s}}it.Node=xe,xe.prototype.nodeType="Node",xe.prototype._attrsAffectingSize=[],xe.prototype.eventListeners={},xe.prototype.on.call(xe.prototype,HS,function(){if(this._batchingTransformChange){this._needClearTransformCache=!0;return}this._clearCache(pn),this._clearSelfAndDescendantCache(Ys)}),xe.prototype.on.call(xe.prototype,"visibleChange.konva",function(){this._clearSelfAndDescendantCache(Xh)}),xe.prototype.on.call(xe.prototype,"listeningChange.konva",function(){this._clearSelfAndDescendantCache(zh)}),xe.prototype.on.call(xe.prototype,"opacityChange.konva",function(){this._clearSelfAndDescendantCache(Zo)});const ze=_l.Factory.addGetterSetter;ze(xe,"zIndex"),ze(xe,"absolutePosition"),ze(xe,"position"),ze(xe,"x",0,(0,mt.getNumberValidator)()),ze(xe,"y",0,(0,mt.getNumberValidator)()),ze(xe,"globalCompositeOperation","source-over",(0,mt.getStringValidator)()),ze(xe,"opacity",1,(0,mt.getNumberValidator)()),ze(xe,"name","",(0,mt.getStringValidator)()),ze(xe,"id","",(0,mt.getStringValidator)()),ze(xe,"rotation",0,(0,mt.getNumberValidator)()),_l.Factory.addComponentsGetterSetter(xe,"scale",["x","y"]),ze(xe,"scaleX",1,(0,mt.getNumberValidator)()),ze(xe,"scaleY",1,(0,mt.getNumberValidator)()),_l.Factory.addComponentsGetterSetter(xe,"skew",["x","y"]),ze(xe,"skewX",0,(0,mt.getNumberValidator)()),ze(xe,"skewY",0,(0,mt.getNumberValidator)()),_l.Factory.addComponentsGetterSetter(xe,"offset",["x","y"]),ze(xe,"offsetX",0,(0,mt.getNumberValidator)()),ze(xe,"offsetY",0,(0,mt.getNumberValidator)()),ze(xe,"dragDistance",null,(0,mt.getNumberValidator)()),ze(xe,"width",0,(0,mt.getNumberValidator)()),ze(xe,"height",0,(0,mt.getNumberValidator)()),ze(xe,"listening",!0,(0,mt.getBooleanValidator)()),ze(xe,"preventDefault",!0,(0,mt.getBooleanValidator)()),ze(xe,"filters",null,function(u){return this._filterUpToDate=!1,u}),ze(xe,"visible",!0,(0,mt.getBooleanValidator)()),ze(xe,"transformsEnabled","all",(0,mt.getStringValidator)()),ze(xe,"size"),ze(xe,"dragBoundFunc"),ze(xe,"draggable",!1,(0,mt.getBooleanValidator)()),_l.Factory.backCompat(xe,{rotateDeg:"rotate",setRotationDeg:"setRotation",getRotationDeg:"getRotation"});var zn={};Object.defineProperty(zn,"__esModule",{value:!0}),zn.Container=void 0;const $i=Fe,Jh=it,su=Ne;class Xn extends Jh.Node{constructor(){super(...arguments),this.children=[]}getChildren(e){if(!e)return this.children||[];const t=this.children||[],r=[];return t.forEach(function(l){e(l)&&r.push(l)}),r}hasChildren(){return this.getChildren().length>0}removeChildren(){return this.getChildren().forEach(e=>{e.parent=null,e.index=0,e.remove()}),this.children=[],this._requestDraw(),this}destroyChildren(){return this.getChildren().forEach(e=>{e.parent=null,e.index=0,e.destroy()}),this.children=[],this._requestDraw(),this}add(...e){if(e.length===0)return this;if(e.length>1){for(let r=0;r<e.length;r++)this.add(e[r]);return this}const t=e[0];return t.getParent()?(t.moveTo(this),this):(this._validateAdd(t),t.index=this.getChildren().length,t.parent=this,t._clearCaches(),this.getChildren().push(t),this._fire("add",{child:t}),this._requestDraw(),this)}destroy(){return this.hasChildren()&&this.destroyChildren(),super.destroy(),this}find(e){return this._generalFind(e,!1)}findOne(e){const t=this._generalFind(e,!0);return t.length>0?t[0]:void 0}_generalFind(e,t){const r=[];return this._descendants(l=>{const s=l._isMatch(e);return s&&r.push(l),!!(s&&t)}),r}_descendants(e){let t=!1;const r=this.getChildren();for(const l of r){if(t=e(l),t)return!0;if(l.hasChildren()&&(t=l._descendants(e),t))return!0}return!1}toObject(){const e=Jh.Node.prototype.toObject.call(this);return e.children=[],this.getChildren().forEach(t=>{e.children.push(t.toObject())}),e}isAncestorOf(e){let t=e.getParent();for(;t;){if(t._id===this._id)return!0;t=t.getParent()}return!1}clone(e){const t=Jh.Node.prototype.clone.call(this,e);return this.getChildren().forEach(function(r){t.add(r.clone())}),t}getAllIntersections(e){const t=[];return this.find("Shape").forEach(r=>{r.isVisible()&&r.intersects(e)&&t.push(r)}),t}_clearSelfAndDescendantCache(e){var t;super._clearSelfAndDescendantCache(e),!this.isCached()&&((t=this.children)===null||t===void 0||t.forEach(function(r){r._clearSelfAndDescendantCache(e)}))}_setChildrenIndices(){var e;(e=this.children)===null||e===void 0||e.forEach(function(t,r){t.index=r}),this._requestDraw()}drawScene(e,t,r){const l=this.getLayer(),s=e||l&&l.getCanvas(),i=s&&s.getContext(),f=this._getCanvasCache(),h=f&&f.scene,d=s&&s.isCache;if(!this.isVisible()&&!d)return this;if(h){i.save();const p=this.getAbsoluteTransform(t).getMatrix();i.transform(p[0],p[1],p[2],p[3],p[4],p[5]),this._drawCachedSceneCanvas(i),i.restore()}else this._drawChildren("drawScene",s,t,r);return this}drawHit(e,t){if(!this.shouldDrawHit(t))return this;const r=this.getLayer(),l=e||r&&r.hitCanvas,s=l&&l.getContext(),i=this._getCanvasCache();if(i&&i.hit){s.save();const h=this.getAbsoluteTransform(t).getMatrix();s.transform(h[0],h[1],h[2],h[3],h[4],h[5]),this._drawCachedHitCanvas(s),s.restore()}else this._drawChildren("drawHit",l,t);return this}_drawChildren(e,t,r,l){var s;const i=t&&t.getContext(),f=this.clipWidth(),h=this.clipHeight(),d=this.clipFunc(),p=typeof f=="number"&&typeof h=="number"||d,v=r===this;if(p){i.save();const y=this.getAbsoluteTransform(r);let S=y.getMatrix();i.transform(S[0],S[1],S[2],S[3],S[4],S[5]),i.beginPath();let A;if(d)A=d.call(this,i,this);else{const R=this.clipX(),O=this.clipY();i.rect(R||0,O||0,f,h)}i.clip.apply(i,A),S=y.copy().invert().getMatrix(),i.transform(S[0],S[1],S[2],S[3],S[4],S[5])}const T=!v&&this.globalCompositeOperation()!=="source-over"&&e==="drawScene";T&&(i.save(),i._applyGlobalCompositeOperation(this)),(s=this.children)===null||s===void 0||s.forEach(function(y){y[e](t,r,l)}),T&&i.restore(),p&&i.restore()}getClientRect(e={}){var t;const r=e.skipTransform,l=e.relativeTo;let s,i,f,h,d={x:1/0,y:1/0,width:0,height:0};const p=this;(t=this.children)===null||t===void 0||t.forEach(function(y){if(!y.visible())return;const S=y.getClientRect({relativeTo:p,skipShadow:e.skipShadow,skipStroke:e.skipStroke});S.width===0&&S.height===0||(s===void 0?(s=S.x,i=S.y,f=S.x+S.width,h=S.y+S.height):(s=Math.min(s,S.x),i=Math.min(i,S.y),f=Math.max(f,S.x+S.width),h=Math.max(h,S.y+S.height)))});const v=this.find("Shape");let T=!1;for(let y=0;y<v.length;y++)if(v[y]._isVisible(this)){T=!0;break}return T&&s!==void 0?d={x:s,y:i,width:f-s,height:h-i}:d={x:0,y:0,width:0,height:0},r?d:this._transformedRect(d,l)}}zn.Container=Xn,$i.Factory.addComponentsGetterSetter(Xn,"clip",["x","y","width","height"]),$i.Factory.addGetterSetter(Xn,"clipX",void 0,(0,su.getNumberValidator)()),$i.Factory.addGetterSetter(Xn,"clipY",void 0,(0,su.getNumberValidator)()),$i.Factory.addGetterSetter(Xn,"clipWidth",void 0,(0,su.getNumberValidator)()),$i.Factory.addGetterSetter(Xn,"clipHeight",void 0,(0,su.getNumberValidator)()),$i.Factory.addGetterSetter(Xn,"clipFunc");var Bg={},mn={};Object.defineProperty(mn,"__esModule",{value:!0}),mn.getCapturedShape=BS,mn.createEvent=Qh,mn.hasPointerCapture=jS,mn.setPointerCapture=qS,mn.releaseCapture=qg;const VS=Le,pl=new Map,jg=VS.Konva._global.PointerEvent!==void 0;function BS(u){return pl.get(u)}function Qh(u){return{evt:u,pointerId:u.pointerId}}function jS(u,e){return pl.get(u)===e}function qS(u,e){qg(u),e.getStage()&&(pl.set(u,e),jg&&e._fire("gotpointercapture",Qh(new PointerEvent("gotpointercapture"))))}function qg(u,e){const t=pl.get(u);if(!t)return;const r=t.getStage();r&&r.content,pl.delete(u),jg&&t._fire("lostpointercapture",Qh(new PointerEvent("lostpointercapture")))}(function(u){Object.defineProperty(u,"__esModule",{value:!0}),u.Stage=u.stages=void 0;const e=rt,t=Fe,r=zn,l=Le,s=ms,i=Qo,f=Le,h=mn,d="Stage",p="string",v="px",T="mouseout",y="mouseleave",S="mouseover",A="mouseenter",R="mousemove",O="mousedown",N="mouseup",C="pointermove",b="pointerdown",w="pointerup",F="pointercancel",q="lostpointercapture",D="pointerout",P="pointerleave",I="pointerover",x="pointerenter",U="contextmenu",B="touchstart",z="touchend",L="touchmove",V="touchcancel",J="wheel",Pe=5,ee=[[A,"_pointerenter"],[O,"_pointerdown"],[R,"_pointermove"],[N,"_pointerup"],[y,"_pointerleave"],[B,"_pointerdown"],[L,"_pointermove"],[z,"_pointerup"],[V,"_pointercancel"],[S,"_pointerover"],[J,"_wheel"],[U,"_contextmenu"],[b,"_pointerdown"],[C,"_pointermove"],[w,"_pointerup"],[F,"_pointercancel"],[q,"_lostpointercapture"]],j={mouse:{[D]:T,[P]:y,[I]:S,[x]:A,[C]:R,[b]:O,[w]:N,[F]:"mousecancel",pointerclick:"click",pointerdblclick:"dblclick"},touch:{[D]:"touchout",[P]:"touchleave",[I]:"touchover",[x]:"touchenter",[C]:L,[b]:B,[w]:z,[F]:V,pointerclick:"tap",pointerdblclick:"dbltap"},pointer:{[D]:D,[P]:P,[I]:I,[x]:x,[C]:C,[b]:b,[w]:w,[F]:F,pointerclick:"pointerclick",pointerdblclick:"pointerdblclick"}},K=be=>be.indexOf("pointer")>=0?"pointer":be.indexOf("touch")>=0?"touch":"mouse",ie=be=>{const M=K(be);if(M==="pointer")return l.Konva.pointerEventsEnabled&&j.pointer;if(M==="touch")return j.touch;if(M==="mouse")return j.mouse};function ue(be={}){return(be.clipFunc||be.clipWidth||be.clipHeight)&&e.Util.warn("Stage does not support clipping. Please use clip for Layers or Groups."),be}const Ce="Pointer position is missing and not registered by the stage. Looks like it is outside of the stage container. You can set it manually from event: stage.setPointersPositions(event);";u.stages=[];class ke extends r.Container{constructor(M){super(ue(M)),this._pointerPositions=[],this._changedPointerPositions=[],this._buildDOM(),this._bindContentEvents(),u.stages.push(this),this.on("widthChange.konva heightChange.konva",this._resizeDOM),this.on("visibleChange.konva",this._checkVisibility),this.on("clipWidthChange.konva clipHeightChange.konva clipFuncChange.konva",()=>{ue(this.attrs)}),this._checkVisibility()}_validateAdd(M){const Y=M.getType()==="Layer",Ee=M.getType()==="FastLayer";Y||Ee||e.Util.throw("You may only add layers to the stage.")}_checkVisibility(){if(!this.content)return;const M=this.visible()?"":"none";this.content.style.display=M}setContainer(M){if(typeof M===p){if(M.charAt(0)==="."){const Ee=M.slice(1);M=document.getElementsByClassName(Ee)[0]}else{var Y;M.charAt(0)!=="#"?Y=M:Y=M.slice(1),M=document.getElementById(Y)}if(!M)throw"Can not find container in document with id "+Y}return this._setAttr("container",M),this.content&&(this.content.parentElement&&this.content.parentElement.removeChild(this.content),M.appendChild(this.content)),this}shouldDrawHit(){return!0}clear(){let M=this.children,Y=M.length,Ee;for(Ee=0;Ee<Y;Ee++)M[Ee].clear();return this}clone(M){return M||(M={}),M.container=typeof document<"u"&&document.createElement("div"),r.Container.prototype.clone.call(this,M)}destroy(){super.destroy();const M=this.content;M&&e.Util._isInDocument(M)&&this.container().removeChild(M);const Y=u.stages.indexOf(this);return Y>-1&&u.stages.splice(Y,1),e.Util.releaseCanvas(this.bufferCanvas._canvas,this.bufferHitCanvas._canvas),this}getPointerPosition(){const M=this._pointerPositions[0]||this._changedPointerPositions[0];return M?{x:M.x,y:M.y}:(e.Util.warn(Ce),null)}_getPointerById(M){return this._pointerPositions.find(Y=>Y.id===M)}getPointersPositions(){return this._pointerPositions}getStage(){return this}getContent(){return this.content}_toKonvaCanvas(M){M=M||{},M.x=M.x||0,M.y=M.y||0,M.width=M.width||this.width(),M.height=M.height||this.height();const Y=new s.SceneCanvas({width:M.width,height:M.height,pixelRatio:M.pixelRatio||1}),Ee=Y.getContext()._context,Me=this.children;return(M.x||M.y)&&Ee.translate(-1*M.x,-1*M.y),Me.forEach(function(fe){if(!fe.isVisible())return;const _e=fe._toKonvaCanvas(M);Ee.drawImage(_e._canvas,M.x,M.y,_e.getWidth()/_e.getPixelRatio(),_e.getHeight()/_e.getPixelRatio())}),Y}getIntersection(M){if(!M)return null;let Y=this.children,Ee=Y.length,Me=Ee-1,fe;for(fe=Me;fe>=0;fe--){const _e=Y[fe].getIntersection(M);if(_e)return _e}return null}_resizeDOM(){const M=this.width(),Y=this.height();this.content&&(this.content.style.width=M+v,this.content.style.height=Y+v),this.bufferCanvas.setSize(M,Y),this.bufferHitCanvas.setSize(M,Y),this.children.forEach(Ee=>{Ee.setSize({width:M,height:Y}),Ee.draw()})}add(M,...Y){if(arguments.length>1){for(let Me=0;Me<arguments.length;Me++)this.add(arguments[Me]);return this}super.add(M);const Ee=this.children.length;return Ee>Pe&&e.Util.warn("The stage has "+Ee+" layers. Recommended maximum number of layers is 3-5. Adding more layers into the stage may drop the performance. Rethink your tree structure, you can use Konva.Group."),M.setSize({width:this.width(),height:this.height()}),M.draw(),l.Konva.isBrowser&&this.content.appendChild(M.canvas._canvas),this}getParent(){return null}getLayer(){return null}hasPointerCapture(M){return h.hasPointerCapture(M,this)}setPointerCapture(M){h.setPointerCapture(M,this)}releaseCapture(M){h.releaseCapture(M,this)}getLayers(){return this.children}_bindContentEvents(){l.Konva.isBrowser&&ee.forEach(([M,Y])=>{this.content.addEventListener(M,Ee=>{this[Y](Ee)},{passive:!1})})}_pointerenter(M){this.setPointersPositions(M);const Y=ie(M.type);Y&&this._fire(Y.pointerenter,{evt:M,target:this,currentTarget:this})}_pointerover(M){this.setPointersPositions(M);const Y=ie(M.type);Y&&this._fire(Y.pointerover,{evt:M,target:this,currentTarget:this})}_getTargetShape(M){let Y=this[M+"targetShape"];return Y&&!Y.getStage()&&(Y=null),Y}_pointerleave(M){const Y=ie(M.type),Ee=K(M.type);if(!Y)return;this.setPointersPositions(M);const Me=this._getTargetShape(Ee),fe=!(l.Konva.isDragging()||l.Konva.isTransforming())||l.Konva.hitOnDragEnabled;Me&&fe?(Me._fireAndBubble(Y.pointerout,{evt:M}),Me._fireAndBubble(Y.pointerleave,{evt:M}),this._fire(Y.pointerleave,{evt:M,target:this,currentTarget:this}),this[Ee+"targetShape"]=null):fe&&(this._fire(Y.pointerleave,{evt:M,target:this,currentTarget:this}),this._fire(Y.pointerout,{evt:M,target:this,currentTarget:this})),this.pointerPos=null,this._pointerPositions=[]}_pointerdown(M){const Y=ie(M.type),Ee=K(M.type);if(!Y)return;this.setPointersPositions(M);let Me=!1;this._changedPointerPositions.forEach(fe=>{const _e=this.getIntersection(fe);if(i.DD.justDragged=!1,l.Konva["_"+Ee+"ListenClick"]=!0,!_e||!_e.isListening()){this[Ee+"ClickStartShape"]=void 0;return}l.Konva.capturePointerEventsEnabled&&_e.setPointerCapture(fe.id),this[Ee+"ClickStartShape"]=_e,_e._fireAndBubble(Y.pointerdown,{evt:M,pointerId:fe.id}),Me=!0;const we=M.type.indexOf("touch")>=0;_e.preventDefault()&&M.cancelable&&we&&M.preventDefault()}),Me||this._fire(Y.pointerdown,{evt:M,target:this,currentTarget:this,pointerId:this._pointerPositions[0].id})}_pointermove(M){const Y=ie(M.type),Ee=K(M.type);if(!Y||(l.Konva.isDragging()&&i.DD.node.preventDefault()&&M.cancelable&&M.preventDefault(),this.setPointersPositions(M),!(!(l.Konva.isDragging()||l.Konva.isTransforming())||l.Konva.hitOnDragEnabled)))return;const fe={};let _e=!1;const we=this._getTargetShape(Ee);this._changedPointerPositions.forEach(De=>{const ce=h.getCapturedShape(De.id)||this.getIntersection(De),de=De.id,ge={evt:M,pointerId:de},Oe=we!==ce;if(Oe&&we&&(we._fireAndBubble(Y.pointerout,{...ge},ce),we._fireAndBubble(Y.pointerleave,{...ge},ce)),ce){if(fe[ce._id])return;fe[ce._id]=!0}ce&&ce.isListening()?(_e=!0,Oe&&(ce._fireAndBubble(Y.pointerover,{...ge},we),ce._fireAndBubble(Y.pointerenter,{...ge},we),this[Ee+"targetShape"]=ce),ce._fireAndBubble(Y.pointermove,{...ge})):we&&(this._fire(Y.pointerover,{evt:M,target:this,currentTarget:this,pointerId:de}),this[Ee+"targetShape"]=null)}),_e||this._fire(Y.pointermove,{evt:M,target:this,currentTarget:this,pointerId:this._changedPointerPositions[0].id})}_pointerup(M){const Y=ie(M.type),Ee=K(M.type);if(!Y)return;this.setPointersPositions(M);const Me=this[Ee+"ClickStartShape"],fe=this[Ee+"ClickEndShape"],_e={};let we=!1;this._changedPointerPositions.forEach(De=>{const ce=h.getCapturedShape(De.id)||this.getIntersection(De);if(ce){if(ce.releaseCapture(De.id),_e[ce._id])return;_e[ce._id]=!0}const de=De.id,ge={evt:M,pointerId:de};let Oe=!1;l.Konva["_"+Ee+"InDblClickWindow"]?(Oe=!0,clearTimeout(this[Ee+"DblTimeout"])):i.DD.justDragged||(l.Konva["_"+Ee+"InDblClickWindow"]=!0,clearTimeout(this[Ee+"DblTimeout"])),this[Ee+"DblTimeout"]=setTimeout(function(){l.Konva["_"+Ee+"InDblClickWindow"]=!1},l.Konva.dblClickWindow),ce&&ce.isListening()?(we=!0,this[Ee+"ClickEndShape"]=ce,ce._fireAndBubble(Y.pointerup,{...ge}),l.Konva["_"+Ee+"ListenClick"]&&Me&&Me===ce&&(ce._fireAndBubble(Y.pointerclick,{...ge}),Oe&&fe&&fe===ce&&ce._fireAndBubble(Y.pointerdblclick,{...ge}))):(this[Ee+"ClickEndShape"]=null,l.Konva["_"+Ee+"ListenClick"]&&this._fire(Y.pointerclick,{evt:M,target:this,currentTarget:this,pointerId:de}),Oe&&this._fire(Y.pointerdblclick,{evt:M,target:this,currentTarget:this,pointerId:de}))}),we||this._fire(Y.pointerup,{evt:M,target:this,currentTarget:this,pointerId:this._changedPointerPositions[0].id}),l.Konva["_"+Ee+"ListenClick"]=!1,M.cancelable&&Ee!=="touch"&&M.preventDefault()}_contextmenu(M){this.setPointersPositions(M);const Y=this.getIntersection(this.getPointerPosition());Y&&Y.isListening()?Y._fireAndBubble(U,{evt:M}):this._fire(U,{evt:M,target:this,currentTarget:this})}_wheel(M){this.setPointersPositions(M);const Y=this.getIntersection(this.getPointerPosition());Y&&Y.isListening()?Y._fireAndBubble(J,{evt:M}):this._fire(J,{evt:M,target:this,currentTarget:this})}_pointercancel(M){this.setPointersPositions(M);const Y=h.getCapturedShape(M.pointerId)||this.getIntersection(this.getPointerPosition());Y&&Y._fireAndBubble(w,h.createEvent(M)),h.releaseCapture(M.pointerId)}_lostpointercapture(M){h.releaseCapture(M.pointerId)}setPointersPositions(M){let Y=this._getContentPosition(),Ee=null,Me=null;M=M||window.event,M.touches!==void 0?(this._pointerPositions=[],this._changedPointerPositions=[],Array.prototype.forEach.call(M.touches,fe=>{this._pointerPositions.push({id:fe.identifier,x:(fe.clientX-Y.left)/Y.scaleX,y:(fe.clientY-Y.top)/Y.scaleY})}),Array.prototype.forEach.call(M.changedTouches||M.touches,fe=>{this._changedPointerPositions.push({id:fe.identifier,x:(fe.clientX-Y.left)/Y.scaleX,y:(fe.clientY-Y.top)/Y.scaleY})})):(Ee=(M.clientX-Y.left)/Y.scaleX,Me=(M.clientY-Y.top)/Y.scaleY,this.pointerPos={x:Ee,y:Me},this._pointerPositions=[{x:Ee,y:Me,id:e.Util._getFirstPointerId(M)}],this._changedPointerPositions=[{x:Ee,y:Me,id:e.Util._getFirstPointerId(M)}])}_setPointerPosition(M){e.Util.warn('Method _setPointerPosition is deprecated. Use "stage.setPointersPositions(event)" instead.'),this.setPointersPositions(M)}_getContentPosition(){if(!this.content||!this.content.getBoundingClientRect)return{top:0,left:0,scaleX:1,scaleY:1};const M=this.content.getBoundingClientRect();return{top:M.top,left:M.left,scaleX:M.width/this.content.clientWidth||1,scaleY:M.height/this.content.clientHeight||1}}_buildDOM(){if(this.bufferCanvas=new s.SceneCanvas({width:this.width(),height:this.height()}),this.bufferHitCanvas=new s.HitCanvas({pixelRatio:1,width:this.width(),height:this.height()}),!l.Konva.isBrowser)return;const M=this.container();if(!M)throw"Stage has no container. A container is required.";M.innerHTML="",this.content=document.createElement("div"),this.content.style.position="relative",this.content.style.userSelect="none",this.content.className="konvajs-content",this.content.setAttribute("role","presentation"),M.appendChild(this.content),this._resizeDOM()}cache(){return e.Util.warn("Cache function is not allowed for stage. You may use cache only for layers, groups and shapes."),this}clearCache(){return this}batchDraw(){return this.getChildren().forEach(function(M){M.batchDraw()}),this}}u.Stage=ke,ke.prototype.nodeType=d,(0,f._registerNode)(ke),t.Factory.addGetterSetter(ke,"container"),l.Konva.isBrowser&&document.addEventListener("visibilitychange",()=>{u.stages.forEach(be=>{be.batchDraw()})})})(Bg);var ml={},Ct={};(function(u){Object.defineProperty(u,"__esModule",{value:!0}),u.Shape=u.shapes=void 0;const e=Le,t=rt,r=Fe,l=it,s=Ne,i=Le,f=mn,h="hasShadow",d="shadowRGBA",p="patternImage",v="linearGradient",T="radialGradient";let y;function S(){return y||(y=t.Util.createCanvasElement().getContext("2d"),y)}u.shapes={};function A(P){const I=this.attrs.fillRule;I?P.fill(I):P.fill()}function R(P){P.stroke()}function O(P){const I=this.attrs.fillRule;I?P.fill(I):P.fill()}function N(P){P.stroke()}function C(){this._clearCache(h)}function b(){this._clearCache(d)}function w(){this._clearCache(p)}function F(){this._clearCache(v)}function q(){this._clearCache(T)}class D extends l.Node{constructor(I){super(I);let x;for(;x=t.Util.getRandomColor(),!(x&&!(x in u.shapes)););this.colorKey=x,u.shapes[x]=this}getContext(){return t.Util.warn("shape.getContext() method is deprecated. Please do not use it."),this.getLayer().getContext()}getCanvas(){return t.Util.warn("shape.getCanvas() method is deprecated. Please do not use it."),this.getLayer().getCanvas()}getSceneFunc(){return this.attrs.sceneFunc||this._sceneFunc}getHitFunc(){return this.attrs.hitFunc||this._hitFunc}hasShadow(){return this._getCache(h,this._hasShadow)}_hasShadow(){return this.shadowEnabled()&&this.shadowOpacity()!==0&&!!(this.shadowColor()||this.shadowBlur()||this.shadowOffsetX()||this.shadowOffsetY())}_getFillPattern(){return this._getCache(p,this.__getFillPattern)}__getFillPattern(){if(this.fillPatternImage()){const x=S().createPattern(this.fillPatternImage(),this.fillPatternRepeat()||"repeat");if(x&&x.setTransform){const U=new t.Transform;U.translate(this.fillPatternX(),this.fillPatternY()),U.rotate(e.Konva.getAngle(this.fillPatternRotation())),U.scale(this.fillPatternScaleX(),this.fillPatternScaleY()),U.translate(-1*this.fillPatternOffsetX(),-1*this.fillPatternOffsetY());const B=U.getMatrix(),z=typeof DOMMatrix>"u"?{a:B[0],b:B[1],c:B[2],d:B[3],e:B[4],f:B[5]}:new DOMMatrix(B);x.setTransform(z)}return x}}_getLinearGradient(){return this._getCache(v,this.__getLinearGradient)}__getLinearGradient(){const I=this.fillLinearGradientColorStops();if(I){const x=S(),U=this.fillLinearGradientStartPoint(),B=this.fillLinearGradientEndPoint(),z=x.createLinearGradient(U.x,U.y,B.x,B.y);for(let L=0;L<I.length;L+=2)z.addColorStop(I[L],I[L+1]);return z}}_getRadialGradient(){return this._getCache(T,this.__getRadialGradient)}__getRadialGradient(){const I=this.fillRadialGradientColorStops();if(I){const x=S(),U=this.fillRadialGradientStartPoint(),B=this.fillRadialGradientEndPoint(),z=x.createRadialGradient(U.x,U.y,this.fillRadialGradientStartRadius(),B.x,B.y,this.fillRadialGradientEndRadius());for(let L=0;L<I.length;L+=2)z.addColorStop(I[L],I[L+1]);return z}}getShadowRGBA(){return this._getCache(d,this._getShadowRGBA)}_getShadowRGBA(){if(!this.hasShadow())return;const I=t.Util.colorToRGBA(this.shadowColor());if(I)return"rgba("+I.r+","+I.g+","+I.b+","+I.a*(this.shadowOpacity()||1)+")"}hasFill(){return this._calculate("hasFill",["fillEnabled","fill","fillPatternImage","fillLinearGradientColorStops","fillRadialGradientColorStops"],()=>this.fillEnabled()&&!!(this.fill()||this.fillPatternImage()||this.fillLinearGradientColorStops()||this.fillRadialGradientColorStops()))}hasStroke(){return this._calculate("hasStroke",["strokeEnabled","strokeWidth","stroke","strokeLinearGradientColorStops"],()=>this.strokeEnabled()&&this.strokeWidth()&&!!(this.stroke()||this.strokeLinearGradientColorStops()))}hasHitStroke(){const I=this.hitStrokeWidth();return I==="auto"?this.hasStroke():this.strokeEnabled()&&!!I}intersects(I){const x=this.getStage();if(!x)return!1;const U=x.bufferHitCanvas;return U.getContext().clear(),this.drawHit(U,void 0,!0),U.context.getImageData(Math.round(I.x),Math.round(I.y),1,1).data[3]>0}destroy(){return l.Node.prototype.destroy.call(this),delete u.shapes[this.colorKey],delete this.colorKey,this}_useBufferCanvas(I){var x;if(!((x=this.attrs.perfectDrawEnabled)!==null&&x!==void 0?x:!0))return!1;const B=I||this.hasFill(),z=this.hasStroke(),L=this.getAbsoluteOpacity()!==1;if(B&&z&&L)return!0;const V=this.hasShadow(),J=this.shadowForStrokeEnabled();return!!(B&&z&&V&&J)}setStrokeHitEnabled(I){t.Util.warn("strokeHitEnabled property is deprecated. Please use hitStrokeWidth instead."),I?this.hitStrokeWidth("auto"):this.hitStrokeWidth(0)}getStrokeHitEnabled(){return this.hitStrokeWidth()!==0}getSelfRect(){const I=this.size();return{x:this._centroid?-I.width/2:0,y:this._centroid?-I.height/2:0,width:I.width,height:I.height}}getClientRect(I={}){let x=!1,U=this.getParent();for(;U;){if(U.isCached()){x=!0;break}U=U.getParent()}const B=I.skipTransform,z=I.relativeTo||x&&this.getStage()||void 0,L=this.getSelfRect(),J=!I.skipStroke&&this.hasStroke()&&this.strokeWidth()||0,Pe=L.width+J,ee=L.height+J,j=!I.skipShadow&&this.hasShadow(),K=j?this.shadowOffsetX():0,ie=j?this.shadowOffsetY():0,ue=Pe+Math.abs(K),Ce=ee+Math.abs(ie),ke=j&&this.shadowBlur()||0,be=ue+ke*2,M=Ce+ke*2,Y={width:be,height:M,x:-(J/2+ke)+Math.min(K,0)+L.x,y:-(J/2+ke)+Math.min(ie,0)+L.y};return B?Y:this._transformedRect(Y,z)}drawScene(I,x,U){const B=this.getLayer();let z=I||B.getCanvas(),L=z.getContext(),V=this._getCanvasCache(),J=this.getSceneFunc(),Pe=this.hasShadow(),ee,j;const K=z.isCache,ie=x===this;if(!this.isVisible()&&!ie)return this;if(V){L.save();const Ce=this.getAbsoluteTransform(x).getMatrix();return L.transform(Ce[0],Ce[1],Ce[2],Ce[3],Ce[4],Ce[5]),this._drawCachedSceneCanvas(L),L.restore(),this}if(!J)return this;if(L.save(),this._useBufferCanvas()&&!K){ee=this.getStage();const Ce=U||ee.bufferCanvas;j=Ce.getContext(),j.clear(),j.save(),j._applyLineJoin(this);var ue=this.getAbsoluteTransform(x).getMatrix();j.transform(ue[0],ue[1],ue[2],ue[3],ue[4],ue[5]),J.call(this,j,this),j.restore();const ke=Ce.pixelRatio;Pe&&L._applyShadow(this),L._applyOpacity(this),L._applyGlobalCompositeOperation(this),L.drawImage(Ce._canvas,0,0,Ce.width/ke,Ce.height/ke)}else{if(L._applyLineJoin(this),!ie){var ue=this.getAbsoluteTransform(x).getMatrix();L.transform(ue[0],ue[1],ue[2],ue[3],ue[4],ue[5]),L._applyOpacity(this),L._applyGlobalCompositeOperation(this)}Pe&&L._applyShadow(this),J.call(this,L,this)}return L.restore(),this}drawHit(I,x,U=!1){if(!this.shouldDrawHit(x,U))return this;const B=this.getLayer(),z=I||B.hitCanvas,L=z&&z.getContext(),V=this.hitFunc()||this.sceneFunc(),J=this._getCanvasCache(),Pe=J&&J.hit;if(this.colorKey||t.Util.warn("Looks like your canvas has a destroyed shape in it. Do not reuse shape after you destroyed it. If you want to reuse shape you should call remove() instead of destroy()"),Pe){L.save();const j=this.getAbsoluteTransform(x).getMatrix();return L.transform(j[0],j[1],j[2],j[3],j[4],j[5]),this._drawCachedHitCanvas(L),L.restore(),this}if(!V)return this;if(L.save(),L._applyLineJoin(this),!(this===x)){const j=this.getAbsoluteTransform(x).getMatrix();L.transform(j[0],j[1],j[2],j[3],j[4],j[5])}return V.call(this,L,this),L.restore(),this}drawHitFromCache(I=0){let x=this._getCanvasCache(),U=this._getCachedSceneCanvas(),B=x.hit,z=B.getContext(),L=B.getWidth(),V=B.getHeight(),J,Pe,ee,j,K,ie;z.clear(),z.drawImage(U._canvas,0,0,L,V);try{for(J=z.getImageData(0,0,L,V),Pe=J.data,ee=Pe.length,j=t.Util._hexToRgb(this.colorKey),K=0;K<ee;K+=4)ie=Pe[K+3],ie>I?(Pe[K]=j.r,Pe[K+1]=j.g,Pe[K+2]=j.b,Pe[K+3]=255):Pe[K+3]=0;z.putImageData(J,0,0)}catch(ue){t.Util.error("Unable to draw hit graph from cached scene canvas. "+ue.message)}return this}hasPointerCapture(I){return f.hasPointerCapture(I,this)}setPointerCapture(I){f.setPointerCapture(I,this)}releaseCapture(I){f.releaseCapture(I,this)}}u.Shape=D,D.prototype._fillFunc=A,D.prototype._strokeFunc=R,D.prototype._fillFuncHit=O,D.prototype._strokeFuncHit=N,D.prototype._centroid=!1,D.prototype.nodeType="Shape",(0,i._registerNode)(D),D.prototype.eventListeners={},D.prototype.on.call(D.prototype,"shadowColorChange.konva shadowBlurChange.konva shadowOffsetChange.konva shadowOpacityChange.konva shadowEnabledChange.konva",C),D.prototype.on.call(D.prototype,"shadowColorChange.konva shadowOpacityChange.konva shadowEnabledChange.konva",b),D.prototype.on.call(D.prototype,"fillPriorityChange.konva fillPatternImageChange.konva fillPatternRepeatChange.konva fillPatternScaleXChange.konva fillPatternScaleYChange.konva fillPatternOffsetXChange.konva fillPatternOffsetYChange.konva fillPatternXChange.konva fillPatternYChange.konva fillPatternRotationChange.konva",w),D.prototype.on.call(D.prototype,"fillPriorityChange.konva fillLinearGradientColorStopsChange.konva fillLinearGradientStartPointXChange.konva fillLinearGradientStartPointYChange.konva fillLinearGradientEndPointXChange.konva fillLinearGradientEndPointYChange.konva",F),D.prototype.on.call(D.prototype,"fillPriorityChange.konva fillRadialGradientColorStopsChange.konva fillRadialGradientStartPointXChange.konva fillRadialGradientStartPointYChange.konva fillRadialGradientEndPointXChange.konva fillRadialGradientEndPointYChange.konva fillRadialGradientStartRadiusChange.konva fillRadialGradientEndRadiusChange.konva",q),r.Factory.addGetterSetter(D,"stroke",void 0,(0,s.getStringOrGradientValidator)()),r.Factory.addGetterSetter(D,"strokeWidth",2,(0,s.getNumberValidator)()),r.Factory.addGetterSetter(D,"fillAfterStrokeEnabled",!1),r.Factory.addGetterSetter(D,"hitStrokeWidth","auto",(0,s.getNumberOrAutoValidator)()),r.Factory.addGetterSetter(D,"strokeHitEnabled",!0,(0,s.getBooleanValidator)()),r.Factory.addGetterSetter(D,"perfectDrawEnabled",!0,(0,s.getBooleanValidator)()),r.Factory.addGetterSetter(D,"shadowForStrokeEnabled",!0,(0,s.getBooleanValidator)()),r.Factory.addGetterSetter(D,"lineJoin"),r.Factory.addGetterSetter(D,"lineCap"),r.Factory.addGetterSetter(D,"sceneFunc"),r.Factory.addGetterSetter(D,"hitFunc"),r.Factory.addGetterSetter(D,"dash"),r.Factory.addGetterSetter(D,"dashOffset",0,(0,s.getNumberValidator)()),r.Factory.addGetterSetter(D,"shadowColor",void 0,(0,s.getStringValidator)()),r.Factory.addGetterSetter(D,"shadowBlur",0,(0,s.getNumberValidator)()),r.Factory.addGetterSetter(D,"shadowOpacity",1,(0,s.getNumberValidator)()),r.Factory.addComponentsGetterSetter(D,"shadowOffset",["x","y"]),r.Factory.addGetterSetter(D,"shadowOffsetX",0,(0,s.getNumberValidator)()),r.Factory.addGetterSetter(D,"shadowOffsetY",0,(0,s.getNumberValidator)()),r.Factory.addGetterSetter(D,"fillPatternImage"),r.Factory.addGetterSetter(D,"fill",void 0,(0,s.getStringOrGradientValidator)()),r.Factory.addGetterSetter(D,"fillPatternX",0,(0,s.getNumberValidator)()),r.Factory.addGetterSetter(D,"fillPatternY",0,(0,s.getNumberValidator)()),r.Factory.addGetterSetter(D,"fillLinearGradientColorStops"),r.Factory.addGetterSetter(D,"strokeLinearGradientColorStops"),r.Factory.addGetterSetter(D,"fillRadialGradientStartRadius",0),r.Factory.addGetterSetter(D,"fillRadialGradientEndRadius",0),r.Factory.addGetterSetter(D,"fillRadialGradientColorStops"),r.Factory.addGetterSetter(D,"fillPatternRepeat","repeat"),r.Factory.addGetterSetter(D,"fillEnabled",!0),r.Factory.addGetterSetter(D,"strokeEnabled",!0),r.Factory.addGetterSetter(D,"shadowEnabled",!0),r.Factory.addGetterSetter(D,"dashEnabled",!0),r.Factory.addGetterSetter(D,"strokeScaleEnabled",!0),r.Factory.addGetterSetter(D,"fillPriority","color"),r.Factory.addComponentsGetterSetter(D,"fillPatternOffset",["x","y"]),r.Factory.addGetterSetter(D,"fillPatternOffsetX",0,(0,s.getNumberValidator)()),r.Factory.addGetterSetter(D,"fillPatternOffsetY",0,(0,s.getNumberValidator)()),r.Factory.addComponentsGetterSetter(D,"fillPatternScale",["x","y"]),r.Factory.addGetterSetter(D,"fillPatternScaleX",1,(0,s.getNumberValidator)()),r.Factory.addGetterSetter(D,"fillPatternScaleY",1,(0,s.getNumberValidator)()),r.Factory.addComponentsGetterSetter(D,"fillLinearGradientStartPoint",["x","y"]),r.Factory.addComponentsGetterSetter(D,"strokeLinearGradientStartPoint",["x","y"]),r.Factory.addGetterSetter(D,"fillLinearGradientStartPointX",0),r.Factory.addGetterSetter(D,"strokeLinearGradientStartPointX",0),r.Factory.addGetterSetter(D,"fillLinearGradientStartPointY",0),r.Factory.addGetterSetter(D,"strokeLinearGradientStartPointY",0),r.Factory.addComponentsGetterSetter(D,"fillLinearGradientEndPoint",["x","y"]),r.Factory.addComponentsGetterSetter(D,"strokeLinearGradientEndPoint",["x","y"]),r.Factory.addGetterSetter(D,"fillLinearGradientEndPointX",0),r.Factory.addGetterSetter(D,"strokeLinearGradientEndPointX",0),r.Factory.addGetterSetter(D,"fillLinearGradientEndPointY",0),r.Factory.addGetterSetter(D,"strokeLinearGradientEndPointY",0),r.Factory.addComponentsGetterSetter(D,"fillRadialGradientStartPoint",["x","y"]),r.Factory.addGetterSetter(D,"fillRadialGradientStartPointX",0),r.Factory.addGetterSetter(D,"fillRadialGradientStartPointY",0),r.Factory.addComponentsGetterSetter(D,"fillRadialGradientEndPoint",["x","y"]),r.Factory.addGetterSetter(D,"fillRadialGradientEndPointX",0),r.Factory.addGetterSetter(D,"fillRadialGradientEndPointY",0),r.Factory.addGetterSetter(D,"fillPatternRotation",0),r.Factory.addGetterSetter(D,"fillRule",void 0,(0,s.getStringValidator)()),r.Factory.backCompat(D,{dashArray:"dash",getDashArray:"getDash",setDashArray:"getDash",drawFunc:"sceneFunc",getDrawFunc:"getSceneFunc",setDrawFunc:"setSceneFunc",drawHitFunc:"hitFunc",getDrawHitFunc:"getHitFunc",setDrawHitFunc:"setHitFunc"})})(Ct),Object.defineProperty(ml,"__esModule",{value:!0}),ml.Layer=void 0;const zs=rt,Zh=zn,Hi=it,ef=Fe,Wg=ms,WS=Ne,KS=Ct,YS=Le,zS="#",XS="beforeDraw",JS="draw",Kg=[{x:0,y:0},{x:-1,y:-1},{x:1,y:-1},{x:1,y:1},{x:-1,y:1}],QS=Kg.length;class Gi extends Zh.Container{constructor(e){super(e),this.canvas=new Wg.SceneCanvas,this.hitCanvas=new Wg.HitCanvas({pixelRatio:1}),this._waitingForDraw=!1,this.on("visibleChange.konva",this._checkVisibility),this._checkVisibility(),this.on("imageSmoothingEnabledChange.konva",this._setSmoothEnabled),this._setSmoothEnabled()}createPNGStream(){return this.canvas._canvas.createPNGStream()}getCanvas(){return this.canvas}getNativeCanvasElement(){return this.canvas._canvas}getHitCanvas(){return this.hitCanvas}getContext(){return this.getCanvas().getContext()}clear(e){return this.getContext().clear(e),this.getHitCanvas().getContext().clear(e),this}setZIndex(e){super.setZIndex(e);const t=this.getStage();return t&&t.content&&(t.content.removeChild(this.getNativeCanvasElement()),e<t.children.length-1?t.content.insertBefore(this.getNativeCanvasElement(),t.children[e+1].getCanvas()._canvas):t.content.appendChild(this.getNativeCanvasElement())),this}moveToTop(){Hi.Node.prototype.moveToTop.call(this);const e=this.getStage();return e&&e.content&&(e.content.removeChild(this.getNativeCanvasElement()),e.content.appendChild(this.getNativeCanvasElement())),!0}moveUp(){if(!Hi.Node.prototype.moveUp.call(this))return!1;const t=this.getStage();return!t||!t.content?!1:(t.content.removeChild(this.getNativeCanvasElement()),this.index<t.children.length-1?t.content.insertBefore(this.getNativeCanvasElement(),t.children[this.index+1].getCanvas()._canvas):t.content.appendChild(this.getNativeCanvasElement()),!0)}moveDown(){if(Hi.Node.prototype.moveDown.call(this)){const e=this.getStage();if(e){const t=e.children;e.content&&(e.content.removeChild(this.getNativeCanvasElement()),e.content.insertBefore(this.getNativeCanvasElement(),t[this.index+1].getCanvas()._canvas))}return!0}return!1}moveToBottom(){if(Hi.Node.prototype.moveToBottom.call(this)){const e=this.getStage();if(e){const t=e.children;e.content&&(e.content.removeChild(this.getNativeCanvasElement()),e.content.insertBefore(this.getNativeCanvasElement(),t[1].getCanvas()._canvas))}return!0}return!1}getLayer(){return this}remove(){const e=this.getNativeCanvasElement();return Hi.Node.prototype.remove.call(this),e&&e.parentNode&&zs.Util._isInDocument(e)&&e.parentNode.removeChild(e),this}getStage(){return this.parent}setSize({width:e,height:t}){return this.canvas.setSize(e,t),this.hitCanvas.setSize(e,t),this._setSmoothEnabled(),this}_validateAdd(e){const t=e.getType();t!=="Group"&&t!=="Shape"&&zs.Util.throw("You may only add groups and shapes to a layer.")}_toKonvaCanvas(e){return e=e||{},e.width=e.width||this.getWidth(),e.height=e.height||this.getHeight(),e.x=e.x!==void 0?e.x:this.x(),e.y=e.y!==void 0?e.y:this.y(),Hi.Node.prototype._toKonvaCanvas.call(this,e)}_checkVisibility(){this.visible()?this.canvas._canvas.style.display="block":this.canvas._canvas.style.display="none"}_setSmoothEnabled(){this.getContext()._context.imageSmoothingEnabled=this.imageSmoothingEnabled()}getWidth(){if(this.parent)return this.parent.width()}setWidth(){zs.Util.warn('Can not change width of layer. Use "stage.width(value)" function instead.')}getHeight(){if(this.parent)return this.parent.height()}setHeight(){zs.Util.warn('Can not change height of layer. Use "stage.height(value)" function instead.')}batchDraw(){return this._waitingForDraw||(this._waitingForDraw=!0,zs.Util.requestAnimFrame(()=>{this.draw(),this._waitingForDraw=!1})),this}getIntersection(e){if(!this.isListening()||!this.isVisible())return null;let t=1,r=!1;for(;;){for(let l=0;l<QS;l++){const s=Kg[l],i=this._getIntersection({x:e.x+s.x*t,y:e.y+s.y*t}),f=i.shape;if(f)return f;if(r=!!i.antialiased,!i.antialiased)break}if(r)t+=1;else return null}}_getIntersection(e){const t=this.hitCanvas.pixelRatio,r=this.hitCanvas.context.getImageData(Math.round(e.x*t),Math.round(e.y*t),1,1).data,l=r[3];if(l===255){const s=zs.Util._rgbToHex(r[0],r[1],r[2]),i=KS.shapes[zS+s];return i?{shape:i}:{antialiased:!0}}else if(l>0)return{antialiased:!0};return{}}drawScene(e,t){const r=this.getLayer(),l=e||r&&r.getCanvas();return this._fire(XS,{node:this}),this.clearBeforeDraw()&&l.getContext().clear(),Zh.Container.prototype.drawScene.call(this,l,t),this._fire(JS,{node:this}),this}drawHit(e,t){const r=this.getLayer(),l=e||r&&r.hitCanvas;return r&&r.clearBeforeDraw()&&r.getHitCanvas().getContext().clear(),Zh.Container.prototype.drawHit.call(this,l,t),this}enableHitGraph(){return this.hitGraphEnabled(!0),this}disableHitGraph(){return this.hitGraphEnabled(!1),this}setHitGraphEnabled(e){zs.Util.warn("hitGraphEnabled method is deprecated. Please use layer.listening() instead."),this.listening(e)}getHitGraphEnabled(e){return zs.Util.warn("hitGraphEnabled method is deprecated. Please use layer.listening() instead."),this.listening()}toggleHitCanvas(){if(!this.parent||!this.parent.content)return;const e=this.parent;!!this.hitCanvas._canvas.parentNode?e.content.removeChild(this.hitCanvas._canvas):e.content.appendChild(this.hitCanvas._canvas)}destroy(){return zs.Util.releaseCanvas(this.getNativeCanvasElement(),this.getHitCanvas()._canvas),super.destroy()}}ml.Layer=Gi,Gi.prototype.nodeType="Layer",(0,YS._registerNode)(Gi),ef.Factory.addGetterSetter(Gi,"imageSmoothingEnabled",!0),ef.Factory.addGetterSetter(Gi,"clearBeforeDraw",!0),ef.Factory.addGetterSetter(Gi,"hitGraphEnabled",!0,(0,WS.getBooleanValidator)());var nu={};Object.defineProperty(nu,"__esModule",{value:!0}),nu.FastLayer=void 0;const ZS=rt,e2=ml,t2=Le;class tf extends e2.Layer{constructor(e){super(e),this.listening(!1),ZS.Util.warn('Konva.Fast layer is deprecated. Please use "new Konva.Layer({ listening: false })" instead.')}}nu.FastLayer=tf,tf.prototype.nodeType="FastLayer",(0,t2._registerNode)(tf);var Vi={};Object.defineProperty(Vi,"__esModule",{value:!0}),Vi.Group=void 0;const s2=rt,n2=zn,i2=Le;class sf extends n2.Container{_validateAdd(e){const t=e.getType();t!=="Group"&&t!=="Shape"&&s2.Util.throw("You may only add groups and shapes to groups.")}}Vi.Group=sf,sf.prototype.nodeType="Group",(0,i2._registerNode)(sf);var Bi={};Object.defineProperty(Bi,"__esModule",{value:!0}),Bi.Animation=void 0;const nf=Le,Yg=rt,rf=function(){return nf.glob.performance&&nf.glob.performance.now?function(){return nf.glob.performance.now()}:function(){return new Date().getTime()}}();class Os{constructor(e,t){this.id=Os.animIdCounter++,this.frame={time:0,timeDiff:0,lastTime:rf(),frameRate:0},this.func=e,this.setLayers(t)}setLayers(e){let t=[];return e&&(t=Array.isArray(e)?e:[e]),this.layers=t,this}getLayers(){return this.layers}addLayer(e){const t=this.layers,r=t.length;for(let l=0;l<r;l++)if(t[l]._id===e._id)return!1;return this.layers.push(e),!0}isRunning(){const t=Os.animations,r=t.length;for(let l=0;l<r;l++)if(t[l].id===this.id)return!0;return!1}start(){return this.stop(),this.frame.timeDiff=0,this.frame.lastTime=rf(),Os._addAnimation(this),this}stop(){return Os._removeAnimation(this),this}_updateFrameObject(e){this.frame.timeDiff=e-this.frame.lastTime,this.frame.lastTime=e,this.frame.time+=this.frame.timeDiff,this.frame.frameRate=1e3/this.frame.timeDiff}static _addAnimation(e){this.animations.push(e),this._handleAnimation()}static _removeAnimation(e){const t=e.id,r=this.animations,l=r.length;for(let s=0;s<l;s++)if(r[s].id===t){this.animations.splice(s,1);break}}static _runFrames(){const e={},t=this.animations;for(let r=0;r<t.length;r++){const l=t[r],s=l.layers,i=l.func;l._updateFrameObject(rf());const f=s.length;let h;if(i?h=i.call(l,l.frame)!==!1:h=!0,!!h)for(let d=0;d<f;d++){const p=s[d];p._id!==void 0&&(e[p._id]=p)}}for(const r in e)e.hasOwnProperty(r)&&e[r].batchDraw()}static _animationLoop(){const e=Os;e.animations.length?(e._runFrames(),Yg.Util.requestAnimFrame(e._animationLoop)):e.animRunning=!1}static _handleAnimation(){this.animRunning||(this.animRunning=!0,Yg.Util.requestAnimFrame(this._animationLoop))}}Bi.Animation=Os,Os.animations=[],Os.animIdCounter=0,Os.animRunning=!1;var zg={};(function(u){Object.defineProperty(u,"__esModule",{value:!0}),u.Easings=u.Tween=void 0;const e=rt,t=Bi,r=it,l=Le;let s={node:1,duration:1,easing:1,onFinish:1,yoyo:1},i=1,f=2,h=3,d=0,p=["fill","stroke","shadowColor"];class v{constructor(S,A,R,O,N,C,b){this.prop=S,this.propFunc=A,this.begin=O,this._pos=O,this.duration=C,this._change=0,this.prevPos=0,this.yoyo=b,this._time=0,this._position=0,this._startTime=0,this._finish=0,this.func=R,this._change=N-this.begin,this.pause()}fire(S){const A=this[S];A&&A()}setTime(S){S>this.duration?this.yoyo?(this._time=this.duration,this.reverse()):this.finish():S<0?this.yoyo?(this._time=0,this.play()):this.reset():(this._time=S,this.update())}getTime(){return this._time}setPosition(S){this.prevPos=this._pos,this.propFunc(S),this._pos=S}getPosition(S){return S===void 0&&(S=this._time),this.func(S,this.begin,this._change,this.duration)}play(){this.state=f,this._startTime=this.getTimer()-this._time,this.onEnterFrame(),this.fire("onPlay")}reverse(){this.state=h,this._time=this.duration-this._time,this._startTime=this.getTimer()-this._time,this.onEnterFrame(),this.fire("onReverse")}seek(S){this.pause(),this._time=S,this.update(),this.fire("onSeek")}reset(){this.pause(),this._time=0,this.update(),this.fire("onReset")}finish(){this.pause(),this._time=this.duration,this.update(),this.fire("onFinish")}update(){this.setPosition(this.getPosition(this._time)),this.fire("onUpdate")}onEnterFrame(){const S=this.getTimer()-this._startTime;this.state===f?this.setTime(S):this.state===h&&this.setTime(this.duration-S)}pause(){this.state=i,this.fire("onPause")}getTimer(){return new Date().getTime()}}class T{constructor(S){let A=this,R=S.node,O=R._id,N,C=S.easing||u.Easings.Linear,b=!!S.yoyo,w;typeof S.duration>"u"?N=.3:S.duration===0?N=.001:N=S.duration,this.node=R,this._id=d++;const F=R.getLayer()||(R instanceof l.Konva.Stage?R.getLayers():null);F||e.Util.error("Tween constructor have `node` that is not in a layer. Please add node into layer first."),this.anim=new t.Animation(function(){A.tween.onEnterFrame()},F),this.tween=new v(w,function(q){A._tweenFunc(q)},C,0,1,N*1e3,b),this._addListeners(),T.attrs[O]||(T.attrs[O]={}),T.attrs[O][this._id]||(T.attrs[O][this._id]={}),T.tweens[O]||(T.tweens[O]={});for(w in S)s[w]===void 0&&this._addAttr(w,S[w]);this.reset(),this.onFinish=S.onFinish,this.onReset=S.onReset,this.onUpdate=S.onUpdate}_addAttr(S,A){let R=this.node,O=R._id,N,C,b,w,F,q,D,P;if(b=T.tweens[O][S],b&&delete T.attrs[O][b][S],N=R.getAttr(S),e.Util._isArray(A))if(C=[],F=Math.max(A.length,N.length),S==="points"&&A.length!==N.length&&(A.length>N.length?(D=N,N=e.Util._prepareArrayForTween(N,A,R.closed())):(q=A,A=e.Util._prepareArrayForTween(A,N,R.closed()))),S.indexOf("fill")===0)for(w=0;w<F;w++)if(w%2===0)C.push(A[w]-N[w]);else{const I=e.Util.colorToRGBA(N[w]);P=e.Util.colorToRGBA(A[w]),N[w]=I,C.push({r:P.r-I.r,g:P.g-I.g,b:P.b-I.b,a:P.a-I.a})}else for(w=0;w<F;w++)C.push(A[w]-N[w]);else p.indexOf(S)!==-1?(N=e.Util.colorToRGBA(N),P=e.Util.colorToRGBA(A),C={r:P.r-N.r,g:P.g-N.g,b:P.b-N.b,a:P.a-N.a}):C=A-N;T.attrs[O][this._id][S]={start:N,diff:C,end:A,trueEnd:q,trueStart:D},T.tweens[O][S]=this._id}_tweenFunc(S){let A=this.node,R=T.attrs[A._id][this._id],O,N,C,b,w,F,q,D;for(O in R){if(N=R[O],C=N.start,b=N.diff,D=N.end,e.Util._isArray(C))if(w=[],q=Math.max(C.length,D.length),O.indexOf("fill")===0)for(F=0;F<q;F++)F%2===0?w.push((C[F]||0)+b[F]*S):w.push("rgba("+Math.round(C[F].r+b[F].r*S)+","+Math.round(C[F].g+b[F].g*S)+","+Math.round(C[F].b+b[F].b*S)+","+(C[F].a+b[F].a*S)+")");else for(F=0;F<q;F++)w.push((C[F]||0)+b[F]*S);else p.indexOf(O)!==-1?w="rgba("+Math.round(C.r+b.r*S)+","+Math.round(C.g+b.g*S)+","+Math.round(C.b+b.b*S)+","+(C.a+b.a*S)+")":w=C+b*S;A.setAttr(O,w)}}_addListeners(){this.tween.onPlay=()=>{this.anim.start()},this.tween.onReverse=()=>{this.anim.start()},this.tween.onPause=()=>{this.anim.stop()},this.tween.onFinish=()=>{const S=this.node,A=T.attrs[S._id][this._id];A.points&&A.points.trueEnd&&S.setAttr("points",A.points.trueEnd),this.onFinish&&this.onFinish.call(this)},this.tween.onReset=()=>{const S=this.node,A=T.attrs[S._id][this._id];A.points&&A.points.trueStart&&S.points(A.points.trueStart),this.onReset&&this.onReset()},this.tween.onUpdate=()=>{this.onUpdate&&this.onUpdate.call(this)}}play(){return this.tween.play(),this}reverse(){return this.tween.reverse(),this}reset(){return this.tween.reset(),this}seek(S){return this.tween.seek(S*1e3),this}pause(){return this.tween.pause(),this}finish(){return this.tween.finish(),this}destroy(){let S=this.node._id,A=this._id,R=T.tweens[S],O;this.pause();for(O in R)delete T.tweens[S][O];delete T.attrs[S][A]}}u.Tween=T,T.attrs={},T.tweens={},r.Node.prototype.to=function(y){const S=y.onFinish;y.node=this,y.onFinish=function(){this.destroy(),S&&S()},new T(y).play()},u.Easings={BackEaseIn(y,S,A,R){return A*(y/=R)*y*(2.70158*y-1.70158)+S},BackEaseOut(y,S,A,R){return A*((y=y/R-1)*y*(2.70158*y+1.70158)+1)+S},BackEaseInOut(y,S,A,R){let O=1.70158;return(y/=R/2)<1?A/2*(y*y*(((O*=1.525)+1)*y-O))+S:A/2*((y-=2)*y*(((O*=1.525)+1)*y+O)+2)+S},ElasticEaseIn(y,S,A,R,O,N){let C=0;return y===0?S:(y/=R)===1?S+A:(N||(N=R*.3),!O||O<Math.abs(A)?(O=A,C=N/4):C=N/(2*Math.PI)*Math.asin(A/O),-(O*Math.pow(2,10*(y-=1))*Math.sin((y*R-C)*(2*Math.PI)/N))+S)},ElasticEaseOut(y,S,A,R,O,N){let C=0;return y===0?S:(y/=R)===1?S+A:(N||(N=R*.3),!O||O<Math.abs(A)?(O=A,C=N/4):C=N/(2*Math.PI)*Math.asin(A/O),O*Math.pow(2,-10*y)*Math.sin((y*R-C)*(2*Math.PI)/N)+A+S)},ElasticEaseInOut(y,S,A,R,O,N){let C=0;return y===0?S:(y/=R/2)===2?S+A:(N||(N=R*.44999999999999996),!O||O<Math.abs(A)?(O=A,C=N/4):C=N/(2*Math.PI)*Math.asin(A/O),y<1?-.5*(O*Math.pow(2,10*(y-=1))*Math.sin((y*R-C)*(2*Math.PI)/N))+S:O*Math.pow(2,-10*(y-=1))*Math.sin((y*R-C)*(2*Math.PI)/N)*.5+A+S)},BounceEaseOut(y,S,A,R){return(y/=R)<.36363636363636365?A*(7.5625*y*y)+S:y<.7272727272727273?A*(7.5625*(y-=.5454545454545454)*y+.75)+S:y<.9090909090909091?A*(7.5625*(y-=.8181818181818182)*y+.9375)+S:A*(7.5625*(y-=.9545454545454546)*y+.984375)+S},BounceEaseIn(y,S,A,R){return A-u.Easings.BounceEaseOut(R-y,0,A,R)+S},BounceEaseInOut(y,S,A,R){return y<R/2?u.Easings.BounceEaseIn(y*2,0,A,R)*.5+S:u.Easings.BounceEaseOut(y*2-R,0,A,R)*.5+A*.5+S},EaseIn(y,S,A,R){return A*(y/=R)*y+S},EaseOut(y,S,A,R){return-A*(y/=R)*(y-2)+S},EaseInOut(y,S,A,R){return(y/=R/2)<1?A/2*y*y+S:-A/2*(--y*(y-2)-1)+S},StrongEaseIn(y,S,A,R){return A*(y/=R)*y*y*y*y+S},StrongEaseOut(y,S,A,R){return A*((y=y/R-1)*y*y*y*y+1)+S},StrongEaseInOut(y,S,A,R){return(y/=R/2)<1?A/2*y*y*y*y*y+S:A/2*((y-=2)*y*y*y*y+2)+S},Linear(y,S,A,R){return A*y/R+S}}})(zg),function(u){Object.defineProperty(u,"__esModule",{value:!0}),u.Konva=void 0;const e=Le,t=rt,r=it,l=zn,s=Bg,i=ml,f=nu,h=Vi,d=Qo,p=Ct,v=Bi,T=zg,y=Ks,S=ms;u.Konva=t.Util._assign(e.Konva,{Util:t.Util,Transform:t.Transform,Node:r.Node,Container:l.Container,Stage:s.Stage,stages:s.stages,Layer:i.Layer,FastLayer:f.FastLayer,Group:h.Group,DD:d.DD,Shape:p.Shape,shapes:p.shapes,Animation:v.Animation,Tween:T.Tween,Easings:T.Easings,Context:y.Context,Canvas:S.Canvas}),u.default=u.Konva}(Ng);var iu={};Object.defineProperty(iu,"__esModule",{value:!0}),iu.Arc=void 0;const ru=Fe,r2=Ct,Xg=Le,lu=Ne,l2=Le;class Xs extends r2.Shape{_sceneFunc(e){const t=Xg.Konva.getAngle(this.angle()),r=this.clockwise();e.beginPath(),e.arc(0,0,this.outerRadius(),0,t,r),e.arc(0,0,this.innerRadius(),t,0,!r),e.closePath(),e.fillStrokeShape(this)}getWidth(){return this.outerRadius()*2}getHeight(){return this.outerRadius()*2}setWidth(e){this.outerRadius(e/2)}setHeight(e){this.outerRadius(e/2)}getSelfRect(){const e=this.innerRadius(),t=this.outerRadius(),r=this.clockwise(),l=Xg.Konva.getAngle(r?360-this.angle():this.angle()),s=Math.cos(Math.min(l,Math.PI)),i=1,f=Math.sin(Math.min(Math.max(Math.PI,l),3*Math.PI/2)),h=Math.sin(Math.min(l,Math.PI/2)),d=s*(s>0?e:t),p=i*t,v=f*(f>0?e:t),T=h*(h>0?t:e);return{x:d,y:r?-1*T:v,width:p-d,height:T-v}}}iu.Arc=Xs,Xs.prototype._centroid=!0,Xs.prototype.className="Arc",Xs.prototype._attrsAffectingSize=["innerRadius","outerRadius"],(0,l2._registerNode)(Xs),ru.Factory.addGetterSetter(Xs,"innerRadius",0,(0,lu.getNumberValidator)()),ru.Factory.addGetterSetter(Xs,"outerRadius",0,(0,lu.getNumberValidator)()),ru.Factory.addGetterSetter(Xs,"angle",0,(0,lu.getNumberValidator)()),ru.Factory.addGetterSetter(Xs,"clockwise",!1,(0,lu.getBooleanValidator)());var au={},vl={};Object.defineProperty(vl,"__esModule",{value:!0}),vl.Line=void 0;const ou=Fe,a2=Le,o2=Ct,Jg=Ne;function lf(u,e,t,r,l,s,i){const f=Math.sqrt(Math.pow(t-u,2)+Math.pow(r-e,2)),h=Math.sqrt(Math.pow(l-t,2)+Math.pow(s-r,2)),d=i*f/(f+h),p=i*h/(f+h),v=t-d*(l-u),T=r-d*(s-e),y=t+p*(l-u),S=r+p*(s-e);return[v,T,y,S]}function Qg(u,e){const t=u.length,r=[];for(let l=2;l<t-2;l+=2){const s=lf(u[l-2],u[l-1],u[l],u[l+1],u[l+2],u[l+3],e);isNaN(s[0])||(r.push(s[0]),r.push(s[1]),r.push(u[l]),r.push(u[l+1]),r.push(s[2]),r.push(s[3]))}return r}class vn extends o2.Shape{constructor(e){super(e),this.on("pointsChange.konva tensionChange.konva closedChange.konva bezierChange.konva",function(){this._clearCache("tensionPoints")})}_sceneFunc(e){let t=this.points(),r=t.length,l=this.tension(),s=this.closed(),i=this.bezier(),f,h,d;if(r){if(e.beginPath(),e.moveTo(t[0],t[1]),l!==0&&r>4){for(f=this.getTensionPoints(),h=f.length,d=s?0:4,s||e.quadraticCurveTo(f[0],f[1],f[2],f[3]);d<h-2;)e.bezierCurveTo(f[d++],f[d++],f[d++],f[d++],f[d++],f[d++]);s||e.quadraticCurveTo(f[h-2],f[h-1],t[r-2],t[r-1])}else if(i)for(d=2;d<r;)e.bezierCurveTo(t[d++],t[d++],t[d++],t[d++],t[d++],t[d++]);else for(d=2;d<r;d+=2)e.lineTo(t[d],t[d+1]);s?(e.closePath(),e.fillStrokeShape(this)):e.strokeShape(this)}}getTensionPoints(){return this._getCache("tensionPoints",this._getTensionPoints)}_getTensionPoints(){return this.closed()?this._getTensionPointsClosed():Qg(this.points(),this.tension())}_getTensionPointsClosed(){const e=this.points(),t=e.length,r=this.tension(),l=lf(e[t-2],e[t-1],e[0],e[1],e[2],e[3],r),s=lf(e[t-4],e[t-3],e[t-2],e[t-1],e[0],e[1],r),i=Qg(e,r);return[l[2],l[3]].concat(i).concat([s[0],s[1],e[t-2],e[t-1],s[2],s[3],l[0],l[1],e[0],e[1]])}getWidth(){return this.getSelfRect().width}getHeight(){return this.getSelfRect().height}getSelfRect(){let e=this.points();if(e.length<4)return{x:e[0]||0,y:e[1]||0,width:0,height:0};this.tension()!==0?e=[e[0],e[1],...this._getTensionPoints(),e[e.length-2],e[e.length-1]]:e=this.points();let t=e[0],r=e[0],l=e[1],s=e[1],i,f;for(let h=0;h<e.length/2;h++)i=e[h*2],f=e[h*2+1],t=Math.min(t,i),r=Math.max(r,i),l=Math.min(l,f),s=Math.max(s,f);return{x:t,y:l,width:r-t,height:s-l}}}vl.Line=vn,vn.prototype.className="Line",vn.prototype._attrsAffectingSize=["points","bezier","tension"],(0,a2._registerNode)(vn),ou.Factory.addGetterSetter(vn,"closed",!1),ou.Factory.addGetterSetter(vn,"bezier",!1),ou.Factory.addGetterSetter(vn,"tension",0,(0,Jg.getNumberValidator)()),ou.Factory.addGetterSetter(vn,"points",[],(0,Jg.getNumberArrayValidator)());var ji={},Zg={};(function(u){Object.defineProperty(u,"__esModule",{value:!0}),u.t2length=u.getQuadraticArcLength=u.getCubicArcLength=u.binomialCoefficients=u.cValues=u.tValues=void 0,u.tValues=[[],[],[-.5773502691896257,.5773502691896257],[0,-.7745966692414834,.7745966692414834],[-.33998104358485626,.33998104358485626,-.8611363115940526,.8611363115940526],[0,-.5384693101056831,.5384693101056831,-.906179845938664,.906179845938664],[.6612093864662645,-.6612093864662645,-.2386191860831969,.2386191860831969,-.932469514203152,.932469514203152],[0,.4058451513773972,-.4058451513773972,-.7415311855993945,.7415311855993945,-.9491079123427585,.9491079123427585],[-.1834346424956498,.1834346424956498,-.525532409916329,.525532409916329,-.7966664774136267,.7966664774136267,-.9602898564975363,.9602898564975363],[0,-.8360311073266358,.8360311073266358,-.9681602395076261,.9681602395076261,-.3242534234038089,.3242534234038089,-.6133714327005904,.6133714327005904],[-.14887433898163122,.14887433898163122,-.4333953941292472,.4333953941292472,-.6794095682990244,.6794095682990244,-.8650633666889845,.8650633666889845,-.9739065285171717,.9739065285171717],[0,-.26954315595234496,.26954315595234496,-.5190961292068118,.5190961292068118,-.7301520055740494,.7301520055740494,-.8870625997680953,.8870625997680953,-.978228658146057,.978228658146057],[-.1252334085114689,.1252334085114689,-.3678314989981802,.3678314989981802,-.5873179542866175,.5873179542866175,-.7699026741943047,.7699026741943047,-.9041172563704749,.9041172563704749,-.9815606342467192,.9815606342467192],[0,-.2304583159551348,.2304583159551348,-.44849275103644687,.44849275103644687,-.6423493394403402,.6423493394403402,-.8015780907333099,.8015780907333099,-.9175983992229779,.9175983992229779,-.9841830547185881,.9841830547185881],[-.10805494870734367,.10805494870734367,-.31911236892788974,.31911236892788974,-.5152486363581541,.5152486363581541,-.6872929048116855,.6872929048116855,-.827201315069765,.827201315069765,-.9284348836635735,.9284348836635735,-.9862838086968123,.9862838086968123],[0,-.20119409399743451,.20119409399743451,-.3941513470775634,.3941513470775634,-.5709721726085388,.5709721726085388,-.7244177313601701,.7244177313601701,-.8482065834104272,.8482065834104272,-.937273392400706,.937273392400706,-.9879925180204854,.9879925180204854],[-.09501250983763744,.09501250983763744,-.2816035507792589,.2816035507792589,-.45801677765722737,.45801677765722737,-.6178762444026438,.6178762444026438,-.755404408355003,.755404408355003,-.8656312023878318,.8656312023878318,-.9445750230732326,.9445750230732326,-.9894009349916499,.9894009349916499],[0,-.17848418149584785,.17848418149584785,-.3512317634538763,.3512317634538763,-.5126905370864769,.5126905370864769,-.6576711592166907,.6576711592166907,-.7815140038968014,.7815140038968014,-.8802391537269859,.8802391537269859,-.9506755217687678,.9506755217687678,-.9905754753144174,.9905754753144174],[-.0847750130417353,.0847750130417353,-.2518862256915055,.2518862256915055,-.41175116146284263,.41175116146284263,-.5597708310739475,.5597708310739475,-.6916870430603532,.6916870430603532,-.8037049589725231,.8037049589725231,-.8926024664975557,.8926024664975557,-.9558239495713977,.9558239495713977,-.9915651684209309,.9915651684209309],[0,-.16035864564022537,.16035864564022537,-.31656409996362983,.31656409996362983,-.46457074137596094,.46457074137596094,-.600545304661681,.600545304661681,-.7209661773352294,.7209661773352294,-.8227146565371428,.8227146565371428,-.9031559036148179,.9031559036148179,-.96020815213483,.96020815213483,-.9924068438435844,.9924068438435844],[-.07652652113349734,.07652652113349734,-.22778585114164507,.22778585114164507,-.37370608871541955,.37370608871541955,-.5108670019508271,.5108670019508271,-.636053680726515,.636053680726515,-.7463319064601508,.7463319064601508,-.8391169718222188,.8391169718222188,-.912234428251326,.912234428251326,-.9639719272779138,.9639719272779138,-.9931285991850949,.9931285991850949],[0,-.1455618541608951,.1455618541608951,-.2880213168024011,.2880213168024011,-.4243421202074388,.4243421202074388,-.5516188358872198,.5516188358872198,-.6671388041974123,.6671388041974123,-.7684399634756779,.7684399634756779,-.8533633645833173,.8533633645833173,-.9200993341504008,.9200993341504008,-.9672268385663063,.9672268385663063,-.9937521706203895,.9937521706203895],[-.06973927331972223,.06973927331972223,-.20786042668822127,.20786042668822127,-.34193582089208424,.34193582089208424,-.469355837986757,.469355837986757,-.5876404035069116,.5876404035069116,-.6944872631866827,.6944872631866827,-.7878168059792081,.7878168059792081,-.8658125777203002,.8658125777203002,-.926956772187174,.926956772187174,-.9700604978354287,.9700604978354287,-.9942945854823992,.9942945854823992],[0,-.1332568242984661,.1332568242984661,-.26413568097034495,.26413568097034495,-.3903010380302908,.3903010380302908,-.5095014778460075,.5095014778460075,-.6196098757636461,.6196098757636461,-.7186613631319502,.7186613631319502,-.8048884016188399,.8048884016188399,-.8767523582704416,.8767523582704416,-.9329710868260161,.9329710868260161,-.9725424712181152,.9725424712181152,-.9947693349975522,.9947693349975522],[-.06405689286260563,.06405689286260563,-.1911188674736163,.1911188674736163,-.3150426796961634,.3150426796961634,-.4337935076260451,.4337935076260451,-.5454214713888396,.5454214713888396,-.6480936519369755,.6480936519369755,-.7401241915785544,.7401241915785544,-.820001985973903,.820001985973903,-.8864155270044011,.8864155270044011,-.9382745520027328,.9382745520027328,-.9747285559713095,.9747285559713095,-.9951872199970213,.9951872199970213]],u.cValues=[[],[],[1,1],[.8888888888888888,.5555555555555556,.5555555555555556],[.6521451548625461,.6521451548625461,.34785484513745385,.34785484513745385],[.5688888888888889,.47862867049936647,.47862867049936647,.23692688505618908,.23692688505618908],[.3607615730481386,.3607615730481386,.46791393457269104,.46791393457269104,.17132449237917036,.17132449237917036],[.4179591836734694,.3818300505051189,.3818300505051189,.27970539148927664,.27970539148927664,.1294849661688697,.1294849661688697],[.362683783378362,.362683783378362,.31370664587788727,.31370664587788727,.22238103445337448,.22238103445337448,.10122853629037626,.10122853629037626],[.3302393550012598,.1806481606948574,.1806481606948574,.08127438836157441,.08127438836157441,.31234707704000286,.31234707704000286,.26061069640293544,.26061069640293544],[.29552422471475287,.29552422471475287,.26926671930999635,.26926671930999635,.21908636251598204,.21908636251598204,.1494513491505806,.1494513491505806,.06667134430868814,.06667134430868814],[.2729250867779006,.26280454451024665,.26280454451024665,.23319376459199048,.23319376459199048,.18629021092773426,.18629021092773426,.1255803694649046,.1255803694649046,.05566856711617366,.05566856711617366],[.24914704581340277,.24914704581340277,.2334925365383548,.2334925365383548,.20316742672306592,.20316742672306592,.16007832854334622,.16007832854334622,.10693932599531843,.10693932599531843,.04717533638651183,.04717533638651183],[.2325515532308739,.22628318026289723,.22628318026289723,.2078160475368885,.2078160475368885,.17814598076194574,.17814598076194574,.13887351021978725,.13887351021978725,.09212149983772845,.09212149983772845,.04048400476531588,.04048400476531588],[.2152638534631578,.2152638534631578,.2051984637212956,.2051984637212956,.18553839747793782,.18553839747793782,.15720316715819355,.15720316715819355,.12151857068790319,.12151857068790319,.08015808715976021,.08015808715976021,.03511946033175186,.03511946033175186],[.2025782419255613,.19843148532711158,.19843148532711158,.1861610000155622,.1861610000155622,.16626920581699392,.16626920581699392,.13957067792615432,.13957067792615432,.10715922046717194,.10715922046717194,.07036604748810812,.07036604748810812,.03075324199611727,.03075324199611727],[.1894506104550685,.1894506104550685,.18260341504492358,.18260341504492358,.16915651939500254,.16915651939500254,.14959598881657674,.14959598881657674,.12462897125553388,.12462897125553388,.09515851168249279,.09515851168249279,.062253523938647894,.062253523938647894,.027152459411754096,.027152459411754096],[.17944647035620653,.17656270536699264,.17656270536699264,.16800410215645004,.16800410215645004,.15404576107681028,.15404576107681028,.13513636846852548,.13513636846852548,.11188384719340397,.11188384719340397,.08503614831717918,.08503614831717918,.0554595293739872,.0554595293739872,.02414830286854793,.02414830286854793],[.1691423829631436,.1691423829631436,.16427648374583273,.16427648374583273,.15468467512626524,.15468467512626524,.14064291467065065,.14064291467065065,.12255520671147846,.12255520671147846,.10094204410628717,.10094204410628717,.07642573025488905,.07642573025488905,.0497145488949698,.0497145488949698,.02161601352648331,.02161601352648331],[.1610544498487837,.15896884339395434,.15896884339395434,.15276604206585967,.15276604206585967,.1426067021736066,.1426067021736066,.12875396253933621,.12875396253933621,.11156664554733399,.11156664554733399,.09149002162245,.09149002162245,.06904454273764123,.06904454273764123,.0448142267656996,.0448142267656996,.019461788229726478,.019461788229726478],[.15275338713072584,.15275338713072584,.14917298647260374,.14917298647260374,.14209610931838204,.14209610931838204,.13168863844917664,.13168863844917664,.11819453196151841,.11819453196151841,.10193011981724044,.10193011981724044,.08327674157670475,.08327674157670475,.06267204833410907,.06267204833410907,.04060142980038694,.04060142980038694,.017614007139152118,.017614007139152118],[.14608113364969041,.14452440398997005,.14452440398997005,.13988739479107315,.13988739479107315,.13226893863333747,.13226893863333747,.12183141605372853,.12183141605372853,.10879729916714838,.10879729916714838,.09344442345603386,.09344442345603386,.0761001136283793,.0761001136283793,.057134425426857205,.057134425426857205,.036953789770852494,.036953789770852494,.016017228257774335,.016017228257774335],[.13925187285563198,.13925187285563198,.13654149834601517,.13654149834601517,.13117350478706238,.13117350478706238,.12325237681051242,.12325237681051242,.11293229608053922,.11293229608053922,.10041414444288096,.10041414444288096,.08594160621706773,.08594160621706773,.06979646842452049,.06979646842452049,.052293335152683286,.052293335152683286,.03377490158481415,.03377490158481415,.0146279952982722,.0146279952982722],[.13365457218610619,.1324620394046966,.1324620394046966,.12890572218808216,.12890572218808216,.12304908430672953,.12304908430672953,.11499664022241136,.11499664022241136,.10489209146454141,.10489209146454141,.09291576606003515,.09291576606003515,.07928141177671895,.07928141177671895,.06423242140852585,.06423242140852585,.04803767173108467,.04803767173108467,.030988005856979445,.030988005856979445,.013411859487141771,.013411859487141771],[.12793819534675216,.12793819534675216,.1258374563468283,.1258374563468283,.12167047292780339,.12167047292780339,.1155056680537256,.1155056680537256,.10744427011596563,.10744427011596563,.09761865210411388,.09761865210411388,.08619016153195327,.08619016153195327,.0733464814110803,.0733464814110803,.05929858491543678,.05929858491543678,.04427743881741981,.04427743881741981,.028531388628933663,.028531388628933663,.0123412297999872,.0123412297999872]],u.binomialCoefficients=[[1],[1,1],[1,2,1],[1,3,3,1]];const e=(i,f,h)=>{let d,p;const T=h/2;d=0;for(let y=0;y<20;y++)p=T*u.tValues[20][y]+T,d+=u.cValues[20][y]*r(i,f,p);return T*d};u.getCubicArcLength=e;const t=(i,f,h)=>{h===void 0&&(h=1);const d=i[0]-2*i[1]+i[2],p=f[0]-2*f[1]+f[2],v=2*i[1]-2*i[0],T=2*f[1]-2*f[0],y=4*(d*d+p*p),S=4*(d*v+p*T),A=v*v+T*T;if(y===0)return h*Math.sqrt(Math.pow(i[2]-i[0],2)+Math.pow(f[2]-f[0],2));const R=S/(2*y),O=A/y,N=h+R,C=O-R*R,b=N*N+C>0?Math.sqrt(N*N+C):0,w=R*R+C>0?Math.sqrt(R*R+C):0,F=R+Math.sqrt(R*R+C)!==0?C*Math.log(Math.abs((N+b)/(R+w))):0;return Math.sqrt(y)/2*(N*b-R*w+F)};u.getQuadraticArcLength=t;function r(i,f,h){const d=l(1,h,i),p=l(1,h,f),v=d*d+p*p;return Math.sqrt(v)}const l=(i,f,h)=>{const d=h.length-1;let p,v;if(d===0)return 0;if(i===0){v=0;for(let T=0;T<=d;T++)v+=u.binomialCoefficients[d][T]*Math.pow(1-f,d-T)*Math.pow(f,T)*h[T];return v}else{p=new Array(d);for(let T=0;T<d;T++)p[T]=d*(h[T+1]-h[T]);return l(i-1,f,p)}},s=(i,f,h)=>{let d=1,p=i/f,v=(i-h(p))/f,T=0;for(;d>.001;){const y=h(p+v),S=Math.abs(i-y)/f;if(S<d)d=S,p+=v;else{const A=h(p-v),R=Math.abs(i-A)/f;R<d?(d=R,p-=v):v/=2}if(T++,T>500)break}return p};u.t2length=s})(Zg),Object.defineProperty(ji,"__esModule",{value:!0}),ji.Path=void 0;const u2=Fe,c2=Ct,h2=Le,qi=Zg;class At extends c2.Shape{constructor(e){super(e),this.dataArray=[],this.pathLength=0,this._readDataAttribute(),this.on("dataChange.konva",function(){this._readDataAttribute()})}_readDataAttribute(){this.dataArray=At.parsePathData(this.data()),this.pathLength=At.getPathLength(this.dataArray)}_sceneFunc(e){const t=this.dataArray;e.beginPath();let r=!1;for(let A=0;A<t.length;A++){const R=t[A].command,O=t[A].points;switch(R){case"L":e.lineTo(O[0],O[1]);break;case"M":e.moveTo(O[0],O[1]);break;case"C":e.bezierCurveTo(O[0],O[1],O[2],O[3],O[4],O[5]);break;case"Q":e.quadraticCurveTo(O[0],O[1],O[2],O[3]);break;case"A":var l=O[0],s=O[1],i=O[2],f=O[3],h=O[4],d=O[5],p=O[6],v=O[7],T=i>f?i:f,y=i>f?1:i/f,S=i>f?f/i:1;e.translate(l,s),e.rotate(p),e.scale(y,S),e.arc(0,0,T,h,h+d,1-v),e.scale(1/y,1/S),e.rotate(-p),e.translate(-l,-s);break;case"z":r=!0,e.closePath();break}}!r&&!this.hasFill()?e.strokeShape(this):e.fillStrokeShape(this)}getSelfRect(){let e=[];this.dataArray.forEach(function(h){if(h.command==="A"){const d=h.points[4],p=h.points[5],v=h.points[4]+p;let T=Math.PI/180;if(Math.abs(d-v)<T&&(T=Math.abs(d-v)),p<0)for(let y=d-T;y>v;y-=T){const S=At.getPointOnEllipticalArc(h.points[0],h.points[1],h.points[2],h.points[3],y,0);e.push(S.x,S.y)}else for(let y=d+T;y<v;y+=T){const S=At.getPointOnEllipticalArc(h.points[0],h.points[1],h.points[2],h.points[3],y,0);e.push(S.x,S.y)}}else if(h.command==="C")for(let d=0;d<=1;d+=.01){const p=At.getPointOnCubicBezier(d,h.start.x,h.start.y,h.points[0],h.points[1],h.points[2],h.points[3],h.points[4],h.points[5]);e.push(p.x,p.y)}else e=e.concat(h.points)});let t=e[0],r=e[0],l=e[1],s=e[1],i,f;for(let h=0;h<e.length/2;h++)i=e[h*2],f=e[h*2+1],isNaN(i)||(t=Math.min(t,i),r=Math.max(r,i)),isNaN(f)||(l=Math.min(l,f),s=Math.max(s,f));return{x:t,y:l,width:r-t,height:s-l}}getLength(){return this.pathLength}getPointAtLength(e){return At.getPointAtLengthOfDataArray(e,this.dataArray)}static getLineLength(e,t,r,l){return Math.sqrt((r-e)*(r-e)+(l-t)*(l-t))}static getPathLength(e){let t=0;for(let r=0;r<e.length;++r)t+=e[r].pathLength;return t}static getPointAtLengthOfDataArray(e,t){let r,l=0,s=t.length;if(!s)return null;for(;l<s&&e>t[l].pathLength;)e-=t[l].pathLength,++l;if(l===s)return r=t[l-1].points.slice(-2),{x:r[0],y:r[1]};if(e<.01)return r=t[l].points.slice(0,2),{x:r[0],y:r[1]};const i=t[l],f=i.points;switch(i.command){case"L":return At.getPointOnLine(e,i.start.x,i.start.y,f[0],f[1]);case"C":return At.getPointOnCubicBezier((0,qi.t2length)(e,At.getPathLength(t),A=>(0,qi.getCubicArcLength)([i.start.x,f[0],f[2],f[4]],[i.start.y,f[1],f[3],f[5]],A)),i.start.x,i.start.y,f[0],f[1],f[2],f[3],f[4],f[5]);case"Q":return At.getPointOnQuadraticBezier((0,qi.t2length)(e,At.getPathLength(t),A=>(0,qi.getQuadraticArcLength)([i.start.x,f[0],f[2]],[i.start.y,f[1],f[3]],A)),i.start.x,i.start.y,f[0],f[1],f[2],f[3]);case"A":var h=f[0],d=f[1],p=f[2],v=f[3],T=f[4],y=f[5],S=f[6];return T+=y*e/i.pathLength,At.getPointOnEllipticalArc(h,d,p,v,T,S)}return null}static getPointOnLine(e,t,r,l,s,i,f){i=i??t,f=f??r;const h=this.getLineLength(t,r,l,s);if(h<1e-10)return{x:t,y:r};if(l===t)return{x:i,y:f+(s>r?e:-e)};const d=(s-r)/(l-t),p=Math.sqrt(e*e/(1+d*d))*(l<t?-1:1),v=d*p;if(Math.abs(f-r-d*(i-t))<1e-10)return{x:i+p,y:f+v};const T=((i-t)*(l-t)+(f-r)*(s-r))/(h*h),y=t+T*(l-t),S=r+T*(s-r),A=this.getLineLength(i,f,y,S),R=Math.sqrt(e*e-A*A),O=Math.sqrt(R*R/(1+d*d))*(l<t?-1:1),N=d*O;return{x:y+O,y:S+N}}static getPointOnCubicBezier(e,t,r,l,s,i,f,h,d){function p(R){return R*R*R}function v(R){return 3*R*R*(1-R)}function T(R){return 3*R*(1-R)*(1-R)}function y(R){return(1-R)*(1-R)*(1-R)}const S=h*p(e)+i*v(e)+l*T(e)+t*y(e),A=d*p(e)+f*v(e)+s*T(e)+r*y(e);return{x:S,y:A}}static getPointOnQuadraticBezier(e,t,r,l,s,i,f){function h(y){return y*y}function d(y){return 2*y*(1-y)}function p(y){return(1-y)*(1-y)}const v=i*h(e)+l*d(e)+t*p(e),T=f*h(e)+s*d(e)+r*p(e);return{x:v,y:T}}static getPointOnEllipticalArc(e,t,r,l,s,i){const f=Math.cos(i),h=Math.sin(i),d={x:r*Math.cos(s),y:l*Math.sin(s)};return{x:e+(d.x*f-d.y*h),y:t+(d.x*h+d.y*f)}}static parsePathData(e){if(!e)return[];let t=e;const r=["m","M","l","L","v","V","h","H","z","Z","c","C","q","Q","t","T","s","S","a","A"];t=t.replace(new RegExp(" ","g"),",");for(var l=0;l<r.length;l++)t=t.replace(new RegExp(r[l],"g"),"|"+r[l]);const s=t.split("|"),i=[],f=[];let h=0,d=0;const p=/([-+]?((\d+\.\d+)|((\d+)|(\.\d+)))(?:e[-+]?\d+)?)/gi;let v;for(l=1;l<s.length;l++){let D=s[l],P=D.charAt(0);for(D=D.slice(1),f.length=0;v=p.exec(D);)f.push(v[0]);const I=[];for(let x=0,U=f.length;x<U;x++){if(f[x]==="00"){I.push(0,0);continue}const B=parseFloat(f[x]);isNaN(B)?I.push(0):I.push(B)}for(;I.length>0&&!isNaN(I[0]);){let x="",U=[];const B=h,z=d;var T,y,S,A,R,O,N,C,b,w;switch(P){case"l":h+=I.shift(),d+=I.shift(),x="L",U.push(h,d);break;case"L":h=I.shift(),d=I.shift(),U.push(h,d);break;case"m":var F=I.shift(),q=I.shift();if(h+=F,d+=q,x="M",i.length>2&&i[i.length-1].command==="z"){for(let L=i.length-2;L>=0;L--)if(i[L].command==="M"){h=i[L].points[0]+F,d=i[L].points[1]+q;break}}U.push(h,d),P="l";break;case"M":h=I.shift(),d=I.shift(),x="M",U.push(h,d),P="L";break;case"h":h+=I.shift(),x="L",U.push(h,d);break;case"H":h=I.shift(),x="L",U.push(h,d);break;case"v":d+=I.shift(),x="L",U.push(h,d);break;case"V":d=I.shift(),x="L",U.push(h,d);break;case"C":U.push(I.shift(),I.shift(),I.shift(),I.shift()),h=I.shift(),d=I.shift(),U.push(h,d);break;case"c":U.push(h+I.shift(),d+I.shift(),h+I.shift(),d+I.shift()),h+=I.shift(),d+=I.shift(),x="C",U.push(h,d);break;case"S":y=h,S=d,T=i[i.length-1],T.command==="C"&&(y=h+(h-T.points[2]),S=d+(d-T.points[3])),U.push(y,S,I.shift(),I.shift()),h=I.shift(),d=I.shift(),x="C",U.push(h,d);break;case"s":y=h,S=d,T=i[i.length-1],T.command==="C"&&(y=h+(h-T.points[2]),S=d+(d-T.points[3])),U.push(y,S,h+I.shift(),d+I.shift()),h+=I.shift(),d+=I.shift(),x="C",U.push(h,d);break;case"Q":U.push(I.shift(),I.shift()),h=I.shift(),d=I.shift(),U.push(h,d);break;case"q":U.push(h+I.shift(),d+I.shift()),h+=I.shift(),d+=I.shift(),x="Q",U.push(h,d);break;case"T":y=h,S=d,T=i[i.length-1],T.command==="Q"&&(y=h+(h-T.points[0]),S=d+(d-T.points[1])),h=I.shift(),d=I.shift(),x="Q",U.push(y,S,h,d);break;case"t":y=h,S=d,T=i[i.length-1],T.command==="Q"&&(y=h+(h-T.points[0]),S=d+(d-T.points[1])),h+=I.shift(),d+=I.shift(),x="Q",U.push(y,S,h,d);break;case"A":A=I.shift(),R=I.shift(),O=I.shift(),N=I.shift(),C=I.shift(),b=h,w=d,h=I.shift(),d=I.shift(),x="A",U=this.convertEndpointToCenterParameterization(b,w,h,d,N,C,A,R,O);break;case"a":A=I.shift(),R=I.shift(),O=I.shift(),N=I.shift(),C=I.shift(),b=h,w=d,h+=I.shift(),d+=I.shift(),x="A",U=this.convertEndpointToCenterParameterization(b,w,h,d,N,C,A,R,O);break}i.push({command:x||P,points:U,start:{x:B,y:z},pathLength:this.calcLength(B,z,x||P,U)})}(P==="z"||P==="Z")&&i.push({command:"z",points:[],start:void 0,pathLength:0})}return i}static calcLength(e,t,r,l){let s,i,f,h;const d=At;switch(r){case"L":return d.getLineLength(e,t,l[0],l[1]);case"C":return(0,qi.getCubicArcLength)([e,l[0],l[2],l[4]],[t,l[1],l[3],l[5]],1);case"Q":return(0,qi.getQuadraticArcLength)([e,l[0],l[2]],[t,l[1],l[3]],1);case"A":s=0;var p=l[4],v=l[5],T=l[4]+v,y=Math.PI/180;if(Math.abs(p-T)<y&&(y=Math.abs(p-T)),i=d.getPointOnEllipticalArc(l[0],l[1],l[2],l[3],p,0),v<0)for(h=p-y;h>T;h-=y)f=d.getPointOnEllipticalArc(l[0],l[1],l[2],l[3],h,0),s+=d.getLineLength(i.x,i.y,f.x,f.y),i=f;else for(h=p+y;h<T;h+=y)f=d.getPointOnEllipticalArc(l[0],l[1],l[2],l[3],h,0),s+=d.getLineLength(i.x,i.y,f.x,f.y),i=f;return f=d.getPointOnEllipticalArc(l[0],l[1],l[2],l[3],T,0),s+=d.getLineLength(i.x,i.y,f.x,f.y),s}return 0}static convertEndpointToCenterParameterization(e,t,r,l,s,i,f,h,d){const p=d*(Math.PI/180),v=Math.cos(p)*(e-r)/2+Math.sin(p)*(t-l)/2,T=-1*Math.sin(p)*(e-r)/2+Math.cos(p)*(t-l)/2,y=v*v/(f*f)+T*T/(h*h);y>1&&(f*=Math.sqrt(y),h*=Math.sqrt(y));let S=Math.sqrt((f*f*(h*h)-f*f*(T*T)-h*h*(v*v))/(f*f*(T*T)+h*h*(v*v)));s===i&&(S*=-1),isNaN(S)&&(S=0);const A=S*f*T/h,R=S*-h*v/f,O=(e+r)/2+Math.cos(p)*A-Math.sin(p)*R,N=(t+l)/2+Math.sin(p)*A+Math.cos(p)*R,C=function(I){return Math.sqrt(I[0]*I[0]+I[1]*I[1])},b=function(I,x){return(I[0]*x[0]+I[1]*x[1])/(C(I)*C(x))},w=function(I,x){return(I[0]*x[1]<I[1]*x[0]?-1:1)*Math.acos(b(I,x))},F=w([1,0],[(v-A)/f,(T-R)/h]),q=[(v-A)/f,(T-R)/h],D=[(-1*v-A)/f,(-1*T-R)/h];let P=w(q,D);return b(q,D)<=-1&&(P=Math.PI),b(q,D)>=1&&(P=0),i===0&&P>0&&(P=P-2*Math.PI),i===1&&P<0&&(P=P+2*Math.PI),[O,N,f,h,F,P,p,i]}}ji.Path=At,At.prototype.className="Path",At.prototype._attrsAffectingSize=["data"],(0,h2._registerNode)(At),u2.Factory.addGetterSetter(At,"data"),Object.defineProperty(au,"__esModule",{value:!0}),au.Arrow=void 0;const uu=Fe,f2=vl,ep=Ne,d2=Le,tp=ji;class Jn extends f2.Line{_sceneFunc(e){super._sceneFunc(e);const t=Math.PI*2,r=this.points();let l=r;const s=this.tension()!==0&&r.length>4;s&&(l=this.getTensionPoints());const i=this.pointerLength(),f=r.length;let h,d;if(s){const T=[l[l.length-4],l[l.length-3],l[l.length-2],l[l.length-1],r[f-2],r[f-1]],y=tp.Path.calcLength(l[l.length-4],l[l.length-3],"C",T),S=tp.Path.getPointOnQuadraticBezier(Math.min(1,1-i/y),T[0],T[1],T[2],T[3],T[4],T[5]);h=r[f-2]-S.x,d=r[f-1]-S.y}else h=r[f-2]-r[f-4],d=r[f-1]-r[f-3];const p=(Math.atan2(d,h)+t)%t,v=this.pointerWidth();this.pointerAtEnding()&&(e.save(),e.beginPath(),e.translate(r[f-2],r[f-1]),e.rotate(p),e.moveTo(0,0),e.lineTo(-i,v/2),e.lineTo(-i,-v/2),e.closePath(),e.restore(),this.__fillStroke(e)),this.pointerAtBeginning()&&(e.save(),e.beginPath(),e.translate(r[0],r[1]),s?(h=(l[0]+l[2])/2-r[0],d=(l[1]+l[3])/2-r[1]):(h=r[2]-r[0],d=r[3]-r[1]),e.rotate((Math.atan2(-d,-h)+t)%t),e.moveTo(0,0),e.lineTo(-i,v/2),e.lineTo(-i,-v/2),e.closePath(),e.restore(),this.__fillStroke(e))}__fillStroke(e){const t=this.dashEnabled();t&&(this.attrs.dashEnabled=!1,e.setLineDash([])),e.fillStrokeShape(this),t&&(this.attrs.dashEnabled=!0)}getSelfRect(){const e=super.getSelfRect(),t=this.pointerWidth()/2;return{x:e.x-t,y:e.y-t,width:e.width+t*2,height:e.height+t*2}}}au.Arrow=Jn,Jn.prototype.className="Arrow",(0,d2._registerNode)(Jn),uu.Factory.addGetterSetter(Jn,"pointerLength",10,(0,ep.getNumberValidator)()),uu.Factory.addGetterSetter(Jn,"pointerWidth",10,(0,ep.getNumberValidator)()),uu.Factory.addGetterSetter(Jn,"pointerAtBeginning",!1),uu.Factory.addGetterSetter(Jn,"pointerAtEnding",!0);var cu={};Object.defineProperty(cu,"__esModule",{value:!0}),cu.Circle=void 0;const _2=Fe,g2=Ct,p2=Ne,m2=Le;class Wi extends g2.Shape{_sceneFunc(e){e.beginPath(),e.arc(0,0,this.attrs.radius||0,0,Math.PI*2,!1),e.closePath(),e.fillStrokeShape(this)}getWidth(){return this.radius()*2}getHeight(){return this.radius()*2}setWidth(e){this.radius()!==e/2&&this.radius(e/2)}setHeight(e){this.radius()!==e/2&&this.radius(e/2)}}cu.Circle=Wi,Wi.prototype._centroid=!0,Wi.prototype.className="Circle",Wi.prototype._attrsAffectingSize=["radius"],(0,m2._registerNode)(Wi),_2.Factory.addGetterSetter(Wi,"radius",0,(0,p2.getNumberValidator)());var hu={};Object.defineProperty(hu,"__esModule",{value:!0}),hu.Ellipse=void 0;const af=Fe,v2=Ct,sp=Ne,T2=Le;class Tn extends v2.Shape{_sceneFunc(e){const t=this.radiusX(),r=this.radiusY();e.beginPath(),e.save(),t!==r&&e.scale(1,r/t),e.arc(0,0,t,0,Math.PI*2,!1),e.restore(),e.closePath(),e.fillStrokeShape(this)}getWidth(){return this.radiusX()*2}getHeight(){return this.radiusY()*2}setWidth(e){this.radiusX(e/2)}setHeight(e){this.radiusY(e/2)}}hu.Ellipse=Tn,Tn.prototype.className="Ellipse",Tn.prototype._centroid=!0,Tn.prototype._attrsAffectingSize=["radiusX","radiusY"],(0,T2._registerNode)(Tn),af.Factory.addComponentsGetterSetter(Tn,"radius",["x","y"]),af.Factory.addGetterSetter(Tn,"radiusX",0,(0,sp.getNumberValidator)()),af.Factory.addGetterSetter(Tn,"radiusY",0,(0,sp.getNumberValidator)());var fu={};Object.defineProperty(fu,"__esModule",{value:!0}),fu.Image=void 0;const of=rt,Qn=Fe,y2=Ct,S2=Le,Tl=Ne;let Ds=class c0 extends y2.Shape{constructor(e){super(e),this.on("imageChange.konva",()=>{this._setImageLoad()}),this._setImageLoad()}_setImageLoad(){const e=this.image();e&&e.complete||e&&e.readyState===4||e&&e.addEventListener&&e.addEventListener("load",()=>{this._requestDraw()})}_useBufferCanvas(){const e=!!this.cornerRadius(),t=this.hasShadow();return e&&t?!0:super._useBufferCanvas(!0)}_sceneFunc(e){const t=this.getWidth(),r=this.getHeight(),l=this.cornerRadius(),s=this.attrs.image;let i;if(s){const f=this.attrs.cropWidth,h=this.attrs.cropHeight;f&&h?i=[s,this.cropX(),this.cropY(),f,h,0,0,t,r]:i=[s,0,0,t,r]}(this.hasFill()||this.hasStroke()||l)&&(e.beginPath(),l?of.Util.drawRoundedRectPath(e,t,r,l):e.rect(0,0,t,r),e.closePath(),e.fillStrokeShape(this)),s&&(l&&e.clip(),e.drawImage.apply(e,i))}_hitFunc(e){const t=this.width(),r=this.height(),l=this.cornerRadius();e.beginPath(),l?of.Util.drawRoundedRectPath(e,t,r,l):e.rect(0,0,t,r),e.closePath(),e.fillStrokeShape(this)}getWidth(){var e,t;return(e=this.attrs.width)!==null&&e!==void 0?e:(t=this.image())===null||t===void 0?void 0:t.width}getHeight(){var e,t;return(e=this.attrs.height)!==null&&e!==void 0?e:(t=this.image())===null||t===void 0?void 0:t.height}static fromURL(e,t,r=null){const l=of.Util.createImageElement();l.onload=function(){const s=new c0({image:l});t(s)},l.onerror=r,l.crossOrigin="Anonymous",l.src=e}};fu.Image=Ds,Ds.prototype.className="Image",(0,S2._registerNode)(Ds),Qn.Factory.addGetterSetter(Ds,"cornerRadius",0,(0,Tl.getNumberOrArrayOfNumbersValidator)(4)),Qn.Factory.addGetterSetter(Ds,"image"),Qn.Factory.addComponentsGetterSetter(Ds,"crop",["x","y","width","height"]),Qn.Factory.addGetterSetter(Ds,"cropX",0,(0,Tl.getNumberValidator)()),Qn.Factory.addGetterSetter(Ds,"cropY",0,(0,Tl.getNumberValidator)()),Qn.Factory.addGetterSetter(Ds,"cropWidth",0,(0,Tl.getNumberValidator)()),Qn.Factory.addGetterSetter(Ds,"cropHeight",0,(0,Tl.getNumberValidator)());var Ki={};Object.defineProperty(Ki,"__esModule",{value:!0}),Ki.Tag=Ki.Label=void 0;const du=Fe,E2=Ct,C2=Vi,uf=Ne,np=Le,ip=["fontFamily","fontSize","fontStyle","padding","lineHeight","text","width","height","pointerDirection","pointerWidth","pointerHeight"],A2="Change.konva",b2="none",cf="up",hf="right",ff="down",df="left",R2=ip.length;class _f extends C2.Group{constructor(e){super(e),this.on("add.konva",function(t){this._addListeners(t.child),this._sync()})}getText(){return this.find("Text")[0]}getTag(){return this.find("Tag")[0]}_addListeners(e){let t=this,r;const l=function(){t._sync()};for(r=0;r<R2;r++)e.on(ip[r]+A2,l)}getWidth(){return this.getText().width()}getHeight(){return this.getText().height()}_sync(){let e=this.getText(),t=this.getTag(),r,l,s,i,f,h,d;if(e&&t){switch(r=e.width(),l=e.height(),s=t.pointerDirection(),i=t.pointerWidth(),d=t.pointerHeight(),f=0,h=0,s){case cf:f=r/2,h=-1*d;break;case hf:f=r+i,h=l/2;break;case ff:f=r/2,h=l+d;break;case df:f=-1*i,h=l/2;break}t.setAttrs({x:-1*f,y:-1*h,width:r,height:l}),e.setAttrs({x:-1*f,y:-1*h})}}}Ki.Label=_f,_f.prototype.className="Label",(0,np._registerNode)(_f);class Zn extends E2.Shape{_sceneFunc(e){const t=this.width(),r=this.height(),l=this.pointerDirection(),s=this.pointerWidth(),i=this.pointerHeight(),f=this.cornerRadius();let h=0,d=0,p=0,v=0;typeof f=="number"?h=d=p=v=Math.min(f,t/2,r/2):(h=Math.min(f[0]||0,t/2,r/2),d=Math.min(f[1]||0,t/2,r/2),v=Math.min(f[2]||0,t/2,r/2),p=Math.min(f[3]||0,t/2,r/2)),e.beginPath(),e.moveTo(h,0),l===cf&&(e.lineTo((t-s)/2,0),e.lineTo(t/2,-1*i),e.lineTo((t+s)/2,0)),e.lineTo(t-d,0),e.arc(t-d,d,d,Math.PI*3/2,0,!1),l===hf&&(e.lineTo(t,(r-i)/2),e.lineTo(t+s,r/2),e.lineTo(t,(r+i)/2)),e.lineTo(t,r-v),e.arc(t-v,r-v,v,0,Math.PI/2,!1),l===ff&&(e.lineTo((t+s)/2,r),e.lineTo(t/2,r+i),e.lineTo((t-s)/2,r)),e.lineTo(p,r),e.arc(p,r-p,p,Math.PI/2,Math.PI,!1),l===df&&(e.lineTo(0,(r+i)/2),e.lineTo(-1*s,r/2),e.lineTo(0,(r-i)/2)),e.lineTo(0,h),e.arc(h,h,h,Math.PI,Math.PI*3/2,!1),e.closePath(),e.fillStrokeShape(this)}getSelfRect(){let e=0,t=0,r=this.pointerWidth(),l=this.pointerHeight(),s=this.pointerDirection(),i=this.width(),f=this.height();return s===cf?(t-=l,f+=l):s===ff?f+=l:s===df?(e-=r*1.5,i+=r):s===hf&&(i+=r*1.5),{x:e,y:t,width:i,height:f}}}Ki.Tag=Zn,Zn.prototype.className="Tag",(0,np._registerNode)(Zn),du.Factory.addGetterSetter(Zn,"pointerDirection",b2),du.Factory.addGetterSetter(Zn,"pointerWidth",0,(0,uf.getNumberValidator)()),du.Factory.addGetterSetter(Zn,"pointerHeight",0,(0,uf.getNumberValidator)()),du.Factory.addGetterSetter(Zn,"cornerRadius",0,(0,uf.getNumberOrArrayOfNumbersValidator)(4));var yl={};Object.defineProperty(yl,"__esModule",{value:!0}),yl.Rect=void 0;const w2=Fe,I2=Ct,O2=Le,D2=rt,N2=Ne;class _u extends I2.Shape{_sceneFunc(e){const t=this.cornerRadius(),r=this.width(),l=this.height();e.beginPath(),t?D2.Util.drawRoundedRectPath(e,r,l,t):e.rect(0,0,r,l),e.closePath(),e.fillStrokeShape(this)}}yl.Rect=_u,_u.prototype.className="Rect",(0,O2._registerNode)(_u),w2.Factory.addGetterSetter(_u,"cornerRadius",0,(0,N2.getNumberOrArrayOfNumbersValidator)(4));var gu={};Object.defineProperty(gu,"__esModule",{value:!0}),gu.RegularPolygon=void 0;const rp=Fe,P2=Ct,lp=Ne,x2=Le;class ei extends P2.Shape{_sceneFunc(e){const t=this._getPoints();e.beginPath(),e.moveTo(t[0].x,t[0].y);for(let r=1;r<t.length;r++)e.lineTo(t[r].x,t[r].y);e.closePath(),e.fillStrokeShape(this)}_getPoints(){const e=this.attrs.sides,t=this.attrs.radius||0,r=[];for(let l=0;l<e;l++)r.push({x:t*Math.sin(l*2*Math.PI/e),y:-1*t*Math.cos(l*2*Math.PI/e)});return r}getSelfRect(){const e=this._getPoints();let t=e[0].x,r=e[0].y,l=e[0].x,s=e[0].y;return e.forEach(i=>{t=Math.min(t,i.x),r=Math.max(r,i.x),l=Math.min(l,i.y),s=Math.max(s,i.y)}),{x:t,y:l,width:r-t,height:s-l}}getWidth(){return this.radius()*2}getHeight(){return this.radius()*2}setWidth(e){this.radius(e/2)}setHeight(e){this.radius(e/2)}}gu.RegularPolygon=ei,ei.prototype.className="RegularPolygon",ei.prototype._centroid=!0,ei.prototype._attrsAffectingSize=["radius"],(0,x2._registerNode)(ei),rp.Factory.addGetterSetter(ei,"radius",0,(0,lp.getNumberValidator)()),rp.Factory.addGetterSetter(ei,"sides",0,(0,lp.getNumberValidator)());var pu={};Object.defineProperty(pu,"__esModule",{value:!0}),pu.Ring=void 0;const ap=Fe,k2=Ct,op=Ne,M2=Le,up=Math.PI*2;class ti extends k2.Shape{_sceneFunc(e){e.beginPath(),e.arc(0,0,this.innerRadius(),0,up,!1),e.moveTo(this.outerRadius(),0),e.arc(0,0,this.outerRadius(),up,0,!0),e.closePath(),e.fillStrokeShape(this)}getWidth(){return this.outerRadius()*2}getHeight(){return this.outerRadius()*2}setWidth(e){this.outerRadius(e/2)}setHeight(e){this.outerRadius(e/2)}}pu.Ring=ti,ti.prototype.className="Ring",ti.prototype._centroid=!0,ti.prototype._attrsAffectingSize=["innerRadius","outerRadius"],(0,M2._registerNode)(ti),ap.Factory.addGetterSetter(ti,"innerRadius",0,(0,op.getNumberValidator)()),ap.Factory.addGetterSetter(ti,"outerRadius",0,(0,op.getNumberValidator)());var mu={};Object.defineProperty(mu,"__esModule",{value:!0}),mu.Sprite=void 0;const si=Fe,U2=Ct,L2=Bi,cp=Ne,F2=Le;class Ns extends U2.Shape{constructor(e){super(e),this._updated=!0,this.anim=new L2.Animation(()=>{const t=this._updated;return this._updated=!1,t}),this.on("animationChange.konva",function(){this.frameIndex(0)}),this.on("frameIndexChange.konva",function(){this._updated=!0}),this.on("frameRateChange.konva",function(){this.anim.isRunning()&&(clearInterval(this.interval),this._setInterval())})}_sceneFunc(e){const t=this.animation(),r=this.frameIndex(),l=r*4,s=this.animations()[t],i=this.frameOffsets(),f=s[l+0],h=s[l+1],d=s[l+2],p=s[l+3],v=this.image();if((this.hasFill()||this.hasStroke())&&(e.beginPath(),e.rect(0,0,d,p),e.closePath(),e.fillStrokeShape(this)),v)if(i){const T=i[t],y=r*2;e.drawImage(v,f,h,d,p,T[y+0],T[y+1],d,p)}else e.drawImage(v,f,h,d,p,0,0,d,p)}_hitFunc(e){const t=this.animation(),r=this.frameIndex(),l=r*4,s=this.animations()[t],i=this.frameOffsets(),f=s[l+2],h=s[l+3];if(e.beginPath(),i){const d=i[t],p=r*2;e.rect(d[p+0],d[p+1],f,h)}else e.rect(0,0,f,h);e.closePath(),e.fillShape(this)}_useBufferCanvas(){return super._useBufferCanvas(!0)}_setInterval(){const e=this;this.interval=setInterval(function(){e._updateIndex()},1e3/this.frameRate())}start(){if(this.isRunning())return;const e=this.getLayer();this.anim.setLayers(e),this._setInterval(),this.anim.start()}stop(){this.anim.stop(),clearInterval(this.interval)}isRunning(){return this.anim.isRunning()}_updateIndex(){const e=this.frameIndex(),t=this.animation(),r=this.animations(),l=r[t],s=l.length/4;e<s-1?this.frameIndex(e+1):this.frameIndex(0)}}mu.Sprite=Ns,Ns.prototype.className="Sprite",(0,F2._registerNode)(Ns),si.Factory.addGetterSetter(Ns,"animation"),si.Factory.addGetterSetter(Ns,"animations"),si.Factory.addGetterSetter(Ns,"frameOffsets"),si.Factory.addGetterSetter(Ns,"image"),si.Factory.addGetterSetter(Ns,"frameIndex",0,(0,cp.getNumberValidator)()),si.Factory.addGetterSetter(Ns,"frameRate",17,(0,cp.getNumberValidator)()),si.Factory.backCompat(Ns,{index:"frameIndex",getIndex:"getFrameIndex",setIndex:"setFrameIndex"});var vu={};Object.defineProperty(vu,"__esModule",{value:!0}),vu.Star=void 0;const gf=Fe,$2=Ct,pf=Ne,H2=Le;class yn extends $2.Shape{_sceneFunc(e){const t=this.innerRadius(),r=this.outerRadius(),l=this.numPoints();e.beginPath(),e.moveTo(0,0-r);for(let s=1;s<l*2;s++){const i=s%2===0?r:t,f=i*Math.sin(s*Math.PI/l),h=-1*i*Math.cos(s*Math.PI/l);e.lineTo(f,h)}e.closePath(),e.fillStrokeShape(this)}getWidth(){return this.outerRadius()*2}getHeight(){return this.outerRadius()*2}setWidth(e){this.outerRadius(e/2)}setHeight(e){this.outerRadius(e/2)}}vu.Star=yn,yn.prototype.className="Star",yn.prototype._centroid=!0,yn.prototype._attrsAffectingSize=["innerRadius","outerRadius"],(0,H2._registerNode)(yn),gf.Factory.addGetterSetter(yn,"numPoints",5,(0,pf.getNumberValidator)()),gf.Factory.addGetterSetter(yn,"innerRadius",0,(0,pf.getNumberValidator)()),gf.Factory.addGetterSetter(yn,"outerRadius",0,(0,pf.getNumberValidator)());var Yi={};Object.defineProperty(Yi,"__esModule",{value:!0}),Yi.Text=void 0,Yi.stringToArray=hp;const mf=rt,Bt=Fe,G2=Ct,vf=Le,Sn=Ne,V2=Le;function hp(u){return[...u].reduce((e,t,r,l)=>(/\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?(?:\u200D\p{Emoji_Presentation})+/u.test(t)?e.push(t):/\p{Regional_Indicator}{2}/u.test(t+(l[r+1]||""))?e.push(t+l[r+1]):r>0&&/\p{Mn}|\p{Me}|\p{Mc}/u.test(t)?e[e.length-1]+=t:e.push(t),e),[])}const zi="auto",B2="center",fp="inherit",Sl="justify",j2="Change.konva",q2="2d",dp="-",_p="left",W2="text",K2="Text",Y2="top",z2="bottom",gp="middle",pp="normal",X2="px ",Tu=" ",J2="right",mp="rtl",Q2="word",Z2="char",vp="none",Tf="…",Tp=["direction","fontFamily","fontSize","fontStyle","fontVariant","padding","align","verticalAlign","lineHeight","text","width","height","wrap","ellipsis","letterSpacing"],eE=Tp.length;function tE(u){return u.split(",").map(e=>{e=e.trim();const t=e.indexOf(" ")>=0,r=e.indexOf('"')>=0||e.indexOf("'")>=0;return t&&!r&&(e=`"${e}"`),e}).join(", ")}let yu;function yf(){return yu||(yu=mf.Util.createCanvasElement().getContext(q2),yu)}function sE(u){u.fillText(this._partialText,this._partialTextX,this._partialTextY)}function nE(u){u.setAttr("miterLimit",2),u.strokeText(this._partialText,this._partialTextX,this._partialTextY)}function iE(u){return u=u||{},!u.fillLinearGradientColorStops&&!u.fillRadialGradientColorStops&&!u.fillPatternImage&&(u.fill=u.fill||"black"),u}class ft extends G2.Shape{constructor(e){super(iE(e)),this._partialTextX=0,this._partialTextY=0;for(let t=0;t<eE;t++)this.on(Tp[t]+j2,this._setTextData);this._setTextData()}_sceneFunc(e){const t=this.textArr,r=t.length;if(!this.text())return;let l=this.padding(),s=this.fontSize(),i=this.lineHeight()*s,f=this.verticalAlign(),h=this.direction(),d=0,p=this.align(),v=this.getWidth(),T=this.letterSpacing(),y=this.fill(),S=this.textDecoration(),A=S.indexOf("underline")!==-1,R=S.indexOf("line-through")!==-1,O;h=h===fp?e.direction:h;let N=i/2,C=gp;if(vf.Konva._fixTextRendering){const B=this.measureSize("M");C="alphabetic",N=(B.fontBoundingBoxAscent-B.fontBoundingBoxDescent)/2+i/2}var b=0,w=0;for(h===mp&&e.setAttr("direction",h),e.setAttr("font",this._getContextFont()),e.setAttr("textBaseline",C),e.setAttr("textAlign",_p),f===gp?d=(this.getHeight()-r*i-l*2)/2:f===z2&&(d=this.getHeight()-r*i-l*2),e.translate(l,d+l),O=0;O<r;O++){var b=0,w=0,F=t[O],q=F.text,D=F.width,P=F.lastInParagraph,I,x,U;if(e.save(),p===J2?b+=v-D-l*2:p===B2&&(b+=(v-D-l*2)/2),A){e.save(),e.beginPath();const L=vf.Konva._fixTextRendering?Math.round(s/4):Math.round(s/2),V=b,J=N+w+L;e.moveTo(V,J),I=q.split(" ").length-1,x=I===0,U=p===Sl&&!P?v-l*2:D,e.lineTo(V+Math.round(U),J),e.lineWidth=s/15;const Pe=this._getLinearGradient();e.strokeStyle=Pe||y,e.stroke(),e.restore()}if(R){e.save(),e.beginPath();const L=vf.Konva._fixTextRendering?-Math.round(s/4):0;e.moveTo(b,N+w+L),I=q.split(" ").length-1,x=I===0,U=p===Sl&&P&&!x?v-l*2:D,e.lineTo(b+Math.round(U),N+w+L),e.lineWidth=s/15;const V=this._getLinearGradient();e.strokeStyle=V||y,e.stroke(),e.restore()}if(h!==mp&&(T!==0||p===Sl)){I=q.split(" ").length-1;const L=hp(q);for(let V=0;V<L.length;V++){const J=L[V];J===" "&&!P&&p===Sl&&(b+=(v-l*2-D)/I),this._partialTextX=b,this._partialTextY=N+w,this._partialText=J,e.fillStrokeShape(this),b+=this.measureSize(J).width+T}}else T!==0&&e.setAttr("letterSpacing",`${T}px`),this._partialTextX=b,this._partialTextY=N+w,this._partialText=q,e.fillStrokeShape(this);e.restore(),r>1&&(N+=i)}}_hitFunc(e){const t=this.getWidth(),r=this.getHeight();e.beginPath(),e.rect(0,0,t,r),e.closePath(),e.fillStrokeShape(this)}setText(e){const t=mf.Util._isString(e)?e:e==null?"":e+"";return this._setAttr(W2,t),this}getWidth(){return this.attrs.width===zi||this.attrs.width===void 0?this.getTextWidth()+this.padding()*2:this.attrs.width}getHeight(){return this.attrs.height===zi||this.attrs.height===void 0?this.fontSize()*this.textArr.length*this.lineHeight()+this.padding()*2:this.attrs.height}getTextWidth(){return this.textWidth}getTextHeight(){return mf.Util.warn("text.getTextHeight() method is deprecated. Use text.height() - for full height and text.fontSize() - for one line height."),this.textHeight}measureSize(e){var t,r,l,s,i,f,h,d,p,v,T;let y=yf(),S=this.fontSize(),A;y.save(),y.font=this._getContextFont(),A=y.measureText(e),y.restore();const R=S/100;return{actualBoundingBoxAscent:(t=A.actualBoundingBoxAscent)!==null&&t!==void 0?t:71.58203125*R,actualBoundingBoxDescent:(r=A.actualBoundingBoxDescent)!==null&&r!==void 0?r:0,actualBoundingBoxLeft:(l=A.actualBoundingBoxLeft)!==null&&l!==void 0?l:-7.421875*R,actualBoundingBoxRight:(s=A.actualBoundingBoxRight)!==null&&s!==void 0?s:75.732421875*R,alphabeticBaseline:(i=A.alphabeticBaseline)!==null&&i!==void 0?i:0,emHeightAscent:(f=A.emHeightAscent)!==null&&f!==void 0?f:100*R,emHeightDescent:(h=A.emHeightDescent)!==null&&h!==void 0?h:-20*R,fontBoundingBoxAscent:(d=A.fontBoundingBoxAscent)!==null&&d!==void 0?d:91*R,fontBoundingBoxDescent:(p=A.fontBoundingBoxDescent)!==null&&p!==void 0?p:21*R,hangingBaseline:(v=A.hangingBaseline)!==null&&v!==void 0?v:72.80000305175781*R,ideographicBaseline:(T=A.ideographicBaseline)!==null&&T!==void 0?T:-21*R,width:A.width,height:S}}_getContextFont(){return this.fontStyle()+Tu+this.fontVariant()+Tu+(this.fontSize()+X2)+tE(this.fontFamily())}_addTextLine(e){this.align()===Sl&&(e=e.trim());const r=this._getTextWidth(e);return this.textArr.push({text:e,width:r,lastInParagraph:!1})}_getTextWidth(e){const t=this.letterSpacing(),r=e.length;return yf().measureText(e).width+(r?t*(r-1):0)}_setTextData(){let e=this.text().split(`
160
- `),t=+this.fontSize(),r=0,l=this.lineHeight()*t,s=this.attrs.width,i=this.attrs.height,f=s!==zi&&s!==void 0,h=i!==zi&&i!==void 0,d=this.padding(),p=s-d*2,v=i-d*2,T=0,y=this.wrap(),S=y!==vp,A=y!==Z2&&S,R=this.ellipsis();this.textArr=[],yf().font=this._getContextFont();const O=R?this._getTextWidth(Tf):0;for(let C=0,b=e.length;C<b;++C){let w=e[C],F=this._getTextWidth(w);if(f&&F>p)for(;w.length>0;){let q=0,D=w.length,P="",I=0;for(;q<D;){const x=q+D>>>1,U=w.slice(0,x+1),B=this._getTextWidth(U)+O;B<=p?(q=x+1,P=U,I=B):D=x}if(P){if(A){var N;const U=w[P.length];(U===Tu||U===dp)&&I<=p?N=P.length:N=Math.max(P.lastIndexOf(Tu),P.lastIndexOf(dp))+1,N>0&&(q=N,P=P.slice(0,q),I=this._getTextWidth(P))}if(P=P.trimRight(),this._addTextLine(P),r=Math.max(r,I),T+=l,this._shouldHandleEllipsis(T)){this._tryToAddEllipsisToLastLine();break}if(w=w.slice(q),w=w.trimLeft(),w.length>0&&(F=this._getTextWidth(w),F<=p)){this._addTextLine(w),T+=l,r=Math.max(r,F);break}}else break}else this._addTextLine(w),T+=l,r=Math.max(r,F),this._shouldHandleEllipsis(T)&&C<b-1&&this._tryToAddEllipsisToLastLine();if(this.textArr[this.textArr.length-1]&&(this.textArr[this.textArr.length-1].lastInParagraph=!0),h&&T+l>v)break}this.textHeight=t,this.textWidth=r}_shouldHandleEllipsis(e){const t=+this.fontSize(),r=this.lineHeight()*t,l=this.attrs.height,s=l!==zi&&l!==void 0,i=this.padding(),f=l-i*2;return!(this.wrap()!==vp)||s&&e+r>f}_tryToAddEllipsisToLastLine(){const e=this.attrs.width,t=e!==zi&&e!==void 0,r=this.padding(),l=e-r*2,s=this.ellipsis(),i=this.textArr[this.textArr.length-1];!i||!s||(t&&(this._getTextWidth(i.text+Tf)<l||(i.text=i.text.slice(0,i.text.length-3))),this.textArr.splice(this.textArr.length-1,1),this._addTextLine(i.text+Tf))}getStrokeScaleEnabled(){return!0}_useBufferCanvas(){const e=this.textDecoration().indexOf("underline")!==-1||this.textDecoration().indexOf("line-through")!==-1,t=this.hasShadow();return e&&t?!0:super._useBufferCanvas()}}Yi.Text=ft,ft.prototype._fillFunc=sE,ft.prototype._strokeFunc=nE,ft.prototype.className=K2,ft.prototype._attrsAffectingSize=["text","fontSize","padding","wrap","lineHeight","letterSpacing"],(0,V2._registerNode)(ft),Bt.Factory.overWriteSetter(ft,"width",(0,Sn.getNumberOrAutoValidator)()),Bt.Factory.overWriteSetter(ft,"height",(0,Sn.getNumberOrAutoValidator)()),Bt.Factory.addGetterSetter(ft,"direction",fp),Bt.Factory.addGetterSetter(ft,"fontFamily","Arial"),Bt.Factory.addGetterSetter(ft,"fontSize",12,(0,Sn.getNumberValidator)()),Bt.Factory.addGetterSetter(ft,"fontStyle",pp),Bt.Factory.addGetterSetter(ft,"fontVariant",pp),Bt.Factory.addGetterSetter(ft,"padding",0,(0,Sn.getNumberValidator)()),Bt.Factory.addGetterSetter(ft,"align",_p),Bt.Factory.addGetterSetter(ft,"verticalAlign",Y2),Bt.Factory.addGetterSetter(ft,"lineHeight",1,(0,Sn.getNumberValidator)()),Bt.Factory.addGetterSetter(ft,"wrap",Q2),Bt.Factory.addGetterSetter(ft,"ellipsis",!1,(0,Sn.getBooleanValidator)()),Bt.Factory.addGetterSetter(ft,"letterSpacing",0,(0,Sn.getNumberValidator)()),Bt.Factory.addGetterSetter(ft,"text","",(0,Sn.getStringValidator)()),Bt.Factory.addGetterSetter(ft,"textDecoration","");var Su={};Object.defineProperty(Su,"__esModule",{value:!0}),Su.TextPath=void 0;const Sf=rt,vs=Fe,rE=Ct,El=ji,Ef=Yi,yp=Ne,lE=Le,aE="",Sp="normal";function Ep(u){u.fillText(this.partialText,0,0)}function Cp(u){u.strokeText(this.partialText,0,0)}class bt extends rE.Shape{constructor(e){super(e),this.dummyCanvas=Sf.Util.createCanvasElement(),this.dataArray=[],this._readDataAttribute(),this.on("dataChange.konva",function(){this._readDataAttribute(),this._setTextData()}),this.on("textChange.konva alignChange.konva letterSpacingChange.konva kerningFuncChange.konva fontSizeChange.konva fontFamilyChange.konva",this._setTextData),this._setTextData()}_getTextPathLength(){return El.Path.getPathLength(this.dataArray)}_getPointAtLength(e){if(!this.attrs.data)return null;const t=this.pathLength;return e-1>t?null:El.Path.getPointAtLengthOfDataArray(e,this.dataArray)}_readDataAttribute(){this.dataArray=El.Path.parsePathData(this.attrs.data),this.pathLength=this._getTextPathLength()}_sceneFunc(e){e.setAttr("font",this._getContextFont()),e.setAttr("textBaseline",this.textBaseline()),e.setAttr("textAlign","left"),e.save();const t=this.textDecoration(),r=this.fill(),l=this.fontSize(),s=this.glyphInfo;t==="underline"&&e.beginPath();for(let i=0;i<s.length;i++){e.save();const f=s[i].p0;e.translate(f.x,f.y),e.rotate(s[i].rotation),this.partialText=s[i].text,e.fillStrokeShape(this),t==="underline"&&(i===0&&e.moveTo(0,l/2+1),e.lineTo(l,l/2+1)),e.restore()}t==="underline"&&(e.strokeStyle=r,e.lineWidth=l/20,e.stroke()),e.restore()}_hitFunc(e){e.beginPath();const t=this.glyphInfo;if(t.length>=1){const r=t[0].p0;e.moveTo(r.x,r.y)}for(let r=0;r<t.length;r++){const l=t[r].p1;e.lineTo(l.x,l.y)}e.setAttr("lineWidth",this.fontSize()),e.setAttr("strokeStyle",this.colorKey),e.stroke()}getTextWidth(){return this.textWidth}getTextHeight(){return Sf.Util.warn("text.getTextHeight() method is deprecated. Use text.height() - for full height and text.fontSize() - for one line height."),this.textHeight}setText(e){return Ef.Text.prototype.setText.call(this,e)}_getContextFont(){return Ef.Text.prototype._getContextFont.call(this)}_getTextSize(e){const r=this.dummyCanvas.getContext("2d");r.save(),r.font=this._getContextFont();const l=r.measureText(e);return r.restore(),{width:l.width,height:parseInt(`${this.fontSize()}`,10)}}_setTextData(){const{width:e,height:t}=this._getTextSize(this.attrs.text);if(this.textWidth=e,this.textHeight=t,this.glyphInfo=[],!this.attrs.data)return null;const r=this.letterSpacing(),l=this.align(),s=this.kerningFunc(),i=Math.max(this.textWidth+((this.attrs.text||"").length-1)*r,0);let f=0;l==="center"&&(f=Math.max(0,this.pathLength/2-i/2)),l==="right"&&(f=Math.max(0,this.pathLength-i));const h=(0,Ef.stringToArray)(this.text());let d=f;for(let p=0;p<h.length;p++){const v=this._getPointAtLength(d);if(!v)return;let T=this._getTextSize(h[p]).width+r;if(h[p]===" "&&l==="justify"){const N=this.text().split(" ").length-1;T+=(this.pathLength-i)/N}const y=this._getPointAtLength(d+T);if(!y)return;const S=El.Path.getLineLength(v.x,v.y,y.x,y.y);let A=0;if(s)try{A=s(h[p-1],h[p])*this.fontSize()}catch{A=0}v.x+=A,y.x+=A,this.textWidth+=A;const R=El.Path.getPointOnLine(A+S/2,v.x,v.y,y.x,y.y),O=Math.atan2(y.y-v.y,y.x-v.x);this.glyphInfo.push({transposeX:R.x,transposeY:R.y,text:h[p],rotation:O,p0:v,p1:y}),d+=T}}getSelfRect(){if(!this.glyphInfo.length)return{x:0,y:0,width:0,height:0};const e=[];this.glyphInfo.forEach(function(d){e.push(d.p0.x),e.push(d.p0.y),e.push(d.p1.x),e.push(d.p1.y)});let t=e[0]||0,r=e[0]||0,l=e[1]||0,s=e[1]||0,i,f;for(let d=0;d<e.length/2;d++)i=e[d*2],f=e[d*2+1],t=Math.min(t,i),r=Math.max(r,i),l=Math.min(l,f),s=Math.max(s,f);const h=this.fontSize();return{x:t-h/2,y:l-h/2,width:r-t+h,height:s-l+h}}destroy(){return Sf.Util.releaseCanvas(this.dummyCanvas),super.destroy()}}Su.TextPath=bt,bt.prototype._fillFunc=Ep,bt.prototype._strokeFunc=Cp,bt.prototype._fillFuncHit=Ep,bt.prototype._strokeFuncHit=Cp,bt.prototype.className="TextPath",bt.prototype._attrsAffectingSize=["text","fontSize","data"],(0,lE._registerNode)(bt),vs.Factory.addGetterSetter(bt,"data"),vs.Factory.addGetterSetter(bt,"fontFamily","Arial"),vs.Factory.addGetterSetter(bt,"fontSize",12,(0,yp.getNumberValidator)()),vs.Factory.addGetterSetter(bt,"fontStyle",Sp),vs.Factory.addGetterSetter(bt,"align","left"),vs.Factory.addGetterSetter(bt,"letterSpacing",0,(0,yp.getNumberValidator)()),vs.Factory.addGetterSetter(bt,"textBaseline","middle"),vs.Factory.addGetterSetter(bt,"fontVariant",Sp),vs.Factory.addGetterSetter(bt,"text",aE),vs.Factory.addGetterSetter(bt,"textDecoration",null),vs.Factory.addGetterSetter(bt,"kerningFunc",null);var Eu={};Object.defineProperty(Eu,"__esModule",{value:!0}),Eu.Transformer=void 0;const Ye=rt,qe=Fe,Ap=it,oE=Ct,uE=yl,bp=Vi,Ts=Le,En=Ne,cE=Le,Rp="tr-konva",hE=["resizeEnabledChange","rotateAnchorOffsetChange","rotateEnabledChange","enabledAnchorsChange","anchorSizeChange","borderEnabledChange","borderStrokeChange","borderStrokeWidthChange","borderDashChange","anchorStrokeChange","anchorStrokeWidthChange","anchorFillChange","anchorCornerRadiusChange","ignoreStrokeChange","anchorStyleFuncChange"].map(u=>u+`.${Rp}`).join(" "),wp="nodesRect",fE=["widthChange","heightChange","scaleXChange","scaleYChange","skewXChange","skewYChange","rotationChange","offsetXChange","offsetYChange","transformsEnabledChange","strokeWidthChange"],dE={"top-left":-45,"top-center":0,"top-right":45,"middle-right":-90,"middle-left":90,"bottom-left":-135,"bottom-center":180,"bottom-right":135},_E="ontouchstart"in Ts.Konva._global;function gE(u,e,t){if(u==="rotater")return t;e+=Ye.Util.degToRad(dE[u]||0);const r=(Ye.Util.radToDeg(e)%360+360)%360;return Ye.Util._inRange(r,337.5,360)||Ye.Util._inRange(r,0,22.5)?"ns-resize":Ye.Util._inRange(r,22.5,67.5)?"nesw-resize":Ye.Util._inRange(r,67.5,112.5)?"ew-resize":Ye.Util._inRange(r,112.5,157.5)?"nwse-resize":Ye.Util._inRange(r,157.5,202.5)?"ns-resize":Ye.Util._inRange(r,202.5,247.5)?"nesw-resize":Ye.Util._inRange(r,247.5,292.5)?"ew-resize":Ye.Util._inRange(r,292.5,337.5)?"nwse-resize":(Ye.Util.error("Transformer has unknown angle for cursor detection: "+r),"pointer")}const Cu=["top-left","top-center","top-right","middle-right","middle-left","bottom-left","bottom-center","bottom-right"],Ip=1e8;function pE(u){return{x:u.x+u.width/2*Math.cos(u.rotation)+u.height/2*Math.sin(-u.rotation),y:u.y+u.height/2*Math.cos(u.rotation)+u.width/2*Math.sin(u.rotation)}}function Op(u,e,t){const r=t.x+(u.x-t.x)*Math.cos(e)-(u.y-t.y)*Math.sin(e),l=t.y+(u.x-t.x)*Math.sin(e)+(u.y-t.y)*Math.cos(e);return{...u,rotation:u.rotation+e,x:r,y:l}}function mE(u,e){const t=pE(u);return Op(u,e,t)}function vE(u,e,t){let r=e;for(let l=0;l<u.length;l++){const s=Ts.Konva.getAngle(u[l]),i=Math.abs(s-e)%(Math.PI*2);Math.min(i,Math.PI*2-i)<t&&(r=s)}return r}let Cf=0;class Ve extends bp.Group{constructor(e){super(e),this._movingAnchorName=null,this._transforming=!1,this._createElements(),this._handleMouseMove=this._handleMouseMove.bind(this),this._handleMouseUp=this._handleMouseUp.bind(this),this.update=this.update.bind(this),this.on(hE,this.update),this.getNode()&&this.update()}attachTo(e){return this.setNode(e),this}setNode(e){return Ye.Util.warn("tr.setNode(shape), tr.node(shape) and tr.attachTo(shape) methods are deprecated. Please use tr.nodes(nodesArray) instead."),this.setNodes([e])}getNode(){return this._nodes&&this._nodes[0]}_getEventNamespace(){return Rp+this._id}setNodes(e=[]){this._nodes&&this._nodes.length&&this.detach();const t=e.filter(l=>l.isAncestorOf(this)?(Ye.Util.error("Konva.Transformer cannot be an a child of the node you are trying to attach"),!1):!0);return this._nodes=e=t,e.length===1&&this.useSingleNodeRotation()?this.rotation(e[0].getAbsoluteRotation()):this.rotation(0),this._nodes.forEach(l=>{const s=()=>{this.nodes().length===1&&this.useSingleNodeRotation()&&this.rotation(this.nodes()[0].getAbsoluteRotation()),this._resetTransformCache(),!this._transforming&&!this.isDragging()&&this.update()},i=l._attrsAffectingSize.map(f=>f+"Change."+this._getEventNamespace()).join(" ");l.on(i,s),l.on(fE.map(f=>f+`.${this._getEventNamespace()}`).join(" "),s),l.on(`absoluteTransformChange.${this._getEventNamespace()}`,s),this._proxyDrag(l)}),this._resetTransformCache(),!!this.findOne(".top-left")&&this.update(),this}_proxyDrag(e){let t;e.on(`dragstart.${this._getEventNamespace()}`,r=>{t=e.getAbsolutePosition(),!this.isDragging()&&e!==this.findOne(".back")&&this.startDrag(r,!1)}),e.on(`dragmove.${this._getEventNamespace()}`,r=>{if(!t)return;const l=e.getAbsolutePosition(),s=l.x-t.x,i=l.y-t.y;this.nodes().forEach(f=>{if(f===e||f.isDragging())return;const h=f.getAbsolutePosition();f.setAbsolutePosition({x:h.x+s,y:h.y+i}),f.startDrag(r)}),t=null})}getNodes(){return this._nodes||[]}getActiveAnchor(){return this._movingAnchorName}detach(){this._nodes&&this._nodes.forEach(e=>{e.off("."+this._getEventNamespace())}),this._nodes=[],this._resetTransformCache()}_resetTransformCache(){this._clearCache(wp),this._clearCache("transform"),this._clearSelfAndDescendantCache("absoluteTransform")}_getNodeRect(){return this._getCache(wp,this.__getNodeRect)}__getNodeShape(e,t=this.rotation(),r){const l=e.getClientRect({skipTransform:!0,skipShadow:!0,skipStroke:this.ignoreStroke()}),s=e.getAbsoluteScale(r),i=e.getAbsolutePosition(r),f=l.x*s.x-e.offsetX()*s.x,h=l.y*s.y-e.offsetY()*s.y,d=(Ts.Konva.getAngle(e.getAbsoluteRotation())+Math.PI*2)%(Math.PI*2),p={x:i.x+f*Math.cos(d)+h*Math.sin(-d),y:i.y+h*Math.cos(d)+f*Math.sin(d),width:l.width*s.x,height:l.height*s.y,rotation:d};return Op(p,-Ts.Konva.getAngle(t),{x:0,y:0})}__getNodeRect(){if(!this.getNode())return{x:-Ip,y:-Ip,width:0,height:0,rotation:0};const t=[];this.nodes().map(d=>{const p=d.getClientRect({skipTransform:!0,skipShadow:!0,skipStroke:this.ignoreStroke()}),v=[{x:p.x,y:p.y},{x:p.x+p.width,y:p.y},{x:p.x+p.width,y:p.y+p.height},{x:p.x,y:p.y+p.height}],T=d.getAbsoluteTransform();v.forEach(function(y){const S=T.point(y);t.push(S)})});const r=new Ye.Transform;r.rotate(-Ts.Konva.getAngle(this.rotation()));let l=1/0,s=1/0,i=-1/0,f=-1/0;t.forEach(function(d){const p=r.point(d);l===void 0&&(l=i=p.x,s=f=p.y),l=Math.min(l,p.x),s=Math.min(s,p.y),i=Math.max(i,p.x),f=Math.max(f,p.y)}),r.invert();const h=r.point({x:l,y:s});return{x:h.x,y:h.y,width:i-l,height:f-s,rotation:Ts.Konva.getAngle(this.rotation())}}getX(){return this._getNodeRect().x}getY(){return this._getNodeRect().y}getWidth(){return this._getNodeRect().width}getHeight(){return this._getNodeRect().height}_createElements(){this._createBack(),Cu.forEach(e=>{this._createAnchor(e)}),this._createAnchor("rotater")}_createAnchor(e){const t=new uE.Rect({stroke:"rgb(0, 161, 255)",fill:"white",strokeWidth:1,name:e+" _anchor",dragDistance:0,draggable:!0,hitStrokeWidth:_E?10:"auto"}),r=this;t.on("mousedown touchstart",function(l){r._handleMouseDown(l)}),t.on("dragstart",l=>{t.stopDrag(),l.cancelBubble=!0}),t.on("dragend",l=>{l.cancelBubble=!0}),t.on("mouseenter",()=>{const l=Ts.Konva.getAngle(this.rotation()),s=this.rotateAnchorCursor(),i=gE(e,l,s);t.getStage().content&&(t.getStage().content.style.cursor=i),this._cursorChange=!0}),t.on("mouseout",()=>{t.getStage().content&&(t.getStage().content.style.cursor=""),this._cursorChange=!1}),this.add(t)}_createBack(){const e=new oE.Shape({name:"back",width:0,height:0,draggable:!0,sceneFunc(t,r){const l=r.getParent(),s=l.padding();t.beginPath(),t.rect(-s,-s,r.width()+s*2,r.height()+s*2),t.moveTo(r.width()/2,-s),l.rotateEnabled()&&l.rotateLineVisible()&&t.lineTo(r.width()/2,-l.rotateAnchorOffset()*Ye.Util._sign(r.height())-s),t.fillStrokeShape(r)},hitFunc:(t,r)=>{if(!this.shouldOverdrawWholeArea())return;const l=this.padding();t.beginPath(),t.rect(-l,-l,r.width()+l*2,r.height()+l*2),t.fillStrokeShape(r)}});this.add(e),this._proxyDrag(e),e.on("dragstart",t=>{t.cancelBubble=!0}),e.on("dragmove",t=>{t.cancelBubble=!0}),e.on("dragend",t=>{t.cancelBubble=!0}),this.on("dragmove",t=>{this.update()})}_handleMouseDown(e){if(this._transforming)return;this._movingAnchorName=e.target.name().split(" ")[0];const t=this._getNodeRect(),r=t.width,l=t.height,s=Math.sqrt(Math.pow(r,2)+Math.pow(l,2));this.sin=Math.abs(l/s),this.cos=Math.abs(r/s),typeof window<"u"&&(window.addEventListener("mousemove",this._handleMouseMove),window.addEventListener("touchmove",this._handleMouseMove),window.addEventListener("mouseup",this._handleMouseUp,!0),window.addEventListener("touchend",this._handleMouseUp,!0)),this._transforming=!0;const i=e.target.getAbsolutePosition(),f=e.target.getStage().getPointerPosition();this._anchorDragOffset={x:f.x-i.x,y:f.y-i.y},Cf++,this._fire("transformstart",{evt:e.evt,target:this.getNode()}),this._nodes.forEach(h=>{h._fire("transformstart",{evt:e.evt,target:h})})}_handleMouseMove(e){let t,r,l;const s=this.findOne("."+this._movingAnchorName),i=s.getStage();i.setPointersPositions(e);const f=i.getPointerPosition();let h={x:f.x-this._anchorDragOffset.x,y:f.y-this._anchorDragOffset.y};const d=s.getAbsolutePosition();this.anchorDragBoundFunc()&&(h=this.anchorDragBoundFunc()(d,h,e)),s.setAbsolutePosition(h);const p=s.getAbsolutePosition();if(d.x===p.x&&d.y===p.y)return;if(this._movingAnchorName==="rotater"){const w=this._getNodeRect();t=s.x()-w.width/2,r=-s.y()+w.height/2;let F=Math.atan2(-r,t)+Math.PI/2;w.height<0&&(F-=Math.PI);const D=Ts.Konva.getAngle(this.rotation())+F,P=Ts.Konva.getAngle(this.rotationSnapTolerance()),x=vE(this.rotationSnaps(),D,P)-w.rotation,U=mE(w,x);this._fitNodesInto(U,e);return}const v=this.shiftBehavior();let T;v==="inverted"?T=this.keepRatio()&&!e.shiftKey:v==="none"?T=this.keepRatio():T=this.keepRatio()||e.shiftKey;var O=this.centeredScaling()||e.altKey;if(this._movingAnchorName==="top-left"){if(T){var y=O?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".bottom-right").x(),y:this.findOne(".bottom-right").y()};l=Math.sqrt(Math.pow(y.x-s.x(),2)+Math.pow(y.y-s.y(),2));var S=this.findOne(".top-left").x()>y.x?-1:1,A=this.findOne(".top-left").y()>y.y?-1:1;t=l*this.cos*S,r=l*this.sin*A,this.findOne(".top-left").x(y.x-t),this.findOne(".top-left").y(y.y-r)}}else if(this._movingAnchorName==="top-center")this.findOne(".top-left").y(s.y());else if(this._movingAnchorName==="top-right"){if(T){var y=O?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".bottom-left").x(),y:this.findOne(".bottom-left").y()};l=Math.sqrt(Math.pow(s.x()-y.x,2)+Math.pow(y.y-s.y(),2));var S=this.findOne(".top-right").x()<y.x?-1:1,A=this.findOne(".top-right").y()>y.y?-1:1;t=l*this.cos*S,r=l*this.sin*A,this.findOne(".top-right").x(y.x+t),this.findOne(".top-right").y(y.y-r)}var R=s.position();this.findOne(".top-left").y(R.y),this.findOne(".bottom-right").x(R.x)}else if(this._movingAnchorName==="middle-left")this.findOne(".top-left").x(s.x());else if(this._movingAnchorName==="middle-right")this.findOne(".bottom-right").x(s.x());else if(this._movingAnchorName==="bottom-left"){if(T){var y=O?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".top-right").x(),y:this.findOne(".top-right").y()};l=Math.sqrt(Math.pow(y.x-s.x(),2)+Math.pow(s.y()-y.y,2));var S=y.x<s.x()?-1:1,A=s.y()<y.y?-1:1;t=l*this.cos*S,r=l*this.sin*A,s.x(y.x-t),s.y(y.y+r)}R=s.position(),this.findOne(".top-left").x(R.x),this.findOne(".bottom-right").y(R.y)}else if(this._movingAnchorName==="bottom-center")this.findOne(".bottom-right").y(s.y());else if(this._movingAnchorName==="bottom-right"){if(T){var y=O?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".top-left").x(),y:this.findOne(".top-left").y()};l=Math.sqrt(Math.pow(s.x()-y.x,2)+Math.pow(s.y()-y.y,2));var S=this.findOne(".bottom-right").x()<y.x?-1:1,A=this.findOne(".bottom-right").y()<y.y?-1:1;t=l*this.cos*S,r=l*this.sin*A,this.findOne(".bottom-right").x(y.x+t),this.findOne(".bottom-right").y(y.y+r)}}else console.error(new Error("Wrong position argument of selection resizer: "+this._movingAnchorName));var O=this.centeredScaling()||e.altKey;if(O){const w=this.findOne(".top-left"),F=this.findOne(".bottom-right"),q=w.x(),D=w.y(),P=this.getWidth()-F.x(),I=this.getHeight()-F.y();F.move({x:-q,y:-D}),w.move({x:P,y:I})}const N=this.findOne(".top-left").getAbsolutePosition();t=N.x,r=N.y;const C=this.findOne(".bottom-right").x()-this.findOne(".top-left").x(),b=this.findOne(".bottom-right").y()-this.findOne(".top-left").y();this._fitNodesInto({x:t,y:r,width:C,height:b,rotation:Ts.Konva.getAngle(this.rotation())},e)}_handleMouseUp(e){this._removeEvents(e)}getAbsoluteTransform(){return this.getTransform()}_removeEvents(e){var t;if(this._transforming){this._transforming=!1,typeof window<"u"&&(window.removeEventListener("mousemove",this._handleMouseMove),window.removeEventListener("touchmove",this._handleMouseMove),window.removeEventListener("mouseup",this._handleMouseUp,!0),window.removeEventListener("touchend",this._handleMouseUp,!0));const r=this.getNode();Cf--,this._fire("transformend",{evt:e,target:r}),(t=this.getLayer())===null||t===void 0||t.batchDraw(),r&&this._nodes.forEach(l=>{var s;l._fire("transformend",{evt:e,target:l}),(s=l.getLayer())===null||s===void 0||s.batchDraw()}),this._movingAnchorName=null}}_fitNodesInto(e,t){const r=this._getNodeRect(),l=1;if(Ye.Util._inRange(e.width,-this.padding()*2-l,l)){this.update();return}if(Ye.Util._inRange(e.height,-this.padding()*2-l,l)){this.update();return}const s=new Ye.Transform;if(s.rotate(Ts.Konva.getAngle(this.rotation())),this._movingAnchorName&&e.width<0&&this._movingAnchorName.indexOf("left")>=0){const T=s.point({x:-this.padding()*2,y:0});e.x+=T.x,e.y+=T.y,e.width+=this.padding()*2,this._movingAnchorName=this._movingAnchorName.replace("left","right"),this._anchorDragOffset.x-=T.x,this._anchorDragOffset.y-=T.y}else if(this._movingAnchorName&&e.width<0&&this._movingAnchorName.indexOf("right")>=0){const T=s.point({x:this.padding()*2,y:0});this._movingAnchorName=this._movingAnchorName.replace("right","left"),this._anchorDragOffset.x-=T.x,this._anchorDragOffset.y-=T.y,e.width+=this.padding()*2}if(this._movingAnchorName&&e.height<0&&this._movingAnchorName.indexOf("top")>=0){const T=s.point({x:0,y:-this.padding()*2});e.x+=T.x,e.y+=T.y,this._movingAnchorName=this._movingAnchorName.replace("top","bottom"),this._anchorDragOffset.x-=T.x,this._anchorDragOffset.y-=T.y,e.height+=this.padding()*2}else if(this._movingAnchorName&&e.height<0&&this._movingAnchorName.indexOf("bottom")>=0){const T=s.point({x:0,y:this.padding()*2});this._movingAnchorName=this._movingAnchorName.replace("bottom","top"),this._anchorDragOffset.x-=T.x,this._anchorDragOffset.y-=T.y,e.height+=this.padding()*2}if(this.boundBoxFunc()){const T=this.boundBoxFunc()(r,e);T?e=T:Ye.Util.warn("boundBoxFunc returned falsy. You should return new bound rect from it!")}const i=1e7,f=new Ye.Transform;f.translate(r.x,r.y),f.rotate(r.rotation),f.scale(r.width/i,r.height/i);const h=new Ye.Transform,d=e.width/i,p=e.height/i;this.flipEnabled()===!1?(h.translate(e.x,e.y),h.rotate(e.rotation),h.translate(e.width<0?e.width:0,e.height<0?e.height:0),h.scale(Math.abs(d),Math.abs(p))):(h.translate(e.x,e.y),h.rotate(e.rotation),h.scale(d,p));const v=h.multiply(f.invert());this._nodes.forEach(T=>{var y;const S=T.getParent().getAbsoluteTransform(),A=T.getTransform().copy();A.translate(T.offsetX(),T.offsetY());const R=new Ye.Transform;R.multiply(S.copy().invert()).multiply(v).multiply(S).multiply(A);const O=R.decompose();T.setAttrs(O),(y=T.getLayer())===null||y===void 0||y.batchDraw()}),this.rotation(Ye.Util._getRotation(e.rotation)),this._nodes.forEach(T=>{this._fire("transform",{evt:t,target:T}),T._fire("transform",{evt:t,target:T})}),this._resetTransformCache(),this.update(),this.getLayer().batchDraw()}forceUpdate(){this._resetTransformCache(),this.update()}_batchChangeChild(e,t){this.findOne(e).setAttrs(t)}update(){var e;const t=this._getNodeRect();this.rotation(Ye.Util._getRotation(t.rotation));const r=t.width,l=t.height,s=this.enabledAnchors(),i=this.resizeEnabled(),f=this.padding(),h=this.anchorSize(),d=this.find("._anchor");d.forEach(v=>{v.setAttrs({width:h,height:h,offsetX:h/2,offsetY:h/2,stroke:this.anchorStroke(),strokeWidth:this.anchorStrokeWidth(),fill:this.anchorFill(),cornerRadius:this.anchorCornerRadius()})}),this._batchChangeChild(".top-left",{x:0,y:0,offsetX:h/2+f,offsetY:h/2+f,visible:i&&s.indexOf("top-left")>=0}),this._batchChangeChild(".top-center",{x:r/2,y:0,offsetY:h/2+f,visible:i&&s.indexOf("top-center")>=0}),this._batchChangeChild(".top-right",{x:r,y:0,offsetX:h/2-f,offsetY:h/2+f,visible:i&&s.indexOf("top-right")>=0}),this._batchChangeChild(".middle-left",{x:0,y:l/2,offsetX:h/2+f,visible:i&&s.indexOf("middle-left")>=0}),this._batchChangeChild(".middle-right",{x:r,y:l/2,offsetX:h/2-f,visible:i&&s.indexOf("middle-right")>=0}),this._batchChangeChild(".bottom-left",{x:0,y:l,offsetX:h/2+f,offsetY:h/2-f,visible:i&&s.indexOf("bottom-left")>=0}),this._batchChangeChild(".bottom-center",{x:r/2,y:l,offsetY:h/2-f,visible:i&&s.indexOf("bottom-center")>=0}),this._batchChangeChild(".bottom-right",{x:r,y:l,offsetX:h/2-f,offsetY:h/2-f,visible:i&&s.indexOf("bottom-right")>=0}),this._batchChangeChild(".rotater",{x:r/2,y:-this.rotateAnchorOffset()*Ye.Util._sign(l)-f,visible:this.rotateEnabled()}),this._batchChangeChild(".back",{width:r,height:l,visible:this.borderEnabled(),stroke:this.borderStroke(),strokeWidth:this.borderStrokeWidth(),dash:this.borderDash(),x:0,y:0});const p=this.anchorStyleFunc();p&&d.forEach(v=>{p(v)}),(e=this.getLayer())===null||e===void 0||e.batchDraw()}isTransforming(){return this._transforming}stopTransform(){if(this._transforming){this._removeEvents();const e=this.findOne("."+this._movingAnchorName);e&&e.stopDrag()}}destroy(){return this.getStage()&&this._cursorChange&&this.getStage().content&&(this.getStage().content.style.cursor=""),bp.Group.prototype.destroy.call(this),this.detach(),this._removeEvents(),this}toObject(){return Ap.Node.prototype.toObject.call(this)}clone(e){return Ap.Node.prototype.clone.call(this,e)}getClientRect(){return this.nodes().length>0?super.getClientRect():{x:0,y:0,width:0,height:0}}}Eu.Transformer=Ve,Ve.isTransforming=()=>Cf>0;function TE(u){return u instanceof Array||Ye.Util.warn("enabledAnchors value should be an array"),u instanceof Array&&u.forEach(function(e){Cu.indexOf(e)===-1&&Ye.Util.warn("Unknown anchor name: "+e+". Available names are: "+Cu.join(", "))}),u||[]}Ve.prototype.className="Transformer",(0,cE._registerNode)(Ve),qe.Factory.addGetterSetter(Ve,"enabledAnchors",Cu,TE),qe.Factory.addGetterSetter(Ve,"flipEnabled",!0,(0,En.getBooleanValidator)()),qe.Factory.addGetterSetter(Ve,"resizeEnabled",!0),qe.Factory.addGetterSetter(Ve,"anchorSize",10,(0,En.getNumberValidator)()),qe.Factory.addGetterSetter(Ve,"rotateEnabled",!0),qe.Factory.addGetterSetter(Ve,"rotateLineVisible",!0),qe.Factory.addGetterSetter(Ve,"rotationSnaps",[]),qe.Factory.addGetterSetter(Ve,"rotateAnchorOffset",50,(0,En.getNumberValidator)()),qe.Factory.addGetterSetter(Ve,"rotateAnchorCursor","crosshair"),qe.Factory.addGetterSetter(Ve,"rotationSnapTolerance",5,(0,En.getNumberValidator)()),qe.Factory.addGetterSetter(Ve,"borderEnabled",!0),qe.Factory.addGetterSetter(Ve,"anchorStroke","rgb(0, 161, 255)"),qe.Factory.addGetterSetter(Ve,"anchorStrokeWidth",1,(0,En.getNumberValidator)()),qe.Factory.addGetterSetter(Ve,"anchorFill","white"),qe.Factory.addGetterSetter(Ve,"anchorCornerRadius",0,(0,En.getNumberValidator)()),qe.Factory.addGetterSetter(Ve,"borderStroke","rgb(0, 161, 255)"),qe.Factory.addGetterSetter(Ve,"borderStrokeWidth",1,(0,En.getNumberValidator)()),qe.Factory.addGetterSetter(Ve,"borderDash"),qe.Factory.addGetterSetter(Ve,"keepRatio",!0),qe.Factory.addGetterSetter(Ve,"shiftBehavior","default"),qe.Factory.addGetterSetter(Ve,"centeredScaling",!1),qe.Factory.addGetterSetter(Ve,"ignoreStroke",!1),qe.Factory.addGetterSetter(Ve,"padding",0,(0,En.getNumberValidator)()),qe.Factory.addGetterSetter(Ve,"node"),qe.Factory.addGetterSetter(Ve,"nodes"),qe.Factory.addGetterSetter(Ve,"boundBoxFunc"),qe.Factory.addGetterSetter(Ve,"anchorDragBoundFunc"),qe.Factory.addGetterSetter(Ve,"anchorStyleFunc"),qe.Factory.addGetterSetter(Ve,"shouldOverdrawWholeArea",!1),qe.Factory.addGetterSetter(Ve,"useSingleNodeRotation",!0),qe.Factory.backCompat(Ve,{lineEnabled:"borderEnabled",rotateHandlerOffset:"rotateAnchorOffset",enabledHandlers:"enabledAnchors"});var Au={};Object.defineProperty(Au,"__esModule",{value:!0}),Au.Wedge=void 0;const bu=Fe,yE=Ct,SE=Le,Dp=Ne,EE=Le;class Js extends yE.Shape{_sceneFunc(e){e.beginPath(),e.arc(0,0,this.radius(),0,SE.Konva.getAngle(this.angle()),this.clockwise()),e.lineTo(0,0),e.closePath(),e.fillStrokeShape(this)}getWidth(){return this.radius()*2}getHeight(){return this.radius()*2}setWidth(e){this.radius(e/2)}setHeight(e){this.radius(e/2)}}Au.Wedge=Js,Js.prototype.className="Wedge",Js.prototype._centroid=!0,Js.prototype._attrsAffectingSize=["radius"],(0,EE._registerNode)(Js),bu.Factory.addGetterSetter(Js,"radius",0,(0,Dp.getNumberValidator)()),bu.Factory.addGetterSetter(Js,"angle",0,(0,Dp.getNumberValidator)()),bu.Factory.addGetterSetter(Js,"clockwise",!1),bu.Factory.backCompat(Js,{angleDeg:"angle",getAngleDeg:"getAngle",setAngleDeg:"setAngle"});var Ru={};Object.defineProperty(Ru,"__esModule",{value:!0}),Ru.Blur=void 0;const Np=Fe,CE=it,AE=Ne;function Pp(){this.r=0,this.g=0,this.b=0,this.a=0,this.next=null}const bE=[512,512,456,512,328,456,335,512,405,328,271,456,388,335,292,512,454,405,364,328,298,271,496,456,420,388,360,335,312,292,273,512,482,454,428,405,383,364,345,328,312,298,284,271,259,496,475,456,437,420,404,388,374,360,347,335,323,312,302,292,282,273,265,512,497,482,468,454,441,428,417,405,394,383,373,364,354,345,337,328,320,312,305,298,291,284,278,271,265,259,507,496,485,475,465,456,446,437,428,420,412,404,396,388,381,374,367,360,354,347,341,335,329,323,318,312,307,302,297,292,287,282,278,273,269,265,261,512,505,497,489,482,475,468,461,454,447,441,435,428,422,417,411,405,399,394,389,383,378,373,368,364,359,354,350,345,341,337,332,328,324,320,316,312,309,305,301,298,294,291,287,284,281,278,274,271,268,265,262,259,257,507,501,496,491,485,480,475,470,465,460,456,451,446,442,437,433,428,424,420,416,412,408,404,400,396,392,388,385,381,377,374,370,367,363,360,357,354,350,347,344,341,338,335,332,329,326,323,320,318,315,312,310,307,304,302,299,297,294,292,289,287,285,282,280,278,275,273,271,269,267,265,263,261,259],RE=[9,11,12,13,13,14,14,15,15,15,15,16,16,16,16,17,17,17,17,17,17,17,18,18,18,18,18,18,18,18,18,19,19,19,19,19,19,19,19,19,19,19,19,19,19,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24];function wE(u,e){const t=u.data,r=u.width,l=u.height;let s,i,f,h,d,p,v,T,y,S,A,R,O,N,C,b,w,F,q,D,P,I,x,U,B=e+e+1,z=r-1,L=l-1,V=e+1,J=V*(V+1)/2,Pe=new Pp,ee=null,j=Pe,K=null,ie=null,ue=bE[e],Ce=RE[e];for(f=1;f<B;f++)j=j.next=new Pp,f===V&&(ee=j);for(j.next=Pe,v=p=0,i=0;i<l;i++){for(b=w=F=q=T=y=S=A=0,R=V*(D=t[p]),O=V*(P=t[p+1]),N=V*(I=t[p+2]),C=V*(x=t[p+3]),T+=J*D,y+=J*P,S+=J*I,A+=J*x,j=Pe,f=0;f<V;f++)j.r=D,j.g=P,j.b=I,j.a=x,j=j.next;for(f=1;f<V;f++)h=p+((z<f?z:f)<<2),T+=(j.r=D=t[h])*(U=V-f),y+=(j.g=P=t[h+1])*U,S+=(j.b=I=t[h+2])*U,A+=(j.a=x=t[h+3])*U,b+=D,w+=P,F+=I,q+=x,j=j.next;for(K=Pe,ie=ee,s=0;s<r;s++)t[p+3]=x=A*ue>>Ce,x!==0?(x=255/x,t[p]=(T*ue>>Ce)*x,t[p+1]=(y*ue>>Ce)*x,t[p+2]=(S*ue>>Ce)*x):t[p]=t[p+1]=t[p+2]=0,T-=R,y-=O,S-=N,A-=C,R-=K.r,O-=K.g,N-=K.b,C-=K.a,h=v+((h=s+e+1)<z?h:z)<<2,b+=K.r=t[h],w+=K.g=t[h+1],F+=K.b=t[h+2],q+=K.a=t[h+3],T+=b,y+=w,S+=F,A+=q,K=K.next,R+=D=ie.r,O+=P=ie.g,N+=I=ie.b,C+=x=ie.a,b-=D,w-=P,F-=I,q-=x,ie=ie.next,p+=4;v+=r}for(s=0;s<r;s++){for(w=F=q=b=y=S=A=T=0,p=s<<2,R=V*(D=t[p]),O=V*(P=t[p+1]),N=V*(I=t[p+2]),C=V*(x=t[p+3]),T+=J*D,y+=J*P,S+=J*I,A+=J*x,j=Pe,f=0;f<V;f++)j.r=D,j.g=P,j.b=I,j.a=x,j=j.next;for(d=r,f=1;f<=e;f++)p=d+s<<2,T+=(j.r=D=t[p])*(U=V-f),y+=(j.g=P=t[p+1])*U,S+=(j.b=I=t[p+2])*U,A+=(j.a=x=t[p+3])*U,b+=D,w+=P,F+=I,q+=x,j=j.next,f<L&&(d+=r);for(p=s,K=Pe,ie=ee,i=0;i<l;i++)h=p<<2,t[h+3]=x=A*ue>>Ce,x>0?(x=255/x,t[h]=(T*ue>>Ce)*x,t[h+1]=(y*ue>>Ce)*x,t[h+2]=(S*ue>>Ce)*x):t[h]=t[h+1]=t[h+2]=0,T-=R,y-=O,S-=N,A-=C,R-=K.r,O-=K.g,N-=K.b,C-=K.a,h=s+((h=i+V)<L?h:L)*r<<2,T+=b+=K.r=t[h],y+=w+=K.g=t[h+1],S+=F+=K.b=t[h+2],A+=q+=K.a=t[h+3],K=K.next,R+=D=ie.r,O+=P=ie.g,N+=I=ie.b,C+=x=ie.a,b-=D,w-=P,F-=I,q-=x,ie=ie.next,p+=r}}const IE=function(e){const t=Math.round(this.blurRadius());t>0&&wE(e,t)};Ru.Blur=IE,Np.Factory.addGetterSetter(CE.Node,"blurRadius",0,(0,AE.getNumberValidator)(),Np.Factory.afterSetFilter);var wu={};Object.defineProperty(wu,"__esModule",{value:!0}),wu.Brighten=void 0;const xp=Fe,OE=it,DE=Ne,NE=function(u){let e=this.brightness()*255,t=u.data,r=t.length,l;for(l=0;l<r;l+=4)t[l]+=e,t[l+1]+=e,t[l+2]+=e};wu.Brighten=NE,xp.Factory.addGetterSetter(OE.Node,"brightness",0,(0,DE.getNumberValidator)(),xp.Factory.afterSetFilter);var Iu={};Object.defineProperty(Iu,"__esModule",{value:!0}),Iu.Contrast=void 0;const kp=Fe,PE=it,xE=Ne,kE=function(u){const e=Math.pow((this.contrast()+100)/100,2);let t=u.data,r=t.length,l=150,s=150,i=150,f;for(f=0;f<r;f+=4)l=t[f],s=t[f+1],i=t[f+2],l/=255,l-=.5,l*=e,l+=.5,l*=255,s/=255,s-=.5,s*=e,s+=.5,s*=255,i/=255,i-=.5,i*=e,i+=.5,i*=255,l=l<0?0:l>255?255:l,s=s<0?0:s>255?255:s,i=i<0?0:i>255?255:i,t[f]=l,t[f+1]=s,t[f+2]=i};Iu.Contrast=kE,kp.Factory.addGetterSetter(PE.Node,"contrast",0,(0,xE.getNumberValidator)(),kp.Factory.afterSetFilter);var Ou={};Object.defineProperty(Ou,"__esModule",{value:!0}),Ou.Emboss=void 0;const Cn=Fe,Du=it,ME=rt,Mp=Ne,UE=function(u){let e=this.embossStrength()*10,t=this.embossWhiteLevel()*255,r=this.embossDirection(),l=this.embossBlend(),s=0,i=0,f=u.data,h=u.width,d=u.height,p=h*4,v=d;switch(r){case"top-left":s=-1,i=-1;break;case"top":s=-1,i=0;break;case"top-right":s=-1,i=1;break;case"right":s=0,i=1;break;case"bottom-right":s=1,i=1;break;case"bottom":s=1,i=0;break;case"bottom-left":s=1,i=-1;break;case"left":s=0,i=-1;break;default:ME.Util.error("Unknown emboss direction: "+r)}do{const T=(v-1)*p;let y=s;v+y<1&&(y=0),v+y>d&&(y=0);const S=(v-1+y)*h*4;let A=h;do{const R=T+(A-1)*4;let O=i;A+O<1&&(O=0),A+O>h&&(O=0);const N=S+(A-1+O)*4,C=f[R]-f[N],b=f[R+1]-f[N+1],w=f[R+2]-f[N+2];let F=C;const q=F>0?F:-F,D=b>0?b:-b,P=w>0?w:-w;if(D>q&&(F=b),P>q&&(F=w),F*=e,l){const I=f[R]+F,x=f[R+1]+F,U=f[R+2]+F;f[R]=I>255?255:I<0?0:I,f[R+1]=x>255?255:x<0?0:x,f[R+2]=U>255?255:U<0?0:U}else{let I=t-F;I<0?I=0:I>255&&(I=255),f[R]=f[R+1]=f[R+2]=I}}while(--A)}while(--v)};Ou.Emboss=UE,Cn.Factory.addGetterSetter(Du.Node,"embossStrength",.5,(0,Mp.getNumberValidator)(),Cn.Factory.afterSetFilter),Cn.Factory.addGetterSetter(Du.Node,"embossWhiteLevel",.5,(0,Mp.getNumberValidator)(),Cn.Factory.afterSetFilter),Cn.Factory.addGetterSetter(Du.Node,"embossDirection","top-left",null,Cn.Factory.afterSetFilter),Cn.Factory.addGetterSetter(Du.Node,"embossBlend",!1,null,Cn.Factory.afterSetFilter);var Nu={};Object.defineProperty(Nu,"__esModule",{value:!0}),Nu.Enhance=void 0;const Up=Fe,LE=it,FE=Ne;function Af(u,e,t,r,l){let s=t-e,i=l-r,f;return s===0?r+i/2:i===0?r:(f=(u-e)/s,f=i*f+r,f)}const $E=function(u){let e=u.data,t=e.length,r=e[0],l=r,s,i=e[1],f=i,h,d=e[2],p=d,v,T;const y=this.enhance();if(y===0)return;for(T=0;T<t;T+=4)s=e[T+0],s<r?r=s:s>l&&(l=s),h=e[T+1],h<i?i=h:h>f&&(f=h),v=e[T+2],v<d?d=v:v>p&&(p=v);l===r&&(l=255,r=0),f===i&&(f=255,i=0),p===d&&(p=255,d=0);let S,A,R,O,N,C,b,w,F;for(y>0?(A=l+y*(255-l),R=r-y*(r-0),N=f+y*(255-f),C=i-y*(i-0),w=p+y*(255-p),F=d-y*(d-0)):(S=(l+r)*.5,A=l+y*(l-S),R=r+y*(r-S),O=(f+i)*.5,N=f+y*(f-O),C=i+y*(i-O),b=(p+d)*.5,w=p+y*(p-b),F=d+y*(d-b)),T=0;T<t;T+=4)e[T+0]=Af(e[T+0],r,l,R,A),e[T+1]=Af(e[T+1],i,f,C,N),e[T+2]=Af(e[T+2],d,p,F,w)};Nu.Enhance=$E,Up.Factory.addGetterSetter(LE.Node,"enhance",0,(0,FE.getNumberValidator)(),Up.Factory.afterSetFilter);var Pu={};Object.defineProperty(Pu,"__esModule",{value:!0}),Pu.Grayscale=void 0;const HE=function(u){let e=u.data,t=e.length,r,l;for(r=0;r<t;r+=4)l=.34*e[r]+.5*e[r+1]+.16*e[r+2],e[r]=l,e[r+1]=l,e[r+2]=l};Pu.Grayscale=HE;var xu={};Object.defineProperty(xu,"__esModule",{value:!0}),xu.HSL=void 0;const Xi=Fe,bf=it,Rf=Ne;Xi.Factory.addGetterSetter(bf.Node,"hue",0,(0,Rf.getNumberValidator)(),Xi.Factory.afterSetFilter),Xi.Factory.addGetterSetter(bf.Node,"saturation",0,(0,Rf.getNumberValidator)(),Xi.Factory.afterSetFilter),Xi.Factory.addGetterSetter(bf.Node,"luminance",0,(0,Rf.getNumberValidator)(),Xi.Factory.afterSetFilter);const GE=function(u){let e=u.data,t=e.length,r=1,l=Math.pow(2,this.saturation()),s=Math.abs(this.hue()+360)%360,i=this.luminance()*127,f;const h=r*l*Math.cos(s*Math.PI/180),d=r*l*Math.sin(s*Math.PI/180),p=.299*r+.701*h+.167*d,v=.587*r-.587*h+.33*d,T=.114*r-.114*h-.497*d,y=.299*r-.299*h-.328*d,S=.587*r+.413*h+.035*d,A=.114*r-.114*h+.293*d,R=.299*r-.3*h+1.25*d,O=.587*r-.586*h-1.05*d,N=.114*r+.886*h-.2*d;let C,b,w,F;for(f=0;f<t;f+=4)C=e[f+0],b=e[f+1],w=e[f+2],F=e[f+3],e[f+0]=p*C+v*b+T*w+i,e[f+1]=y*C+S*b+A*w+i,e[f+2]=R*C+O*b+N*w+i,e[f+3]=F};xu.HSL=GE;var ku={};Object.defineProperty(ku,"__esModule",{value:!0}),ku.HSV=void 0;const Ji=Fe,wf=it,If=Ne,VE=function(u){const e=u.data,t=e.length,r=Math.pow(2,this.value()),l=Math.pow(2,this.saturation()),s=Math.abs(this.hue()+360)%360,i=r*l*Math.cos(s*Math.PI/180),f=r*l*Math.sin(s*Math.PI/180),h=.299*r+.701*i+.167*f,d=.587*r-.587*i+.33*f,p=.114*r-.114*i-.497*f,v=.299*r-.299*i-.328*f,T=.587*r+.413*i+.035*f,y=.114*r-.114*i+.293*f,S=.299*r-.3*i+1.25*f,A=.587*r-.586*i-1.05*f,R=.114*r+.886*i-.2*f;let O,N,C,b;for(let w=0;w<t;w+=4)O=e[w+0],N=e[w+1],C=e[w+2],b=e[w+3],e[w+0]=h*O+d*N+p*C,e[w+1]=v*O+T*N+y*C,e[w+2]=S*O+A*N+R*C,e[w+3]=b};ku.HSV=VE,Ji.Factory.addGetterSetter(wf.Node,"hue",0,(0,If.getNumberValidator)(),Ji.Factory.afterSetFilter),Ji.Factory.addGetterSetter(wf.Node,"saturation",0,(0,If.getNumberValidator)(),Ji.Factory.afterSetFilter),Ji.Factory.addGetterSetter(wf.Node,"value",0,(0,If.getNumberValidator)(),Ji.Factory.afterSetFilter);var Mu={};Object.defineProperty(Mu,"__esModule",{value:!0}),Mu.Invert=void 0;const BE=function(u){let e=u.data,t=e.length,r;for(r=0;r<t;r+=4)e[r]=255-e[r],e[r+1]=255-e[r+1],e[r+2]=255-e[r+2]};Mu.Invert=BE;var Uu={};Object.defineProperty(Uu,"__esModule",{value:!0}),Uu.Kaleidoscope=void 0;const Lu=Fe,Lp=it,Fp=rt,$p=Ne,jE=function(u,e,t){let r=u.data,l=e.data,s=u.width,i=u.height,f=t.polarCenterX||s/2,h=t.polarCenterY||i/2,d,p,v,T=0,y=0,S=0,A=0,R,O=Math.sqrt(f*f+h*h);p=s-f,v=i-h,R=Math.sqrt(p*p+v*v),O=R>O?R:O;let N=i,C=s,b,w,F=360/C*Math.PI/180,q,D;for(w=0;w<C;w+=1)for(q=Math.sin(w*F),D=Math.cos(w*F),b=0;b<N;b+=1)p=Math.floor(f+O*b/N*D),v=Math.floor(h+O*b/N*q),d=(v*s+p)*4,T=r[d+0],y=r[d+1],S=r[d+2],A=r[d+3],d=(w+b*s)*4,l[d+0]=T,l[d+1]=y,l[d+2]=S,l[d+3]=A},qE=function(u,e,t){let r=u.data,l=e.data,s=u.width,i=u.height,f=t.polarCenterX||s/2,h=t.polarCenterY||i/2,d,p,v,T,y,S=0,A=0,R=0,O=0,N,C=Math.sqrt(f*f+h*h);p=s-f,v=i-h,N=Math.sqrt(p*p+v*v),C=N>C?N:C;let b=i,w=s,F,q,D=t.polarRotation||0,P,I;for(p=0;p<s;p+=1)for(v=0;v<i;v+=1)T=p-f,y=v-h,F=Math.sqrt(T*T+y*y)*b/C,q=(Math.atan2(y,T)*180/Math.PI+360+D)%360,q=q*w/360,P=Math.floor(q),I=Math.floor(F),d=(I*s+P)*4,S=r[d+0],A=r[d+1],R=r[d+2],O=r[d+3],d=(v*s+p)*4,l[d+0]=S,l[d+1]=A,l[d+2]=R,l[d+3]=O},WE=function(u){const e=u.width,t=u.height;let r,l,s,i,f,h,d,p,v,T,y=Math.round(this.kaleidoscopePower());const S=Math.round(this.kaleidoscopeAngle()),A=Math.floor(e*(S%360)/360);if(y<1)return;const R=Fp.Util.createCanvasElement();R.width=e,R.height=t;const O=R.getContext("2d").getImageData(0,0,e,t);Fp.Util.releaseCanvas(R),jE(u,O,{polarCenterX:e/2,polarCenterY:t/2});let N=e/Math.pow(2,y);for(;N<=8;)N=N*2,y-=1;N=Math.ceil(N);let C=N,b=0,w=C,F=1;for(A+N>e&&(b=C,w=0,F=-1),l=0;l<t;l+=1)for(r=b;r!==w;r+=F)s=Math.round(r+A)%e,v=(e*l+s)*4,f=O.data[v+0],h=O.data[v+1],d=O.data[v+2],p=O.data[v+3],T=(e*l+r)*4,O.data[T+0]=f,O.data[T+1]=h,O.data[T+2]=d,O.data[T+3]=p;for(l=0;l<t;l+=1)for(C=Math.floor(N),i=0;i<y;i+=1){for(r=0;r<C+1;r+=1)v=(e*l+r)*4,f=O.data[v+0],h=O.data[v+1],d=O.data[v+2],p=O.data[v+3],T=(e*l+C*2-r-1)*4,O.data[T+0]=f,O.data[T+1]=h,O.data[T+2]=d,O.data[T+3]=p;C*=2}qE(O,u,{polarRotation:0})};Uu.Kaleidoscope=WE,Lu.Factory.addGetterSetter(Lp.Node,"kaleidoscopePower",2,(0,$p.getNumberValidator)(),Lu.Factory.afterSetFilter),Lu.Factory.addGetterSetter(Lp.Node,"kaleidoscopeAngle",0,(0,$p.getNumberValidator)(),Lu.Factory.afterSetFilter);var Fu={};Object.defineProperty(Fu,"__esModule",{value:!0}),Fu.Mask=void 0;const Hp=Fe,KE=it,YE=Ne;function $u(u,e,t){let r=(t*u.width+e)*4;const l=[];return l.push(u.data[r++],u.data[r++],u.data[r++],u.data[r++]),l}function Cl(u,e){return Math.sqrt(Math.pow(u[0]-e[0],2)+Math.pow(u[1]-e[1],2)+Math.pow(u[2]-e[2],2))}function zE(u){const e=[0,0,0];for(let t=0;t<u.length;t++)e[0]+=u[t][0],e[1]+=u[t][1],e[2]+=u[t][2];return e[0]/=u.length,e[1]/=u.length,e[2]/=u.length,e}function XE(u,e){const t=$u(u,0,0),r=$u(u,u.width-1,0),l=$u(u,0,u.height-1),s=$u(u,u.width-1,u.height-1),i=e||10;if(Cl(t,r)<i&&Cl(r,s)<i&&Cl(s,l)<i&&Cl(l,t)<i){const f=zE([r,t,s,l]),h=[];for(let d=0;d<u.width*u.height;d++){const p=Cl(f,[u.data[d*4],u.data[d*4+1],u.data[d*4+2]]);h[d]=p<i?0:255}return h}}function JE(u,e){for(let t=0;t<u.width*u.height;t++)u.data[4*t+3]=e[t]}function QE(u,e,t){const r=[1,1,1,1,0,1,1,1,1],l=Math.round(Math.sqrt(r.length)),s=Math.floor(l/2),i=[];for(let f=0;f<t;f++)for(let h=0;h<e;h++){const d=f*e+h;let p=0;for(let v=0;v<l;v++)for(let T=0;T<l;T++){const y=f+v-s,S=h+T-s;if(y>=0&&y<t&&S>=0&&S<e){const A=y*e+S,R=r[v*l+T];p+=u[A]*R}}i[d]=p===2040?255:0}return i}function ZE(u,e,t){const r=[1,1,1,1,1,1,1,1,1],l=Math.round(Math.sqrt(r.length)),s=Math.floor(l/2),i=[];for(let f=0;f<t;f++)for(let h=0;h<e;h++){const d=f*e+h;let p=0;for(let v=0;v<l;v++)for(let T=0;T<l;T++){const y=f+v-s,S=h+T-s;if(y>=0&&y<t&&S>=0&&S<e){const A=y*e+S,R=r[v*l+T];p+=u[A]*R}}i[d]=p>=1020?255:0}return i}function eC(u,e,t){const r=[.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111],l=Math.round(Math.sqrt(r.length)),s=Math.floor(l/2),i=[];for(let f=0;f<t;f++)for(let h=0;h<e;h++){const d=f*e+h;let p=0;for(let v=0;v<l;v++)for(let T=0;T<l;T++){const y=f+v-s,S=h+T-s;if(y>=0&&y<t&&S>=0&&S<e){const A=y*e+S,R=r[v*l+T];p+=u[A]*R}}i[d]=p}return i}const tC=function(u){let e=this.threshold(),t=XE(u,e);return t&&(t=QE(t,u.width,u.height),t=ZE(t,u.width,u.height),t=eC(t,u.width,u.height),JE(u,t)),u};Fu.Mask=tC,Hp.Factory.addGetterSetter(KE.Node,"threshold",0,(0,YE.getNumberValidator)(),Hp.Factory.afterSetFilter);var Hu={};Object.defineProperty(Hu,"__esModule",{value:!0}),Hu.Noise=void 0;const Gp=Fe,sC=it,nC=Ne,iC=function(u){const e=this.noise()*255,t=u.data,r=t.length,l=e/2;for(let s=0;s<r;s+=4)t[s+0]+=l-2*l*Math.random(),t[s+1]+=l-2*l*Math.random(),t[s+2]+=l-2*l*Math.random()};Hu.Noise=iC,Gp.Factory.addGetterSetter(sC.Node,"noise",.2,(0,nC.getNumberValidator)(),Gp.Factory.afterSetFilter);var Gu={};Object.defineProperty(Gu,"__esModule",{value:!0}),Gu.Pixelate=void 0;const Vp=Fe,rC=rt,lC=it,aC=Ne,oC=function(u){let e=Math.ceil(this.pixelSize()),t=u.width,r=u.height,l,s,i,f,h,d,p,v=Math.ceil(t/e),T=Math.ceil(r/e),y,S,A,R,O,N,C,b=u.data;if(e<=0){rC.Util.error("pixelSize value can not be <= 0");return}for(O=0;O<v;O+=1)for(N=0;N<T;N+=1){for(f=0,h=0,d=0,p=0,y=O*e,S=y+e,A=N*e,R=A+e,C=0,l=y;l<S;l+=1)if(!(l>=t))for(s=A;s<R;s+=1)s>=r||(i=(t*s+l)*4,f+=b[i+0],h+=b[i+1],d+=b[i+2],p+=b[i+3],C+=1);for(f=f/C,h=h/C,d=d/C,p=p/C,l=y;l<S;l+=1)if(!(l>=t))for(s=A;s<R;s+=1)s>=r||(i=(t*s+l)*4,b[i+0]=f,b[i+1]=h,b[i+2]=d,b[i+3]=p)}};Gu.Pixelate=oC,Vp.Factory.addGetterSetter(lC.Node,"pixelSize",8,(0,aC.getNumberValidator)(),Vp.Factory.afterSetFilter);var Vu={};Object.defineProperty(Vu,"__esModule",{value:!0}),Vu.Posterize=void 0;const Bp=Fe,uC=it,cC=Ne,hC=function(u){let e=Math.round(this.levels()*254)+1,t=u.data,r=t.length,l=255/e,s;for(s=0;s<r;s+=1)t[s]=Math.floor(t[s]/l)*l};Vu.Posterize=hC,Bp.Factory.addGetterSetter(uC.Node,"levels",.5,(0,cC.getNumberValidator)(),Bp.Factory.afterSetFilter);var Bu={};Object.defineProperty(Bu,"__esModule",{value:!0}),Bu.RGB=void 0;const ju=Fe,Of=it,fC=Ne,dC=function(u){let e=u.data,t=e.length,r=this.red(),l=this.green(),s=this.blue(),i,f;for(i=0;i<t;i+=4)f=(.34*e[i]+.5*e[i+1]+.16*e[i+2])/255,e[i]=f*r,e[i+1]=f*l,e[i+2]=f*s,e[i+3]=e[i+3]};Bu.RGB=dC,ju.Factory.addGetterSetter(Of.Node,"red",0,function(u){return this._filterUpToDate=!1,u>255?255:u<0?0:Math.round(u)}),ju.Factory.addGetterSetter(Of.Node,"green",0,function(u){return this._filterUpToDate=!1,u>255?255:u<0?0:Math.round(u)}),ju.Factory.addGetterSetter(Of.Node,"blue",0,fC.RGBComponent,ju.Factory.afterSetFilter);var qu={};Object.defineProperty(qu,"__esModule",{value:!0}),qu.RGBA=void 0;const Al=Fe,Wu=it,_C=Ne,gC=function(u){const e=u.data,t=e.length,r=this.red(),l=this.green(),s=this.blue(),i=this.alpha();for(let f=0;f<t;f+=4){const h=1-i;e[f]=r*i+e[f]*h,e[f+1]=l*i+e[f+1]*h,e[f+2]=s*i+e[f+2]*h}};qu.RGBA=gC,Al.Factory.addGetterSetter(Wu.Node,"red",0,function(u){return this._filterUpToDate=!1,u>255?255:u<0?0:Math.round(u)}),Al.Factory.addGetterSetter(Wu.Node,"green",0,function(u){return this._filterUpToDate=!1,u>255?255:u<0?0:Math.round(u)}),Al.Factory.addGetterSetter(Wu.Node,"blue",0,_C.RGBComponent,Al.Factory.afterSetFilter),Al.Factory.addGetterSetter(Wu.Node,"alpha",1,function(u){return this._filterUpToDate=!1,u>1?1:u<0?0:u});var Ku={};Object.defineProperty(Ku,"__esModule",{value:!0}),Ku.Sepia=void 0;const pC=function(u){let e=u.data,t=e.length,r,l,s,i;for(r=0;r<t;r+=4)l=e[r+0],s=e[r+1],i=e[r+2],e[r+0]=Math.min(255,l*.393+s*.769+i*.189),e[r+1]=Math.min(255,l*.349+s*.686+i*.168),e[r+2]=Math.min(255,l*.272+s*.534+i*.131)};Ku.Sepia=pC;var Yu={};Object.defineProperty(Yu,"__esModule",{value:!0}),Yu.Solarize=void 0;const mC=function(u){const e=u.data,t=u.width,r=u.height,l=t*4;let s=r;do{const i=(s-1)*l;let f=t;do{const h=i+(f-1)*4;let d=e[h],p=e[h+1],v=e[h+2];d>127&&(d=255-d),p>127&&(p=255-p),v>127&&(v=255-v),e[h]=d,e[h+1]=p,e[h+2]=v}while(--f)}while(--s)};Yu.Solarize=mC;var zu={};Object.defineProperty(zu,"__esModule",{value:!0}),zu.Threshold=void 0;const jp=Fe,vC=it,TC=Ne,yC=function(u){const e=this.threshold()*255,t=u.data,r=t.length;for(let l=0;l<r;l+=1)t[l]=t[l]<e?0:255};zu.Threshold=yC,jp.Factory.addGetterSetter(vC.Node,"threshold",.5,(0,TC.getNumberValidator)(),jp.Factory.afterSetFilter),Object.defineProperty(Ko,"__esModule",{value:!0}),Ko.Konva=void 0;const qp=Ng,SC=iu,EC=au,CC=cu,AC=hu,bC=fu,Wp=Ki,RC=vl,wC=ji,IC=yl,OC=gu,DC=pu,NC=mu,PC=vu,xC=Yi,kC=Su,MC=Eu,UC=Au,LC=Ru,FC=wu,$C=Iu,HC=Ou,GC=Nu,VC=Pu,BC=xu,jC=ku,qC=Mu,WC=Uu,KC=Fu,YC=Hu,zC=Gu,XC=Vu,JC=Bu,QC=qu,ZC=Ku,eA=Yu,tA=zu;Ko.Konva=qp.Konva.Util._assign(qp.Konva,{Arc:SC.Arc,Arrow:EC.Arrow,Circle:CC.Circle,Ellipse:AC.Ellipse,Image:bC.Image,Label:Wp.Label,Tag:Wp.Tag,Line:RC.Line,Path:wC.Path,Rect:IC.Rect,RegularPolygon:OC.RegularPolygon,Ring:DC.Ring,Sprite:NC.Sprite,Star:PC.Star,Text:xC.Text,TextPath:kC.TextPath,Transformer:MC.Transformer,Wedge:UC.Wedge,Filters:{Blur:LC.Blur,Brighten:FC.Brighten,Contrast:$C.Contrast,Emboss:HC.Emboss,Enhance:GC.Enhance,Grayscale:VC.Grayscale,HSL:BC.HSL,HSV:jC.HSV,Invert:qC.Invert,Kaleidoscope:WC.Kaleidoscope,Mask:KC.Mask,Noise:YC.Noise,Pixelate:zC.Pixelate,Posterize:XC.Posterize,RGB:JC.RGB,RGBA:QC.RGBA,Sepia:ZC.Sepia,Solarize:eA.Solarize,Threshold:tA.Threshold}});var sA=Yh.exports;Object.defineProperty(sA,"__esModule",{value:!0});const nA=Ko;Yh.exports=nA.Konva;var iA=Yh.exports;const Qi=We(iA),Df={STROKE_WIDTH:5,STROKE_COLOR:"#f32",EMPTY_DRAWER_RECT_COLOR:"#fff"};class Nf{constructor(e){this.stage=null,this.strokeWidth=Df.STROKE_WIDTH,this.strokeColor=Df.STROKE_COLOR,this.emptyDrawerRectColor=Df.EMPTY_DRAWER_RECT_COLOR,this.emptyDrawerRect=null;const{container:t,width:r,height:l}=e,s=new Qi.Stage({container:t,width:r,height:l});this.stage=s,this.setupDrawerOptions(e)}setupDrawerOptions(e){e.strokeWidth&&(this.strokeWidth=e.strokeWidth),e.strokeColor&&(this.strokeColor=e.strokeColor),e.emptyDrawerRectColor&&(this.emptyDrawerRectColor=e.emptyDrawerRectColor,this.emptyDrawerRect&&this.emptyDrawerRect.fill(e.emptyDrawerRectColor))}addLayer(){const e=new Qi.Layer;return this.stage.add(e),e}initFreeDrawing(e){let t=!1,r;this.stage.on("mousedown touchstart",l=>{t=!0;const s=this.stage.getPointerPosition();r=new Qi.Line({stroke:this.strokeColor,strokeWidth:this.strokeWidth,globalCompositeOperation:"source-over",lineCap:"round",lineJoin:"round",points:[s.x,s.y,s.x,s.y]}),e.add(r)}),this.stage.on("mouseup touchend",()=>{t=!1}),this.stage.on("mousemove touchmove",l=>{if(!t)return;l.evt.preventDefault();const s=this.stage.getPointerPosition(),i=r.points().concat([s.x,s.y]);r.points(i)})}addRect(e,t,r){const l=new Qi.Rect({width:t,height:r,fill:this.emptyDrawerRectColor});return e.add(l),this.emptyDrawerRect=l,l}addImage(e,t){let r,l;const s=t.width/t.height;this.stage.width()<t.width?(r=this.stage.width(),l=this.stage.width()/s):(r=t.width,l=t.width/s);const i=new Qi.Image({image:t,x:(this.stage.width()-r)/2,y:(this.stage.height()-l)/2,width:r,height:l});return e.add(i),i}addWakeupLine(e){const t=new Qi.Line({stroke:"#ffffff",strokeWidth:1,globalCompositeOperation:"source-over",lineCap:"round",lineJoin:"round",points:[0,0,0,0]});e.add(t)}}class Pf extends Dg{constructor(e,t,r={}){super(e),this.stream=null,this.running=!1,this.immediate=!1,this.type="video",this.immediate=r.immediate||!1,this.type=t}start(e){return e}stop(){throw new Error("stop method is not implemented")}async process(e){if(this.immediate){const t=await this.start(e);return this.running=!0,t}return e}async connect(){this.running=!0,await this.session.resyncPlugins(this.type)}terminate(){this.stop()}async kill(){this.stop(),this.running=!1,await this.session.resyncPlugins(this.type)}}const rA={container:"screen-share-video-container",compositeCanvasContainer:"composite-canvas-container",compositeCanvas:"composite-canvas",drawerContainer:"container",videoElement:"whiteboard-source-video",videoElementContainer:"whiteboard-wrapper"};class lA extends Pf{constructor(e,t={}){super("ScreenShareWhiteboard","screen"),this.video=null,this.wrapperEl=null,this.screenShareKonvaDrawer=null,this.initialStream=null,this.imageSrc=null,this.konvaDrawer=null,this.mode=void 0,this.screenSharePlugin=null,this.selectors={},this.screenSharePlugin=e,this.selectors={...rA,...t.selectors||{}},this.selectors.document||(this.selectors.document=document)}createVideoElement(){const e=document.createElement("video");e.setAttribute("id",this.selectors.videoElement),e.setAttribute("autoplay",""),e.style.setProperty("visibility","hidden"),e.style.setProperty("width","auto"),e.style.setProperty("height","auto"),this.video=e;const t=document.createElement("div");t.classList.add(this.selectors.videoElementContainer),t.style.setProperty("display","none"),t.appendChild(e),this.wrapperEl=t,this.selectors.document.body?this.selectors.document.body.appendChild(t):this.selectors.document.appendChild(t)}getAspectRatioDimensions(e,t){const r=e.getTracks()[0].getSettings(),l=t.clientWidth,s=t.clientHeight,i=r.width,f=r.height,h=i/f,d=l/s;let p=0,v=0;return h>d?(p=l,v=l/h):(v=s,p=s*h),{width:p,height:v}}async start(e){this.createVideoElement(),this.initialStream=e,this.video.srcObject=e.clone();const t=this.selectors.document.getElementById(this.selectors.container);t.style.setProperty("position","relative"),t.style.setProperty("min-width","100%"),t.style.setProperty("height","100%"),t.style.setProperty("display","flex"),t.style.setProperty("justify-content","center");const r=this.selectors.document.getElementById(this.selectors.compositeCanvasContainer);r.style.setProperty("position","relative"),r.style.setProperty("margin","auto 0");const{width:l,height:s}=this.getAspectRatioDimensions(e,t);let i=l,f=s;const h=this.selectors.document.getElementById(this.selectors.drawerContainer);this.screenShareKonvaDrawer=new Nf({container:h,width:i,height:f});const d=this.screenShareKonvaDrawer.addLayer();this.screenShareKonvaDrawer.initFreeDrawing(d);const p=this.selectors.document.getElementById(this.selectors.drawerContainer),v=p.querySelector("canvas"),T=p.querySelector(".konvajs-content"),y=this.selectors.document.getElementById(this.selectors.compositeCanvas);y.style.setProperty("position","absolute"),y.style.setProperty("top","0"),y.style.setProperty("left","0");const S=y.getContext("2d"),A=()=>{const{width:N,height:C}=this.getAspectRatioDimensions(e,t);i=N,f=C,v.width=N,v.height=C,v.style.width=`${N}px`,v.style.height=`${C}px`,T.style.width=`${N}px`,T.style.height=`${C}px`,r.style.height=`${C}px`,y.width=N,y.height=C};A(),window.addEventListener("resize",()=>{A(),this.screenShareKonvaDrawer.addWakeupLine(d)});const R=this.video,O=()=>{S.drawImage(R,0,0,i,f),S.drawImage(v,0,0,i,f),requestAnimationFrame(O)};return O(),y.captureStream(30)}stop(){this.initialStream=null,this.video=null,this.wrapperEl=null,this.screenShareKonvaDrawer=null}setupScreenShareDrawerOptions(e){this.screenShareKonvaDrawer&&this.screenShareKonvaDrawer.setupDrawerOptions(e)}}function aA(u){return new Promise((e,t)=>{const r=new Image;r.onload=()=>{e(r)},r.onerror=l=>{t(l)},r.src=u})}const Kp={WHITEBOARD:"whiteboard",IMAGE_WHITEBOARD:"imageWhiteboard"},oA={container:"presentation-video-container",drawerContainer:"presentationCanvasWrapper"};class uA extends Wo{constructor(e){super("WhiteBoard"),this.visualizationConfig={},this.rafId=null,this.imageSrc=null,this.konvaDrawer=null,this.selectors={},this.mode=void 0,this.mode=e.mode,e.imageSrc&&(this.imageSrc=e.imageSrc),this.selectors={...oA,...e.selectors||{}},this.selectors.document||(this.selectors.document=document)}setupDrawerOptions(e){this.konvaDrawer&&this.konvaDrawer.setupDrawerOptions(e)}setMode(e,t){this.mode=e,t&&(this.imageSrc=t)}setupDrawerImage(e){this.imageSrc=e}drawEmptyWhiteboard(){const e=this.selectors.document.getElementById(this.selectors.container);e.style.setProperty("min-width","100%"),e.style.setProperty("height","100%");const t=e.clientWidth,r=e.clientHeight,l=this.selectors.document.getElementById(this.selectors.drawerContainer);this.konvaDrawer=new Nf({container:l,width:t,height:r});const s=this.konvaDrawer.addLayer();this.konvaDrawer.addRect(s,t,r),this.konvaDrawer.initFreeDrawing(s)}async drawImageWhiteboard(){const e=this.selectors.document.getElementById(this.selectors.container);e.style.setProperty("min-width","100%"),e.style.setProperty("height","100%");const t=e.clientWidth,r=e.clientHeight,l=await aA(this.imageSrc),s=this.selectors.document.getElementById(this.selectors.drawerContainer);this.konvaDrawer=new Nf({container:s,width:t,height:r});const i=this.konvaDrawer.addLayer();this.konvaDrawer.addImage(i,l),i.batchDraw(),this.konvaDrawer.initFreeDrawing(i)}async generateStream(){if(this.mode===Kp.WHITEBOARD)this.drawEmptyWhiteboard();else if(this.mode===Kp.IMAGE_WHITEBOARD)await this.drawImageWhiteboard();else return;const t=this.selectors.document.getElementById(this.selectors.drawerContainer).querySelector("canvas"),r=t.getContext("2d");function l(){r.fillRect(0,0,1,1),requestAnimationFrame(l)}l();const s=t.captureStream(30);this.stream=s}async kill(){this.konvaDrawer=null,await this.stop(),this.session._ua.emit("stopWhiteboard")}}const cA=Et,hA=_s(),Kt=new cA("WebSocketInterface");var fA=class{constructor(e){Kt.debug('new() [url:"%s"]',e),this._url=e,this._sip_uri=null,this._via_transport=null,this._ws=null;const t=hA.parse(e,"absoluteURI");if(t===-1)throw Kt.warn(`invalid WebSocket URI: ${e}`),new TypeError(`Invalid argument: ${e}`);if(t.scheme!=="wss"&&t.scheme!=="ws")throw Kt.warn(`invalid WebSocket URI scheme: ${t.scheme}`),new TypeError(`Invalid argument: ${e}`);this._sip_uri=`sip:${t.host}${t.port?`:${t.port}`:""};transport=ws`,this._via_transport=t.scheme.toUpperCase()}get via_transport(){return this._via_transport}set via_transport(e){this._via_transport=e.toUpperCase()}get sip_uri(){return this._sip_uri}get url(){return this._url}connect(){if(Kt.debug("connect()"),this.isConnected()){Kt.debug(`WebSocket ${this._url} is already connected`);return}else if(this.isConnecting()){Kt.debug(`WebSocket ${this._url} is connecting`);return}this._ws&&this.disconnect(),Kt.debug(`connecting to WebSocket ${this._url}`);try{this._ws=new WebSocket(this._url,"sip"),this._ws.binaryType="arraybuffer",this._ws.onopen=this._onOpen.bind(this),this._ws.onclose=this._onClose.bind(this),this._ws.onmessage=this._onMessage.bind(this),this._ws.onerror=this._onError.bind(this)}catch(e){this._onError(e)}}disconnect(){Kt.debug("disconnect()"),this._ws&&(this._ws.onopen=()=>{},this._ws.onclose=()=>{},this._ws.onmessage=()=>{},this._ws.onerror=()=>{},this._ws.close(),this._ws=null)}send(e){return Kt.debug("send()"),this.isConnected()?(this._ws.send(e),!0):(Kt.warn("unable to send message, WebSocket is not open"),!1)}isConnected(){return this._ws&&this._ws.readyState===this._ws.OPEN}isConnecting(){return this._ws&&this._ws.readyState===this._ws.CONNECTING}_onOpen(){Kt.debug(`WebSocket ${this._url} connected`),this.onconnect()}_onClose({wasClean:e,code:t,reason:r}){Kt.debug(`WebSocket ${this._url} closed`),e===!1&&Kt.debug("WebSocket abrupt disconnection"),this.ondisconnect(!e,t,r)}_onMessage({data:e}){Kt.debug("received WebSocket message"),this.ondata(e)}_onError(e){Kt.warn(`WebSocket ${this._url} error: `,e)}};const xf=Ha,dA=Ue,_A=Bs,gA=xt(),pA=Cg,mA=Hs(),vA=_h(),TA=_s(),yA=fA;Ii("JsSIP")("version %s",xf.version);var SA={C:dA,Exceptions:_A,Utils:gA,UA:pA,URI:mA,NameAddrHeader:vA,WebSocketInterface:yA,Grammar:TA,debug:Ii,get name(){return xf.title},get version(){return xf.version}};const EA=We(SA);function kf(u){return u<10?`0${u}`:`${u}`}function CA(u){let e=u.hours||0,t=u.minutes||0,r=u.seconds||0;r++,r===60&&(r=0,t++,t===60&&(t=0,e++));const l=`${kf(e)}:${kf(t)}:${kf(r)}`;return{seconds:r,minutes:t,hours:e,formatted:l}}var $t={};$t.forEach=async(u,e,t)=>{const r=[];for(let l=0;l<u.length;l++)if(l in u){const s=Promise.resolve(u[l]).then(i=>e.call(t||globalThis,i,l,u));r.push(s)}await Promise.all(r)},$t.forEachSeries=async(u,e,t)=>{for(let r=0;r<u.length;r++)r in u&&await e.call(t||globalThis,await u[r],r,u)},$t.map=async(u,e,t)=>{const r=[];for(let l=0;l<u.length;l++)l in u&&(r[l]=Promise.resolve(u[l]).then(s=>e.call(t||globalThis,s,l,u)));return Promise.all(r)},$t.mapSeries=async(u,e,t)=>{const r=[];for(let l=0;l<u.length;l++)l in u&&(r[l]=await e.call(t||globalThis,await u[l],l,u));return r},$t.find=(u,e,t)=>new Promise((r,l)=>{if(u.length===0)return r();let s=1;for(let i=0;i<u.length;i++){const f=h=>{h?r(u[i]):s===u.length&&r(),s++};Promise.resolve(u[i]).then(h=>e.call(t||globalThis,h,i,u)).then(f).catch(l)}}),$t.findSeries=async(u,e,t)=>{for(let r=0;r<u.length;r++)if(await e.call(t||globalThis,await u[r],r,u))return u[r]},$t.findIndex=(u,e,t)=>new Promise((r,l)=>{if(u.length===0)return r(-1);let s=1;for(let i=0;i<u.length;i++){const f=h=>{h?r(i):s===u.length&&r(-1),s++};Promise.resolve(u[i]).then(h=>e.call(t||globalThis,h,i,u)).then(f).catch(l)}}),$t.findIndexSeries=async(u,e,t)=>{for(let r=0;r<u.length;r++)if(await e.call(t||globalThis,await u[r],r,u))return r},$t.some=(u,e,t)=>new Promise((r,l)=>{if(u.length===0)return r(!1);let s=1;for(let i=0;i<u.length;i++){if(!(i in u)){s++;continue}const f=h=>{h?r(!0):s===u.length&&r(!1),s++};Promise.resolve(u[i]).then(h=>e.call(t||globalThis,h,i,u)).then(f).catch(l)}}),$t.someSeries=async(u,e,t)=>{for(let r=0;r<u.length;r++)if(r in u&&await e.call(t||globalThis,await u[r],r,u))return!0;return!1},$t.every=(u,e,t)=>new Promise((r,l)=>{if(u.length===0)return r(!0);let s=1;for(let i=0;i<u.length;i++){if(!(i in u)){s++;continue}const f=h=>{h?s===u.length&&r(!0):r(!1),s++};Promise.resolve(u[i]).then(h=>e.call(t||globalThis,h,i,u)).then(f).catch(l)}}),$t.everySeries=async(u,e,t)=>{for(let r=0;r<u.length;r++)if(r in u&&!await e.call(t||globalThis,await u[r],r,u))return!1;return!0},$t.filter=(u,e,t)=>new Promise(async(r,l)=>{const s=[];for(let f=0;f<u.length;f++)f in u&&(s[f]=Promise.resolve(u[f]).then(h=>e.call(t||globalThis,h,f,u)).catch(l));const i=[];for(let f=0;f<s.length;f++)await s[f]&&i.push(await u[f]);r(i)}),$t.filterSeries=async(u,e,t)=>{const r=[];for(let l=0;l<u.length;l++)l in u&&await e.call(t||globalThis,await u[l],l,u)&&r.push(await u[l]);return r},$t.reduce=async(u,e,t)=>{if(u.length===0&&t===void 0)throw TypeError("Reduce of empty array with no initial value");let r,l;for(t!==void 0?(l=t,r=0):(l=u[0],r=1),r;r<u.length;r++)r in u&&(l=await e(await l,await u[r],r,u));return l};var Yp={};(function(u){const e=$t;Object.keys(e).forEach(t=>{const r=t.charAt(0).toUpperCase()+t.slice(1);u[`async${r}`]=async function(...l){return e[t](this,...l)}})})(Yp);var AA=Object.assign($t,{instanceMethods:Yp});const ni=new AudioContext,ys={NEW_CALL:"new_call",CALL_CONFIRMED:"confirmed",CALL_FAILED:"failed",CALL_PROGRESS:"progress",CALL_ENDED:"ended"};var bA={exports:{}};(function(u){var e=function(t){var r=Object.prototype,l=r.hasOwnProperty,s=Object.defineProperty||function(ee,j,K){ee[j]=K.value},i,f=typeof Symbol=="function"?Symbol:{},h=f.iterator||"@@iterator",d=f.asyncIterator||"@@asyncIterator",p=f.toStringTag||"@@toStringTag";function v(ee,j,K){return Object.defineProperty(ee,j,{value:K,enumerable:!0,configurable:!0,writable:!0}),ee[j]}try{v({},"")}catch{v=function(j,K,ie){return j[K]=ie}}function T(ee,j,K,ie){var ue=j&&j.prototype instanceof C?j:C,Ce=Object.create(ue.prototype),ke=new V(ie||[]);return s(Ce,"_invoke",{value:U(ee,K,ke)}),Ce}t.wrap=T;function y(ee,j,K){try{return{type:"normal",arg:ee.call(j,K)}}catch(ie){return{type:"throw",arg:ie}}}var S="suspendedStart",A="suspendedYield",R="executing",O="completed",N={};function C(){}function b(){}function w(){}var F={};v(F,h,function(){return this});var q=Object.getPrototypeOf,D=q&&q(q(J([])));D&&D!==r&&l.call(D,h)&&(F=D);var P=w.prototype=C.prototype=Object.create(F);b.prototype=w,s(P,"constructor",{value:w,configurable:!0}),s(w,"constructor",{value:b,configurable:!0}),b.displayName=v(w,p,"GeneratorFunction");function I(ee){["next","throw","return"].forEach(function(j){v(ee,j,function(K){return this._invoke(j,K)})})}t.isGeneratorFunction=function(ee){var j=typeof ee=="function"&&ee.constructor;return j?j===b||(j.displayName||j.name)==="GeneratorFunction":!1},t.mark=function(ee){return Object.setPrototypeOf?Object.setPrototypeOf(ee,w):(ee.__proto__=w,v(ee,p,"GeneratorFunction")),ee.prototype=Object.create(P),ee},t.awrap=function(ee){return{__await:ee}};function x(ee,j){function K(Ce,ke,be,M){var Y=y(ee[Ce],ee,ke);if(Y.type==="throw")M(Y.arg);else{var Ee=Y.arg,Me=Ee.value;return Me&&typeof Me=="object"&&l.call(Me,"__await")?j.resolve(Me.__await).then(function(fe){K("next",fe,be,M)},function(fe){K("throw",fe,be,M)}):j.resolve(Me).then(function(fe){Ee.value=fe,be(Ee)},function(fe){return K("throw",fe,be,M)})}}var ie;function ue(Ce,ke){function be(){return new j(function(M,Y){K(Ce,ke,M,Y)})}return ie=ie?ie.then(be,be):be()}s(this,"_invoke",{value:ue})}I(x.prototype),v(x.prototype,d,function(){return this}),t.AsyncIterator=x,t.async=function(ee,j,K,ie,ue){ue===void 0&&(ue=Promise);var Ce=new x(T(ee,j,K,ie),ue);return t.isGeneratorFunction(j)?Ce:Ce.next().then(function(ke){return ke.done?ke.value:Ce.next()})};function U(ee,j,K){var ie=S;return function(Ce,ke){if(ie===R)throw new Error("Generator is already running");if(ie===O){if(Ce==="throw")throw ke;return Pe()}for(K.method=Ce,K.arg=ke;;){var be=K.delegate;if(be){var M=B(be,K);if(M){if(M===N)continue;return M}}if(K.method==="next")K.sent=K._sent=K.arg;else if(K.method==="throw"){if(ie===S)throw ie=O,K.arg;K.dispatchException(K.arg)}else K.method==="return"&&K.abrupt("return",K.arg);ie=R;var Y=y(ee,j,K);if(Y.type==="normal"){if(ie=K.done?O:A,Y.arg===N)continue;return{value:Y.arg,done:K.done}}else Y.type==="throw"&&(ie=O,K.method="throw",K.arg=Y.arg)}}}function B(ee,j){var K=j.method,ie=ee.iterator[K];if(ie===i)return j.delegate=null,K==="throw"&&ee.iterator.return&&(j.method="return",j.arg=i,B(ee,j),j.method==="throw")||K!=="return"&&(j.method="throw",j.arg=new TypeError("The iterator does not provide a '"+K+"' method")),N;var ue=y(ie,ee.iterator,j.arg);if(ue.type==="throw")return j.method="throw",j.arg=ue.arg,j.delegate=null,N;var Ce=ue.arg;if(!Ce)return j.method="throw",j.arg=new TypeError("iterator result is not an object"),j.delegate=null,N;if(Ce.done)j[ee.resultName]=Ce.value,j.next=ee.nextLoc,j.method!=="return"&&(j.method="next",j.arg=i);else return Ce;return j.delegate=null,N}I(P),v(P,p,"Generator"),v(P,h,function(){return this}),v(P,"toString",function(){return"[object Generator]"});function z(ee){var j={tryLoc:ee[0]};1 in ee&&(j.catchLoc=ee[1]),2 in ee&&(j.finallyLoc=ee[2],j.afterLoc=ee[3]),this.tryEntries.push(j)}function L(ee){var j=ee.completion||{};j.type="normal",delete j.arg,ee.completion=j}function V(ee){this.tryEntries=[{tryLoc:"root"}],ee.forEach(z,this),this.reset(!0)}t.keys=function(ee){var j=Object(ee),K=[];for(var ie in j)K.push(ie);return K.reverse(),function ue(){for(;K.length;){var Ce=K.pop();if(Ce in j)return ue.value=Ce,ue.done=!1,ue}return ue.done=!0,ue}};function J(ee){if(ee){var j=ee[h];if(j)return j.call(ee);if(typeof ee.next=="function")return ee;if(!isNaN(ee.length)){var K=-1,ie=function ue(){for(;++K<ee.length;)if(l.call(ee,K))return ue.value=ee[K],ue.done=!1,ue;return ue.value=i,ue.done=!0,ue};return ie.next=ie}}return{next:Pe}}t.values=J;function Pe(){return{value:i,done:!0}}return V.prototype={constructor:V,reset:function(ee){if(this.prev=0,this.next=0,this.sent=this._sent=i,this.done=!1,this.delegate=null,this.method="next",this.arg=i,this.tryEntries.forEach(L),!ee)for(var j in this)j.charAt(0)==="t"&&l.call(this,j)&&!isNaN(+j.slice(1))&&(this[j]=i)},stop:function(){this.done=!0;var ee=this.tryEntries[0],j=ee.completion;if(j.type==="throw")throw j.arg;return this.rval},dispatchException:function(ee){if(this.done)throw ee;var j=this;function K(M,Y){return Ce.type="throw",Ce.arg=ee,j.next=M,Y&&(j.method="next",j.arg=i),!!Y}for(var ie=this.tryEntries.length-1;ie>=0;--ie){var ue=this.tryEntries[ie],Ce=ue.completion;if(ue.tryLoc==="root")return K("end");if(ue.tryLoc<=this.prev){var ke=l.call(ue,"catchLoc"),be=l.call(ue,"finallyLoc");if(ke&&be){if(this.prev<ue.catchLoc)return K(ue.catchLoc,!0);if(this.prev<ue.finallyLoc)return K(ue.finallyLoc)}else if(ke){if(this.prev<ue.catchLoc)return K(ue.catchLoc,!0)}else if(be){if(this.prev<ue.finallyLoc)return K(ue.finallyLoc)}else throw new Error("try statement without catch or finally")}}},abrupt:function(ee,j){for(var K=this.tryEntries.length-1;K>=0;--K){var ie=this.tryEntries[K];if(ie.tryLoc<=this.prev&&l.call(ie,"finallyLoc")&&this.prev<ie.finallyLoc){var ue=ie;break}}ue&&(ee==="break"||ee==="continue")&&ue.tryLoc<=j&&j<=ue.finallyLoc&&(ue=null);var Ce=ue?ue.completion:{};return Ce.type=ee,Ce.arg=j,ue?(this.method="next",this.next=ue.finallyLoc,N):this.complete(Ce)},complete:function(ee,j){if(ee.type==="throw")throw ee.arg;return ee.type==="break"||ee.type==="continue"?this.next=ee.arg:ee.type==="return"?(this.rval=this.arg=ee.arg,this.method="return",this.next="end"):ee.type==="normal"&&j&&(this.next=j),N},finish:function(ee){for(var j=this.tryEntries.length-1;j>=0;--j){var K=this.tryEntries[j];if(K.finallyLoc===ee)return this.complete(K.completion,K.afterLoc),L(K),N}},catch:function(ee){for(var j=this.tryEntries.length-1;j>=0;--j){var K=this.tryEntries[j];if(K.tryLoc===ee){var ie=K.completion;if(ie.type==="throw"){var ue=ie.arg;L(K)}return ue}}throw new Error("illegal catch attempt")},delegateYield:function(ee,j,K){return this.delegate={iterator:J(ee),resultName:j,nextLoc:K},this.method==="next"&&(this.arg=i),N}},t}(u.exports);try{regeneratorRuntime=e}catch{typeof globalThis=="object"?globalThis.regeneratorRuntime=e:Function("r","regeneratorRuntime = r")(e)}})(bA);var zp={exports:{}};(function(u){(function(e,t){u.exports?u.exports=t():e.log=t()})(fs,function(){var e=function(){},t="undefined",r=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),l=["trace","debug","info","warn","error"];function s(A,R){var O=A[R];if(typeof O.bind=="function")return O.bind(A);try{return Function.prototype.bind.call(O,A)}catch{return function(){return Function.prototype.apply.apply(O,[A,arguments])}}}function i(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function f(A){return A==="debug"&&(A="log"),typeof console===t?!1:A==="trace"&&r?i:console[A]!==void 0?s(console,A):console.log!==void 0?s(console,"log"):e}function h(A,R){for(var O=0;O<l.length;O++){var N=l[O];this[N]=O<A?e:this.methodFactory(N,A,R)}this.log=this.debug}function d(A,R,O){return function(){typeof console!==t&&(h.call(this,R,O),this[A].apply(this,arguments))}}function p(A,R,O){return f(A)||d.apply(this,arguments)}function v(A,R,O){var N=this,C;R=R??"WARN";var b="loglevel";typeof A=="string"?b+=":"+A:typeof A=="symbol"&&(b=void 0);function w(P){var I=(l[P]||"silent").toUpperCase();if(!(typeof window===t||!b)){try{window.localStorage[b]=I;return}catch{}try{window.document.cookie=encodeURIComponent(b)+"="+I+";"}catch{}}}function F(){var P;if(!(typeof window===t||!b)){try{P=window.localStorage[b]}catch{}if(typeof P===t)try{var I=window.document.cookie,x=I.indexOf(encodeURIComponent(b)+"=");x!==-1&&(P=/^([^;]+)/.exec(I.slice(x))[1])}catch{}return N.levels[P]===void 0&&(P=void 0),P}}function q(){if(!(typeof window===t||!b)){try{window.localStorage.removeItem(b);return}catch{}try{window.document.cookie=encodeURIComponent(b)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}N.name=A,N.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},N.methodFactory=O||p,N.getLevel=function(){return C},N.setLevel=function(P,I){if(typeof P=="string"&&N.levels[P.toUpperCase()]!==void 0&&(P=N.levels[P.toUpperCase()]),typeof P=="number"&&P>=0&&P<=N.levels.SILENT){if(C=P,I!==!1&&w(P),h.call(N,P,A),typeof console===t&&P<N.levels.SILENT)return"No console available for logging"}else throw"log.setLevel() called with invalid level: "+P},N.setDefaultLevel=function(P){R=P,F()||N.setLevel(P,!1)},N.resetLevel=function(){N.setLevel(R,!1),q()},N.enableAll=function(P){N.setLevel(N.levels.TRACE,P)},N.disableAll=function(P){N.setLevel(N.levels.SILENT,P)};var D=F();D==null&&(D=R),N.setLevel(D,!1)}var T=new v,y={};T.getLogger=function(R){if(typeof R!="symbol"&&typeof R!="string"||R==="")throw new TypeError("You must supply a name when creating a logger.");var O=y[R];return O||(O=y[R]=new v(R,T.getLevel(),T.methodFactory)),O};var S=typeof window!==t?window.log:void 0;return T.noConflict=function(){return typeof window!==t&&window.log===T&&(window.log=S),T},T.getLoggers=function(){return y},T.default=T,T})})(zp);var jt=zp.exports;const Qs=()=>`${new Date().toISOString()} | metrics`,Zs=(u,e,t)=>`${u} | ${e} | ${t}`;jt.setDefaultLevel(jt.levels.TRACE);const RA=u=>{jt.info(Zs(Qs(),"log ",`set log level to ${u?"verbose":"info"}`)),jt.setLevel(u?jt.levels.TRACE:jt.levels.INFO)},wA=u=>{const e=[...Object.keys(jt.levels)];e.includes(u)?(jt.info(Zs(Qs(),"log ",`update log level to ${u.toLowerCase()}`)),jt.setLevel(u)):jt.warn(Zs(Qs(),"log ","Incorrect log level please choose one of "),e)},Be=(u,e,t)=>{t?jt.debug(Zs(Qs(),u,e),t):jt.debug(Zs(Qs(),u,e))},Mf=(u,e)=>{jt.info(Zs(Qs(),u,e))},ii=(u,e)=>{jt.info(Zs(Qs(),u,e))},Xu=(u,e)=>{jt.warn(Zs(Qs(),u,e))},Zi=(u,e)=>{jt.error(Zs(Qs(),u,e))};function IA(u){return Math.floor(Math.random()*u).toString()}function Xp(u,e){let t=e;return u.forEach(r=>{t=t.replace(r,"")}),t}function OA(u,e){let t="";for(let r=0;r<e;r+=1)t+=u[IA(u.length)];return t}function DA({length:u=20,useLetters:e=!0,useNumbers:t=!0,includeSymbols:r=[],excludeSymbols:l=[]}={}){let s="abcdefghijklmnopqrstuvwxyz",i="0123456789",f=[],h=[],d=[];return e&&(l.length&&(s=Xp(l,s)),h=s.split("")),t&&(l.length&&(i=Xp(l,i)),d=i.split("")),f=[...h,...d,...r],OA(f,u)}var NA=DA;const bl=We(NA),PA=()=>"WebRTCMetrics",xA=()=>"5.0.3",Xe={INBOUND:"inbound",OUTBOUND:"outbound"},en={IDLE:"idle",RUNNING:"running",MUTED:"muted"},Rl={NEW:"new",CHECKING:"checking",CONNECTED:"connected",COMPLETED:"completed",DISCONNECTED:"disconnected",FAILED:"failed",CLOSED:"closed"},kA=()=>({...{delta_time_to_measure_probes_ms:0,delta_time_consumed_to_measure_ms:0,delta_KBytes_in:0,delta_KBytes_out:0,delta_kbs_in:0,delta_kbs_out:0,total_time_decoded_in:0,total_time_encoded_out:0,probes:[]}}),Jp={level_in:0,codec_id_in:"",codec_in:{mime_type:null,clock_rate:null,sdp_fmtp_line:null},delta_jitter_ms_in:0,percent_packets_lost_in:0,delta_packets_in:0,delta_packets_lost_in:0,total_packets_in:0,total_packets_lost_in:0,total_KBytes_in:0,delta_KBytes_in:0,delta_kbs_in:0,mos_in:0,mos_emodel_in:0,ssrc:"",direction:Xe.INBOUND},Qp={level_out:0,codec_id_out:"",codec_out:{mime_type:null,clock_rate:null,sdp_fmtp_line:null},delta_jitter_ms_out:0,delta_rtt_ms_out:null,total_rtt_ms_out:0,total_rtt_measure_out:0,percent_packets_lost_out:0,delta_packets_out:0,delta_packets_lost_out:0,total_packets_out:0,total_packets_lost_out:0,total_KBytes_out:0,delta_KBytes_out:0,delta_kbs_out:0,timestamp_out:null,mos_out:0,mos_emodel_out:0,ssrc:"",direction:Xe.OUTBOUND},Zp={codec_id_in:"",size_in:{width:null,height:null,framerate:null},codec_in:{mime_type:null,clock_rate:null},delta_jitter_ms_in:0,percent_packets_lost_in:0,delta_packets_in:0,delta_packets_lost_in:0,total_packets_in:0,total_packets_lost_in:0,total_KBytes_in:0,delta_KBytes_in:0,delta_kbs_in:0,decoder_in:null,delta_ms_decode_frame_in:0,total_frames_decoded_in:0,total_time_decoded_in:0,delta_nack_sent_in:0,delta_pli_sent_in:0,total_nack_sent_in:0,total_pli_sent_in:0,ssrc:"",direction:Xe.INBOUND},e0={codec_id_out:"",size_out:{width:null,height:null,framerate:null},codec_out:{mime_type:null,clock_rate:null},delta_jitter_ms_out:0,delta_rtt_ms_out:null,total_rtt_ms_out:0,total_rtt_measure_out:0,percent_packets_lost_out:0,delta_packets_out:0,delta_packets_lost_out:0,total_packets_out:0,total_packets_lost_out:0,total_KBytes_out:0,delta_KBytes_out:0,delta_kbs_out:0,encoder_out:null,delta_ms_encode_frame_out:0,total_time_encoded_out:0,total_frames_encoded_out:0,delta_nack_received_out:0,delta_pli_received_out:0,total_nack_received_out:0,total_pli_received_out:0,limitation_out:{reason:null,durations:null,resolutionChanges:0},timestamp_out:null,ssrc:"",direction:Xe.OUTBOUND},MA=u=>{const e={pname:"",call_id:"",user_id:"",timestamp:null,count:0,audio:{},video:{},network:{infrastructure:3,local_candidate_id:"",local_candidate_type:"",local_candidate_protocol:"",local_candidate_relay_protocol:"",remote_candidate_id:"",remote_candidate_type:"",remote_candidate_protocol:""},data:{total_KBytes_in:0,total_KBytes_out:0,delta_KBytes_in:0,delta_KBytes_out:0,delta_kbs_in:0,delta_kbs_out:0,delta_kbs_bandwidth_in:0,delta_kbs_bandwidth_out:0,delta_rtt_connectivity_ms:null,total_rtt_connectivity_ms:0,total_rtt_connectivity_measure:0},experimental:{time_to_measure_ms:0}};if(u){const t={...u,audio:{},video:{},data:{...u.data},network:{...u.network},experimental:{...u.experimental}};return Object.keys(u.audio).forEach(r=>{t.audio[r]={...u.audio[r]}}),Object.keys(u.video).forEach(r=>{t.video[r]={...u.video[r]}}),t}return{...e,audio:{},video:{},data:{...e.data},network:{...e.network},experimental:{...e.experimental}}},UA={refreshEvery:2e3,startAfter:0,stopAfter:-1,verbose:!1,pname:`p-${bl()}`,cid:`c-${bl()}`,uid:`u-${bl()}`,record:!1,ticket:!0},Ss={CANDIDATE_PAIR:"candidate-pair",CODEC:"codec",INBOUND_RTP:"inbound-rtp",LOCAL_CANDIDATE:"local-candidate",MEDIA_SOURCE:"media-source",OUTBOUND_RTP:"outbound-rtp",REMOTE_CANDIDATE:"remote-candidate",REMOTE_INBOUND_RTP:"remote-inbound-rtp",TRACK:"track"},te={AUDIO_LEVEL:"audioLevel",AVAILABLE_OUTGOING_BITRATE:"availableOutgoingBitrate",AVAILABLE_INCOMING_BITRATE:"availableIncomingBitrate",BYTES_RECEIVED:"bytesReceived",BYTES_SENT:"bytesSent",CANDIDATE_TYPE:"candidateType",CHANNELS:"channels",CLOCK_RATE:"clockRate",CODEC_ID:"codecId",CURRENT_ROUND_TRIP_TIME:"currentRoundTripTime",ROUND_TRIP_TIME:"roundTripTime",FRACTION_LOST:"fractionLost",FRAME_HEIGHT:"frameHeight",FRAME_WIDTH:"frameWidth",QUALITY_LIMITATION_REASON:"qualityLimitationReason",QUALITY_LIMITATION_DURATIONS:"qualityLimitationDurations",QUALITY_LIMITATION_RESOLUTION_CHANGES:"qualityLimitationResolutionChanges",ID:"id",JITTER:"jitter",KIND:"kind",MEDIA_TYPE:"mediaType",MIME_TYPE:"mimeType",LOCAL_CANDIDATE_ID:"localCandidateId",NETWORK_TYPE:"networkType",RELAY_PROTOCOL:"relayProtocol",NOMINATED:"nominated",PACKETS_LOST:"packetsLost",PACKETS_RECEIVED:"packetsReceived",PACKETS_SENT:"packetsSent",PROTOCOL:"protocol",PORT:"port",REMOTE_CANDIDATE_ID:"remoteCandidateId",REMOTE_SOURCE:"remoteSource",RESPONSES_RECEIVED:"responsesReceived",SDP_FMTP_LINE:"sdpFmtpLine",SSRC:"ssrc",SELECTED:"selected",STATE:"state",TIMESTAMP:"timestamp",TOTAL_ROUND_TRIP_TIME:"totalRoundTripTime",TOTAL_ROUND_TRIP_TIME_MEASUREMENTS:"roundTripTimeMeasurements",TYPE:"type",DECODER_IMPLEMENTATION:"decoderImplementation",ENCODER_IMPLEMENTATION:"encoderImplementation",FRAMES_DECODED:"framesDecoded",FRAMES_ENCODED:"framesEncoded",FRAMES_PER_SECOND:"framesPerSecond",TOTAL_DECODE_TIME:"totalDecodeTime",TOTAL_ENCODE_TIME:"totalEncodeTime",PLI:"pliCount",NACK:"nackCount"},X={SUCCEEDED:"succeeded",AUDIO:"audio",VIDEO:"video"},wl={ETHERNET:0,CELLULAR_5G:2,WIFI:3,CELLULAR_4G:5,CELLULAR:10},Uf={ETHERNET:"ethernet",CELLULAR_4G:"cellular",WIFI:"wifi"},he={AUDIO:"audio",VIDEO:"video",NETWORK:"network",DATA:"data"},Lf="config ",LA=(u,e={},t)=>{const r={...t,...e};return e.pname||Xu(Lf,`Argument [String] 'cfg.pname' for the peerConnection name or id is missing - use generated '${t.pname}'`),e.cid||Xu(Lf,`Argument [String] 'cfg.cid' for the call name or id is missing - use generated '${t.cid}'`),e.uid||Xu(Lf,`Argument [String] 'cfg.uid' for the user name or id is missing - use generated '${t.uid}'`),r.pc=u,r},FA=(u={})=>{const e={...UA,...u};return e.name=PA(),e.version=xA(),e},Il=(u,e,t,r=!1,l)=>{let s=u.map(i=>{if(!t)return i[e];if(!l)return i[e][t];const f=i[e][l];return f?f[t]:null});return s=s.filter(i=>r?Number.isFinite(i)&&i>0:Number.isFinite(i)),s.length===0?[]:s},An=u=>u.reduce((e,t)=>e+t,0)/u.length,$A=()=>`probe-${bl()}`,HA=()=>`coltr-${bl()}`,t0=u=>new Promise(e=>setTimeout(e,u)),Ff=(u,e,t)=>{e?u.call(e,t):u(t)},lt=(u,e,t,r)=>{const l=Il(u,e,t,!0,r);if(l.length===0)return null;const s=l.reduce((d,p)=>d+p,0)/l.length;return s===0?null:l.map(d=>Math.abs(s-d)).reduce((d,p)=>d+p,0)/l.length*100/s},dt=(u,e,t,r=!1,l)=>{const s=Il(u,e,t,r,l);return s.length===0?null:s.reduce((i,f)=>i+f,0)/s.length},ri=(u,e,t)=>Il(u,e,t).reduce((l,s)=>l+s,0),at=(u,e,t,r)=>{const l=Il(u,e,t,!0,r);return l.length===0?null:Math.min(...l)},ot=(u,e,t,r)=>{const l=Il(u,e,t,!1,r);return l.length===0?null:Math.max(...l)},Ht=(u,e,t,r)=>{const l=u.slice().pop();if(!l)return null;if(!t)return l[e];if(!r)return l[e][t];const s=l[e][r];return s?s[t]:null},GA=u=>u.slice().pop(),Ot=(u,e,t)=>{if(!e)return null;const r={};let l=e[X.AUDIO][u];l||(l=t===Xe.INBOUND?{...Jp}:{...Qp}),r[X.AUDIO]=l;let s=e[X.VIDEO][u];return s||(s=t===Xe.INBOUND?{...Zp}:{...e0}),r[X.VIDEO]=s,r},Ol="exporter ",VA="2.0",s0=(u,e,t)=>{if(!u||u.length===0)return 0;const r=u[u.length-1];if(!r)return 0;const l=r[e][t];if(l){const s=l.total_rtt_ms_out,i=l.total_rtt_measure_out;return!i||!s?dt(u,e,"delta_rtt_ms_out",!1,t):Number(s/i)}return null},BA=(u,e)=>{if(!u||u.length===0)return 0;const t=u[u.length-1];if(!t)return 0;const r=t[e].total_rtt_connectivity_ms,l=t[e].total_rtt_connectivity_measure;return!l||!r?dt(u,e,"delta_rtt_connectivity_ms"):Number(r/l)},jA=u=>Ht(u,"network","local_candidate_type")!=="relay"?`direct/${Ht(u,"network","local_candidate_protocol")}`:`turn/${Ht(u,"network","local_candidate_relay_protocol")}`,qA=u=>{const e=Ht(u,"network","remote_candidate_type"),t=Ht(u,"network","remote_candidate_protocol");return e!=="relay"?`direct/${t}`:`turn/${t}`};class WA{constructor(e){this._start=null,this._end=null,this._cfg=e,this._referenceReport=null,this._reports=[],this._events=[]}start(){Mf(Ol,"start() - start exporter...");const e=new Date;return this._start=e.toJSON(),e}stop(){Mf(Ol,"stop() - stop exporter...");const e=new Date;return this._end=e.toJSON(),e}saveReferenceReport(e){this._referenceReport=e}getReferenceReport(){return this._referenceReport}addReport(e){this._cfg.ticket&&(Be(Ol,`addReport() - add report to exporter at ${e.timestamp}`),this._reports.push(e))}addCustomEvent(e){this._events.push(e)}reset(){Mf(Ol,"resetReports() - reset reports"),this._reports=[],this._referenceReport=null,this._start=null,this._end=null}get ticket(){Be(Ol,"ticket() - generate ticket");const e=Ht(this._reports,"audio","total_packets_lost_in"),t=Ht(this._reports,"audio","total_packets_in"),r=Ht(this._reports,"video","total_packets_lost_in"),l=Ht(this._reports,"video","total_packets_in"),s={},i=GA(this._reports);return i&&(Object.keys(i[X.AUDIO]).forEach(f=>{const h=i[X.AUDIO][f];if(s[h.ssrc]={type:X.AUDIO,direction:h.direction},h.direction===Xe.INBOUND){const d={avg:dt(this._reports,X.AUDIO,"delta_jitter_ms_in",!1,f),min:at(this._reports,X.AUDIO,"delta_jitter_ms_in",f),max:ot(this._reports,X.AUDIO,"delta_jitter_ms_in",f),volatility:lt(this._reports,X.AUDIO,"delta_jitter_ms_in",f),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},p={avg:dt(this._reports,X.AUDIO,"delta_kbs_in",!1,f),min:at(this._reports,X.AUDIO,"delta_kbs_in",f),max:ot(this._reports,X.AUDIO,"delta_kbs_in",f),volatility:lt(this._reports,X.AUDIO,"delta_kbs_in",f),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},v={avg:dt(this._reports,X.AUDIO,"delta_KBytes_in",!1,f),min:at(this._reports,X.AUDIO,"delta_KBytes_in",f),max:ot(this._reports,X.AUDIO,"delta_KBytes_in",f),volatility:lt(this._reports,X.AUDIO,"delta_KBytes_in",f),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},T={emodel:{avg:dt(this._reports,X.AUDIO,"mos_emodel_in",!1,f),min:at(this._reports,X.AUDIO,"mos_emodel_in",f),max:ot(this._reports,X.AUDIO,"mos_emodel_in",f),volatility:lt(this._reports,X.AUDIO,"mos_emodel_in",f)},effective:{avg:dt(this._reports,X.AUDIO,"mos_in",!1,f),min:at(this._reports,X.AUDIO,"mos_in",f),max:ot(this._reports,X.AUDIO,"mos_in",f),volatility:lt(this._reports,X.AUDIO,"mos_in",f)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}},y=Ht(this._reports,X.AUDIO,"total_packets_lost_in",f),S=Ht(this._reports,X.AUDIO,"total_packets_in",f),A={lost:y,avg:Math.round((y/(y+S)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};s[f].jitter=d,s[f].mos=T,s[f].traffic=v,s[f].bitrate=p,s[f].loss=A}else{const d={avg:dt(this._reports,X.AUDIO,"delta_jitter_ms_out",!1,f),min:at(this._reports,X.AUDIO,"delta_jitter_ms_out",f),max:ot(this._reports,X.AUDIO,"delta_jitter_ms_out",f),volatility:lt(this._reports,X.AUDIO,"delta_jitter_ms_out",f),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},p={avg:dt(this._reports,X.AUDIO,"delta_kbs_out",!1,f),min:at(this._reports,X.AUDIO,"delta_kbs_out",f),max:ot(this._reports,X.AUDIO,"delta_kbs_out",f),volatility:lt(this._reports,X.AUDIO,"delta_kbs_out",f),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},v={avg:dt(this._reports,X.AUDIO,"delta_KBytes_out",!1,f),min:at(this._reports,X.AUDIO,"delta_KBytes_out",f),max:ot(this._reports,X.AUDIO,"delta_KBytes_out",f),volatility:lt(this._reports,X.AUDIO,"delta_KBytes_out",f),_unit:{avg:"KB",min:"KB",max:"KB",bitrate:"kbs",volatility:"percent"}},T={avg:s0(this._reports,X.AUDIO,f),min:at(this._reports,X.AUDIO,"delta_rtt_ms_out",f),max:ot(this._reports,X.AUDIO,"delta_rtt_ms_out",f),volatility:lt(this._reports,X.AUDIO,"delta_rtt_ms_out",f),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},y=Ht(this._reports,X.AUDIO,"total_packets_lost_out",f),S=Ht(this._reports,X.AUDIO,"total_packets_out",f),A={lost:y,avg:Math.round((y/(y+S)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}},R={emodel:{avg:dt(this._reports,X.AUDIO,"mos_emodel_out",!1,f),min:at(this._reports,X.AUDIO,"mos_emodel_out",f),max:ot(this._reports,X.AUDIO,"mos_emodel_out",f),volatility:lt(this._reports,X.AUDIO,"mos_emodel_out",f)},effective:{avg:dt(this._reports,X.AUDIO,"mos_out",!1,f),min:at(this._reports,X.AUDIO,"mos_out",f),max:ot(this._reports,X.AUDIO,"mos_out",f),volatility:lt(this._reports,X.AUDIO,"mos_out",f)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}};s[f].jitter=d,s[f].rtt=T,s[f].traffic=v,s[f].bitrate=p,s[f].loss=A,s[f].mos=R}}),Object.keys(i[X.VIDEO]).forEach(f=>{const h=i[X.VIDEO][f];if(s[f]={type:X.VIDEO,direction:h.direction},h.direction===Xe.INBOUND){const d={avg:dt(this._reports,X.VIDEO,"delta_jitter_ms_in",!1,f),min:at(this._reports,X.VIDEO,"delta_jitter_ms_in",f),max:ot(this._reports,X.VIDEO,"delta_jitter_ms_in",f),volatility:lt(this._reports,X.VIDEO,"delta_jitter_ms_in",f),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},p={avg:dt(this._reports,X.VIDEO,"delta_kbs_in",!1,f),min:at(this._reports,X.VIDEO,"delta_kbs_in",f),max:ot(this._reports,X.VIDEO,"delta_kbs_in",f),volatility:lt(this._reports,X.VIDEO,"delta_kbs_in",f),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},v={avg:dt(this._reports,X.VIDEO,"delta_KBytes_in",!1,f),min:at(this._reports,X.VIDEO,"delta_KBytes_in",f),max:ot(this._reports,X.VIDEO,"delta_KBytes_in",f),volatility:lt(this._reports,X.VIDEO,"delta_KBytes_in",f),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},T=Ht(this._reports,X.VIDEO,"total_packets_lost_in",f),y=Ht(this._reports,X.VIDEO,"total_packets_in",f),S={lost:T,avg:Math.round((T/(T+y)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};s[f].jitter=d,s[f].traffic=v,s[f].bitrate=p,s[f].loss=S}else{const d={avg:dt(this._reports,X.VIDEO,"delta_jitter_ms_out",!1,f),min:at(this._reports,X.VIDEO,"delta_jitter_ms_out",f),max:ot(this._reports,X.VIDEO,"delta_jitter_ms_out",f),volatility:lt(this._reports,X.VIDEO,"delta_jitter_ms_out",f),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},p={avg:dt(this._reports,X.VIDEO,"delta_kbs_out",!1,f),min:at(this._reports,X.VIDEO,"delta_kbs_out",f),max:ot(this._reports,X.VIDEO,"delta_kbs_out",f),volatility:lt(this._reports,X.VIDEO,"delta_kbs_out",f),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},v={avg:dt(this._reports,X.VIDEO,"delta_KBytes_out",!1,f),min:at(this._reports,X.VIDEO,"delta_KBytes_out",f),max:ot(this._reports,X.VIDEO,"delta_KBytes_out",f),volatility:lt(this._reports,X.VIDEO,"delta_KBytes_out",f),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},T={avg:s0(this._reports,X.VIDEO,f),min:at(this._reports,X.VIDEO,"delta_rtt_ms_out",f),max:ot(this._reports,X.VIDEO,"delta_rtt_ms_out",f),volatility:lt(this._reports,X.VIDEO,"delta_rtt_ms_out",f),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},y=Ht(this._reports,X.VIDEO,"total_packets_lost_out",f),S=Ht(this._reports,X.VIDEO,"total_packets_out",f),A={lost:y,avg:Math.round((y/(y+S)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};s[f].jitter=d,s[f].rtt=T,s[f].traffic=v,s[f].bitrate=p,s[f].loss=A}})),{version:VA,configuration:{frequency:this._cfg.refreshEvery},started:this._start,ended:this._end,ua:{agent:navigator.userAgent,pname:this._cfg.pname,user_id:this._cfg.uid},call:{call_id:this._cfg.cid,events:this._events},details:{count:this._reports.length,reports:this._cfg.record?this._reports:[],reference:this._referenceReport||null},ssrc:s,data:{rtt:{avg:BA(this._reports,"data"),min:at(this._reports,"data","delta_rtt_connectivity_ms"),max:ot(this._reports,"data","delta_rtt_connectivity_ms"),volatility:lt(this._reports,"data","delta_rtt_connectivity_ms"),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},packetsLost:{audio:{in:{avg:Math.round((e/(e+t)*100||0)*100)/100}},video:{in:{avg:Math.round((r/(r+l)*100||0)*100)/100}},unit:{avg:"percent"}},bitrate:{in:{avg:dt(this._reports,"data","delta_kbs_in"),min:at(this._reports,"data","delta_kbs_in"),max:ot(this._reports,"data","delta_kbs_in"),volatility:lt(this._reports,"data","delta_kbs_in")},out:{avg:dt(this._reports,"data","delta_kbs_out"),min:at(this._reports,"data","delta_kbs_out"),max:ot(this._reports,"data","delta_kbs_out"),volatility:lt(this._reports,"data","delta_kbs_out")},unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},traffic:{in:{avg:dt(this._reports,"data","delta_KBytes_in"),min:at(this._reports,"data","delta_KBytes_in"),max:ot(this._reports,"data","delta_KBytes_in"),volatility:lt(this._reports,"data","delta_KBytes_in")},out:{avg:dt(this._reports,"data","delta_KBytes_out"),min:at(this._reports,"data","delta_KBytes_out"),max:ot(this._reports,"data","delta_KBytes_out"),volatility:lt(this._reports,"data","delta_KBytes_out")},unit:{avg:"KBytes",min:"KBytes",max:"KBytes",volatility:"percent"}},network:{localConnection:jA(this._reports),remoteConnection:qA(this._reports)}}}}updateConfig(e){this._cfg=e}getLastReport(){return this._reports.slice().pop()||null}getBeforeLastReport(){const e=this._reports.slice();return e.pop(),e.pop()||null}getReportsNumber(){return this._reports.length}}const bn="extractor ",n0=(u,e,t,r)=>{let l=!1;const s=r[e].total_rtt_ms_out,i=r[e].total_rtt_measure_out,f=t?t[e].total_rtt_ms_out:0,h=t?t[e].total_rtt_measure_out:0,d={rtt:null,totalRTT:s,totalRTTMeasurements:i};if(u[te.TIMESTAMP]===r[e].timestamp_out||!Object.prototype.hasOwnProperty.call(u,te.ROUND_TRIP_TIME)||Object.prototype.hasOwnProperty.call(u,te.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS)&&(l=!0,Number(u[te.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])===0||Number(u[te.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])-h===i))return d;const p=1e3*Number(u[te.ROUND_TRIP_TIME]);let v=s+p,T=i+1;return l&&(v=1e3*Number(u[te.TOTAL_ROUND_TRIP_TIME])-f,T=Number(u[te.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])-h),{rtt:p,totalRTT:v,totalRTTMeasurements:T}},KA=(u,e,t,r)=>{if(!Object.prototype.hasOwnProperty.call(u,te.CURRENT_ROUND_TRIP_TIME))return{rtt:null,totalRTT:r[e].total_rtt_connectivity_ms,totalRTTMeasurements:r[e].total_rtt_connectivity_measure};const l=1e3*Number(u[te.CURRENT_ROUND_TRIP_TIME]);let s=r[e].total_rtt_connectivity_ms+l,i=r[e].total_rtt_connectivity_measure+1;return Object.prototype.hasOwnProperty.call(u,te.TOTAL_ROUND_TRIP_TIME)&&(s=1e3*Number(u[te.TOTAL_ROUND_TRIP_TIME])-(t?t[e].total_rtt_connectivity_ms:0)),Object.prototype.hasOwnProperty.call(u,te.RESPONSES_RECEIVED)&&(i=Number(u[te.RESPONSES_RECEIVED])-(t?t[e].total_rtt_connectivity_measure:0)),{rtt:l,totalRTT:s,totalRTTMeasurements:i}},Ju=(u,e,t)=>u[te.TIMESTAMP]===t[e].timestamp_out||!Object.prototype.hasOwnProperty.call(u,te.JITTER)?null:1e3*(Number(u[te.JITTER])||0),YA=(u,e)=>{if(!Object.prototype.hasOwnProperty.call(u,te.FRAMES_DECODED)||!Object.prototype.hasOwnProperty.call(u,te.TOTAL_DECODE_TIME))return{delta_ms_decode_frame:e[X.VIDEO].delta_ms_decode_frame_in,frames_decoded:e[X.VIDEO].total_frames_decoded_in,total_decode_time:e[X.VIDEO].total_time_decoded_in};const t=u[te.FRAMES_DECODED],r=u[te.TOTAL_DECODE_TIME],l=r-e[X.VIDEO].total_time_decoded_in,s=t-e[X.VIDEO].total_frames_decoded_in;return{delta_ms_decode_frame:s>0?l*1e3/s:0,frames_decoded:t,total_decode_time:r}},zA=(u,e)=>{if(!Object.prototype.hasOwnProperty.call(u,te.FRAMES_ENCODED)||!Object.prototype.hasOwnProperty.call(u,te.TOTAL_ENCODE_TIME))return{delta_ms_encode_frame:e[X.VIDEO].delta_ms_encode_frame_out,frames_encoded:e[X.VIDEO].total_frames_encoded_out,total_encode_time:e[X.VIDEO].total_time_encoded_out};const t=u[te.FRAMES_ENCODED],r=u[te.TOTAL_ENCODE_TIME],l=r-e[X.VIDEO].total_time_encoded_out,s=t-e[X.VIDEO].total_frames_encoded_out;return{delta_ms_encode_frame:s>0&&l?l*1e3/s:0,frames_encoded:t,total_encode_time:r}},i0=(u,e,t,r)=>{if(!Object.prototype.hasOwnProperty.call(u,te.PACKETS_SENT)||!Object.prototype.hasOwnProperty.call(u,te.BYTES_SENT))return{packetsSent:t[e].total_packets_out,packetsLost:t[e].total_packets_lost_out,bytesSent:t[e].total_KBytes_out};const l=Number(u[te.PACKETS_SENT])||0-(r?r[e].total_packets_out:0),s=l-t[e].total_packets_out,i=Number(u[te.BYTES_SENT])/1024-(r?r[e].total_KBytes_out:0),f=i-t[e].total_KBytes_out,h=u[te.TIMESTAMP]||Date.now(),d=r?r.timestamp:null;let p=t.timestamp;!p&&d&&(p=d);const v=p?h-p:0,T=v>0?f*.008*1024/v*1e3:0;return{packetsSent:l,deltaPacketsSent:s,KBytesSent:i,deltaKBytesSent:f,kbsSent:T}},r0=(u,e,t,r)=>{let l=t[e].total_packets_lost_out,s=0,i=0;return Object.prototype.hasOwnProperty.call(u,te.PACKETS_LOST)&&(l=Number(u[te.PACKETS_LOST])||0-(r?r[e].total_packets_lost_out:0),s=l-t[e].total_packets_lost_out),Object.prototype.hasOwnProperty.call(u,te.FRACTION_LOST)&&(i=Number(100*u[te.FRACTION_LOST])),{packetsLost:l,deltaPacketsLost:s,fractionLost:i}},l0=(u,e,t,r)=>{if(!Object.prototype.hasOwnProperty.call(u,te.PACKETS_RECEIVED)||!Object.prototype.hasOwnProperty.call(u,te.PACKETS_LOST)||!Object.prototype.hasOwnProperty.call(u,te.BYTES_RECEIVED))return{percent_packets_lost:t[e].percent_packets_lost_in,packetsReceived:t[e].total_packets_in,packetsLost:t[e].total_packets_lost_in,bytesReceived:t[e].total_KBytes_in};const l=Number(u[te.PACKETS_RECEIVED])||0-(r?r[e].total_packets_in:0),s=Number(u[te.PACKETS_LOST])||0-(r?r[e].total_packets_lost_in:0),i=s-t[e].total_packets_lost_in,f=l-t[e].total_packets_in,h=l!==t[e].total_packets_in?i*100/(i+f):0,d=Number(u[te.BYTES_RECEIVED])/1024-(r?r[e].total_KBytes_in:0),p=d-t[e].total_KBytes_in,v=u[te.TIMESTAMP]||Date.now(),T=r?r.timestamp:null;let y=t.timestamp;!y&&T&&(y=T);const S=y?v-y:0,A=S>0?p*.008*1024/S*1e3:0;return{percentPacketsLost:h,packetsReceived:l,deltaPacketsReceived:f,packetsLost:s,deltaPacketsLost:i,KBytesReceived:d,deltaKBytesReceived:p,kbsReceived:A}},XA=u=>u[te.CANDIDATE_TYPE]!=="relay"?"":u[te.RELAY_PROTOCOL]||"",JA=u=>{if(!Object.prototype.hasOwnProperty.call(u,te.NETWORK_TYPE))return wl.WIFI;switch(u[te.NETWORK_TYPE]){case Uf.ETHERNET:return wl.ETHERNET;case Uf.CELLULAR_4G:return wl.CELLULAR_4G;case Uf.WIFI:return wl.WIFI;default:return wl.CELLULAR}},a0=u=>!Object.prototype.hasOwnProperty.call(u,te.FRAME_HEIGHT)||!Object.prototype.hasOwnProperty.call(u,te.FRAME_WIDTH)?{width:null,height:null,framerate:null}:{width:u[te.FRAME_WIDTH]||null,height:u[te.FRAME_HEIGHT]||null,framerate:u[te.FRAMES_PER_SECOND]},QA=u=>{const e=Object.prototype.hasOwnProperty.call(u,te.QUALITY_LIMITATION_REASON)?u[te.QUALITY_LIMITATION_REASON]:null,t=Object.prototype.hasOwnProperty.call(u,te.QUALITY_LIMITATION_RESOLUTION_CHANGES)?u[te.QUALITY_LIMITATION_RESOLUTION_CHANGES]:null,r=Object.prototype.hasOwnProperty.call(u,te.QUALITY_LIMITATION_DURATIONS)?u[te.QUALITY_LIMITATION_DURATIONS]:null;return r&&Object.keys(r).forEach(l=>{r[l]>1e3&&(r[l]=Number(r[l]/1e3))}),{reason:e,durations:r,resolutionChanges:t}},ZA=(u,e,t)=>{if(!Object.prototype.hasOwnProperty.call(u,te.PLI)||!Object.prototype.hasOwnProperty.call(u,te.NACK))return{pliCount:e.total_pli_sent_in,nackCount:e.total_nack_sent_in,deltaPliCount:0,deltaNackCount:0};const r=(u[te.PLI]||0)-(t?t[X.VIDEO].total_pli_sent_in:0),l=(u[te.NACK]||0)-(t?t[X.VIDEO].total_nack_sent_in:0);return{pliCount:r,nackCount:l,deltaPliCount:r-e[X.VIDEO].total_pli_sent_in,deltaNackCount:l-e[X.VIDEO].total_nack_sent_in}},eb=(u,e,t)=>{if(!Object.prototype.hasOwnProperty.call(u,te.PLI)||!Object.prototype.hasOwnProperty.call(u,te.NACK))return{pliCount:e.total_pli_received_out,nackCount:e.total_nack_received_out,deltaPliCount:0,deltaNackCount:0};const r=(u[te.PLI]||0)-(t?t[X.VIDEO].total_pli_received_out:0),l=(u[te.NACK]||0)-(t?t[X.VIDEO].total_nack_received_out:0);return{pliCount:r,nackCount:l,deltaPliCount:r-e[X.VIDEO].total_pli_received_out,deltaNackCount:l-e[X.VIDEO].total_nack_received_out}},tb=u=>({channels:u[te.CHANNELS]||null,clock_rate:u[te.CLOCK_RATE]||null,mime_type:u[te.MIME_TYPE]||null,sdp_fmtp_line:u[te.SDP_FMTP_LINE]||null}),sb=u=>({clock_rate:u[te.CLOCK_RATE]||null,mime_type:u[te.MIME_TYPE]||null}),nb=(u,e,t)=>{const r=(u[te.BYTES_RECEIVED]||0)/1024-(t?t.data.total_KBytes_in:0),l=(u[te.BYTES_SENT]||0)/1024-(t?t.data.total_KBytes_out:0),s=u[te.TIMESTAMP]||Date.now(),i=r-e.data.total_KBytes_in,f=l-e.data.total_KBytes_out,h=t?t.timestamp:null;let d=e.timestamp;!d&&h&&(d=h);const p=d?s-d:0,v=p>0?i*.008*1024/p*1e3:0,T=p>0?f*.008*1024/p*1e3:0;return{total_KBytes_received:r,total_KBytes_sent:l,delta_KBytes_received:i,delta_KBytes_sent:f,kbs_speed_received:v,kbs_speed_sent:T}},ib=u=>{const e=u[te.AVAILABLE_INCOMING_BITRATE]/1024||0,t=u[te.AVAILABLE_OUTGOING_BITRATE]/1024||0;return{kbs_incoming_bandwidth:e,kbs_outgoing_bandwidth:t}},rb=(u,e,t,r)=>{if(!u)return[];switch(u[te.TYPE]){case Ss.CANDIDATE_PAIR:let l=!1;if(u[te.NOMINATED]&&u[te.STATE]===X.SUCCEEDED&&(l=!0,Be(bn,`analyze() - got stats ${u[te.TYPE]} for ${t}`,u),te.SELECTED in u&&!u[te.SELECTED]&&(l=!1)),l){const i=u[te.LOCAL_CANDIDATE_ID],f=u[te.REMOTE_CANDIDATE_ID],h=nb(u,e,r),d=ib(u),p=KA(u,"data",r,e);return[{type:he.NETWORK,value:{local_candidate_id:i}},{type:he.NETWORK,value:{remote_candidate_id:f}},{type:he.DATA,value:{total_KBytes_in:h.total_KBytes_received}},{type:he.DATA,value:{total_KBytes_out:h.total_KBytes_sent}},{type:he.DATA,value:{delta_KBytes_in:h.delta_KBytes_received}},{type:he.DATA,value:{delta_KBytes_out:h.delta_KBytes_sent}},{type:he.DATA,value:{delta_kbs_in:h.kbs_speed_received}},{type:he.DATA,value:{delta_kbs_out:h.kbs_speed_sent}},{type:he.DATA,value:{delta_kbs_bandwidth_in:d.kbs_incoming_bandwidth}},{type:he.DATA,value:{delta_kbs_bandwidth_out:d.kbs_outgoing_bandwidth}},{type:he.DATA,value:{delta_rtt_connectivity_ms:p.rtt}},{type:he.DATA,value:{total_rtt_connectivity_ms:p.totalRTT}},{type:he.DATA,value:{total_rtt_connectivity_measure:p.totalRTTMeasurements}}]}break;case Ss.LOCAL_CANDIDATE:if(u[te.ID]===e.network.local_candidate_id)return[{type:he.NETWORK,value:{infrastructure:JA(u)}},{type:he.NETWORK,value:{local_candidate_type:u[te.CANDIDATE_TYPE]||""}},{type:he.NETWORK,value:{local_candidate_protocol:u[te.PROTOCOL]||""}},{type:he.NETWORK,value:{local_candidate_relay_protocol:XA(u)}}];break;case Ss.REMOTE_CANDIDATE:if(u[te.ID]===e.network.remote_candidate_id)return[{type:he.NETWORK,value:{remote_candidate_type:u[te.CANDIDATE_TYPE]||""}},{type:he.NETWORK,value:{remote_candidate_protocol:u[te.PROTOCOL]||""}}];break;case Ss.INBOUND_RTP:{Be(bn,`analyze() - got stats ${u[te.TYPE]} for ${t}`,u);const i=u[te.SSRC],f=Ot(i,e,Xe.INBOUND);f&&(f.timestamp=e.timestamp);const h=Ot(i,r,Xe.INBOUND);if(h&&(h.timestamp=r.timestamp),u[te.MEDIA_TYPE]===X.AUDIO){const d=l0(u,X.AUDIO,f,h),p=Ju(u,X.AUDIO,f),v=u[te.CODEC_ID]||"";return[{ssrc:i,type:he.AUDIO,value:{codec_id_in:v}},{ssrc:i,type:he.AUDIO,value:{total_packets_in:d.packetsReceived}},{ssrc:i,type:he.AUDIO,value:{delta_packets_in:d.deltaPacketsReceived}},{ssrc:i,type:he.AUDIO,value:{total_packets_lost_in:d.packetsLost}},{ssrc:i,type:he.AUDIO,value:{delta_packets_lost_in:d.deltaPacketsLost}},{ssrc:i,type:he.AUDIO,value:{percent_packets_lost_in:d.percentPacketsLost}},{ssrc:i,type:he.AUDIO,value:{total_KBytes_in:d.KBytesReceived}},{ssrc:i,type:he.AUDIO,value:{delta_KBytes_in:d.deltaKBytesReceived}},{ssrc:i,type:he.AUDIO,value:{delta_kbs_in:d.kbsReceived}},{ssrc:i,type:he.AUDIO,value:{delta_jitter_ms_in:p}}]}if(u[te.MEDIA_TYPE]===X.VIDEO){const d=YA(u,f),p=l0(u,X.VIDEO,f,h),v=Ju(u,X.VIDEO,f),T=u[te.DECODER_IMPLEMENTATION]||null,y=u[te.CODEC_ID]||null,S=a0(u),A=ZA(u,f,h);return[{ssrc:i,type:he.VIDEO,value:{codec_id_in:y}},{ssrc:i,type:he.VIDEO,value:{total_packets_in:p.packetsReceived}},{ssrc:i,type:he.VIDEO,value:{delta_packets_in:p.deltaPacketsReceived}},{ssrc:i,type:he.VIDEO,value:{total_packets_lost_in:p.packetsLost}},{ssrc:i,type:he.VIDEO,value:{delta_packets_lost_in:p.deltaPacketsLost}},{ssrc:i,type:he.VIDEO,value:{percent_packets_lost_in:p.percentPacketsLost}},{ssrc:i,type:he.VIDEO,value:{total_KBytes_in:p.KBytesReceived}},{ssrc:i,type:he.VIDEO,value:{delta_KBytes_in:p.deltaKBytesReceived}},{ssrc:i,type:he.VIDEO,value:{delta_kbs_in:p.kbsReceived}},{ssrc:i,type:he.VIDEO,value:{delta_jitter_ms_in:v}},{ssrc:i,type:he.VIDEO,value:{decoder_in:T}},{ssrc:i,type:he.VIDEO,value:{delta_ms_decode_frame_in:d.delta_ms_decode_frame}},{ssrc:i,type:he.VIDEO,value:{total_frames_decoded_in:d.frames_decoded}},{ssrc:i,type:he.VIDEO,value:{total_time_decoded_in:d.total_decode_time}},{ssrc:i,type:he.VIDEO,value:{total_nack_sent_in:A.nackCount}},{ssrc:i,type:he.VIDEO,value:{delta_nack_sent_in:A.deltaNackCount}},{ssrc:i,type:he.VIDEO,value:{total_pli_sent_in:A.pliCount}},{ssrc:i,type:he.VIDEO,value:{delta_pli_sent_in:A.deltaPliCount}},{ssrc:i,type:he.VIDEO,value:{size_in:S}}]}break}case Ss.OUTBOUND_RTP:{Be(bn,`analyze() - got stats ${u[te.TYPE]} for ${t}`,u);const i=u[te.SSRC],f=Ot(i,e,Xe.OUTBOUND);f&&(f.timestamp=e.timestamp);const h=Ot(i,r,Xe.OUTBOUND);if(h&&(h.timestamp=r.timestamp),u[te.MEDIA_TYPE]===X.AUDIO){const d=u[te.CODEC_ID]||null,p=i0(u,X.AUDIO,f,h);return[{ssrc:i,type:he.AUDIO,value:{codec_id_out:d}},{ssrc:i,type:he.AUDIO,value:{total_packets_out:p.packetsSent}},{ssrc:i,type:he.AUDIO,value:{delta_packets_out:p.deltaPacketsSent}},{ssrc:i,type:he.AUDIO,value:{total_KBytes_out:p.KBytesSent}},{ssrc:i,type:he.AUDIO,value:{delta_KBytes_out:p.deltaKBytesSent}},{ssrc:i,type:he.AUDIO,value:{delta_kbs_out:p.kbsSent}}]}if(u[te.MEDIA_TYPE]===X.VIDEO){const d=u[te.ENCODER_IMPLEMENTATION]||null,p=u[te.CODEC_ID]||null,v=zA(u,f),T=a0(u),y=QA(u),S=eb(u,f,h),A=i0(u,X.VIDEO,f,h);return[{ssrc:i,type:he.VIDEO,value:{codec_id_out:p}},{ssrc:i,type:he.VIDEO,value:{total_packets_out:A.packetsSent}},{ssrc:i,type:he.VIDEO,value:{delta_packets_out:A.deltaPacketsSent}},{ssrc:i,type:he.VIDEO,value:{total_KBytes_out:A.KBytesSent}},{ssrc:i,type:he.VIDEO,value:{delta_KBytes_out:A.deltaKBytesSent}},{ssrc:i,type:he.VIDEO,value:{delta_kbs_out:A.kbsSent}},{ssrc:i,type:he.VIDEO,value:{encoder_out:d}},{ssrc:i,type:he.VIDEO,value:{delta_ms_encode_frame_out:v.delta_ms_encode_frame}},{ssrc:i,type:he.VIDEO,value:{total_frames_encoded_out:v.frames_encoded}},{ssrc:i,type:he.VIDEO,value:{total_time_encoded_out:v.total_encode_time}},{ssrc:i,type:he.VIDEO,value:{total_nack_received_out:S.nackCount}},{ssrc:i,type:he.VIDEO,value:{delta_nack_received_out:S.deltaNackCount}},{ssrc:i,type:he.VIDEO,value:{total_pli_received_out:S.pliCount}},{ssrc:i,type:he.VIDEO,value:{delta_pli_received_out:S.deltaPliCount}},{ssrc:i,type:he.VIDEO,value:{size_out:T}},{ssrc:i,type:he.VIDEO,value:{limitation_out:y}}]}break}case Ss.MEDIA_SOURCE:{Be(bn,`analyze() - got stats ${u[te.TYPE]} for ${t}`,u);break}case Ss.TRACK:{Be(bn,`analyze() - got stats ${u[te.TYPE]} for ${t}`,u);break}case Ss.CODEC:const s=[];return Object.keys(e[X.AUDIO]).forEach(i=>{const f=e[X.AUDIO][i];if(f.codec_id_in===u[te.ID]||f.codec_id_out===u[te.ID]){Be(bn,`analyze() - got stats ${u[te.TYPE]} for ${t}`,u);const h=tb(u);u[te.ID]===f.codec_id_in?s.push({ssrc:f.ssrc,type:he.AUDIO,value:{codec_in:h}}):s.push({ssrc:f.ssrc,type:he.AUDIO,value:{codec_out:h}})}}),Object.keys(e[X.VIDEO]).forEach(i=>{const f=e[X.VIDEO][i];if(f.codec_id_in===u[te.ID]||f.codec_id_out===u[te.ID]){Be(bn,`analyze() - got stats ${u[te.TYPE]} for ${t}`,u);const h=sb(u);u[te.ID]===f.codec_id_in?s.push({ssrc:f.ssrc,type:he.VIDEO,value:{codec_in:h}}):s.push({ssrc:f.ssrc,type:he.VIDEO,value:{codec_out:h}})}}),s;case Ss.REMOTE_INBOUND_RTP:{Be(bn,`analyze() - got stats ${u[te.TYPE]} for ${t}`,u);const i=u[te.SSRC],f=Ot(i,e,Xe.OUTBOUND),h=Ot(i,r,Xe.OUTBOUND);if(u[te.KIND]===X.AUDIO){const d=n0(u,X.AUDIO,h,f),p=Ju(u,X.AUDIO,f),v=r0(u,X.AUDIO,f,h);return[{ssrc:i,type:he.AUDIO,value:{delta_rtt_ms_out:d.rtt}},{ssrc:i,type:he.AUDIO,value:{total_rtt_ms_out:d.totalRTT}},{ssrc:i,type:he.AUDIO,value:{total_rtt_measure_out:d.totalRTTMeasurements}},{ssrc:i,type:he.AUDIO,value:{delta_jitter_ms_out:p}},{ssrc:i,type:he.AUDIO,value:{timestamp_out:u[te.TIMESTAMP]}},{ssrc:i,type:he.AUDIO,value:{total_packets_lost_out:v.packetsLost}},{ssrc:i,type:he.AUDIO,value:{delta_packets_lost_out:v.deltaPacketsLost}},{ssrc:i,type:he.AUDIO,value:{percent_packets_lost_out:v.fractionLost}}]}if(u[te.KIND]===X.VIDEO){const d=n0(u,X.VIDEO,h,f),p=Ju(u,X.VIDEO,f),v=r0(u,X.VIDEO,f,h);return[{ssrc:i,type:he.VIDEO,value:{delta_rtt_ms_out:d.rtt}},{ssrc:i,type:he.VIDEO,value:{total_rtt_ms_out:d.totalRTT}},{ssrc:i,type:he.VIDEO,value:{total_rtt_measure_out:d.totalRTTMeasurements}},{ssrc:i,type:he.VIDEO,value:{delta_jitter_ms_out:p}},{ssrc:i,type:he.VIDEO,value:{timestamp_out:u[te.TIMESTAMP]}},{ssrc:i,type:he.VIDEO,value:{total_packets_lost_out:v.packetsLost}},{ssrc:i,type:he.VIDEO,value:{delta_packets_lost_out:v.deltaPacketsLost}},{ssrc:i,type:he.VIDEO,value:{percent_packets_lost_out:v.fractionLost}}]}break}}return[]},Qu=u=>u<0?1:u>100?4.5:1+.035*u+7/1e6*u*(u-60)*(100-u),lb=(u,e=X.AUDIO,t,r,l)=>{const s=Ot(l,u,Xe.INBOUND),i=Ot(l,t,Xe.INBOUND),f=Ot(l,r,Xe.INBOUND),h=[],d=[],p=s[e].percent_packets_lost_in,v=s[e].delta_jitter_ms_in,T=i&&i[e].delta_jitter_ms_in||null,y=f&&f[e].delta_jitter_ms_in||null,S=u.data.delta_rtt_connectivity_ms,A=t&&t.data.delta_rtt_connectivity_ms||null,R=r&&r.data.delta_rtt_connectivity_ms||null;S&&h.push(S),A&&h.push(A),R&&h.push(R),v&&d.push(v),t&&T&&d.push(T),r&&y&&d.push(y);const O=h.length>0?An(h):100,N=d.length>0?An(d):10,C=93.2-p,b=.18*C*C-27.9*C+1126.62,w=(O+N)/2,F=w-177.3<0?0:1,q=.024*w+.11*(w-177.3)*F,D=b-q;return Qu(D)},ab=(u,e=X.AUDIO,t,r,l)=>{const s=Ot(l,u,Xe.OUTBOUND),i=Ot(l,t,Xe.OUTBOUND),f=Ot(l,r,Xe.OUTBOUND),h=[],d=[],p=s[e].percent_packets_lost_out,v=s[e].delta_rtt_ms_out,T=i&&i[e].delta_rtt_ms_out||null,y=f&&f[e].delta_rtt_ms_out||null,S=s[e].delta_jitter_ms_out,A=i&&i[e].delta_jitter_ms_out||null,R=f&&f[e].delta_jitter_ms_out||null,O=u.data.delta_rtt_connectivity_ms,N=t&&t.data.delta_rtt_connectivity_ms||null,C=r&&r.data.delta_rtt_connectivity_ms||null;v?h.push(v):O&&h.push(O),T?h.push(T):N&&h.push(N),y?h.push(y):C&&h.push(C),S&&d.push(S),t&&A&&d.push(A),r&&R&&d.push(R);const b=h.length>0?An(h):100,w=d.length>0?An(d):10,F=93.2-p,q=.18*F*F-27.9*F+1126.62,D=(b+w)/2,P=D-177.3<0?0:1,I=.024*D+.11*(D-177.3)*P,x=q-I;return Qu(x)},ob=(u,e=X.AUDIO,t,r,l)=>{const s=Ot(l,u,Xe.INBOUND),i=Ot(l,t,Xe.INBOUND),f=Ot(l,r,Xe.INBOUND),h=[],d=[],p=s[e].percent_packets_lost_in/100,v=s[e].delta_jitter_ms_in,T=i&&i[e].delta_jitter_ms_in||null,y=f&&f[e].delta_jitter_ms_in||null,S=u.data.delta_rtt_connectivity_ms,A=t&&t.data.delta_rtt_connectivity_ms||null,R=r&&r.data.delta_rtt_connectivity_ms||null;S&&h.push(S),A&&h.push(A),R&&h.push(R),v&&d.push(v),i&&T&&d.push(T),f&&y&&d.push(y);const O=h.length>0?An(h):100,N=d.length>0?An(d):10,C=0,b=19.8,w=29.7,F=30,q=(O+N)/2+F,D=q-177.3<0?0:1,P=.024*q+.11*(q-177.3)*D,x=93.2-(C+b*Math.log(1+w*p)+P);return Qu(x)},ub=(u,e=X.AUDIO,t,r,l)=>{const s=Ot(l,u,Xe.OUTBOUND),i=Ot(l,t,Xe.OUTBOUND),f=Ot(l,r,Xe.OUTBOUND),h=[],d=[],p=s[e].percent_packets_lost_out/100,v=s[e].delta_rtt_ms_out,T=i&&i[e].delta_rtt_ms_out||null,y=f&&f[e].delta_rtt_ms_out||null,S=s[e].delta_jitter_ms_out,A=i&&i[e].delta_jitter_ms_out||null,R=f&&f[e].delta_jitter_ms_out||null,O=u.data.delta_rtt_connectivity_ms,N=t&&t.data.delta_rtt_connectivity_ms||null,C=r&&r.data.delta_rtt_connectivity_ms||null;v?h.push(v):O&&h.push(O),T?h.push(T):N&&h.push(N),y?h.push(y):C&&h.push(C),S&&d.push(S),i&&A&&d.push(A),f&&R&&d.push(R);const b=h.length>0?An(h):100,w=d.length>0?An(d):10,F=0,q=19.8,D=29.7,P=30,I=(b+w)/2+P,x=I-177.3<0?0:1,U=.024*I+.11*(I-177.3)*x,z=93.2-(F+q*Math.log(1+D*p)+U);return Qu(z)};class cb{constructor(e,t){this._callbacks={onreport:null,onticket:null},this._id=HA(),this._moduleName=this._id,this._probeId=t,this._config=e,this._exporter=new WA(e),this._state=en.IDLE,this.registerToPCEvents(),ii(this._moduleName,`new collector created for probe ${this._probeId}`)}analyze(e,t,r,l){const s=(h,d)=>h===X.AUDIO?d===Ss.INBOUND_RTP?{...Jp}:{...Qp}:d===Ss.INBOUND_RTP?{...Zp}:{...e0},i=MA(t);i.pname=this._config.pname,i.call_id=this._config.cid,i.user_id=this._config.uid,i.count=t?t.count+1:1;let f=null;return e.forEach(h=>{!f&&h.timestamp&&(f=h.timestamp),rb(h,i,i.pname,l).forEach(p=>{if(p.value&&p.type)if(p.ssrc){let v=i[p.type][p.ssrc];v||(v=s(p.type,h.type),v.ssrc=p.ssrc,i[p.type][p.ssrc]=v),Object.keys(p.value).forEach(T=>{v[T]=p.value[T]})}else Object.keys(p.value).forEach(v=>{i[p.type][v]=p.value[v]})})}),i.timestamp=f,Object.keys(i[X.AUDIO]).forEach(h=>{const d=i[X.AUDIO][h];d.direction===Xe.INBOUND?(d.mos_emodel_in=lb(i,X.AUDIO,t,r,d.ssrc),d.mos_in=ob(i,X.AUDIO,t,r,d.ssrc)):(d.mos_emodel_out=ab(i,X.AUDIO,t,r,d.ssrc),d.mos_out=ub(i,X.AUDIO,t,r,d.ssrc))}),i}async takeReferenceStats(){return new Promise((e,t)=>{const r=Date.now();setTimeout(async()=>{try{const l=Date.now()-r,s=Date.now(),i=await this._config.pc.getStats(),f=this.analyze(i,null,null,null),h=Date.now();f.experimental.time_to_measure_ms=h-s,f.experimental.time_to_wait_ms=l,this._exporter.saveReferenceReport(f),Be(this._moduleName,`got reference report for probe ${this._probeId}`),e()}catch(l){t(l)}},this._config.startAfter)})}async collectStats(){try{if(this._state!==en.RUNNING||!this._config.pc)return Be(this._moduleName,`report discarded (too late) for probe ${this._probeId}`),null;const e=Date.now(),t=await this._config.pc.getStats(),r=this.analyze(t,this._exporter.getLastReport(),this._exporter.getBeforeLastReport(),this._exporter.getReferenceReport()),l=Date.now();return r.experimental.time_to_measure_ms=l-e,this._exporter.addReport(r),Be(this._moduleName,`got report for probe ${this._probeId}#${this._exporter.getReportsNumber()+1}`),this.fireOnReport(r),r}catch(e){return Zi(this._moduleName,`got error ${e}`),null}}async start(){Be(this._moduleName,"starting"),this.state=en.RUNNING,this._startedTime=this._exporter.start(),Be(this._moduleName,"started")}async mute(){this.state=en.MUTED,Be(this._moduleName,"muted")}async unmute(){this.state=en.RUNNING,Be(this._moduleName,"unmuted")}async stop(e){if(Be(this._moduleName,`stopping${e?" by watchdog":""}...`),this._stoppedTime=this._exporter.stop(),this.state=en.IDLE,this._config.ticket){const{ticket:t}=this._exporter;this.fireOnTicket(t)}this._exporter.reset(),Be(this._moduleName,"stopped")}registerCallback(e,t,r){e in this._callbacks?(this._callbacks[e]={callback:t,context:r},Be(this._moduleName,`registered callback '${e}'`)):Zi(this._moduleName,`can't register callback for '${e}' - not found`)}unregisterCallback(e){e in this._callbacks?(this._callbacks[e]=null,delete this._callbacks[e],Be(this._moduleName,`unregistered callback '${e}'`)):Zi(this._moduleName,`can't unregister callback for '${e}' - not found`)}fireOnReport(e){this._callbacks.onreport&&Ff(this._callbacks.onreport.callback,this._callbacks.onreport.context,e)}fireOnTicket(e){this._callbacks.onticket&&Ff(this._callbacks.onticket.callback,this._callbacks.onticket.context,e)}updateConfig(e){this._config=e,this._exporter.updateConfig(e)}get state(){return this._state}set state(e){this._state=e,Be(this._moduleName,`state changed to ${e}`)}addCustomEvent(e,t,r,l){this._exporter.addCustomEvent({at:typeof e=="object"?e.toJSON():e,category:t,name:r,description:l})}async registerToPCEvents(){const{pc:e}=this._config;if(navigator.mediaDevices.ondevicechange=async()=>{try{const t=await navigator.mediaDevices.enumerateDevices();this.addCustomEvent(new Date().toJSON(),"device",`${t.length} devices found`,"Media Devices state")}catch{Zi(this._moduleName,"can't get devices")}},e){e.oniceconnectionstatechange=()=>{const r=e.iceConnectionState;r===Rl.CONNECTED||r===Rl.COMPLETED?this.addCustomEvent(new Date().toJSON(),"call",r,"ICE connection state"):r===Rl.DISCONNECTED||r===Rl.FAILED?this.addCustomEvent(new Date().toJSON(),"call",r,"ICE connection state"):r===Rl.CLOSED&&this.addCustomEvent(new Date().toJSON(),"call","ended","ICE connection state")},e.onicegatheringstatechange=()=>{const r=e.iceGatheringState;this.addCustomEvent(new Date().toJSON(),"call",r,"ICE gathering state")},e.ontrack=r=>{this.addCustomEvent(new Date().toJSON(),"call",`${r.track.kind}track`,"MediaStreamTrack received")},e.onnegotiationneeded=()=>{this.addCustomEvent(new Date().toJSON(),"call","negotiation","Media changed")};const t=e.getReceivers();if(t&&t.length>0){const r=t[0],{transport:l}=r;if(l){const{iceTransport:s}=l;s&&(s.onselectedcandidatepairchange=()=>{this.addCustomEvent(new Date().toJSON(),"call","transport","Candidates Pair changed")})}}}}}class hb{constructor(e){this._id=e.pname&&e.pname.substr(0,12).padEnd(12," ")||$A(),this._moduleName=this._id,ii(this._moduleName,"probe created"),this._config=e,this._collector=new cb(this._config,this._id)}set onreport(e){e?this._collector.registerCallback("onreport",e):this._collector.unregisterCallback("onreport")}set onticket(e){e?this._collector.registerCallback("onticket",e):this._collector.unregisterCallback("onticket")}get id(){return this._id}get pname(){return this._config.pname}get cid(){return this._config.cid}get uid(){return this._config.uid}get state(){return this._collector.state}set state(e){this._collector.state=e}addCustomEvent(e,t,r,l=new Date().toJSON()){this._collector.addCustomEvent(l,t,e,r)}get isRunning(){return this._collector.state===en.RUNNING}get isIdle(){return this._collector.state===en.IDLE}updateUserId(e){this._config.uid=e,this._collector.updateConfig(this._config)}updateCallId(e){this._config.cid=e,this._collector.updateConfig(this._config)}start(){if(!this.isIdle){Xu(this._moduleName,"probe is already running");return}this._collector.start()}stop(e=!1){this.isRunning&&this._collector.stop(e)}async takeReferenceStats(){return this._collector.takeReferenceStats()}async collectStats(){return this._collector.collectStats()}}const qt="engine ";class fb{constructor(e){this._config=e,this._probes=[],this._startedTime=null,this._callbacks={onresult:null},ii(qt,`configured for probing every ${this._config.refreshEvery}ms`),ii(qt,`configured for starting after ${this._config.startAfter}ms`),ii(qt,`${!this._config.stopAfter||this._config.stopAfter!==-1?`configured for stopped after ${this._config.stopAfter}ms`:"configured for never stopped"}`),Be(qt,"engine initialized")}get probes(){return this._probes}get isRunning(){return this._probes.some(e=>e.isRunning)}get isIdle(){return this._probes.every(e=>e.isIdle)}addNewProbe(e,t){if(!e)throw new Error("undefined peer connection");const r=LA(e,t,this._config),l=new hb(r);return this._probes.push(l),Be(qt,`${this._probes.length} probes registered`),l}removeExistingProbe(e){if(!e)throw new Error("undefined probe");e.state===en.RUNNING&&e.stop(),this._probes=this._probes.filter(t=>e.id!==t.id)}async start(){const e=()=>{this._probes.forEach(s=>s.start())},t=async()=>Promise.all(this._probes.map(s=>s.takeReferenceStats())),r=()=>this.isIdle?!1:!this._config.stopAfter||this._config.stopAfter<0?!0:Date.now()<this._startedTime+this._config.stopAfter,l=async()=>{const s=kA(),i=this._probes.filter(f=>f.isRunning);for(const f of i){const h=await f.collectStats();h&&s.probes.push(h),Be(qt,`got probe ${f.id}`),await t0(0)}return s.delta_time_to_measure_probes_ms=ri(s.probes,"experimental","time_to_measure_ms"),s.delta_KBytes_in=ri(s.probes,"data","delta_KBytes_in"),s.delta_KBytes_out=ri(s.probes,"data","delta_KBytes_out"),s.delta_kbs_in=ri(s.probes,"data","delta_kbs_in"),s.delta_kbs_out=ri(s.probes,"data","delta_kbs_out"),s.total_time_decoded_in=ri(s.probes,"video","total_time_decoded_in"),s.total_time_encoded_out=ri(s.probes,"video","total_time_encoded_out"),s};for(Be(qt,"starting to collect"),e(),Be(qt,"generating reference reports..."),await t(),Be(qt,"reference reports generated"),this._startedTime=Date.now();r();)if(Be(qt,`wait ${this._config.refreshEvery}ms before collecting`),await t0(this._config.refreshEvery),r()){Be(qt,"collecting...");const s=Date.now(),i=await l(),f=Date.now();i.delta_time_consumed_to_measure_ms=f-s,this.fireOnReports(i),Be(qt,"collected")}Be(qt,"reaching end of the collecting period..."),this.isRunning&&setTimeout(()=>{this.stop()},0)}stop(e){const t=r=>{this._probes.forEach(l=>{l.stop(r)})};ii(qt,"stop collecting"),t(e)}registerCallback(e,t,r){e in this._callbacks?(this._callbacks[e]={callback:t,context:r},Be(qt,`registered callback '${e}'`)):Zi(qt,`can't register callback for '${e}' - not found`)}unregisterCallback(e){e in this._callbacks?(this._callbacks[e]=null,delete this._callbacks[e],Be(this._moduleName,`unregistered callback '${e}'`)):Zi(this._moduleName,`can't unregister callback for '${e}' - not found`)}fireOnReports(e){this._callbacks.onresult&&e.probes.length>0&&Ff(this._callbacks.onresult.callback,this._callbacks.onresult.context,e)}}const db="interface ";class _b{constructor(e){this._config=FA(e),ii(db,`welcome to ${this._config.name} version ${this._config.version}`),RA(this._config.verbose||!1),this._engine=new fb(this._config)}setupLogLevel(e){wA(e)}get version(){return this._config.version}get name(){return this._config.name}get probes(){return this._engine.probes}createProbe(e,t){return this._engine.addNewProbe(e,t)}startAllProbes(){this._engine.start()}stopAllProbes(){this._engine.stop()}get running(){return this._engine.isRunning}get idle(){return this._engine.isIdle}removeProbe(e){this._engine.removeExistingProbe(e)}set onresult(e){e?this._engine.registerCallback("onresult",e):this._engine.unregisterCallback("onresult")}}function gb(u,e){return Object.keys(u).filter(t=>e.includes(t)).reduce((t,r)=>{const l=r;return{...t,[l]:u[l]}},{})}const pb=["mos_in","codec_in","delta_KBytes_in","delta_kbs_in","delta_jitter_ms_in","delta_packets_lost_in"];class mb{constructor(e){this.intervals={},this.emitInterval=e.emitInterval||200,this.onChangeFunction=e.onChangeFunction}start(e,t){e&&e.getTracks().length&&requestAnimationFrame(()=>this.beginCalculation(e,t))}stop(e){this.clearVolumeInterval(e)}clearVolumeInterval(e){clearInterval(this.intervals[e]),delete this.intervals[e]}clearAllIntervals(){Object.keys(this.intervals).forEach(e=>{clearInterval(this.intervals[e])}),this.intervals={}}beginCalculation(e,t){this.clearVolumeInterval(t);const r=ni.createAnalyser(),l=ni.createMediaStreamSource(e),s=ni.createScriptProcessor(2048,1,1);r.smoothingTimeConstant=.8,r.fftSize=1024,l.connect(r),r.connect(s),s.connect(ni.destination),this.intervals[t]=setInterval(()=>{const i=new Uint8Array(r.frequencyBinCount);r.getByteFrequencyData(i);let f=0;const h=i.length;for(let p=0;p<h;p++)f+=i[p];const d=f/h;this.onChangeFunction(t,d)},this.emitInterval)}}const Zu={SELECTED_INPUT_DEVICE:"OpensipsJSInputDevice",SELECTED_OUTPUT_DEVICE:"OpensipsJSOutputDevice"},vb=0;class Tb{constructor(e){this.isAutoAnswer=!1,this.muteWhenJoinEnabled=!1,this.isDNDEnabled=!1,this.muted=!1,this.microphoneInputLevelValue=1,this.speakerVolumeValue=1,this.activeRooms={},this.activeCalls={},this.extendedCalls={},this.availableMediaDevices=[],this.selectedMediaDevices={input:"default",output:"default"},this.callStatus={},this.callTime={},this.callMetrics={},this.timeIntervals={},this.metricConfig={refreshEvery:1e3},this.activeStreamValue=null,this.initialStreamValue=null,this.context=e,this.context.on(this.context.newRTCSessionEventName,this.newRTCSessionCallback.bind(this)),this.VUMeter=new mb({onChangeFunction:this.emitVolumeChange.bind(this)}),this.initializeMediaDevices()}get sipOptions(){return{...this.context.options.sipOptions,mediaConstraints:this.getUserMediaConstraints}}get currentActiveRoomId(){return this.currentActiveRoomIdValue}set currentActiveRoomId(e){this.currentActiveRoomIdValue=e,this.context.emit("currentActiveRoomChanged",e)}get autoAnswer(){return this.isAutoAnswer}get callAddingInProgress(){return this.isCallAddingInProgress}set callAddingInProgress(e){this.isCallAddingInProgress=e,this.context.emit("callAddingInProgressChanged",e)}get muteWhenJoin(){return this.muteWhenJoinEnabled}get isDND(){return this.isDNDEnabled}get speakerVolume(){return this.speakerVolumeValue}get microphoneInputLevel(){return this.microphoneInputLevelValue}get getActiveCalls(){return this.activeCalls}get hasActiveCalls(){return Object.values(this.extendedCalls).length>0}get getActiveRooms(){return this.activeRooms}get isMuted(){return this.muted}get getInputDeviceList(){return this.availableMediaDevices.filter(e=>e.kind==="audioinput")}get getOutputDeviceList(){return this.availableMediaDevices.filter(e=>e.kind==="audiooutput")}get getUserMediaConstraints(){return Og()?{video:!1,audio:!0}:{audio:{deviceId:{exact:this.selectedMediaDevices.input}},video:!1}}get selectedInputDevice(){return this.selectedMediaDevices.input}get selectedOutputDevice(){return this.selectedMediaDevices.output}get activeStream(){return this.activeStreamValue}setAvailableMediaDevices(e){this.availableMediaDevices=e,this.context.emit("changeAvailableDeviceList",e)}async updateDeviceList(){await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints);const e=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(e)}async initializeMediaDevices(){const e=localStorage.getItem(Zu.SELECTED_INPUT_DEVICE)||"default",t=localStorage.getItem(Zu.SELECTED_OUTPUT_DEVICE)||"default";try{const r=await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints),l=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(l),await this.setMicrophone(e),await this.setSpeaker(t),navigator.mediaDevices.addEventListener("devicechange",async()=>{const s=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(s)}),r.getTracks().forEach(s=>s.stop())}catch(r){console.error(r)}}setCallTime(e){const t={...e};delete t.callId,this.callTime={...this.callTime,[e.callId]:t},this.context.emit("changeCallTime",this.callTime)}removeCallTime(e){const t={...this.callTime};delete t[e],this.callTime={...t},this.context.emit("changeCallTime",this.callTime)}setTimeInterval(e,t){this.timeIntervals={...this.timeIntervals,[e]:t}}removeTimeInterval(e){const t={...this.timeIntervals};t[e]&&(clearInterval(t[e]),delete t[e],this.timeIntervals={...t})}stopCallTimer(e){this.removeTimeInterval(e),this.removeCallTime(e)}emitVolumeChange(e,t){this.context.emit("changeCallVolume",{callId:e,volume:t})}setMetricsConfig(e){this.metricConfig={...this.metricConfig,...e}}sendDTMF(e,t){if(!/^[A-D0-9]+$/g.test(t))throw new Error("Not allowed character in DTMF input");this.extendedCalls[e].sendDTMF(t)}setIsMuted(e){this.muted=e,this.context.emit("changeIsMuted",e)}processMute(e){const t=this.currentActiveRoomId;this.setIsMuted(e),this.initialStreamValue.getTracks().forEach(r=>r.enabled=!e),this.roomReconfigure(t)}mute(){this.processMute(!0)}unmute(){this.processMute(!1)}async processHold({callId:e,toHold:t,automatic:r}){const l=this.extendedCalls[e];l._automaticHold=r??!1,await new Promise(f=>{const h=()=>{l.putOnHoldTimestamp=t?Date.now():void 0,f()};t?l.hold({},h):l.unhold({},h)}),this.updateCall(l);const i=Object.values(this.extendedCalls).filter(f=>f.roomId===this.currentActiveRoomId&&(t?e!==f._id:!0));i.length>1&&await this.doConference(i)}holdCall(e,t=!1){return this.processHold({callId:e,automatic:t,toHold:!0})}unholdCall(e){return this.processHold({callId:e,toHold:!1})}cancelAllOutgoingUnanswered(){Object.values(this.getActiveCalls).filter(e=>e.direction==="outgoing"&&e.status===vb).forEach(e=>this.terminateCall(e._id))}answerCall(e){const t=this.extendedCalls[e];this.cancelAllOutgoingUnanswered(),t.answer(this.sipOptions),this.updateCall(t),this.setActiveRoom(t.roomId),t.connection.addEventListener("track",r=>{this.triggerAddStream(r,t)})}async moveCall(e,t){this.updateCallStatus({callId:e,isMoving:!0}),await this.processRoomChange({callId:e,roomId:t}),this.updateCallStatus({callId:e,isMoving:!1})}updateCall(e){this.activeCalls[e._id]=Rg(e),this.context.emit("changeActiveCalls",this.activeCalls)}updateRoom(e){const r={...this.activeRooms[e.roomId],...e};this.activeRooms={...this.activeRooms,[e.roomId]:{...r}},this.context.emit("updateRoom",{room:r,roomList:this.activeRooms})}hasAutoAnswerHeaders(e){const t=/answer-after=0/,l=e.request.getHeader("Call-Info");return l&&t.test(l)}addCall(e,t=!0){this.activeCalls={...this.activeCalls,[e._id]:Rg(e)},this.extendedCalls[e._id]=e,t&&this.context.emit("changeActiveCalls",this.activeCalls)}addCallStatus(e){this.callStatus={...this.callStatus,[e]:{isMoving:!1,isTransferring:!1,isMerging:!1}},this.context.emit("changeCallStatus",this.callStatus)}updateCallStatus(e){const r={...{...this.callStatus[e.callId]}};e.isMoving!==void 0&&(r.isMoving=e.isMoving),e.isTransferring!==void 0&&(r.isTransferring=e.isTransferring),e.isMerging!==void 0&&(r.isMerging=e.isMerging),this.callStatus={...this.callStatus,[e.callId]:{...r}},this.context.emit("changeCallStatus",this.callStatus)}removeCallStatus(e){const t={...this.callStatus};delete t[e],this.callStatus={...t},this.context.emit("changeCallStatus",this.callStatus)}addRoom(e){this.activeRooms={...this.activeRooms,[e.roomId]:e},this.context.emit("addRoom",{room:e,roomList:this.activeRooms})}getActiveStream(){const e=Ig(this.initialStreamValue,this.microphoneInputLevel*2);return e.getTracks().forEach(t=>t.enabled=!this.isMuted),this.setActiveStream(e),e}async setMicrophone(e){if(!this.getInputDeviceList.find(({deviceId:r})=>r===e)||(this.setSelectedInputDevice(e),Object.keys(this.getActiveCalls).length===0))return;await this.setupStream();const t=Object.values(this.extendedCalls).filter(r=>r.roomId===this.currentActiveRoomId);t.length===1?Object.values(t).forEach(async r=>{const l=this.getActiveStream();r.connection.getSenders()[0].replaceTrack(l.getTracks()[0]),this.updateCall(r)}):await this.doConference(t)}setActiveStream(e){this.activeStream&&this.stopVUMeter("origin"),this.setupVUMeter(e,"origin"),this.activeStreamValue=e,this.context.emit("changeActiveStream",e)}async setSpeaker(e){if(!this.getOutputDeviceList.find(({deviceId:l})=>l===e))return;this.setSelectedOutputDevice(e);const t=Object.values(this.extendedCalls);if(t.length===0)return;const r=t.filter(l=>l.roomId===this.currentActiveRoomId);r.length===1?t.forEach(l=>{var s;(s=l.audioTag)==null||s.setSinkId(e),this.updateCall(l)}):await this.doConference(r)}removeRoom(e){const t={...this.activeRooms},r={...t[e]};delete t[e],this.activeRooms={...t},this.context.emit("removeRoom",{room:r,roomList:this.activeRooms})}deleteRoomIfEmpty(e){e!==void 0&&Object.values(this.extendedCalls).filter(t=>t.roomId===e).length===0&&(this.removeRoom(e),this.currentActiveRoomId===e&&(this.currentActiveRoomId=void 0))}checkInitialized(){if(!this.context.initialized)throw new Error("[OpenSIPSJS] You must call `start` method first!")}muteReconfigure(e){this.muted?e.mute({audio:!0}):e.unmute({audio:!0})}async roomReconfigure(e){var r;if(e===void 0)return;const t=Object.values(this.extendedCalls).filter(l=>l.roomId===e);if(this.currentActiveRoomId===e?t.forEach(l=>{l.audioTag&&(this.muteReconfigure(l),l.audioTag.muted=!1,this.updateCall(l))}):t.forEach(l=>{l.audioTag&&(l.audioTag.muted=!0,this.updateCall(l))}),t.length===0)this.deleteRoomIfEmpty(e);else if(t.length===1&&this.currentActiveRoomId!==e)t[0].isOnHold().local||await this.holdCall(t[0].id,!0);else if(t.length===1&&this.currentActiveRoomId===e){if(t[0].isOnHold().local&&t[0]._automaticHold&&await this.unholdCall(t[0].id),t[0].connection&&((r=t[0].connection)!=null&&r.getSenders()[0])){const l=this.getActiveStream();await t[0].connection.getSenders()[0].replaceTrack(l.getTracks()[0]),this.muteReconfigure(t[0])}}else t.length>1&&await this.doConference(t)}async doConference(e){const t=[];e.forEach(r=>{r!=null&&r.connection.getReceivers().forEach(l=>{t.push(l.track)})}),await AA.forEach(e,async r=>{var i;if(r==null)return;const l=new MediaStream,s=ni.createMediaStreamDestination();if(r.connection.getReceivers().forEach(f=>{t.forEach(h=>{l.addTrack(f.track),f.track.id!==h.id&&ni.createMediaStreamSource(new MediaStream([h])).connect(s)})}),e[0].roomId===this.currentActiveRoomId){const f=this.getActiveStream();ni.createMediaStreamSource(f).connect(s)}(i=r.connection)!=null&&i.getSenders()[0]&&(await r.connection.getSenders()[0].replaceTrack(s.stream.getTracks()[0]),this.muteReconfigure(r))})}processCallerMute(e,t){const r=this.extendedCalls[e];r&&r.connection.getReceivers().length&&(r.localMuted=t,r.connection.getReceivers().forEach(l=>{l.track.enabled=!t}),this.updateCall(r))}muteCaller(e){this.processCallerMute(e,!0)}unmuteCaller(e){this.processCallerMute(e,!1)}terminateCall(e){const t=this.extendedCalls[e];t._status!==8&&t.terminate()}transferCall(e,t){if(t.toString().length===0)return new Error("Target must be passed");const r=this.extendedCalls[e];if(!r._is_confirmed&&!r._is_canceled){const l=`sip:${t}@${this.context.sipDomain}`;r.terminate({status_code:302,reason_phrase:"Moved Temporarily",extraHeaders:[`Contact: ${l}`]});return}this.updateCallStatus({callId:e,isTransferring:!0}),r.refer(`sip:${t}@${this.context.sipDomain}`),this.updateCall(r)}mergeCall(e){const t=Object.values(this.extendedCalls).filter(s=>s.roomId===e);if(t.length!==2)return;const r=t[0],l=t[1];!r||!l||(this.updateCallStatus({callId:r._id,isMerging:!0}),this.updateCallStatus({callId:l._id,isMerging:!0}),r.refer(l.remote_identity.uri.toString(),{replaces:l}),this.updateCall(r))}mergeCallByIds(e,t){const r=Object.values(this.extendedCalls).find(s=>s._id===e),l=Object.values(this.extendedCalls).find(s=>s._id===t);if(!r||!l)throw new Error("Call ID is not provided");this.updateCallStatus({callId:e,isMerging:!0}),this.updateCallStatus({callId:t,isMerging:!0}),r.refer(l.remote_identity.uri.toString(),{replaces:l}),this.updateCall(r)}setDND(e){this.isDNDEnabled=e,this.context.emit("changeIsDND",e)}startCallTimer(e){this.removeTimeInterval(e);const t={callId:e,hours:0,minutes:0,seconds:0,formatted:""};this.setCallTime(t);const r=setInterval(()=>{const l={...this.callTime[e]},s=CA(l);this.setCallTime({callId:e,...s})},1e3);this.setTimeInterval(e,r)}async setActiveRoom(e){const t=this.currentActiveRoomId;e!==t&&(this.currentActiveRoomId=e,await this.roomReconfigure(t),await this.roomReconfigure(e))}getNewRoomId(){const e=Object.keys(this.activeRooms);return e.length===0?1:parseInt(e.sort()[e.length-1])+1}async setupCall(e){var d,p;const t=e.session;if(this.getActiveCalls[t.id]!==void 0)return;const l=this.getNewRoomId(),s={started:new Date,incomingInProgress:!1,roomId:l};t.direction==="incoming"?(this.context.logger.log("New incoming call from",(p=(d=t._remote_identity)==null?void 0:d._uri)==null?void 0:p._user),s.incomingInProgress=!0,this.context.subscribe(ys.CALL_CONFIRMED,v=>{t.id===v.id&&(this.updateRoom({incomingInProgress:!1,roomId:l}),this.startCallTimer(t.id))}),this.context.subscribe(ys.CALL_FAILED,v=>{t.id===v.id&&(this.updateRoom({incomingInProgress:!1,roomId:l}),this.deleteRoomIfEmpty(l))})):t.direction==="outgoing"&&(t.once("confirmed",()=>{this.startCallTimer(t.id)}),this.startCallTimer(t.id));const i=t,f=this.hasAutoAnswerHeaders(e),h=i.direction==="incoming"&&!this.hasActiveCalls&&(f||this.autoAnswer);i.roomId=l,i.localMuted=!1,i.autoAnswer=h,h?this.addCall(i,!1):this.addCall(i),this.addCallStatus(t.id),this.addRoom(s),h&&this.answerCall(i._id)}removeCall(e){const t={...this.activeCalls};delete t[e],this.activeCalls={...t};const r={...this.extendedCalls};delete r[e],this.extendedCalls={...r},this.context.emit("changeActiveCalls",this.activeCalls)}activeCallListRemove(e){var l;const t=this.extendedCalls[e._id];this.stopVUMeter("origin"),(l=t.connection)==null||l.getSenders().forEach(s=>{s.track.stop()});const r=t.roomId;this.removeCall(e._id),this.roomReconfigure(r)}async newRTCSessionCallback(e){const t=e.session;if(this.isDND){t.terminate({status_code:486,reason_phrase:"Do Not Disturb"});return}if(this.context.triggerListener({listenerType:ys.NEW_CALL,session:t,event:e}),t.on("ended",r=>{var s,i,f;this.stopVUMeter(t.id),this.context.logger.log("Session ended for",(i=(s=t._remote_identity)==null?void 0:s._uri)==null?void 0:i._user),this.context.triggerListener({listenerType:ys.CALL_ENDED,session:t,event:r});const l=this.getActiveCalls[t.id];l&&this.activeCallListRemove(l),this.stopCallTimer(t.id),this.removeCallStatus(t.id),this.removeCallMetrics(t.id),Object.keys(this.extendedCalls).length||(this.setIsMuted(!1),(f=this.initialStreamValue)==null||f.getTracks().forEach(h=>h.stop()),this.initialStreamValue=null)}),t.on("progress",r=>{var l,s;this.context.logger.log("Session in progress for",(s=(l=t._remote_identity)==null?void 0:l._uri)==null?void 0:s._user),this.context.triggerListener({listenerType:ys.CALL_PROGRESS,session:t,event:r})}),t.on("failed",r=>{var s,i,f;this.stopVUMeter(t.id),this.context.logger.log("Session failed for",(i=(s=t._remote_identity)==null?void 0:s._uri)==null?void 0:i._user),this.context.triggerListener({listenerType:ys.CALL_FAILED,session:t,event:r}),t.id===this.callAddingInProgress&&(this.callAddingInProgress=void 0);const l=this.getActiveCalls[t.id];l&&this.activeCallListRemove(l),this.stopCallTimer(t.id),this.removeCallStatus(t.id),this.removeCallMetrics(t.id),Object.keys(this.extendedCalls).length||(this.setIsMuted(!1),(f=this.initialStreamValue)==null||f.getTracks().forEach(h=>h.stop()),this.initialStreamValue=null)}),t.on("confirmed",r=>{var l,s;this.context.logger.log("Session confirmed for",(s=(l=t._remote_identity)==null?void 0:l._uri)==null?void 0:s._user),this.context.triggerListener({listenerType:ys.CALL_CONFIRMED,session:t,event:r}),this.updateCall(t),t.id===this.callAddingInProgress&&(this.callAddingInProgress=void 0)}),await this.setupCall(e),t.direction==="outgoing"){const r=this.getActiveCalls[t.id].roomId;this.setActiveRoom(r)}}setMuteWhenJoin(e){this.muteWhenJoinEnabled=e,this.context.emit("changeMuteWhenJoin",e)}setMicrophoneSensitivity(e){if(e<0||e>1)throw new Error("Value should be in range from 0 to 1!");this.microphoneInputLevelValue=e,this.roomReconfigure(this.currentActiveRoomId)}setSpeakerVolume(e){this.speakerVolumeValue=e,Object.values(this.extendedCalls).forEach(t=>{t.audioTag&&(t.audioTag.volume=e,this.updateCall(t))})}setAutoAnswer(e){this.isAutoAnswer=e}setSelectedInputDevice(e){localStorage.setItem(Zu.SELECTED_INPUT_DEVICE,e),this.selectedMediaDevices.input=e,this.context.emit("changeActiveInputMediaDevice",e)}setSelectedOutputDevice(e){localStorage.setItem(Zu.SELECTED_OUTPUT_DEVICE,e),this.selectedMediaDevices.output=e,this.context.emit("changeActiveOutputMediaDevice",e)}setCallMetrics(e){const t={...e};delete t.callId,this.callMetrics={...this.callMetrics,[e.callId]:t},this.context.emit("changeCallMetrics",this.callMetrics)}removeCallMetrics(e){const t={...this.callMetrics};delete t[e],this.callMetrics={...t},this.context.emit("changeCallMetrics",this.callMetrics)}getCallQuality(e){const t=new _b(this.metricConfig),r=t.createProbe(e.connection,{cid:e._id}),l=[];let s;r.onreport=i=>{Object.entries(i.audio).forEach(([d,p])=>{p.direction==="inbound"&&!l.includes(d)&&(l.push(d),s=d)});const f=i.audio[s];if(!f)return;const h=gb(f,pb);h.callId=e._id,this.setCallMetrics(h)},this.context.subscribe(ys.CALL_ENDED,i=>{i._id===e._id&&t.stopAllProbes()}),t.startAllProbes()}setupVUMeter(e,t){this.VUMeter.start(e,t)}stopVUMeter(e){this.VUMeter.stop(e)}async setupStream(){const e=await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints);this.initialStreamValue&&(this.initialStreamValue.getTracks().forEach(t=>t.stop()),this.initialStreamValue=null),this.initialStreamValue=e}async triggerAddStream(e,t){this.setIsMuted(this.muteWhenJoin||this.isMuted),this.initialStreamValue||await this.setupStream();const r=Ig(this.initialStreamValue,this.microphoneInputLevel*2),l=this.isMuted||this.muteWhenJoin;r.getTracks().forEach(i=>i.enabled=!l),this.setActiveStream(r),await t.connection.getSenders()[0].replaceTrack(r.getTracks()[0]);const s=new MediaStream([e.track]);iS(s,t,this.selectedOutputDevice,this.speakerVolume),this.setupVUMeter(s,t._id),this.getCallQuality(t),this.updateCall(t)}initCall(e,t,r=!1){if(e.length===0)return console.error("Target must be a valid string");this.context.logger.log(`Calling sip:${e}@${this.context.sipDomain}...`);const l=this.context.call(`sip:${e}@${this.context.sipDomain}`,this.sipOptions);if(this.callAddingInProgress=l.id,t&&this.currentActiveRoomId!==void 0&&(this.processRoomChange({callId:l.id,roomId:this.currentActiveRoomId}),r)){const s=Object.values(this.extendedCalls).filter(i=>i.roomId===this.currentActiveRoomId&&i._id!==l.id);for(const i of s)this.holdCall(i._id,!0)}l.connection.addEventListener("track",s=>{this.triggerAddStream(s,l)})}async processRoomChange({callId:e,roomId:t}){const r=this.extendedCalls[e].roomId;this.extendedCalls[e].roomId=t;const l=this.extendedCalls[e];return this.updateCall(l),await this.setActiveRoom(t),Promise.all([this.roomReconfigure(r),this.roomReconfigure(t)]).then(()=>{this.deleteRoomIfEmpty(r),this.deleteRoomIfEmpty(t)})}}class yb{constructor(e){this.context=e}get sipOptions(){return{...this.context.options.sipOptions}}initCall(e,t){if(e.length===0)return console.error("Target must be a valid string");this.context.logger.log(`Calling sip:${e}@${this.context.sipDomain}...`),this.context.joinVideoCall(`sip:${e}@${this.context.sipDomain}`,t,this.sipOptions)}stop(e={}){this.context.terminateJanusSessions(e)}startAudio(){this.context.enableJanusAudio(!0)}stopAudio(){this.context.enableJanusAudio(!1)}startVideo(){this.context.enableJanusVideo(!0)}stopVideo(){this.context.enableJanusVideo(!1)}changeMediaConstraints(e){this.context.changeMediaConstraints(e)}startScreenShare(){this.context.startScreenShare()}startBlur(){this.context.startBlur()}stopBlur(){this.context.stopBlur()}}class Sb{constructor(e){this.activeMessages={},this.extendedMessages={},this.msrpHistory={},this.context=e,this.context.on(this.context.newMSRPSessionEventName,this.newMSRPSessionCallback.bind(this.context))}get isMSRPInitializing(){return this.isMSRPInitializingValue}get getActiveMessages(){return this.activeMessages}msrpAnswer(e){const t=this.extendedMessages[e];this.updateMSRPSession(t)}updateMSRPSession(e){this.activeMessages[e._id]=wg(e),this.context.emit("changeActiveMessages",this.activeMessages)}addMMSRPSession(e){this.activeMessages={...this.activeMessages,[e._id]:wg(e)},this.extendedMessages[e._id]=e,this.context.emit("changeActiveMessages",this.activeMessages)}addMSRPMessage(e,t){const r=this.msrpHistory[t.id]||[];r.push(e),this.msrpHistory={...this.msrpHistory,[t.id]:[...r]},this.context.emit("newMSRPMessage",{message:e,session:t})}messageTerminate(e){const t=this.extendedMessages[e];t._status!==8&&t.terminate()}addMessageSession(e){if(!e._id||this.getActiveMessages[e._id]!==void 0)return;const r=e;this.addMMSRPSession(r)}triggerMSRPListener({listenerType:e,session:t,event:r}){const l=this.context.listenersList[e];!l||!l.length||l.forEach(s=>{s(t,r)})}removeMMSRPSession(e){const t={...this.activeMessages};delete t[e],this.activeMessages={...t};const r={...this.extendedMessages};delete r[e],this.extendedMessages={...r},this.context.emit("changeActiveMessages",this.activeMessages)}activeMessageListRemove(e){this.removeMMSRPSession(e._id)}newMSRPSessionCallback(e){const t=e.session;t.on("ended",r=>{this.triggerMSRPListener({listenerType:ys.CALL_ENDED,session:t,event:r});const l=this.getActiveMessages[t.id];this.activeMessageListRemove(l)}),t.on("failed",r=>{this.triggerMSRPListener({listenerType:ys.CALL_FAILED,session:t,event:r});const l=this.getActiveMessages[t.id];this.activeMessageListRemove(l)}),t.on("confirmed",r=>{this.triggerMSRPListener({listenerType:ys.CALL_CONFIRMED,session:t,event:r}),this.updateMSRPSession(t)}),t.on("newMessage",r=>{this.addMSRPMessage(r,t)}),this.addMessageSession(t)}setIsMSRPInitializing(e){this.isMSRPInitializingValue=e,this.context.emit("isMSRPInitializingChanged",e)}initMSRP(e,t,r){if(e.length===0)return console.error("Target must be a valid string");const l=this.context.startMSRP(e,r);l.on("active",()=>{this.addMessageSession(l),l.sendMSRP(t),this.setIsMSRPInitializing(!1)}),this.setIsMSRPInitializing(!0)}sendMSRP(e,t){const r=this.extendedMessages[e];if(!r)throw new Error(`MSRP session with id ${e} doesn't exist!`);r.sendMSRP(t)}}const $f={AUDIO:"audio",VIDEO:"video",MSRP:"msrp"};class Eb extends Jy{constructor(e,t){if(!e.modules.length)throw new Error("options.modules should include at least 1 module");const r={...e.configuration,sockets:e.socketInterfaces.map(l=>new EA.WebSocketInterface(l))};super(r),this.initialized=!1,this.connected=!1,this.logger=console,this.newRTCSessionEventName="newRTCSession",this.registeredEventName="registered",this.unregisteredEventName="unregistered",this.disconnectedEventName="disconnected",this.connectedEventName="connected",this.newMSRPSessionEventName="newMSRPSession",this.isReconnecting=!1,this.activeConnection=!1,this.audio=null,this.msrp=null,this.video=null,this.listenersList={},this.modules=[],e.pnExtraHeaders&&Object.keys(e.pnExtraHeaders).length&&this.registrator().setExtraContactUriParams(e.pnExtraHeaders),this.options=e,this.modules=e.modules,t&&rS(t)&&(this.logger=t)}on(e,t){return super.on(e,t)}off(e,t){return super.off(e,t)}emit(e,t){return super.emit(e,t)}get sipDomain(){return this.options.sipDomain}use(e){if(this.newStreamPlugins.find(t=>t.name===e.name)||this.processStreamPlugins.find(t=>t.name===e.name))throw new Error(`Plugin with name ${e.name} already exists`);if(e instanceof Wo)e.setOpensips(this),this.newStreamPlugins.push(e);else if(e instanceof Pf)e.setOpensips(this),this.processStreamPlugins.push(e);else throw new Error("Wrong plugin instance")}getPlugin(e){return this.newStreamPlugins.find(t=>t.name===e)||this.processStreamPlugins.find(t=>t.name===e)}begin(){if(this.isConnected()){console.error("Connection is already established");return}return this.modules.includes($f.AUDIO)&&(this.audio=new Tb(this)),this.modules.includes($f.MSRP)&&(this.msrp=new Sb(this)),this.modules.includes($f.VIDEO)&&(this.video=new yb(this)),this.on(this.registeredEventName,()=>{this.logger.log("Successfully registered to",this.options.socketInterfaces[0]),this.setInitialized(!0)}),this.on(this.unregisteredEventName,()=>{this.logger.log("Unregistered from",this.options.socketInterfaces[0]),this.setInitialized(!1)}),this.on(this.connectedEventName,()=>{this.logger.log("Connected to",this.options.socketInterfaces[0]),this.setConnected(!0),this.isReconnecting=!1,this.activeConnection=!0}),this.on(this.disconnectedEventName,()=>{this.isReconnecting||(this.isReconnecting=!0,this.logger.log("Disconnected from",this.options.socketInterfaces[0]),this.logger.log("Reconnecting to",this.options.socketInterfaces[0]),this.stop(),this.setInitialized(!1),this.setConnected(!1),this.activeConnection&&setTimeout(this.start.bind(this),5e3))}),this.logger.log("Connecting to",this.options.socketInterfaces[0]),this.start(),this}disconnect(){this.activeConnection=!1,this.stop()}subscribe(e,t){const l=!this.listenersList[e]||!this.listenersList[e].length?[t]:[...this.listenersList[e],t];this.listenersList={...this.listenersList,[e]:l}}removeIListener(e){const t={...this.listenersList};delete t[e],this.listenersList={...t}}triggerListener({listenerType:e,session:t,event:r}){const l=this.listenersList[e];!l||!l.length||l.forEach(s=>{s(t,r)})}setInitialized(e){this.initialized=e,this.emit("ready",e)}setConnected(e){this.connected=e,this.emit("connection",e)}}return zt.BaseNewStreamPlugin=Wo,zt.BaseProcessStreamPlugin=Pf,zt.ScreenSharePlugin=lS,zt.ScreenShareWhiteBoardPlugin=lA,zt.WhiteBoardPlugin=uA,zt.default=Eb,Object.defineProperties(zt,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}}),zt}({});
160
+ `),t=+this.fontSize(),r=0,l=this.lineHeight()*t,s=this.attrs.width,i=this.attrs.height,f=s!==zi&&s!==void 0,h=i!==zi&&i!==void 0,d=this.padding(),p=s-d*2,v=i-d*2,T=0,y=this.wrap(),S=y!==vp,A=y!==Z2&&S,R=this.ellipsis();this.textArr=[],yf().font=this._getContextFont();const O=R?this._getTextWidth(Tf):0;for(let C=0,b=e.length;C<b;++C){let w=e[C],F=this._getTextWidth(w);if(f&&F>p)for(;w.length>0;){let q=0,D=w.length,P="",I=0;for(;q<D;){const x=q+D>>>1,U=w.slice(0,x+1),B=this._getTextWidth(U)+O;B<=p?(q=x+1,P=U,I=B):D=x}if(P){if(A){var N;const U=w[P.length];(U===Tu||U===dp)&&I<=p?N=P.length:N=Math.max(P.lastIndexOf(Tu),P.lastIndexOf(dp))+1,N>0&&(q=N,P=P.slice(0,q),I=this._getTextWidth(P))}if(P=P.trimRight(),this._addTextLine(P),r=Math.max(r,I),T+=l,this._shouldHandleEllipsis(T)){this._tryToAddEllipsisToLastLine();break}if(w=w.slice(q),w=w.trimLeft(),w.length>0&&(F=this._getTextWidth(w),F<=p)){this._addTextLine(w),T+=l,r=Math.max(r,F);break}}else break}else this._addTextLine(w),T+=l,r=Math.max(r,F),this._shouldHandleEllipsis(T)&&C<b-1&&this._tryToAddEllipsisToLastLine();if(this.textArr[this.textArr.length-1]&&(this.textArr[this.textArr.length-1].lastInParagraph=!0),h&&T+l>v)break}this.textHeight=t,this.textWidth=r}_shouldHandleEllipsis(e){const t=+this.fontSize(),r=this.lineHeight()*t,l=this.attrs.height,s=l!==zi&&l!==void 0,i=this.padding(),f=l-i*2;return!(this.wrap()!==vp)||s&&e+r>f}_tryToAddEllipsisToLastLine(){const e=this.attrs.width,t=e!==zi&&e!==void 0,r=this.padding(),l=e-r*2,s=this.ellipsis(),i=this.textArr[this.textArr.length-1];!i||!s||(t&&(this._getTextWidth(i.text+Tf)<l||(i.text=i.text.slice(0,i.text.length-3))),this.textArr.splice(this.textArr.length-1,1),this._addTextLine(i.text+Tf))}getStrokeScaleEnabled(){return!0}_useBufferCanvas(){const e=this.textDecoration().indexOf("underline")!==-1||this.textDecoration().indexOf("line-through")!==-1,t=this.hasShadow();return e&&t?!0:super._useBufferCanvas()}}Yi.Text=ft,ft.prototype._fillFunc=sE,ft.prototype._strokeFunc=nE,ft.prototype.className=K2,ft.prototype._attrsAffectingSize=["text","fontSize","padding","wrap","lineHeight","letterSpacing"],(0,V2._registerNode)(ft),Bt.Factory.overWriteSetter(ft,"width",(0,Sn.getNumberOrAutoValidator)()),Bt.Factory.overWriteSetter(ft,"height",(0,Sn.getNumberOrAutoValidator)()),Bt.Factory.addGetterSetter(ft,"direction",fp),Bt.Factory.addGetterSetter(ft,"fontFamily","Arial"),Bt.Factory.addGetterSetter(ft,"fontSize",12,(0,Sn.getNumberValidator)()),Bt.Factory.addGetterSetter(ft,"fontStyle",pp),Bt.Factory.addGetterSetter(ft,"fontVariant",pp),Bt.Factory.addGetterSetter(ft,"padding",0,(0,Sn.getNumberValidator)()),Bt.Factory.addGetterSetter(ft,"align",_p),Bt.Factory.addGetterSetter(ft,"verticalAlign",Y2),Bt.Factory.addGetterSetter(ft,"lineHeight",1,(0,Sn.getNumberValidator)()),Bt.Factory.addGetterSetter(ft,"wrap",Q2),Bt.Factory.addGetterSetter(ft,"ellipsis",!1,(0,Sn.getBooleanValidator)()),Bt.Factory.addGetterSetter(ft,"letterSpacing",0,(0,Sn.getNumberValidator)()),Bt.Factory.addGetterSetter(ft,"text","",(0,Sn.getStringValidator)()),Bt.Factory.addGetterSetter(ft,"textDecoration","");var Su={};Object.defineProperty(Su,"__esModule",{value:!0}),Su.TextPath=void 0;const Sf=rt,vs=Fe,rE=Ct,El=ji,Ef=Yi,yp=Ne,lE=Le,aE="",Sp="normal";function Ep(u){u.fillText(this.partialText,0,0)}function Cp(u){u.strokeText(this.partialText,0,0)}class bt extends rE.Shape{constructor(e){super(e),this.dummyCanvas=Sf.Util.createCanvasElement(),this.dataArray=[],this._readDataAttribute(),this.on("dataChange.konva",function(){this._readDataAttribute(),this._setTextData()}),this.on("textChange.konva alignChange.konva letterSpacingChange.konva kerningFuncChange.konva fontSizeChange.konva fontFamilyChange.konva",this._setTextData),this._setTextData()}_getTextPathLength(){return El.Path.getPathLength(this.dataArray)}_getPointAtLength(e){if(!this.attrs.data)return null;const t=this.pathLength;return e-1>t?null:El.Path.getPointAtLengthOfDataArray(e,this.dataArray)}_readDataAttribute(){this.dataArray=El.Path.parsePathData(this.attrs.data),this.pathLength=this._getTextPathLength()}_sceneFunc(e){e.setAttr("font",this._getContextFont()),e.setAttr("textBaseline",this.textBaseline()),e.setAttr("textAlign","left"),e.save();const t=this.textDecoration(),r=this.fill(),l=this.fontSize(),s=this.glyphInfo;t==="underline"&&e.beginPath();for(let i=0;i<s.length;i++){e.save();const f=s[i].p0;e.translate(f.x,f.y),e.rotate(s[i].rotation),this.partialText=s[i].text,e.fillStrokeShape(this),t==="underline"&&(i===0&&e.moveTo(0,l/2+1),e.lineTo(l,l/2+1)),e.restore()}t==="underline"&&(e.strokeStyle=r,e.lineWidth=l/20,e.stroke()),e.restore()}_hitFunc(e){e.beginPath();const t=this.glyphInfo;if(t.length>=1){const r=t[0].p0;e.moveTo(r.x,r.y)}for(let r=0;r<t.length;r++){const l=t[r].p1;e.lineTo(l.x,l.y)}e.setAttr("lineWidth",this.fontSize()),e.setAttr("strokeStyle",this.colorKey),e.stroke()}getTextWidth(){return this.textWidth}getTextHeight(){return Sf.Util.warn("text.getTextHeight() method is deprecated. Use text.height() - for full height and text.fontSize() - for one line height."),this.textHeight}setText(e){return Ef.Text.prototype.setText.call(this,e)}_getContextFont(){return Ef.Text.prototype._getContextFont.call(this)}_getTextSize(e){const r=this.dummyCanvas.getContext("2d");r.save(),r.font=this._getContextFont();const l=r.measureText(e);return r.restore(),{width:l.width,height:parseInt(`${this.fontSize()}`,10)}}_setTextData(){const{width:e,height:t}=this._getTextSize(this.attrs.text);if(this.textWidth=e,this.textHeight=t,this.glyphInfo=[],!this.attrs.data)return null;const r=this.letterSpacing(),l=this.align(),s=this.kerningFunc(),i=Math.max(this.textWidth+((this.attrs.text||"").length-1)*r,0);let f=0;l==="center"&&(f=Math.max(0,this.pathLength/2-i/2)),l==="right"&&(f=Math.max(0,this.pathLength-i));const h=(0,Ef.stringToArray)(this.text());let d=f;for(let p=0;p<h.length;p++){const v=this._getPointAtLength(d);if(!v)return;let T=this._getTextSize(h[p]).width+r;if(h[p]===" "&&l==="justify"){const N=this.text().split(" ").length-1;T+=(this.pathLength-i)/N}const y=this._getPointAtLength(d+T);if(!y)return;const S=El.Path.getLineLength(v.x,v.y,y.x,y.y);let A=0;if(s)try{A=s(h[p-1],h[p])*this.fontSize()}catch{A=0}v.x+=A,y.x+=A,this.textWidth+=A;const R=El.Path.getPointOnLine(A+S/2,v.x,v.y,y.x,y.y),O=Math.atan2(y.y-v.y,y.x-v.x);this.glyphInfo.push({transposeX:R.x,transposeY:R.y,text:h[p],rotation:O,p0:v,p1:y}),d+=T}}getSelfRect(){if(!this.glyphInfo.length)return{x:0,y:0,width:0,height:0};const e=[];this.glyphInfo.forEach(function(d){e.push(d.p0.x),e.push(d.p0.y),e.push(d.p1.x),e.push(d.p1.y)});let t=e[0]||0,r=e[0]||0,l=e[1]||0,s=e[1]||0,i,f;for(let d=0;d<e.length/2;d++)i=e[d*2],f=e[d*2+1],t=Math.min(t,i),r=Math.max(r,i),l=Math.min(l,f),s=Math.max(s,f);const h=this.fontSize();return{x:t-h/2,y:l-h/2,width:r-t+h,height:s-l+h}}destroy(){return Sf.Util.releaseCanvas(this.dummyCanvas),super.destroy()}}Su.TextPath=bt,bt.prototype._fillFunc=Ep,bt.prototype._strokeFunc=Cp,bt.prototype._fillFuncHit=Ep,bt.prototype._strokeFuncHit=Cp,bt.prototype.className="TextPath",bt.prototype._attrsAffectingSize=["text","fontSize","data"],(0,lE._registerNode)(bt),vs.Factory.addGetterSetter(bt,"data"),vs.Factory.addGetterSetter(bt,"fontFamily","Arial"),vs.Factory.addGetterSetter(bt,"fontSize",12,(0,yp.getNumberValidator)()),vs.Factory.addGetterSetter(bt,"fontStyle",Sp),vs.Factory.addGetterSetter(bt,"align","left"),vs.Factory.addGetterSetter(bt,"letterSpacing",0,(0,yp.getNumberValidator)()),vs.Factory.addGetterSetter(bt,"textBaseline","middle"),vs.Factory.addGetterSetter(bt,"fontVariant",Sp),vs.Factory.addGetterSetter(bt,"text",aE),vs.Factory.addGetterSetter(bt,"textDecoration",null),vs.Factory.addGetterSetter(bt,"kerningFunc",null);var Eu={};Object.defineProperty(Eu,"__esModule",{value:!0}),Eu.Transformer=void 0;const Ye=rt,qe=Fe,Ap=it,oE=Ct,uE=yl,bp=Vi,Ts=Le,En=Ne,cE=Le,Rp="tr-konva",hE=["resizeEnabledChange","rotateAnchorOffsetChange","rotateEnabledChange","enabledAnchorsChange","anchorSizeChange","borderEnabledChange","borderStrokeChange","borderStrokeWidthChange","borderDashChange","anchorStrokeChange","anchorStrokeWidthChange","anchorFillChange","anchorCornerRadiusChange","ignoreStrokeChange","anchorStyleFuncChange"].map(u=>u+`.${Rp}`).join(" "),wp="nodesRect",fE=["widthChange","heightChange","scaleXChange","scaleYChange","skewXChange","skewYChange","rotationChange","offsetXChange","offsetYChange","transformsEnabledChange","strokeWidthChange"],dE={"top-left":-45,"top-center":0,"top-right":45,"middle-right":-90,"middle-left":90,"bottom-left":-135,"bottom-center":180,"bottom-right":135},_E="ontouchstart"in Ts.Konva._global;function gE(u,e,t){if(u==="rotater")return t;e+=Ye.Util.degToRad(dE[u]||0);const r=(Ye.Util.radToDeg(e)%360+360)%360;return Ye.Util._inRange(r,337.5,360)||Ye.Util._inRange(r,0,22.5)?"ns-resize":Ye.Util._inRange(r,22.5,67.5)?"nesw-resize":Ye.Util._inRange(r,67.5,112.5)?"ew-resize":Ye.Util._inRange(r,112.5,157.5)?"nwse-resize":Ye.Util._inRange(r,157.5,202.5)?"ns-resize":Ye.Util._inRange(r,202.5,247.5)?"nesw-resize":Ye.Util._inRange(r,247.5,292.5)?"ew-resize":Ye.Util._inRange(r,292.5,337.5)?"nwse-resize":(Ye.Util.error("Transformer has unknown angle for cursor detection: "+r),"pointer")}const Cu=["top-left","top-center","top-right","middle-right","middle-left","bottom-left","bottom-center","bottom-right"],Ip=1e8;function pE(u){return{x:u.x+u.width/2*Math.cos(u.rotation)+u.height/2*Math.sin(-u.rotation),y:u.y+u.height/2*Math.cos(u.rotation)+u.width/2*Math.sin(u.rotation)}}function Op(u,e,t){const r=t.x+(u.x-t.x)*Math.cos(e)-(u.y-t.y)*Math.sin(e),l=t.y+(u.x-t.x)*Math.sin(e)+(u.y-t.y)*Math.cos(e);return{...u,rotation:u.rotation+e,x:r,y:l}}function mE(u,e){const t=pE(u);return Op(u,e,t)}function vE(u,e,t){let r=e;for(let l=0;l<u.length;l++){const s=Ts.Konva.getAngle(u[l]),i=Math.abs(s-e)%(Math.PI*2);Math.min(i,Math.PI*2-i)<t&&(r=s)}return r}let Cf=0;class Ve extends bp.Group{constructor(e){super(e),this._movingAnchorName=null,this._transforming=!1,this._createElements(),this._handleMouseMove=this._handleMouseMove.bind(this),this._handleMouseUp=this._handleMouseUp.bind(this),this.update=this.update.bind(this),this.on(hE,this.update),this.getNode()&&this.update()}attachTo(e){return this.setNode(e),this}setNode(e){return Ye.Util.warn("tr.setNode(shape), tr.node(shape) and tr.attachTo(shape) methods are deprecated. Please use tr.nodes(nodesArray) instead."),this.setNodes([e])}getNode(){return this._nodes&&this._nodes[0]}_getEventNamespace(){return Rp+this._id}setNodes(e=[]){this._nodes&&this._nodes.length&&this.detach();const t=e.filter(l=>l.isAncestorOf(this)?(Ye.Util.error("Konva.Transformer cannot be an a child of the node you are trying to attach"),!1):!0);return this._nodes=e=t,e.length===1&&this.useSingleNodeRotation()?this.rotation(e[0].getAbsoluteRotation()):this.rotation(0),this._nodes.forEach(l=>{const s=()=>{this.nodes().length===1&&this.useSingleNodeRotation()&&this.rotation(this.nodes()[0].getAbsoluteRotation()),this._resetTransformCache(),!this._transforming&&!this.isDragging()&&this.update()},i=l._attrsAffectingSize.map(f=>f+"Change."+this._getEventNamespace()).join(" ");l.on(i,s),l.on(fE.map(f=>f+`.${this._getEventNamespace()}`).join(" "),s),l.on(`absoluteTransformChange.${this._getEventNamespace()}`,s),this._proxyDrag(l)}),this._resetTransformCache(),!!this.findOne(".top-left")&&this.update(),this}_proxyDrag(e){let t;e.on(`dragstart.${this._getEventNamespace()}`,r=>{t=e.getAbsolutePosition(),!this.isDragging()&&e!==this.findOne(".back")&&this.startDrag(r,!1)}),e.on(`dragmove.${this._getEventNamespace()}`,r=>{if(!t)return;const l=e.getAbsolutePosition(),s=l.x-t.x,i=l.y-t.y;this.nodes().forEach(f=>{if(f===e||f.isDragging())return;const h=f.getAbsolutePosition();f.setAbsolutePosition({x:h.x+s,y:h.y+i}),f.startDrag(r)}),t=null})}getNodes(){return this._nodes||[]}getActiveAnchor(){return this._movingAnchorName}detach(){this._nodes&&this._nodes.forEach(e=>{e.off("."+this._getEventNamespace())}),this._nodes=[],this._resetTransformCache()}_resetTransformCache(){this._clearCache(wp),this._clearCache("transform"),this._clearSelfAndDescendantCache("absoluteTransform")}_getNodeRect(){return this._getCache(wp,this.__getNodeRect)}__getNodeShape(e,t=this.rotation(),r){const l=e.getClientRect({skipTransform:!0,skipShadow:!0,skipStroke:this.ignoreStroke()}),s=e.getAbsoluteScale(r),i=e.getAbsolutePosition(r),f=l.x*s.x-e.offsetX()*s.x,h=l.y*s.y-e.offsetY()*s.y,d=(Ts.Konva.getAngle(e.getAbsoluteRotation())+Math.PI*2)%(Math.PI*2),p={x:i.x+f*Math.cos(d)+h*Math.sin(-d),y:i.y+h*Math.cos(d)+f*Math.sin(d),width:l.width*s.x,height:l.height*s.y,rotation:d};return Op(p,-Ts.Konva.getAngle(t),{x:0,y:0})}__getNodeRect(){if(!this.getNode())return{x:-Ip,y:-Ip,width:0,height:0,rotation:0};const t=[];this.nodes().map(d=>{const p=d.getClientRect({skipTransform:!0,skipShadow:!0,skipStroke:this.ignoreStroke()}),v=[{x:p.x,y:p.y},{x:p.x+p.width,y:p.y},{x:p.x+p.width,y:p.y+p.height},{x:p.x,y:p.y+p.height}],T=d.getAbsoluteTransform();v.forEach(function(y){const S=T.point(y);t.push(S)})});const r=new Ye.Transform;r.rotate(-Ts.Konva.getAngle(this.rotation()));let l=1/0,s=1/0,i=-1/0,f=-1/0;t.forEach(function(d){const p=r.point(d);l===void 0&&(l=i=p.x,s=f=p.y),l=Math.min(l,p.x),s=Math.min(s,p.y),i=Math.max(i,p.x),f=Math.max(f,p.y)}),r.invert();const h=r.point({x:l,y:s});return{x:h.x,y:h.y,width:i-l,height:f-s,rotation:Ts.Konva.getAngle(this.rotation())}}getX(){return this._getNodeRect().x}getY(){return this._getNodeRect().y}getWidth(){return this._getNodeRect().width}getHeight(){return this._getNodeRect().height}_createElements(){this._createBack(),Cu.forEach(e=>{this._createAnchor(e)}),this._createAnchor("rotater")}_createAnchor(e){const t=new uE.Rect({stroke:"rgb(0, 161, 255)",fill:"white",strokeWidth:1,name:e+" _anchor",dragDistance:0,draggable:!0,hitStrokeWidth:_E?10:"auto"}),r=this;t.on("mousedown touchstart",function(l){r._handleMouseDown(l)}),t.on("dragstart",l=>{t.stopDrag(),l.cancelBubble=!0}),t.on("dragend",l=>{l.cancelBubble=!0}),t.on("mouseenter",()=>{const l=Ts.Konva.getAngle(this.rotation()),s=this.rotateAnchorCursor(),i=gE(e,l,s);t.getStage().content&&(t.getStage().content.style.cursor=i),this._cursorChange=!0}),t.on("mouseout",()=>{t.getStage().content&&(t.getStage().content.style.cursor=""),this._cursorChange=!1}),this.add(t)}_createBack(){const e=new oE.Shape({name:"back",width:0,height:0,draggable:!0,sceneFunc(t,r){const l=r.getParent(),s=l.padding();t.beginPath(),t.rect(-s,-s,r.width()+s*2,r.height()+s*2),t.moveTo(r.width()/2,-s),l.rotateEnabled()&&l.rotateLineVisible()&&t.lineTo(r.width()/2,-l.rotateAnchorOffset()*Ye.Util._sign(r.height())-s),t.fillStrokeShape(r)},hitFunc:(t,r)=>{if(!this.shouldOverdrawWholeArea())return;const l=this.padding();t.beginPath(),t.rect(-l,-l,r.width()+l*2,r.height()+l*2),t.fillStrokeShape(r)}});this.add(e),this._proxyDrag(e),e.on("dragstart",t=>{t.cancelBubble=!0}),e.on("dragmove",t=>{t.cancelBubble=!0}),e.on("dragend",t=>{t.cancelBubble=!0}),this.on("dragmove",t=>{this.update()})}_handleMouseDown(e){if(this._transforming)return;this._movingAnchorName=e.target.name().split(" ")[0];const t=this._getNodeRect(),r=t.width,l=t.height,s=Math.sqrt(Math.pow(r,2)+Math.pow(l,2));this.sin=Math.abs(l/s),this.cos=Math.abs(r/s),typeof window<"u"&&(window.addEventListener("mousemove",this._handleMouseMove),window.addEventListener("touchmove",this._handleMouseMove),window.addEventListener("mouseup",this._handleMouseUp,!0),window.addEventListener("touchend",this._handleMouseUp,!0)),this._transforming=!0;const i=e.target.getAbsolutePosition(),f=e.target.getStage().getPointerPosition();this._anchorDragOffset={x:f.x-i.x,y:f.y-i.y},Cf++,this._fire("transformstart",{evt:e.evt,target:this.getNode()}),this._nodes.forEach(h=>{h._fire("transformstart",{evt:e.evt,target:h})})}_handleMouseMove(e){let t,r,l;const s=this.findOne("."+this._movingAnchorName),i=s.getStage();i.setPointersPositions(e);const f=i.getPointerPosition();let h={x:f.x-this._anchorDragOffset.x,y:f.y-this._anchorDragOffset.y};const d=s.getAbsolutePosition();this.anchorDragBoundFunc()&&(h=this.anchorDragBoundFunc()(d,h,e)),s.setAbsolutePosition(h);const p=s.getAbsolutePosition();if(d.x===p.x&&d.y===p.y)return;if(this._movingAnchorName==="rotater"){const w=this._getNodeRect();t=s.x()-w.width/2,r=-s.y()+w.height/2;let F=Math.atan2(-r,t)+Math.PI/2;w.height<0&&(F-=Math.PI);const D=Ts.Konva.getAngle(this.rotation())+F,P=Ts.Konva.getAngle(this.rotationSnapTolerance()),x=vE(this.rotationSnaps(),D,P)-w.rotation,U=mE(w,x);this._fitNodesInto(U,e);return}const v=this.shiftBehavior();let T;v==="inverted"?T=this.keepRatio()&&!e.shiftKey:v==="none"?T=this.keepRatio():T=this.keepRatio()||e.shiftKey;var O=this.centeredScaling()||e.altKey;if(this._movingAnchorName==="top-left"){if(T){var y=O?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".bottom-right").x(),y:this.findOne(".bottom-right").y()};l=Math.sqrt(Math.pow(y.x-s.x(),2)+Math.pow(y.y-s.y(),2));var S=this.findOne(".top-left").x()>y.x?-1:1,A=this.findOne(".top-left").y()>y.y?-1:1;t=l*this.cos*S,r=l*this.sin*A,this.findOne(".top-left").x(y.x-t),this.findOne(".top-left").y(y.y-r)}}else if(this._movingAnchorName==="top-center")this.findOne(".top-left").y(s.y());else if(this._movingAnchorName==="top-right"){if(T){var y=O?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".bottom-left").x(),y:this.findOne(".bottom-left").y()};l=Math.sqrt(Math.pow(s.x()-y.x,2)+Math.pow(y.y-s.y(),2));var S=this.findOne(".top-right").x()<y.x?-1:1,A=this.findOne(".top-right").y()>y.y?-1:1;t=l*this.cos*S,r=l*this.sin*A,this.findOne(".top-right").x(y.x+t),this.findOne(".top-right").y(y.y-r)}var R=s.position();this.findOne(".top-left").y(R.y),this.findOne(".bottom-right").x(R.x)}else if(this._movingAnchorName==="middle-left")this.findOne(".top-left").x(s.x());else if(this._movingAnchorName==="middle-right")this.findOne(".bottom-right").x(s.x());else if(this._movingAnchorName==="bottom-left"){if(T){var y=O?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".top-right").x(),y:this.findOne(".top-right").y()};l=Math.sqrt(Math.pow(y.x-s.x(),2)+Math.pow(s.y()-y.y,2));var S=y.x<s.x()?-1:1,A=s.y()<y.y?-1:1;t=l*this.cos*S,r=l*this.sin*A,s.x(y.x-t),s.y(y.y+r)}R=s.position(),this.findOne(".top-left").x(R.x),this.findOne(".bottom-right").y(R.y)}else if(this._movingAnchorName==="bottom-center")this.findOne(".bottom-right").y(s.y());else if(this._movingAnchorName==="bottom-right"){if(T){var y=O?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".top-left").x(),y:this.findOne(".top-left").y()};l=Math.sqrt(Math.pow(s.x()-y.x,2)+Math.pow(s.y()-y.y,2));var S=this.findOne(".bottom-right").x()<y.x?-1:1,A=this.findOne(".bottom-right").y()<y.y?-1:1;t=l*this.cos*S,r=l*this.sin*A,this.findOne(".bottom-right").x(y.x+t),this.findOne(".bottom-right").y(y.y+r)}}else console.error(new Error("Wrong position argument of selection resizer: "+this._movingAnchorName));var O=this.centeredScaling()||e.altKey;if(O){const w=this.findOne(".top-left"),F=this.findOne(".bottom-right"),q=w.x(),D=w.y(),P=this.getWidth()-F.x(),I=this.getHeight()-F.y();F.move({x:-q,y:-D}),w.move({x:P,y:I})}const N=this.findOne(".top-left").getAbsolutePosition();t=N.x,r=N.y;const C=this.findOne(".bottom-right").x()-this.findOne(".top-left").x(),b=this.findOne(".bottom-right").y()-this.findOne(".top-left").y();this._fitNodesInto({x:t,y:r,width:C,height:b,rotation:Ts.Konva.getAngle(this.rotation())},e)}_handleMouseUp(e){this._removeEvents(e)}getAbsoluteTransform(){return this.getTransform()}_removeEvents(e){var t;if(this._transforming){this._transforming=!1,typeof window<"u"&&(window.removeEventListener("mousemove",this._handleMouseMove),window.removeEventListener("touchmove",this._handleMouseMove),window.removeEventListener("mouseup",this._handleMouseUp,!0),window.removeEventListener("touchend",this._handleMouseUp,!0));const r=this.getNode();Cf--,this._fire("transformend",{evt:e,target:r}),(t=this.getLayer())===null||t===void 0||t.batchDraw(),r&&this._nodes.forEach(l=>{var s;l._fire("transformend",{evt:e,target:l}),(s=l.getLayer())===null||s===void 0||s.batchDraw()}),this._movingAnchorName=null}}_fitNodesInto(e,t){const r=this._getNodeRect(),l=1;if(Ye.Util._inRange(e.width,-this.padding()*2-l,l)){this.update();return}if(Ye.Util._inRange(e.height,-this.padding()*2-l,l)){this.update();return}const s=new Ye.Transform;if(s.rotate(Ts.Konva.getAngle(this.rotation())),this._movingAnchorName&&e.width<0&&this._movingAnchorName.indexOf("left")>=0){const T=s.point({x:-this.padding()*2,y:0});e.x+=T.x,e.y+=T.y,e.width+=this.padding()*2,this._movingAnchorName=this._movingAnchorName.replace("left","right"),this._anchorDragOffset.x-=T.x,this._anchorDragOffset.y-=T.y}else if(this._movingAnchorName&&e.width<0&&this._movingAnchorName.indexOf("right")>=0){const T=s.point({x:this.padding()*2,y:0});this._movingAnchorName=this._movingAnchorName.replace("right","left"),this._anchorDragOffset.x-=T.x,this._anchorDragOffset.y-=T.y,e.width+=this.padding()*2}if(this._movingAnchorName&&e.height<0&&this._movingAnchorName.indexOf("top")>=0){const T=s.point({x:0,y:-this.padding()*2});e.x+=T.x,e.y+=T.y,this._movingAnchorName=this._movingAnchorName.replace("top","bottom"),this._anchorDragOffset.x-=T.x,this._anchorDragOffset.y-=T.y,e.height+=this.padding()*2}else if(this._movingAnchorName&&e.height<0&&this._movingAnchorName.indexOf("bottom")>=0){const T=s.point({x:0,y:this.padding()*2});this._movingAnchorName=this._movingAnchorName.replace("bottom","top"),this._anchorDragOffset.x-=T.x,this._anchorDragOffset.y-=T.y,e.height+=this.padding()*2}if(this.boundBoxFunc()){const T=this.boundBoxFunc()(r,e);T?e=T:Ye.Util.warn("boundBoxFunc returned falsy. You should return new bound rect from it!")}const i=1e7,f=new Ye.Transform;f.translate(r.x,r.y),f.rotate(r.rotation),f.scale(r.width/i,r.height/i);const h=new Ye.Transform,d=e.width/i,p=e.height/i;this.flipEnabled()===!1?(h.translate(e.x,e.y),h.rotate(e.rotation),h.translate(e.width<0?e.width:0,e.height<0?e.height:0),h.scale(Math.abs(d),Math.abs(p))):(h.translate(e.x,e.y),h.rotate(e.rotation),h.scale(d,p));const v=h.multiply(f.invert());this._nodes.forEach(T=>{var y;const S=T.getParent().getAbsoluteTransform(),A=T.getTransform().copy();A.translate(T.offsetX(),T.offsetY());const R=new Ye.Transform;R.multiply(S.copy().invert()).multiply(v).multiply(S).multiply(A);const O=R.decompose();T.setAttrs(O),(y=T.getLayer())===null||y===void 0||y.batchDraw()}),this.rotation(Ye.Util._getRotation(e.rotation)),this._nodes.forEach(T=>{this._fire("transform",{evt:t,target:T}),T._fire("transform",{evt:t,target:T})}),this._resetTransformCache(),this.update(),this.getLayer().batchDraw()}forceUpdate(){this._resetTransformCache(),this.update()}_batchChangeChild(e,t){this.findOne(e).setAttrs(t)}update(){var e;const t=this._getNodeRect();this.rotation(Ye.Util._getRotation(t.rotation));const r=t.width,l=t.height,s=this.enabledAnchors(),i=this.resizeEnabled(),f=this.padding(),h=this.anchorSize(),d=this.find("._anchor");d.forEach(v=>{v.setAttrs({width:h,height:h,offsetX:h/2,offsetY:h/2,stroke:this.anchorStroke(),strokeWidth:this.anchorStrokeWidth(),fill:this.anchorFill(),cornerRadius:this.anchorCornerRadius()})}),this._batchChangeChild(".top-left",{x:0,y:0,offsetX:h/2+f,offsetY:h/2+f,visible:i&&s.indexOf("top-left")>=0}),this._batchChangeChild(".top-center",{x:r/2,y:0,offsetY:h/2+f,visible:i&&s.indexOf("top-center")>=0}),this._batchChangeChild(".top-right",{x:r,y:0,offsetX:h/2-f,offsetY:h/2+f,visible:i&&s.indexOf("top-right")>=0}),this._batchChangeChild(".middle-left",{x:0,y:l/2,offsetX:h/2+f,visible:i&&s.indexOf("middle-left")>=0}),this._batchChangeChild(".middle-right",{x:r,y:l/2,offsetX:h/2-f,visible:i&&s.indexOf("middle-right")>=0}),this._batchChangeChild(".bottom-left",{x:0,y:l,offsetX:h/2+f,offsetY:h/2-f,visible:i&&s.indexOf("bottom-left")>=0}),this._batchChangeChild(".bottom-center",{x:r/2,y:l,offsetY:h/2-f,visible:i&&s.indexOf("bottom-center")>=0}),this._batchChangeChild(".bottom-right",{x:r,y:l,offsetX:h/2-f,offsetY:h/2-f,visible:i&&s.indexOf("bottom-right")>=0}),this._batchChangeChild(".rotater",{x:r/2,y:-this.rotateAnchorOffset()*Ye.Util._sign(l)-f,visible:this.rotateEnabled()}),this._batchChangeChild(".back",{width:r,height:l,visible:this.borderEnabled(),stroke:this.borderStroke(),strokeWidth:this.borderStrokeWidth(),dash:this.borderDash(),x:0,y:0});const p=this.anchorStyleFunc();p&&d.forEach(v=>{p(v)}),(e=this.getLayer())===null||e===void 0||e.batchDraw()}isTransforming(){return this._transforming}stopTransform(){if(this._transforming){this._removeEvents();const e=this.findOne("."+this._movingAnchorName);e&&e.stopDrag()}}destroy(){return this.getStage()&&this._cursorChange&&this.getStage().content&&(this.getStage().content.style.cursor=""),bp.Group.prototype.destroy.call(this),this.detach(),this._removeEvents(),this}toObject(){return Ap.Node.prototype.toObject.call(this)}clone(e){return Ap.Node.prototype.clone.call(this,e)}getClientRect(){return this.nodes().length>0?super.getClientRect():{x:0,y:0,width:0,height:0}}}Eu.Transformer=Ve,Ve.isTransforming=()=>Cf>0;function TE(u){return u instanceof Array||Ye.Util.warn("enabledAnchors value should be an array"),u instanceof Array&&u.forEach(function(e){Cu.indexOf(e)===-1&&Ye.Util.warn("Unknown anchor name: "+e+". Available names are: "+Cu.join(", "))}),u||[]}Ve.prototype.className="Transformer",(0,cE._registerNode)(Ve),qe.Factory.addGetterSetter(Ve,"enabledAnchors",Cu,TE),qe.Factory.addGetterSetter(Ve,"flipEnabled",!0,(0,En.getBooleanValidator)()),qe.Factory.addGetterSetter(Ve,"resizeEnabled",!0),qe.Factory.addGetterSetter(Ve,"anchorSize",10,(0,En.getNumberValidator)()),qe.Factory.addGetterSetter(Ve,"rotateEnabled",!0),qe.Factory.addGetterSetter(Ve,"rotateLineVisible",!0),qe.Factory.addGetterSetter(Ve,"rotationSnaps",[]),qe.Factory.addGetterSetter(Ve,"rotateAnchorOffset",50,(0,En.getNumberValidator)()),qe.Factory.addGetterSetter(Ve,"rotateAnchorCursor","crosshair"),qe.Factory.addGetterSetter(Ve,"rotationSnapTolerance",5,(0,En.getNumberValidator)()),qe.Factory.addGetterSetter(Ve,"borderEnabled",!0),qe.Factory.addGetterSetter(Ve,"anchorStroke","rgb(0, 161, 255)"),qe.Factory.addGetterSetter(Ve,"anchorStrokeWidth",1,(0,En.getNumberValidator)()),qe.Factory.addGetterSetter(Ve,"anchorFill","white"),qe.Factory.addGetterSetter(Ve,"anchorCornerRadius",0,(0,En.getNumberValidator)()),qe.Factory.addGetterSetter(Ve,"borderStroke","rgb(0, 161, 255)"),qe.Factory.addGetterSetter(Ve,"borderStrokeWidth",1,(0,En.getNumberValidator)()),qe.Factory.addGetterSetter(Ve,"borderDash"),qe.Factory.addGetterSetter(Ve,"keepRatio",!0),qe.Factory.addGetterSetter(Ve,"shiftBehavior","default"),qe.Factory.addGetterSetter(Ve,"centeredScaling",!1),qe.Factory.addGetterSetter(Ve,"ignoreStroke",!1),qe.Factory.addGetterSetter(Ve,"padding",0,(0,En.getNumberValidator)()),qe.Factory.addGetterSetter(Ve,"node"),qe.Factory.addGetterSetter(Ve,"nodes"),qe.Factory.addGetterSetter(Ve,"boundBoxFunc"),qe.Factory.addGetterSetter(Ve,"anchorDragBoundFunc"),qe.Factory.addGetterSetter(Ve,"anchorStyleFunc"),qe.Factory.addGetterSetter(Ve,"shouldOverdrawWholeArea",!1),qe.Factory.addGetterSetter(Ve,"useSingleNodeRotation",!0),qe.Factory.backCompat(Ve,{lineEnabled:"borderEnabled",rotateHandlerOffset:"rotateAnchorOffset",enabledHandlers:"enabledAnchors"});var Au={};Object.defineProperty(Au,"__esModule",{value:!0}),Au.Wedge=void 0;const bu=Fe,yE=Ct,SE=Le,Dp=Ne,EE=Le;class Js extends yE.Shape{_sceneFunc(e){e.beginPath(),e.arc(0,0,this.radius(),0,SE.Konva.getAngle(this.angle()),this.clockwise()),e.lineTo(0,0),e.closePath(),e.fillStrokeShape(this)}getWidth(){return this.radius()*2}getHeight(){return this.radius()*2}setWidth(e){this.radius(e/2)}setHeight(e){this.radius(e/2)}}Au.Wedge=Js,Js.prototype.className="Wedge",Js.prototype._centroid=!0,Js.prototype._attrsAffectingSize=["radius"],(0,EE._registerNode)(Js),bu.Factory.addGetterSetter(Js,"radius",0,(0,Dp.getNumberValidator)()),bu.Factory.addGetterSetter(Js,"angle",0,(0,Dp.getNumberValidator)()),bu.Factory.addGetterSetter(Js,"clockwise",!1),bu.Factory.backCompat(Js,{angleDeg:"angle",getAngleDeg:"getAngle",setAngleDeg:"setAngle"});var Ru={};Object.defineProperty(Ru,"__esModule",{value:!0}),Ru.Blur=void 0;const Np=Fe,CE=it,AE=Ne;function Pp(){this.r=0,this.g=0,this.b=0,this.a=0,this.next=null}const bE=[512,512,456,512,328,456,335,512,405,328,271,456,388,335,292,512,454,405,364,328,298,271,496,456,420,388,360,335,312,292,273,512,482,454,428,405,383,364,345,328,312,298,284,271,259,496,475,456,437,420,404,388,374,360,347,335,323,312,302,292,282,273,265,512,497,482,468,454,441,428,417,405,394,383,373,364,354,345,337,328,320,312,305,298,291,284,278,271,265,259,507,496,485,475,465,456,446,437,428,420,412,404,396,388,381,374,367,360,354,347,341,335,329,323,318,312,307,302,297,292,287,282,278,273,269,265,261,512,505,497,489,482,475,468,461,454,447,441,435,428,422,417,411,405,399,394,389,383,378,373,368,364,359,354,350,345,341,337,332,328,324,320,316,312,309,305,301,298,294,291,287,284,281,278,274,271,268,265,262,259,257,507,501,496,491,485,480,475,470,465,460,456,451,446,442,437,433,428,424,420,416,412,408,404,400,396,392,388,385,381,377,374,370,367,363,360,357,354,350,347,344,341,338,335,332,329,326,323,320,318,315,312,310,307,304,302,299,297,294,292,289,287,285,282,280,278,275,273,271,269,267,265,263,261,259],RE=[9,11,12,13,13,14,14,15,15,15,15,16,16,16,16,17,17,17,17,17,17,17,18,18,18,18,18,18,18,18,18,19,19,19,19,19,19,19,19,19,19,19,19,19,19,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24];function wE(u,e){const t=u.data,r=u.width,l=u.height;let s,i,f,h,d,p,v,T,y,S,A,R,O,N,C,b,w,F,q,D,P,I,x,U,B=e+e+1,z=r-1,L=l-1,V=e+1,J=V*(V+1)/2,Pe=new Pp,ee=null,j=Pe,K=null,ie=null,ue=bE[e],Ce=RE[e];for(f=1;f<B;f++)j=j.next=new Pp,f===V&&(ee=j);for(j.next=Pe,v=p=0,i=0;i<l;i++){for(b=w=F=q=T=y=S=A=0,R=V*(D=t[p]),O=V*(P=t[p+1]),N=V*(I=t[p+2]),C=V*(x=t[p+3]),T+=J*D,y+=J*P,S+=J*I,A+=J*x,j=Pe,f=0;f<V;f++)j.r=D,j.g=P,j.b=I,j.a=x,j=j.next;for(f=1;f<V;f++)h=p+((z<f?z:f)<<2),T+=(j.r=D=t[h])*(U=V-f),y+=(j.g=P=t[h+1])*U,S+=(j.b=I=t[h+2])*U,A+=(j.a=x=t[h+3])*U,b+=D,w+=P,F+=I,q+=x,j=j.next;for(K=Pe,ie=ee,s=0;s<r;s++)t[p+3]=x=A*ue>>Ce,x!==0?(x=255/x,t[p]=(T*ue>>Ce)*x,t[p+1]=(y*ue>>Ce)*x,t[p+2]=(S*ue>>Ce)*x):t[p]=t[p+1]=t[p+2]=0,T-=R,y-=O,S-=N,A-=C,R-=K.r,O-=K.g,N-=K.b,C-=K.a,h=v+((h=s+e+1)<z?h:z)<<2,b+=K.r=t[h],w+=K.g=t[h+1],F+=K.b=t[h+2],q+=K.a=t[h+3],T+=b,y+=w,S+=F,A+=q,K=K.next,R+=D=ie.r,O+=P=ie.g,N+=I=ie.b,C+=x=ie.a,b-=D,w-=P,F-=I,q-=x,ie=ie.next,p+=4;v+=r}for(s=0;s<r;s++){for(w=F=q=b=y=S=A=T=0,p=s<<2,R=V*(D=t[p]),O=V*(P=t[p+1]),N=V*(I=t[p+2]),C=V*(x=t[p+3]),T+=J*D,y+=J*P,S+=J*I,A+=J*x,j=Pe,f=0;f<V;f++)j.r=D,j.g=P,j.b=I,j.a=x,j=j.next;for(d=r,f=1;f<=e;f++)p=d+s<<2,T+=(j.r=D=t[p])*(U=V-f),y+=(j.g=P=t[p+1])*U,S+=(j.b=I=t[p+2])*U,A+=(j.a=x=t[p+3])*U,b+=D,w+=P,F+=I,q+=x,j=j.next,f<L&&(d+=r);for(p=s,K=Pe,ie=ee,i=0;i<l;i++)h=p<<2,t[h+3]=x=A*ue>>Ce,x>0?(x=255/x,t[h]=(T*ue>>Ce)*x,t[h+1]=(y*ue>>Ce)*x,t[h+2]=(S*ue>>Ce)*x):t[h]=t[h+1]=t[h+2]=0,T-=R,y-=O,S-=N,A-=C,R-=K.r,O-=K.g,N-=K.b,C-=K.a,h=s+((h=i+V)<L?h:L)*r<<2,T+=b+=K.r=t[h],y+=w+=K.g=t[h+1],S+=F+=K.b=t[h+2],A+=q+=K.a=t[h+3],K=K.next,R+=D=ie.r,O+=P=ie.g,N+=I=ie.b,C+=x=ie.a,b-=D,w-=P,F-=I,q-=x,ie=ie.next,p+=r}}const IE=function(e){const t=Math.round(this.blurRadius());t>0&&wE(e,t)};Ru.Blur=IE,Np.Factory.addGetterSetter(CE.Node,"blurRadius",0,(0,AE.getNumberValidator)(),Np.Factory.afterSetFilter);var wu={};Object.defineProperty(wu,"__esModule",{value:!0}),wu.Brighten=void 0;const xp=Fe,OE=it,DE=Ne,NE=function(u){let e=this.brightness()*255,t=u.data,r=t.length,l;for(l=0;l<r;l+=4)t[l]+=e,t[l+1]+=e,t[l+2]+=e};wu.Brighten=NE,xp.Factory.addGetterSetter(OE.Node,"brightness",0,(0,DE.getNumberValidator)(),xp.Factory.afterSetFilter);var Iu={};Object.defineProperty(Iu,"__esModule",{value:!0}),Iu.Contrast=void 0;const kp=Fe,PE=it,xE=Ne,kE=function(u){const e=Math.pow((this.contrast()+100)/100,2);let t=u.data,r=t.length,l=150,s=150,i=150,f;for(f=0;f<r;f+=4)l=t[f],s=t[f+1],i=t[f+2],l/=255,l-=.5,l*=e,l+=.5,l*=255,s/=255,s-=.5,s*=e,s+=.5,s*=255,i/=255,i-=.5,i*=e,i+=.5,i*=255,l=l<0?0:l>255?255:l,s=s<0?0:s>255?255:s,i=i<0?0:i>255?255:i,t[f]=l,t[f+1]=s,t[f+2]=i};Iu.Contrast=kE,kp.Factory.addGetterSetter(PE.Node,"contrast",0,(0,xE.getNumberValidator)(),kp.Factory.afterSetFilter);var Ou={};Object.defineProperty(Ou,"__esModule",{value:!0}),Ou.Emboss=void 0;const Cn=Fe,Du=it,ME=rt,Mp=Ne,UE=function(u){let e=this.embossStrength()*10,t=this.embossWhiteLevel()*255,r=this.embossDirection(),l=this.embossBlend(),s=0,i=0,f=u.data,h=u.width,d=u.height,p=h*4,v=d;switch(r){case"top-left":s=-1,i=-1;break;case"top":s=-1,i=0;break;case"top-right":s=-1,i=1;break;case"right":s=0,i=1;break;case"bottom-right":s=1,i=1;break;case"bottom":s=1,i=0;break;case"bottom-left":s=1,i=-1;break;case"left":s=0,i=-1;break;default:ME.Util.error("Unknown emboss direction: "+r)}do{const T=(v-1)*p;let y=s;v+y<1&&(y=0),v+y>d&&(y=0);const S=(v-1+y)*h*4;let A=h;do{const R=T+(A-1)*4;let O=i;A+O<1&&(O=0),A+O>h&&(O=0);const N=S+(A-1+O)*4,C=f[R]-f[N],b=f[R+1]-f[N+1],w=f[R+2]-f[N+2];let F=C;const q=F>0?F:-F,D=b>0?b:-b,P=w>0?w:-w;if(D>q&&(F=b),P>q&&(F=w),F*=e,l){const I=f[R]+F,x=f[R+1]+F,U=f[R+2]+F;f[R]=I>255?255:I<0?0:I,f[R+1]=x>255?255:x<0?0:x,f[R+2]=U>255?255:U<0?0:U}else{let I=t-F;I<0?I=0:I>255&&(I=255),f[R]=f[R+1]=f[R+2]=I}}while(--A)}while(--v)};Ou.Emboss=UE,Cn.Factory.addGetterSetter(Du.Node,"embossStrength",.5,(0,Mp.getNumberValidator)(),Cn.Factory.afterSetFilter),Cn.Factory.addGetterSetter(Du.Node,"embossWhiteLevel",.5,(0,Mp.getNumberValidator)(),Cn.Factory.afterSetFilter),Cn.Factory.addGetterSetter(Du.Node,"embossDirection","top-left",null,Cn.Factory.afterSetFilter),Cn.Factory.addGetterSetter(Du.Node,"embossBlend",!1,null,Cn.Factory.afterSetFilter);var Nu={};Object.defineProperty(Nu,"__esModule",{value:!0}),Nu.Enhance=void 0;const Up=Fe,LE=it,FE=Ne;function Af(u,e,t,r,l){let s=t-e,i=l-r,f;return s===0?r+i/2:i===0?r:(f=(u-e)/s,f=i*f+r,f)}const $E=function(u){let e=u.data,t=e.length,r=e[0],l=r,s,i=e[1],f=i,h,d=e[2],p=d,v,T;const y=this.enhance();if(y===0)return;for(T=0;T<t;T+=4)s=e[T+0],s<r?r=s:s>l&&(l=s),h=e[T+1],h<i?i=h:h>f&&(f=h),v=e[T+2],v<d?d=v:v>p&&(p=v);l===r&&(l=255,r=0),f===i&&(f=255,i=0),p===d&&(p=255,d=0);let S,A,R,O,N,C,b,w,F;for(y>0?(A=l+y*(255-l),R=r-y*(r-0),N=f+y*(255-f),C=i-y*(i-0),w=p+y*(255-p),F=d-y*(d-0)):(S=(l+r)*.5,A=l+y*(l-S),R=r+y*(r-S),O=(f+i)*.5,N=f+y*(f-O),C=i+y*(i-O),b=(p+d)*.5,w=p+y*(p-b),F=d+y*(d-b)),T=0;T<t;T+=4)e[T+0]=Af(e[T+0],r,l,R,A),e[T+1]=Af(e[T+1],i,f,C,N),e[T+2]=Af(e[T+2],d,p,F,w)};Nu.Enhance=$E,Up.Factory.addGetterSetter(LE.Node,"enhance",0,(0,FE.getNumberValidator)(),Up.Factory.afterSetFilter);var Pu={};Object.defineProperty(Pu,"__esModule",{value:!0}),Pu.Grayscale=void 0;const HE=function(u){let e=u.data,t=e.length,r,l;for(r=0;r<t;r+=4)l=.34*e[r]+.5*e[r+1]+.16*e[r+2],e[r]=l,e[r+1]=l,e[r+2]=l};Pu.Grayscale=HE;var xu={};Object.defineProperty(xu,"__esModule",{value:!0}),xu.HSL=void 0;const Xi=Fe,bf=it,Rf=Ne;Xi.Factory.addGetterSetter(bf.Node,"hue",0,(0,Rf.getNumberValidator)(),Xi.Factory.afterSetFilter),Xi.Factory.addGetterSetter(bf.Node,"saturation",0,(0,Rf.getNumberValidator)(),Xi.Factory.afterSetFilter),Xi.Factory.addGetterSetter(bf.Node,"luminance",0,(0,Rf.getNumberValidator)(),Xi.Factory.afterSetFilter);const GE=function(u){let e=u.data,t=e.length,r=1,l=Math.pow(2,this.saturation()),s=Math.abs(this.hue()+360)%360,i=this.luminance()*127,f;const h=r*l*Math.cos(s*Math.PI/180),d=r*l*Math.sin(s*Math.PI/180),p=.299*r+.701*h+.167*d,v=.587*r-.587*h+.33*d,T=.114*r-.114*h-.497*d,y=.299*r-.299*h-.328*d,S=.587*r+.413*h+.035*d,A=.114*r-.114*h+.293*d,R=.299*r-.3*h+1.25*d,O=.587*r-.586*h-1.05*d,N=.114*r+.886*h-.2*d;let C,b,w,F;for(f=0;f<t;f+=4)C=e[f+0],b=e[f+1],w=e[f+2],F=e[f+3],e[f+0]=p*C+v*b+T*w+i,e[f+1]=y*C+S*b+A*w+i,e[f+2]=R*C+O*b+N*w+i,e[f+3]=F};xu.HSL=GE;var ku={};Object.defineProperty(ku,"__esModule",{value:!0}),ku.HSV=void 0;const Ji=Fe,wf=it,If=Ne,VE=function(u){const e=u.data,t=e.length,r=Math.pow(2,this.value()),l=Math.pow(2,this.saturation()),s=Math.abs(this.hue()+360)%360,i=r*l*Math.cos(s*Math.PI/180),f=r*l*Math.sin(s*Math.PI/180),h=.299*r+.701*i+.167*f,d=.587*r-.587*i+.33*f,p=.114*r-.114*i-.497*f,v=.299*r-.299*i-.328*f,T=.587*r+.413*i+.035*f,y=.114*r-.114*i+.293*f,S=.299*r-.3*i+1.25*f,A=.587*r-.586*i-1.05*f,R=.114*r+.886*i-.2*f;let O,N,C,b;for(let w=0;w<t;w+=4)O=e[w+0],N=e[w+1],C=e[w+2],b=e[w+3],e[w+0]=h*O+d*N+p*C,e[w+1]=v*O+T*N+y*C,e[w+2]=S*O+A*N+R*C,e[w+3]=b};ku.HSV=VE,Ji.Factory.addGetterSetter(wf.Node,"hue",0,(0,If.getNumberValidator)(),Ji.Factory.afterSetFilter),Ji.Factory.addGetterSetter(wf.Node,"saturation",0,(0,If.getNumberValidator)(),Ji.Factory.afterSetFilter),Ji.Factory.addGetterSetter(wf.Node,"value",0,(0,If.getNumberValidator)(),Ji.Factory.afterSetFilter);var Mu={};Object.defineProperty(Mu,"__esModule",{value:!0}),Mu.Invert=void 0;const BE=function(u){let e=u.data,t=e.length,r;for(r=0;r<t;r+=4)e[r]=255-e[r],e[r+1]=255-e[r+1],e[r+2]=255-e[r+2]};Mu.Invert=BE;var Uu={};Object.defineProperty(Uu,"__esModule",{value:!0}),Uu.Kaleidoscope=void 0;const Lu=Fe,Lp=it,Fp=rt,$p=Ne,jE=function(u,e,t){let r=u.data,l=e.data,s=u.width,i=u.height,f=t.polarCenterX||s/2,h=t.polarCenterY||i/2,d,p,v,T=0,y=0,S=0,A=0,R,O=Math.sqrt(f*f+h*h);p=s-f,v=i-h,R=Math.sqrt(p*p+v*v),O=R>O?R:O;let N=i,C=s,b,w,F=360/C*Math.PI/180,q,D;for(w=0;w<C;w+=1)for(q=Math.sin(w*F),D=Math.cos(w*F),b=0;b<N;b+=1)p=Math.floor(f+O*b/N*D),v=Math.floor(h+O*b/N*q),d=(v*s+p)*4,T=r[d+0],y=r[d+1],S=r[d+2],A=r[d+3],d=(w+b*s)*4,l[d+0]=T,l[d+1]=y,l[d+2]=S,l[d+3]=A},qE=function(u,e,t){let r=u.data,l=e.data,s=u.width,i=u.height,f=t.polarCenterX||s/2,h=t.polarCenterY||i/2,d,p,v,T,y,S=0,A=0,R=0,O=0,N,C=Math.sqrt(f*f+h*h);p=s-f,v=i-h,N=Math.sqrt(p*p+v*v),C=N>C?N:C;let b=i,w=s,F,q,D=t.polarRotation||0,P,I;for(p=0;p<s;p+=1)for(v=0;v<i;v+=1)T=p-f,y=v-h,F=Math.sqrt(T*T+y*y)*b/C,q=(Math.atan2(y,T)*180/Math.PI+360+D)%360,q=q*w/360,P=Math.floor(q),I=Math.floor(F),d=(I*s+P)*4,S=r[d+0],A=r[d+1],R=r[d+2],O=r[d+3],d=(v*s+p)*4,l[d+0]=S,l[d+1]=A,l[d+2]=R,l[d+3]=O},WE=function(u){const e=u.width,t=u.height;let r,l,s,i,f,h,d,p,v,T,y=Math.round(this.kaleidoscopePower());const S=Math.round(this.kaleidoscopeAngle()),A=Math.floor(e*(S%360)/360);if(y<1)return;const R=Fp.Util.createCanvasElement();R.width=e,R.height=t;const O=R.getContext("2d").getImageData(0,0,e,t);Fp.Util.releaseCanvas(R),jE(u,O,{polarCenterX:e/2,polarCenterY:t/2});let N=e/Math.pow(2,y);for(;N<=8;)N=N*2,y-=1;N=Math.ceil(N);let C=N,b=0,w=C,F=1;for(A+N>e&&(b=C,w=0,F=-1),l=0;l<t;l+=1)for(r=b;r!==w;r+=F)s=Math.round(r+A)%e,v=(e*l+s)*4,f=O.data[v+0],h=O.data[v+1],d=O.data[v+2],p=O.data[v+3],T=(e*l+r)*4,O.data[T+0]=f,O.data[T+1]=h,O.data[T+2]=d,O.data[T+3]=p;for(l=0;l<t;l+=1)for(C=Math.floor(N),i=0;i<y;i+=1){for(r=0;r<C+1;r+=1)v=(e*l+r)*4,f=O.data[v+0],h=O.data[v+1],d=O.data[v+2],p=O.data[v+3],T=(e*l+C*2-r-1)*4,O.data[T+0]=f,O.data[T+1]=h,O.data[T+2]=d,O.data[T+3]=p;C*=2}qE(O,u,{polarRotation:0})};Uu.Kaleidoscope=WE,Lu.Factory.addGetterSetter(Lp.Node,"kaleidoscopePower",2,(0,$p.getNumberValidator)(),Lu.Factory.afterSetFilter),Lu.Factory.addGetterSetter(Lp.Node,"kaleidoscopeAngle",0,(0,$p.getNumberValidator)(),Lu.Factory.afterSetFilter);var Fu={};Object.defineProperty(Fu,"__esModule",{value:!0}),Fu.Mask=void 0;const Hp=Fe,KE=it,YE=Ne;function $u(u,e,t){let r=(t*u.width+e)*4;const l=[];return l.push(u.data[r++],u.data[r++],u.data[r++],u.data[r++]),l}function Cl(u,e){return Math.sqrt(Math.pow(u[0]-e[0],2)+Math.pow(u[1]-e[1],2)+Math.pow(u[2]-e[2],2))}function zE(u){const e=[0,0,0];for(let t=0;t<u.length;t++)e[0]+=u[t][0],e[1]+=u[t][1],e[2]+=u[t][2];return e[0]/=u.length,e[1]/=u.length,e[2]/=u.length,e}function XE(u,e){const t=$u(u,0,0),r=$u(u,u.width-1,0),l=$u(u,0,u.height-1),s=$u(u,u.width-1,u.height-1),i=e||10;if(Cl(t,r)<i&&Cl(r,s)<i&&Cl(s,l)<i&&Cl(l,t)<i){const f=zE([r,t,s,l]),h=[];for(let d=0;d<u.width*u.height;d++){const p=Cl(f,[u.data[d*4],u.data[d*4+1],u.data[d*4+2]]);h[d]=p<i?0:255}return h}}function JE(u,e){for(let t=0;t<u.width*u.height;t++)u.data[4*t+3]=e[t]}function QE(u,e,t){const r=[1,1,1,1,0,1,1,1,1],l=Math.round(Math.sqrt(r.length)),s=Math.floor(l/2),i=[];for(let f=0;f<t;f++)for(let h=0;h<e;h++){const d=f*e+h;let p=0;for(let v=0;v<l;v++)for(let T=0;T<l;T++){const y=f+v-s,S=h+T-s;if(y>=0&&y<t&&S>=0&&S<e){const A=y*e+S,R=r[v*l+T];p+=u[A]*R}}i[d]=p===2040?255:0}return i}function ZE(u,e,t){const r=[1,1,1,1,1,1,1,1,1],l=Math.round(Math.sqrt(r.length)),s=Math.floor(l/2),i=[];for(let f=0;f<t;f++)for(let h=0;h<e;h++){const d=f*e+h;let p=0;for(let v=0;v<l;v++)for(let T=0;T<l;T++){const y=f+v-s,S=h+T-s;if(y>=0&&y<t&&S>=0&&S<e){const A=y*e+S,R=r[v*l+T];p+=u[A]*R}}i[d]=p>=1020?255:0}return i}function eC(u,e,t){const r=[.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111],l=Math.round(Math.sqrt(r.length)),s=Math.floor(l/2),i=[];for(let f=0;f<t;f++)for(let h=0;h<e;h++){const d=f*e+h;let p=0;for(let v=0;v<l;v++)for(let T=0;T<l;T++){const y=f+v-s,S=h+T-s;if(y>=0&&y<t&&S>=0&&S<e){const A=y*e+S,R=r[v*l+T];p+=u[A]*R}}i[d]=p}return i}const tC=function(u){let e=this.threshold(),t=XE(u,e);return t&&(t=QE(t,u.width,u.height),t=ZE(t,u.width,u.height),t=eC(t,u.width,u.height),JE(u,t)),u};Fu.Mask=tC,Hp.Factory.addGetterSetter(KE.Node,"threshold",0,(0,YE.getNumberValidator)(),Hp.Factory.afterSetFilter);var Hu={};Object.defineProperty(Hu,"__esModule",{value:!0}),Hu.Noise=void 0;const Gp=Fe,sC=it,nC=Ne,iC=function(u){const e=this.noise()*255,t=u.data,r=t.length,l=e/2;for(let s=0;s<r;s+=4)t[s+0]+=l-2*l*Math.random(),t[s+1]+=l-2*l*Math.random(),t[s+2]+=l-2*l*Math.random()};Hu.Noise=iC,Gp.Factory.addGetterSetter(sC.Node,"noise",.2,(0,nC.getNumberValidator)(),Gp.Factory.afterSetFilter);var Gu={};Object.defineProperty(Gu,"__esModule",{value:!0}),Gu.Pixelate=void 0;const Vp=Fe,rC=rt,lC=it,aC=Ne,oC=function(u){let e=Math.ceil(this.pixelSize()),t=u.width,r=u.height,l,s,i,f,h,d,p,v=Math.ceil(t/e),T=Math.ceil(r/e),y,S,A,R,O,N,C,b=u.data;if(e<=0){rC.Util.error("pixelSize value can not be <= 0");return}for(O=0;O<v;O+=1)for(N=0;N<T;N+=1){for(f=0,h=0,d=0,p=0,y=O*e,S=y+e,A=N*e,R=A+e,C=0,l=y;l<S;l+=1)if(!(l>=t))for(s=A;s<R;s+=1)s>=r||(i=(t*s+l)*4,f+=b[i+0],h+=b[i+1],d+=b[i+2],p+=b[i+3],C+=1);for(f=f/C,h=h/C,d=d/C,p=p/C,l=y;l<S;l+=1)if(!(l>=t))for(s=A;s<R;s+=1)s>=r||(i=(t*s+l)*4,b[i+0]=f,b[i+1]=h,b[i+2]=d,b[i+3]=p)}};Gu.Pixelate=oC,Vp.Factory.addGetterSetter(lC.Node,"pixelSize",8,(0,aC.getNumberValidator)(),Vp.Factory.afterSetFilter);var Vu={};Object.defineProperty(Vu,"__esModule",{value:!0}),Vu.Posterize=void 0;const Bp=Fe,uC=it,cC=Ne,hC=function(u){let e=Math.round(this.levels()*254)+1,t=u.data,r=t.length,l=255/e,s;for(s=0;s<r;s+=1)t[s]=Math.floor(t[s]/l)*l};Vu.Posterize=hC,Bp.Factory.addGetterSetter(uC.Node,"levels",.5,(0,cC.getNumberValidator)(),Bp.Factory.afterSetFilter);var Bu={};Object.defineProperty(Bu,"__esModule",{value:!0}),Bu.RGB=void 0;const ju=Fe,Of=it,fC=Ne,dC=function(u){let e=u.data,t=e.length,r=this.red(),l=this.green(),s=this.blue(),i,f;for(i=0;i<t;i+=4)f=(.34*e[i]+.5*e[i+1]+.16*e[i+2])/255,e[i]=f*r,e[i+1]=f*l,e[i+2]=f*s,e[i+3]=e[i+3]};Bu.RGB=dC,ju.Factory.addGetterSetter(Of.Node,"red",0,function(u){return this._filterUpToDate=!1,u>255?255:u<0?0:Math.round(u)}),ju.Factory.addGetterSetter(Of.Node,"green",0,function(u){return this._filterUpToDate=!1,u>255?255:u<0?0:Math.round(u)}),ju.Factory.addGetterSetter(Of.Node,"blue",0,fC.RGBComponent,ju.Factory.afterSetFilter);var qu={};Object.defineProperty(qu,"__esModule",{value:!0}),qu.RGBA=void 0;const Al=Fe,Wu=it,_C=Ne,gC=function(u){const e=u.data,t=e.length,r=this.red(),l=this.green(),s=this.blue(),i=this.alpha();for(let f=0;f<t;f+=4){const h=1-i;e[f]=r*i+e[f]*h,e[f+1]=l*i+e[f+1]*h,e[f+2]=s*i+e[f+2]*h}};qu.RGBA=gC,Al.Factory.addGetterSetter(Wu.Node,"red",0,function(u){return this._filterUpToDate=!1,u>255?255:u<0?0:Math.round(u)}),Al.Factory.addGetterSetter(Wu.Node,"green",0,function(u){return this._filterUpToDate=!1,u>255?255:u<0?0:Math.round(u)}),Al.Factory.addGetterSetter(Wu.Node,"blue",0,_C.RGBComponent,Al.Factory.afterSetFilter),Al.Factory.addGetterSetter(Wu.Node,"alpha",1,function(u){return this._filterUpToDate=!1,u>1?1:u<0?0:u});var Ku={};Object.defineProperty(Ku,"__esModule",{value:!0}),Ku.Sepia=void 0;const pC=function(u){let e=u.data,t=e.length,r,l,s,i;for(r=0;r<t;r+=4)l=e[r+0],s=e[r+1],i=e[r+2],e[r+0]=Math.min(255,l*.393+s*.769+i*.189),e[r+1]=Math.min(255,l*.349+s*.686+i*.168),e[r+2]=Math.min(255,l*.272+s*.534+i*.131)};Ku.Sepia=pC;var Yu={};Object.defineProperty(Yu,"__esModule",{value:!0}),Yu.Solarize=void 0;const mC=function(u){const e=u.data,t=u.width,r=u.height,l=t*4;let s=r;do{const i=(s-1)*l;let f=t;do{const h=i+(f-1)*4;let d=e[h],p=e[h+1],v=e[h+2];d>127&&(d=255-d),p>127&&(p=255-p),v>127&&(v=255-v),e[h]=d,e[h+1]=p,e[h+2]=v}while(--f)}while(--s)};Yu.Solarize=mC;var zu={};Object.defineProperty(zu,"__esModule",{value:!0}),zu.Threshold=void 0;const jp=Fe,vC=it,TC=Ne,yC=function(u){const e=this.threshold()*255,t=u.data,r=t.length;for(let l=0;l<r;l+=1)t[l]=t[l]<e?0:255};zu.Threshold=yC,jp.Factory.addGetterSetter(vC.Node,"threshold",.5,(0,TC.getNumberValidator)(),jp.Factory.afterSetFilter),Object.defineProperty(Ko,"__esModule",{value:!0}),Ko.Konva=void 0;const qp=Ng,SC=iu,EC=au,CC=cu,AC=hu,bC=fu,Wp=Ki,RC=vl,wC=ji,IC=yl,OC=gu,DC=pu,NC=mu,PC=vu,xC=Yi,kC=Su,MC=Eu,UC=Au,LC=Ru,FC=wu,$C=Iu,HC=Ou,GC=Nu,VC=Pu,BC=xu,jC=ku,qC=Mu,WC=Uu,KC=Fu,YC=Hu,zC=Gu,XC=Vu,JC=Bu,QC=qu,ZC=Ku,eA=Yu,tA=zu;Ko.Konva=qp.Konva.Util._assign(qp.Konva,{Arc:SC.Arc,Arrow:EC.Arrow,Circle:CC.Circle,Ellipse:AC.Ellipse,Image:bC.Image,Label:Wp.Label,Tag:Wp.Tag,Line:RC.Line,Path:wC.Path,Rect:IC.Rect,RegularPolygon:OC.RegularPolygon,Ring:DC.Ring,Sprite:NC.Sprite,Star:PC.Star,Text:xC.Text,TextPath:kC.TextPath,Transformer:MC.Transformer,Wedge:UC.Wedge,Filters:{Blur:LC.Blur,Brighten:FC.Brighten,Contrast:$C.Contrast,Emboss:HC.Emboss,Enhance:GC.Enhance,Grayscale:VC.Grayscale,HSL:BC.HSL,HSV:jC.HSV,Invert:qC.Invert,Kaleidoscope:WC.Kaleidoscope,Mask:KC.Mask,Noise:YC.Noise,Pixelate:zC.Pixelate,Posterize:XC.Posterize,RGB:JC.RGB,RGBA:QC.RGBA,Sepia:ZC.Sepia,Solarize:eA.Solarize,Threshold:tA.Threshold}});var sA=Yh.exports;Object.defineProperty(sA,"__esModule",{value:!0});const nA=Ko;Yh.exports=nA.Konva;var iA=Yh.exports;const Qi=We(iA),Df={STROKE_WIDTH:5,STROKE_COLOR:"#f32",EMPTY_DRAWER_RECT_COLOR:"#fff"};class Nf{constructor(e){this.stage=null,this.strokeWidth=Df.STROKE_WIDTH,this.strokeColor=Df.STROKE_COLOR,this.emptyDrawerRectColor=Df.EMPTY_DRAWER_RECT_COLOR,this.emptyDrawerRect=null;const{container:t,width:r,height:l}=e,s=new Qi.Stage({container:t,width:r,height:l});this.stage=s,this.setupDrawerOptions(e)}setupDrawerOptions(e){e.strokeWidth&&(this.strokeWidth=e.strokeWidth),e.strokeColor&&(this.strokeColor=e.strokeColor),e.emptyDrawerRectColor&&(this.emptyDrawerRectColor=e.emptyDrawerRectColor,this.emptyDrawerRect&&this.emptyDrawerRect.fill(e.emptyDrawerRectColor))}addLayer(){const e=new Qi.Layer;return this.stage.add(e),e}initFreeDrawing(e){let t=!1,r;this.stage.on("mousedown touchstart",l=>{t=!0;const s=this.stage.getPointerPosition();r=new Qi.Line({stroke:this.strokeColor,strokeWidth:this.strokeWidth,globalCompositeOperation:"source-over",lineCap:"round",lineJoin:"round",points:[s.x,s.y,s.x,s.y]}),e.add(r)}),this.stage.on("mouseup touchend",()=>{t=!1}),this.stage.on("mousemove touchmove",l=>{if(!t)return;l.evt.preventDefault();const s=this.stage.getPointerPosition(),i=r.points().concat([s.x,s.y]);r.points(i)})}addRect(e,t,r){const l=new Qi.Rect({width:t,height:r,fill:this.emptyDrawerRectColor});return e.add(l),this.emptyDrawerRect=l,l}addImage(e,t){let r,l;const s=t.width/t.height;this.stage.width()<t.width?(r=this.stage.width(),l=this.stage.width()/s):(r=t.width,l=t.width/s);const i=new Qi.Image({image:t,x:(this.stage.width()-r)/2,y:(this.stage.height()-l)/2,width:r,height:l});return e.add(i),i}addWakeupLine(e){const t=new Qi.Line({stroke:"#ffffff",strokeWidth:1,globalCompositeOperation:"source-over",lineCap:"round",lineJoin:"round",points:[0,0,0,0]});e.add(t)}}class Pf extends Dg{constructor(e,t,r={}){super(e),this.stream=null,this.running=!1,this.immediate=!1,this.type="video",this.immediate=r.immediate||!1,this.type=t}start(e){return e}stop(){throw new Error("stop method is not implemented")}async process(e){if(this.immediate){const t=await this.start(e);return this.running=!0,t}return e}async connect(){this.running=!0,await this.session.resyncPlugins(this.type)}terminate(){this.stop()}async kill(){this.stop(),this.running=!1,await this.session.resyncPlugins(this.type)}}const rA={container:"screen-share-video-container",compositeCanvasContainer:"composite-canvas-container",compositeCanvas:"composite-canvas",drawerContainer:"container",videoElement:"whiteboard-source-video",videoElementContainer:"whiteboard-wrapper"};class lA extends Pf{constructor(e,t={}){super("ScreenShareWhiteboard","screen"),this.video=null,this.wrapperEl=null,this.screenShareKonvaDrawer=null,this.initialStream=null,this.imageSrc=null,this.konvaDrawer=null,this.mode=void 0,this.screenSharePlugin=null,this.selectors={},this.screenSharePlugin=e,this.selectors={...rA,...t.selectors||{}},this.selectors.document||(this.selectors.document=document)}createVideoElement(){const e=document.createElement("video");e.setAttribute("id",this.selectors.videoElement),e.setAttribute("autoplay",""),e.style.setProperty("visibility","hidden"),e.style.setProperty("width","auto"),e.style.setProperty("height","auto"),this.video=e;const t=document.createElement("div");t.classList.add(this.selectors.videoElementContainer),t.style.setProperty("display","none"),t.appendChild(e),this.wrapperEl=t,this.selectors.document.body?this.selectors.document.body.appendChild(t):this.selectors.document.appendChild(t)}getAspectRatioDimensions(e,t){const r=e.getTracks()[0].getSettings(),l=t.clientWidth,s=t.clientHeight,i=r.width,f=r.height,h=i/f,d=l/s;let p=0,v=0;return h>d?(p=l,v=l/h):(v=s,p=s*h),{width:p,height:v}}async start(e){this.createVideoElement(),this.initialStream=e,this.video.srcObject=e.clone();const t=this.selectors.document.getElementById(this.selectors.container);t.style.setProperty("position","relative"),t.style.setProperty("min-width","100%"),t.style.setProperty("height","100%"),t.style.setProperty("display","flex"),t.style.setProperty("justify-content","center");const r=this.selectors.document.getElementById(this.selectors.compositeCanvasContainer);r.style.setProperty("position","relative"),r.style.setProperty("margin","auto 0");const{width:l,height:s}=this.getAspectRatioDimensions(e,t);let i=l,f=s;const h=this.selectors.document.getElementById(this.selectors.drawerContainer);this.screenShareKonvaDrawer=new Nf({container:h,width:i,height:f});const d=this.screenShareKonvaDrawer.addLayer();this.screenShareKonvaDrawer.initFreeDrawing(d);const p=this.selectors.document.getElementById(this.selectors.drawerContainer),v=p.querySelector("canvas"),T=p.querySelector(".konvajs-content"),y=this.selectors.document.getElementById(this.selectors.compositeCanvas);y.style.setProperty("position","absolute"),y.style.setProperty("top","0"),y.style.setProperty("left","0");const S=y.getContext("2d"),A=()=>{const{width:N,height:C}=this.getAspectRatioDimensions(e,t);i=N,f=C,v.width=N,v.height=C,v.style.width=`${N}px`,v.style.height=`${C}px`,T.style.width=`${N}px`,T.style.height=`${C}px`,r.style.height=`${C}px`,y.width=N,y.height=C};A(),window&&window.addEventListener&&typeof window.addEventListener=="function"&&window.addEventListener("resize",()=>{A(),this.screenShareKonvaDrawer.addWakeupLine(d)});const R=this.video,O=()=>{S.drawImage(R,0,0,i,f),S.drawImage(v,0,0,i,f),requestAnimationFrame(O)};return O(),y.captureStream(30)}stop(){this.initialStream=null,this.video=null,this.wrapperEl=null,this.screenShareKonvaDrawer=null}setupScreenShareDrawerOptions(e){this.screenShareKonvaDrawer&&this.screenShareKonvaDrawer.setupDrawerOptions(e)}}function aA(u){return new Promise((e,t)=>{const r=new Image;r.onload=()=>{e(r)},r.onerror=l=>{t(l)},r.src=u})}const Kp={WHITEBOARD:"whiteboard",IMAGE_WHITEBOARD:"imageWhiteboard"},oA={container:"presentation-video-container",drawerContainer:"presentationCanvasWrapper"};class uA extends Wo{constructor(e){super("WhiteBoard"),this.visualizationConfig={},this.rafId=null,this.imageSrc=null,this.konvaDrawer=null,this.selectors={},this.mode=void 0,this.mode=e.mode,e.imageSrc&&(this.imageSrc=e.imageSrc),this.selectors={...oA,...e.selectors||{}},this.selectors.document||(this.selectors.document=document)}setupDrawerOptions(e){this.konvaDrawer&&this.konvaDrawer.setupDrawerOptions(e)}setMode(e,t){this.mode=e,t&&(this.imageSrc=t)}setupDrawerImage(e){this.imageSrc=e}drawEmptyWhiteboard(){const e=this.selectors.document.getElementById(this.selectors.container);e.style.setProperty("min-width","100%"),e.style.setProperty("height","100%");const t=e.clientWidth,r=e.clientHeight,l=this.selectors.document.getElementById(this.selectors.drawerContainer);this.konvaDrawer=new Nf({container:l,width:t,height:r});const s=this.konvaDrawer.addLayer();this.konvaDrawer.addRect(s,t,r),this.konvaDrawer.initFreeDrawing(s)}async drawImageWhiteboard(){const e=this.selectors.document.getElementById(this.selectors.container);e.style.setProperty("min-width","100%"),e.style.setProperty("height","100%");const t=e.clientWidth,r=e.clientHeight,l=await aA(this.imageSrc),s=this.selectors.document.getElementById(this.selectors.drawerContainer);this.konvaDrawer=new Nf({container:s,width:t,height:r});const i=this.konvaDrawer.addLayer();this.konvaDrawer.addImage(i,l),i.batchDraw(),this.konvaDrawer.initFreeDrawing(i)}async generateStream(){if(this.mode===Kp.WHITEBOARD)this.drawEmptyWhiteboard();else if(this.mode===Kp.IMAGE_WHITEBOARD)await this.drawImageWhiteboard();else return;const t=this.selectors.document.getElementById(this.selectors.drawerContainer).querySelector("canvas"),r=t.getContext("2d");function l(){r.fillRect(0,0,1,1),requestAnimationFrame(l)}l();const s=t.captureStream(30);this.stream=s}async kill(){this.konvaDrawer=null,await this.stop(),this.session._ua.emit("stopWhiteboard")}}const cA=Et,hA=_s(),Kt=new cA("WebSocketInterface");var fA=class{constructor(e){Kt.debug('new() [url:"%s"]',e),this._url=e,this._sip_uri=null,this._via_transport=null,this._ws=null;const t=hA.parse(e,"absoluteURI");if(t===-1)throw Kt.warn(`invalid WebSocket URI: ${e}`),new TypeError(`Invalid argument: ${e}`);if(t.scheme!=="wss"&&t.scheme!=="ws")throw Kt.warn(`invalid WebSocket URI scheme: ${t.scheme}`),new TypeError(`Invalid argument: ${e}`);this._sip_uri=`sip:${t.host}${t.port?`:${t.port}`:""};transport=ws`,this._via_transport=t.scheme.toUpperCase()}get via_transport(){return this._via_transport}set via_transport(e){this._via_transport=e.toUpperCase()}get sip_uri(){return this._sip_uri}get url(){return this._url}connect(){if(Kt.debug("connect()"),this.isConnected()){Kt.debug(`WebSocket ${this._url} is already connected`);return}else if(this.isConnecting()){Kt.debug(`WebSocket ${this._url} is connecting`);return}this._ws&&this.disconnect(),Kt.debug(`connecting to WebSocket ${this._url}`);try{this._ws=new WebSocket(this._url,"sip"),this._ws.binaryType="arraybuffer",this._ws.onopen=this._onOpen.bind(this),this._ws.onclose=this._onClose.bind(this),this._ws.onmessage=this._onMessage.bind(this),this._ws.onerror=this._onError.bind(this)}catch(e){this._onError(e)}}disconnect(){Kt.debug("disconnect()"),this._ws&&(this._ws.onopen=()=>{},this._ws.onclose=()=>{},this._ws.onmessage=()=>{},this._ws.onerror=()=>{},this._ws.close(),this._ws=null)}send(e){return Kt.debug("send()"),this.isConnected()?(this._ws.send(e),!0):(Kt.warn("unable to send message, WebSocket is not open"),!1)}isConnected(){return this._ws&&this._ws.readyState===this._ws.OPEN}isConnecting(){return this._ws&&this._ws.readyState===this._ws.CONNECTING}_onOpen(){Kt.debug(`WebSocket ${this._url} connected`),this.onconnect()}_onClose({wasClean:e,code:t,reason:r}){Kt.debug(`WebSocket ${this._url} closed`),e===!1&&Kt.debug("WebSocket abrupt disconnection"),this.ondisconnect(!e,t,r)}_onMessage({data:e}){Kt.debug("received WebSocket message"),this.ondata(e)}_onError(e){Kt.warn(`WebSocket ${this._url} error: `,e)}};const xf=Ha,dA=Ue,_A=Bs,gA=xt(),pA=Cg,mA=Hs(),vA=_h(),TA=_s(),yA=fA;Ii("JsSIP")("version %s",xf.version);var SA={C:dA,Exceptions:_A,Utils:gA,UA:pA,URI:mA,NameAddrHeader:vA,WebSocketInterface:yA,Grammar:TA,debug:Ii,get name(){return xf.title},get version(){return xf.version}};const EA=We(SA);function kf(u){return u<10?`0${u}`:`${u}`}function CA(u){let e=u.hours||0,t=u.minutes||0,r=u.seconds||0;r++,r===60&&(r=0,t++,t===60&&(t=0,e++));const l=`${kf(e)}:${kf(t)}:${kf(r)}`;return{seconds:r,minutes:t,hours:e,formatted:l}}var $t={};$t.forEach=async(u,e,t)=>{const r=[];for(let l=0;l<u.length;l++)if(l in u){const s=Promise.resolve(u[l]).then(i=>e.call(t||globalThis,i,l,u));r.push(s)}await Promise.all(r)},$t.forEachSeries=async(u,e,t)=>{for(let r=0;r<u.length;r++)r in u&&await e.call(t||globalThis,await u[r],r,u)},$t.map=async(u,e,t)=>{const r=[];for(let l=0;l<u.length;l++)l in u&&(r[l]=Promise.resolve(u[l]).then(s=>e.call(t||globalThis,s,l,u)));return Promise.all(r)},$t.mapSeries=async(u,e,t)=>{const r=[];for(let l=0;l<u.length;l++)l in u&&(r[l]=await e.call(t||globalThis,await u[l],l,u));return r},$t.find=(u,e,t)=>new Promise((r,l)=>{if(u.length===0)return r();let s=1;for(let i=0;i<u.length;i++){const f=h=>{h?r(u[i]):s===u.length&&r(),s++};Promise.resolve(u[i]).then(h=>e.call(t||globalThis,h,i,u)).then(f).catch(l)}}),$t.findSeries=async(u,e,t)=>{for(let r=0;r<u.length;r++)if(await e.call(t||globalThis,await u[r],r,u))return u[r]},$t.findIndex=(u,e,t)=>new Promise((r,l)=>{if(u.length===0)return r(-1);let s=1;for(let i=0;i<u.length;i++){const f=h=>{h?r(i):s===u.length&&r(-1),s++};Promise.resolve(u[i]).then(h=>e.call(t||globalThis,h,i,u)).then(f).catch(l)}}),$t.findIndexSeries=async(u,e,t)=>{for(let r=0;r<u.length;r++)if(await e.call(t||globalThis,await u[r],r,u))return r},$t.some=(u,e,t)=>new Promise((r,l)=>{if(u.length===0)return r(!1);let s=1;for(let i=0;i<u.length;i++){if(!(i in u)){s++;continue}const f=h=>{h?r(!0):s===u.length&&r(!1),s++};Promise.resolve(u[i]).then(h=>e.call(t||globalThis,h,i,u)).then(f).catch(l)}}),$t.someSeries=async(u,e,t)=>{for(let r=0;r<u.length;r++)if(r in u&&await e.call(t||globalThis,await u[r],r,u))return!0;return!1},$t.every=(u,e,t)=>new Promise((r,l)=>{if(u.length===0)return r(!0);let s=1;for(let i=0;i<u.length;i++){if(!(i in u)){s++;continue}const f=h=>{h?s===u.length&&r(!0):r(!1),s++};Promise.resolve(u[i]).then(h=>e.call(t||globalThis,h,i,u)).then(f).catch(l)}}),$t.everySeries=async(u,e,t)=>{for(let r=0;r<u.length;r++)if(r in u&&!await e.call(t||globalThis,await u[r],r,u))return!1;return!0},$t.filter=(u,e,t)=>new Promise(async(r,l)=>{const s=[];for(let f=0;f<u.length;f++)f in u&&(s[f]=Promise.resolve(u[f]).then(h=>e.call(t||globalThis,h,f,u)).catch(l));const i=[];for(let f=0;f<s.length;f++)await s[f]&&i.push(await u[f]);r(i)}),$t.filterSeries=async(u,e,t)=>{const r=[];for(let l=0;l<u.length;l++)l in u&&await e.call(t||globalThis,await u[l],l,u)&&r.push(await u[l]);return r},$t.reduce=async(u,e,t)=>{if(u.length===0&&t===void 0)throw TypeError("Reduce of empty array with no initial value");let r,l;for(t!==void 0?(l=t,r=0):(l=u[0],r=1),r;r<u.length;r++)r in u&&(l=await e(await l,await u[r],r,u));return l};var Yp={};(function(u){const e=$t;Object.keys(e).forEach(t=>{const r=t.charAt(0).toUpperCase()+t.slice(1);u[`async${r}`]=async function(...l){return e[t](this,...l)}})})(Yp);var AA=Object.assign($t,{instanceMethods:Yp});const ni=new AudioContext,ys={NEW_CALL:"new_call",CALL_CONFIRMED:"confirmed",CALL_FAILED:"failed",CALL_PROGRESS:"progress",CALL_ENDED:"ended"};var bA={exports:{}};(function(u){var e=function(t){var r=Object.prototype,l=r.hasOwnProperty,s=Object.defineProperty||function(ee,j,K){ee[j]=K.value},i,f=typeof Symbol=="function"?Symbol:{},h=f.iterator||"@@iterator",d=f.asyncIterator||"@@asyncIterator",p=f.toStringTag||"@@toStringTag";function v(ee,j,K){return Object.defineProperty(ee,j,{value:K,enumerable:!0,configurable:!0,writable:!0}),ee[j]}try{v({},"")}catch{v=function(j,K,ie){return j[K]=ie}}function T(ee,j,K,ie){var ue=j&&j.prototype instanceof C?j:C,Ce=Object.create(ue.prototype),ke=new V(ie||[]);return s(Ce,"_invoke",{value:U(ee,K,ke)}),Ce}t.wrap=T;function y(ee,j,K){try{return{type:"normal",arg:ee.call(j,K)}}catch(ie){return{type:"throw",arg:ie}}}var S="suspendedStart",A="suspendedYield",R="executing",O="completed",N={};function C(){}function b(){}function w(){}var F={};v(F,h,function(){return this});var q=Object.getPrototypeOf,D=q&&q(q(J([])));D&&D!==r&&l.call(D,h)&&(F=D);var P=w.prototype=C.prototype=Object.create(F);b.prototype=w,s(P,"constructor",{value:w,configurable:!0}),s(w,"constructor",{value:b,configurable:!0}),b.displayName=v(w,p,"GeneratorFunction");function I(ee){["next","throw","return"].forEach(function(j){v(ee,j,function(K){return this._invoke(j,K)})})}t.isGeneratorFunction=function(ee){var j=typeof ee=="function"&&ee.constructor;return j?j===b||(j.displayName||j.name)==="GeneratorFunction":!1},t.mark=function(ee){return Object.setPrototypeOf?Object.setPrototypeOf(ee,w):(ee.__proto__=w,v(ee,p,"GeneratorFunction")),ee.prototype=Object.create(P),ee},t.awrap=function(ee){return{__await:ee}};function x(ee,j){function K(Ce,ke,be,M){var Y=y(ee[Ce],ee,ke);if(Y.type==="throw")M(Y.arg);else{var Ee=Y.arg,Me=Ee.value;return Me&&typeof Me=="object"&&l.call(Me,"__await")?j.resolve(Me.__await).then(function(fe){K("next",fe,be,M)},function(fe){K("throw",fe,be,M)}):j.resolve(Me).then(function(fe){Ee.value=fe,be(Ee)},function(fe){return K("throw",fe,be,M)})}}var ie;function ue(Ce,ke){function be(){return new j(function(M,Y){K(Ce,ke,M,Y)})}return ie=ie?ie.then(be,be):be()}s(this,"_invoke",{value:ue})}I(x.prototype),v(x.prototype,d,function(){return this}),t.AsyncIterator=x,t.async=function(ee,j,K,ie,ue){ue===void 0&&(ue=Promise);var Ce=new x(T(ee,j,K,ie),ue);return t.isGeneratorFunction(j)?Ce:Ce.next().then(function(ke){return ke.done?ke.value:Ce.next()})};function U(ee,j,K){var ie=S;return function(Ce,ke){if(ie===R)throw new Error("Generator is already running");if(ie===O){if(Ce==="throw")throw ke;return Pe()}for(K.method=Ce,K.arg=ke;;){var be=K.delegate;if(be){var M=B(be,K);if(M){if(M===N)continue;return M}}if(K.method==="next")K.sent=K._sent=K.arg;else if(K.method==="throw"){if(ie===S)throw ie=O,K.arg;K.dispatchException(K.arg)}else K.method==="return"&&K.abrupt("return",K.arg);ie=R;var Y=y(ee,j,K);if(Y.type==="normal"){if(ie=K.done?O:A,Y.arg===N)continue;return{value:Y.arg,done:K.done}}else Y.type==="throw"&&(ie=O,K.method="throw",K.arg=Y.arg)}}}function B(ee,j){var K=j.method,ie=ee.iterator[K];if(ie===i)return j.delegate=null,K==="throw"&&ee.iterator.return&&(j.method="return",j.arg=i,B(ee,j),j.method==="throw")||K!=="return"&&(j.method="throw",j.arg=new TypeError("The iterator does not provide a '"+K+"' method")),N;var ue=y(ie,ee.iterator,j.arg);if(ue.type==="throw")return j.method="throw",j.arg=ue.arg,j.delegate=null,N;var Ce=ue.arg;if(!Ce)return j.method="throw",j.arg=new TypeError("iterator result is not an object"),j.delegate=null,N;if(Ce.done)j[ee.resultName]=Ce.value,j.next=ee.nextLoc,j.method!=="return"&&(j.method="next",j.arg=i);else return Ce;return j.delegate=null,N}I(P),v(P,p,"Generator"),v(P,h,function(){return this}),v(P,"toString",function(){return"[object Generator]"});function z(ee){var j={tryLoc:ee[0]};1 in ee&&(j.catchLoc=ee[1]),2 in ee&&(j.finallyLoc=ee[2],j.afterLoc=ee[3]),this.tryEntries.push(j)}function L(ee){var j=ee.completion||{};j.type="normal",delete j.arg,ee.completion=j}function V(ee){this.tryEntries=[{tryLoc:"root"}],ee.forEach(z,this),this.reset(!0)}t.keys=function(ee){var j=Object(ee),K=[];for(var ie in j)K.push(ie);return K.reverse(),function ue(){for(;K.length;){var Ce=K.pop();if(Ce in j)return ue.value=Ce,ue.done=!1,ue}return ue.done=!0,ue}};function J(ee){if(ee){var j=ee[h];if(j)return j.call(ee);if(typeof ee.next=="function")return ee;if(!isNaN(ee.length)){var K=-1,ie=function ue(){for(;++K<ee.length;)if(l.call(ee,K))return ue.value=ee[K],ue.done=!1,ue;return ue.value=i,ue.done=!0,ue};return ie.next=ie}}return{next:Pe}}t.values=J;function Pe(){return{value:i,done:!0}}return V.prototype={constructor:V,reset:function(ee){if(this.prev=0,this.next=0,this.sent=this._sent=i,this.done=!1,this.delegate=null,this.method="next",this.arg=i,this.tryEntries.forEach(L),!ee)for(var j in this)j.charAt(0)==="t"&&l.call(this,j)&&!isNaN(+j.slice(1))&&(this[j]=i)},stop:function(){this.done=!0;var ee=this.tryEntries[0],j=ee.completion;if(j.type==="throw")throw j.arg;return this.rval},dispatchException:function(ee){if(this.done)throw ee;var j=this;function K(M,Y){return Ce.type="throw",Ce.arg=ee,j.next=M,Y&&(j.method="next",j.arg=i),!!Y}for(var ie=this.tryEntries.length-1;ie>=0;--ie){var ue=this.tryEntries[ie],Ce=ue.completion;if(ue.tryLoc==="root")return K("end");if(ue.tryLoc<=this.prev){var ke=l.call(ue,"catchLoc"),be=l.call(ue,"finallyLoc");if(ke&&be){if(this.prev<ue.catchLoc)return K(ue.catchLoc,!0);if(this.prev<ue.finallyLoc)return K(ue.finallyLoc)}else if(ke){if(this.prev<ue.catchLoc)return K(ue.catchLoc,!0)}else if(be){if(this.prev<ue.finallyLoc)return K(ue.finallyLoc)}else throw new Error("try statement without catch or finally")}}},abrupt:function(ee,j){for(var K=this.tryEntries.length-1;K>=0;--K){var ie=this.tryEntries[K];if(ie.tryLoc<=this.prev&&l.call(ie,"finallyLoc")&&this.prev<ie.finallyLoc){var ue=ie;break}}ue&&(ee==="break"||ee==="continue")&&ue.tryLoc<=j&&j<=ue.finallyLoc&&(ue=null);var Ce=ue?ue.completion:{};return Ce.type=ee,Ce.arg=j,ue?(this.method="next",this.next=ue.finallyLoc,N):this.complete(Ce)},complete:function(ee,j){if(ee.type==="throw")throw ee.arg;return ee.type==="break"||ee.type==="continue"?this.next=ee.arg:ee.type==="return"?(this.rval=this.arg=ee.arg,this.method="return",this.next="end"):ee.type==="normal"&&j&&(this.next=j),N},finish:function(ee){for(var j=this.tryEntries.length-1;j>=0;--j){var K=this.tryEntries[j];if(K.finallyLoc===ee)return this.complete(K.completion,K.afterLoc),L(K),N}},catch:function(ee){for(var j=this.tryEntries.length-1;j>=0;--j){var K=this.tryEntries[j];if(K.tryLoc===ee){var ie=K.completion;if(ie.type==="throw"){var ue=ie.arg;L(K)}return ue}}throw new Error("illegal catch attempt")},delegateYield:function(ee,j,K){return this.delegate={iterator:J(ee),resultName:j,nextLoc:K},this.method==="next"&&(this.arg=i),N}},t}(u.exports);try{regeneratorRuntime=e}catch{typeof globalThis=="object"?globalThis.regeneratorRuntime=e:Function("r","regeneratorRuntime = r")(e)}})(bA);var zp={exports:{}};(function(u){(function(e,t){u.exports?u.exports=t():e.log=t()})(fs,function(){var e=function(){},t="undefined",r=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),l=["trace","debug","info","warn","error"];function s(A,R){var O=A[R];if(typeof O.bind=="function")return O.bind(A);try{return Function.prototype.bind.call(O,A)}catch{return function(){return Function.prototype.apply.apply(O,[A,arguments])}}}function i(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function f(A){return A==="debug"&&(A="log"),typeof console===t?!1:A==="trace"&&r?i:console[A]!==void 0?s(console,A):console.log!==void 0?s(console,"log"):e}function h(A,R){for(var O=0;O<l.length;O++){var N=l[O];this[N]=O<A?e:this.methodFactory(N,A,R)}this.log=this.debug}function d(A,R,O){return function(){typeof console!==t&&(h.call(this,R,O),this[A].apply(this,arguments))}}function p(A,R,O){return f(A)||d.apply(this,arguments)}function v(A,R,O){var N=this,C;R=R??"WARN";var b="loglevel";typeof A=="string"?b+=":"+A:typeof A=="symbol"&&(b=void 0);function w(P){var I=(l[P]||"silent").toUpperCase();if(!(typeof window===t||!b)){try{window.localStorage[b]=I;return}catch{}try{window.document.cookie=encodeURIComponent(b)+"="+I+";"}catch{}}}function F(){var P;if(!(typeof window===t||!b)){try{P=window.localStorage[b]}catch{}if(typeof P===t)try{var I=window.document.cookie,x=I.indexOf(encodeURIComponent(b)+"=");x!==-1&&(P=/^([^;]+)/.exec(I.slice(x))[1])}catch{}return N.levels[P]===void 0&&(P=void 0),P}}function q(){if(!(typeof window===t||!b)){try{window.localStorage.removeItem(b);return}catch{}try{window.document.cookie=encodeURIComponent(b)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}N.name=A,N.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},N.methodFactory=O||p,N.getLevel=function(){return C},N.setLevel=function(P,I){if(typeof P=="string"&&N.levels[P.toUpperCase()]!==void 0&&(P=N.levels[P.toUpperCase()]),typeof P=="number"&&P>=0&&P<=N.levels.SILENT){if(C=P,I!==!1&&w(P),h.call(N,P,A),typeof console===t&&P<N.levels.SILENT)return"No console available for logging"}else throw"log.setLevel() called with invalid level: "+P},N.setDefaultLevel=function(P){R=P,F()||N.setLevel(P,!1)},N.resetLevel=function(){N.setLevel(R,!1),q()},N.enableAll=function(P){N.setLevel(N.levels.TRACE,P)},N.disableAll=function(P){N.setLevel(N.levels.SILENT,P)};var D=F();D==null&&(D=R),N.setLevel(D,!1)}var T=new v,y={};T.getLogger=function(R){if(typeof R!="symbol"&&typeof R!="string"||R==="")throw new TypeError("You must supply a name when creating a logger.");var O=y[R];return O||(O=y[R]=new v(R,T.getLevel(),T.methodFactory)),O};var S=typeof window!==t?window.log:void 0;return T.noConflict=function(){return typeof window!==t&&window.log===T&&(window.log=S),T},T.getLoggers=function(){return y},T.default=T,T})})(zp);var jt=zp.exports;const Qs=()=>`${new Date().toISOString()} | metrics`,Zs=(u,e,t)=>`${u} | ${e} | ${t}`;jt.setDefaultLevel(jt.levels.TRACE);const RA=u=>{jt.info(Zs(Qs(),"log ",`set log level to ${u?"verbose":"info"}`)),jt.setLevel(u?jt.levels.TRACE:jt.levels.INFO)},wA=u=>{const e=[...Object.keys(jt.levels)];e.includes(u)?(jt.info(Zs(Qs(),"log ",`update log level to ${u.toLowerCase()}`)),jt.setLevel(u)):jt.warn(Zs(Qs(),"log ","Incorrect log level please choose one of "),e)},Be=(u,e,t)=>{t?jt.debug(Zs(Qs(),u,e),t):jt.debug(Zs(Qs(),u,e))},Mf=(u,e)=>{jt.info(Zs(Qs(),u,e))},ii=(u,e)=>{jt.info(Zs(Qs(),u,e))},Xu=(u,e)=>{jt.warn(Zs(Qs(),u,e))},Zi=(u,e)=>{jt.error(Zs(Qs(),u,e))};function IA(u){return Math.floor(Math.random()*u).toString()}function Xp(u,e){let t=e;return u.forEach(r=>{t=t.replace(r,"")}),t}function OA(u,e){let t="";for(let r=0;r<e;r+=1)t+=u[IA(u.length)];return t}function DA({length:u=20,useLetters:e=!0,useNumbers:t=!0,includeSymbols:r=[],excludeSymbols:l=[]}={}){let s="abcdefghijklmnopqrstuvwxyz",i="0123456789",f=[],h=[],d=[];return e&&(l.length&&(s=Xp(l,s)),h=s.split("")),t&&(l.length&&(i=Xp(l,i)),d=i.split("")),f=[...h,...d,...r],OA(f,u)}var NA=DA;const bl=We(NA),PA=()=>"WebRTCMetrics",xA=()=>"5.0.3",Xe={INBOUND:"inbound",OUTBOUND:"outbound"},en={IDLE:"idle",RUNNING:"running",MUTED:"muted"},Rl={NEW:"new",CHECKING:"checking",CONNECTED:"connected",COMPLETED:"completed",DISCONNECTED:"disconnected",FAILED:"failed",CLOSED:"closed"},kA=()=>({...{delta_time_to_measure_probes_ms:0,delta_time_consumed_to_measure_ms:0,delta_KBytes_in:0,delta_KBytes_out:0,delta_kbs_in:0,delta_kbs_out:0,total_time_decoded_in:0,total_time_encoded_out:0,probes:[]}}),Jp={level_in:0,codec_id_in:"",codec_in:{mime_type:null,clock_rate:null,sdp_fmtp_line:null},delta_jitter_ms_in:0,percent_packets_lost_in:0,delta_packets_in:0,delta_packets_lost_in:0,total_packets_in:0,total_packets_lost_in:0,total_KBytes_in:0,delta_KBytes_in:0,delta_kbs_in:0,mos_in:0,mos_emodel_in:0,ssrc:"",direction:Xe.INBOUND},Qp={level_out:0,codec_id_out:"",codec_out:{mime_type:null,clock_rate:null,sdp_fmtp_line:null},delta_jitter_ms_out:0,delta_rtt_ms_out:null,total_rtt_ms_out:0,total_rtt_measure_out:0,percent_packets_lost_out:0,delta_packets_out:0,delta_packets_lost_out:0,total_packets_out:0,total_packets_lost_out:0,total_KBytes_out:0,delta_KBytes_out:0,delta_kbs_out:0,timestamp_out:null,mos_out:0,mos_emodel_out:0,ssrc:"",direction:Xe.OUTBOUND},Zp={codec_id_in:"",size_in:{width:null,height:null,framerate:null},codec_in:{mime_type:null,clock_rate:null},delta_jitter_ms_in:0,percent_packets_lost_in:0,delta_packets_in:0,delta_packets_lost_in:0,total_packets_in:0,total_packets_lost_in:0,total_KBytes_in:0,delta_KBytes_in:0,delta_kbs_in:0,decoder_in:null,delta_ms_decode_frame_in:0,total_frames_decoded_in:0,total_time_decoded_in:0,delta_nack_sent_in:0,delta_pli_sent_in:0,total_nack_sent_in:0,total_pli_sent_in:0,ssrc:"",direction:Xe.INBOUND},e0={codec_id_out:"",size_out:{width:null,height:null,framerate:null},codec_out:{mime_type:null,clock_rate:null},delta_jitter_ms_out:0,delta_rtt_ms_out:null,total_rtt_ms_out:0,total_rtt_measure_out:0,percent_packets_lost_out:0,delta_packets_out:0,delta_packets_lost_out:0,total_packets_out:0,total_packets_lost_out:0,total_KBytes_out:0,delta_KBytes_out:0,delta_kbs_out:0,encoder_out:null,delta_ms_encode_frame_out:0,total_time_encoded_out:0,total_frames_encoded_out:0,delta_nack_received_out:0,delta_pli_received_out:0,total_nack_received_out:0,total_pli_received_out:0,limitation_out:{reason:null,durations:null,resolutionChanges:0},timestamp_out:null,ssrc:"",direction:Xe.OUTBOUND},MA=u=>{const e={pname:"",call_id:"",user_id:"",timestamp:null,count:0,audio:{},video:{},network:{infrastructure:3,local_candidate_id:"",local_candidate_type:"",local_candidate_protocol:"",local_candidate_relay_protocol:"",remote_candidate_id:"",remote_candidate_type:"",remote_candidate_protocol:""},data:{total_KBytes_in:0,total_KBytes_out:0,delta_KBytes_in:0,delta_KBytes_out:0,delta_kbs_in:0,delta_kbs_out:0,delta_kbs_bandwidth_in:0,delta_kbs_bandwidth_out:0,delta_rtt_connectivity_ms:null,total_rtt_connectivity_ms:0,total_rtt_connectivity_measure:0},experimental:{time_to_measure_ms:0}};if(u){const t={...u,audio:{},video:{},data:{...u.data},network:{...u.network},experimental:{...u.experimental}};return Object.keys(u.audio).forEach(r=>{t.audio[r]={...u.audio[r]}}),Object.keys(u.video).forEach(r=>{t.video[r]={...u.video[r]}}),t}return{...e,audio:{},video:{},data:{...e.data},network:{...e.network},experimental:{...e.experimental}}},UA={refreshEvery:2e3,startAfter:0,stopAfter:-1,verbose:!1,pname:`p-${bl()}`,cid:`c-${bl()}`,uid:`u-${bl()}`,record:!1,ticket:!0},Ss={CANDIDATE_PAIR:"candidate-pair",CODEC:"codec",INBOUND_RTP:"inbound-rtp",LOCAL_CANDIDATE:"local-candidate",MEDIA_SOURCE:"media-source",OUTBOUND_RTP:"outbound-rtp",REMOTE_CANDIDATE:"remote-candidate",REMOTE_INBOUND_RTP:"remote-inbound-rtp",TRACK:"track"},te={AUDIO_LEVEL:"audioLevel",AVAILABLE_OUTGOING_BITRATE:"availableOutgoingBitrate",AVAILABLE_INCOMING_BITRATE:"availableIncomingBitrate",BYTES_RECEIVED:"bytesReceived",BYTES_SENT:"bytesSent",CANDIDATE_TYPE:"candidateType",CHANNELS:"channels",CLOCK_RATE:"clockRate",CODEC_ID:"codecId",CURRENT_ROUND_TRIP_TIME:"currentRoundTripTime",ROUND_TRIP_TIME:"roundTripTime",FRACTION_LOST:"fractionLost",FRAME_HEIGHT:"frameHeight",FRAME_WIDTH:"frameWidth",QUALITY_LIMITATION_REASON:"qualityLimitationReason",QUALITY_LIMITATION_DURATIONS:"qualityLimitationDurations",QUALITY_LIMITATION_RESOLUTION_CHANGES:"qualityLimitationResolutionChanges",ID:"id",JITTER:"jitter",KIND:"kind",MEDIA_TYPE:"mediaType",MIME_TYPE:"mimeType",LOCAL_CANDIDATE_ID:"localCandidateId",NETWORK_TYPE:"networkType",RELAY_PROTOCOL:"relayProtocol",NOMINATED:"nominated",PACKETS_LOST:"packetsLost",PACKETS_RECEIVED:"packetsReceived",PACKETS_SENT:"packetsSent",PROTOCOL:"protocol",PORT:"port",REMOTE_CANDIDATE_ID:"remoteCandidateId",REMOTE_SOURCE:"remoteSource",RESPONSES_RECEIVED:"responsesReceived",SDP_FMTP_LINE:"sdpFmtpLine",SSRC:"ssrc",SELECTED:"selected",STATE:"state",TIMESTAMP:"timestamp",TOTAL_ROUND_TRIP_TIME:"totalRoundTripTime",TOTAL_ROUND_TRIP_TIME_MEASUREMENTS:"roundTripTimeMeasurements",TYPE:"type",DECODER_IMPLEMENTATION:"decoderImplementation",ENCODER_IMPLEMENTATION:"encoderImplementation",FRAMES_DECODED:"framesDecoded",FRAMES_ENCODED:"framesEncoded",FRAMES_PER_SECOND:"framesPerSecond",TOTAL_DECODE_TIME:"totalDecodeTime",TOTAL_ENCODE_TIME:"totalEncodeTime",PLI:"pliCount",NACK:"nackCount"},X={SUCCEEDED:"succeeded",AUDIO:"audio",VIDEO:"video"},wl={ETHERNET:0,CELLULAR_5G:2,WIFI:3,CELLULAR_4G:5,CELLULAR:10},Uf={ETHERNET:"ethernet",CELLULAR_4G:"cellular",WIFI:"wifi"},he={AUDIO:"audio",VIDEO:"video",NETWORK:"network",DATA:"data"},Lf="config ",LA=(u,e={},t)=>{const r={...t,...e};return e.pname||Xu(Lf,`Argument [String] 'cfg.pname' for the peerConnection name or id is missing - use generated '${t.pname}'`),e.cid||Xu(Lf,`Argument [String] 'cfg.cid' for the call name or id is missing - use generated '${t.cid}'`),e.uid||Xu(Lf,`Argument [String] 'cfg.uid' for the user name or id is missing - use generated '${t.uid}'`),r.pc=u,r},FA=(u={})=>{const e={...UA,...u};return e.name=PA(),e.version=xA(),e},Il=(u,e,t,r=!1,l)=>{let s=u.map(i=>{if(!t)return i[e];if(!l)return i[e][t];const f=i[e][l];return f?f[t]:null});return s=s.filter(i=>r?Number.isFinite(i)&&i>0:Number.isFinite(i)),s.length===0?[]:s},An=u=>u.reduce((e,t)=>e+t,0)/u.length,$A=()=>`probe-${bl()}`,HA=()=>`coltr-${bl()}`,t0=u=>new Promise(e=>setTimeout(e,u)),Ff=(u,e,t)=>{e?u.call(e,t):u(t)},lt=(u,e,t,r)=>{const l=Il(u,e,t,!0,r);if(l.length===0)return null;const s=l.reduce((d,p)=>d+p,0)/l.length;return s===0?null:l.map(d=>Math.abs(s-d)).reduce((d,p)=>d+p,0)/l.length*100/s},dt=(u,e,t,r=!1,l)=>{const s=Il(u,e,t,r,l);return s.length===0?null:s.reduce((i,f)=>i+f,0)/s.length},ri=(u,e,t)=>Il(u,e,t).reduce((l,s)=>l+s,0),at=(u,e,t,r)=>{const l=Il(u,e,t,!0,r);return l.length===0?null:Math.min(...l)},ot=(u,e,t,r)=>{const l=Il(u,e,t,!1,r);return l.length===0?null:Math.max(...l)},Ht=(u,e,t,r)=>{const l=u.slice().pop();if(!l)return null;if(!t)return l[e];if(!r)return l[e][t];const s=l[e][r];return s?s[t]:null},GA=u=>u.slice().pop(),Ot=(u,e,t)=>{if(!e)return null;const r={};let l=e[X.AUDIO][u];l||(l=t===Xe.INBOUND?{...Jp}:{...Qp}),r[X.AUDIO]=l;let s=e[X.VIDEO][u];return s||(s=t===Xe.INBOUND?{...Zp}:{...e0}),r[X.VIDEO]=s,r},Ol="exporter ",VA="2.0",s0=(u,e,t)=>{if(!u||u.length===0)return 0;const r=u[u.length-1];if(!r)return 0;const l=r[e][t];if(l){const s=l.total_rtt_ms_out,i=l.total_rtt_measure_out;return!i||!s?dt(u,e,"delta_rtt_ms_out",!1,t):Number(s/i)}return null},BA=(u,e)=>{if(!u||u.length===0)return 0;const t=u[u.length-1];if(!t)return 0;const r=t[e].total_rtt_connectivity_ms,l=t[e].total_rtt_connectivity_measure;return!l||!r?dt(u,e,"delta_rtt_connectivity_ms"):Number(r/l)},jA=u=>Ht(u,"network","local_candidate_type")!=="relay"?`direct/${Ht(u,"network","local_candidate_protocol")}`:`turn/${Ht(u,"network","local_candidate_relay_protocol")}`,qA=u=>{const e=Ht(u,"network","remote_candidate_type"),t=Ht(u,"network","remote_candidate_protocol");return e!=="relay"?`direct/${t}`:`turn/${t}`};class WA{constructor(e){this._start=null,this._end=null,this._cfg=e,this._referenceReport=null,this._reports=[],this._events=[]}start(){Mf(Ol,"start() - start exporter...");const e=new Date;return this._start=e.toJSON(),e}stop(){Mf(Ol,"stop() - stop exporter...");const e=new Date;return this._end=e.toJSON(),e}saveReferenceReport(e){this._referenceReport=e}getReferenceReport(){return this._referenceReport}addReport(e){this._cfg.ticket&&(Be(Ol,`addReport() - add report to exporter at ${e.timestamp}`),this._reports.push(e))}addCustomEvent(e){this._events.push(e)}reset(){Mf(Ol,"resetReports() - reset reports"),this._reports=[],this._referenceReport=null,this._start=null,this._end=null}get ticket(){Be(Ol,"ticket() - generate ticket");const e=Ht(this._reports,"audio","total_packets_lost_in"),t=Ht(this._reports,"audio","total_packets_in"),r=Ht(this._reports,"video","total_packets_lost_in"),l=Ht(this._reports,"video","total_packets_in"),s={},i=GA(this._reports);return i&&(Object.keys(i[X.AUDIO]).forEach(f=>{const h=i[X.AUDIO][f];if(s[h.ssrc]={type:X.AUDIO,direction:h.direction},h.direction===Xe.INBOUND){const d={avg:dt(this._reports,X.AUDIO,"delta_jitter_ms_in",!1,f),min:at(this._reports,X.AUDIO,"delta_jitter_ms_in",f),max:ot(this._reports,X.AUDIO,"delta_jitter_ms_in",f),volatility:lt(this._reports,X.AUDIO,"delta_jitter_ms_in",f),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},p={avg:dt(this._reports,X.AUDIO,"delta_kbs_in",!1,f),min:at(this._reports,X.AUDIO,"delta_kbs_in",f),max:ot(this._reports,X.AUDIO,"delta_kbs_in",f),volatility:lt(this._reports,X.AUDIO,"delta_kbs_in",f),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},v={avg:dt(this._reports,X.AUDIO,"delta_KBytes_in",!1,f),min:at(this._reports,X.AUDIO,"delta_KBytes_in",f),max:ot(this._reports,X.AUDIO,"delta_KBytes_in",f),volatility:lt(this._reports,X.AUDIO,"delta_KBytes_in",f),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},T={emodel:{avg:dt(this._reports,X.AUDIO,"mos_emodel_in",!1,f),min:at(this._reports,X.AUDIO,"mos_emodel_in",f),max:ot(this._reports,X.AUDIO,"mos_emodel_in",f),volatility:lt(this._reports,X.AUDIO,"mos_emodel_in",f)},effective:{avg:dt(this._reports,X.AUDIO,"mos_in",!1,f),min:at(this._reports,X.AUDIO,"mos_in",f),max:ot(this._reports,X.AUDIO,"mos_in",f),volatility:lt(this._reports,X.AUDIO,"mos_in",f)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}},y=Ht(this._reports,X.AUDIO,"total_packets_lost_in",f),S=Ht(this._reports,X.AUDIO,"total_packets_in",f),A={lost:y,avg:Math.round((y/(y+S)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};s[f].jitter=d,s[f].mos=T,s[f].traffic=v,s[f].bitrate=p,s[f].loss=A}else{const d={avg:dt(this._reports,X.AUDIO,"delta_jitter_ms_out",!1,f),min:at(this._reports,X.AUDIO,"delta_jitter_ms_out",f),max:ot(this._reports,X.AUDIO,"delta_jitter_ms_out",f),volatility:lt(this._reports,X.AUDIO,"delta_jitter_ms_out",f),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},p={avg:dt(this._reports,X.AUDIO,"delta_kbs_out",!1,f),min:at(this._reports,X.AUDIO,"delta_kbs_out",f),max:ot(this._reports,X.AUDIO,"delta_kbs_out",f),volatility:lt(this._reports,X.AUDIO,"delta_kbs_out",f),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},v={avg:dt(this._reports,X.AUDIO,"delta_KBytes_out",!1,f),min:at(this._reports,X.AUDIO,"delta_KBytes_out",f),max:ot(this._reports,X.AUDIO,"delta_KBytes_out",f),volatility:lt(this._reports,X.AUDIO,"delta_KBytes_out",f),_unit:{avg:"KB",min:"KB",max:"KB",bitrate:"kbs",volatility:"percent"}},T={avg:s0(this._reports,X.AUDIO,f),min:at(this._reports,X.AUDIO,"delta_rtt_ms_out",f),max:ot(this._reports,X.AUDIO,"delta_rtt_ms_out",f),volatility:lt(this._reports,X.AUDIO,"delta_rtt_ms_out",f),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},y=Ht(this._reports,X.AUDIO,"total_packets_lost_out",f),S=Ht(this._reports,X.AUDIO,"total_packets_out",f),A={lost:y,avg:Math.round((y/(y+S)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}},R={emodel:{avg:dt(this._reports,X.AUDIO,"mos_emodel_out",!1,f),min:at(this._reports,X.AUDIO,"mos_emodel_out",f),max:ot(this._reports,X.AUDIO,"mos_emodel_out",f),volatility:lt(this._reports,X.AUDIO,"mos_emodel_out",f)},effective:{avg:dt(this._reports,X.AUDIO,"mos_out",!1,f),min:at(this._reports,X.AUDIO,"mos_out",f),max:ot(this._reports,X.AUDIO,"mos_out",f),volatility:lt(this._reports,X.AUDIO,"mos_out",f)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}};s[f].jitter=d,s[f].rtt=T,s[f].traffic=v,s[f].bitrate=p,s[f].loss=A,s[f].mos=R}}),Object.keys(i[X.VIDEO]).forEach(f=>{const h=i[X.VIDEO][f];if(s[f]={type:X.VIDEO,direction:h.direction},h.direction===Xe.INBOUND){const d={avg:dt(this._reports,X.VIDEO,"delta_jitter_ms_in",!1,f),min:at(this._reports,X.VIDEO,"delta_jitter_ms_in",f),max:ot(this._reports,X.VIDEO,"delta_jitter_ms_in",f),volatility:lt(this._reports,X.VIDEO,"delta_jitter_ms_in",f),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},p={avg:dt(this._reports,X.VIDEO,"delta_kbs_in",!1,f),min:at(this._reports,X.VIDEO,"delta_kbs_in",f),max:ot(this._reports,X.VIDEO,"delta_kbs_in",f),volatility:lt(this._reports,X.VIDEO,"delta_kbs_in",f),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},v={avg:dt(this._reports,X.VIDEO,"delta_KBytes_in",!1,f),min:at(this._reports,X.VIDEO,"delta_KBytes_in",f),max:ot(this._reports,X.VIDEO,"delta_KBytes_in",f),volatility:lt(this._reports,X.VIDEO,"delta_KBytes_in",f),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},T=Ht(this._reports,X.VIDEO,"total_packets_lost_in",f),y=Ht(this._reports,X.VIDEO,"total_packets_in",f),S={lost:T,avg:Math.round((T/(T+y)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};s[f].jitter=d,s[f].traffic=v,s[f].bitrate=p,s[f].loss=S}else{const d={avg:dt(this._reports,X.VIDEO,"delta_jitter_ms_out",!1,f),min:at(this._reports,X.VIDEO,"delta_jitter_ms_out",f),max:ot(this._reports,X.VIDEO,"delta_jitter_ms_out",f),volatility:lt(this._reports,X.VIDEO,"delta_jitter_ms_out",f),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},p={avg:dt(this._reports,X.VIDEO,"delta_kbs_out",!1,f),min:at(this._reports,X.VIDEO,"delta_kbs_out",f),max:ot(this._reports,X.VIDEO,"delta_kbs_out",f),volatility:lt(this._reports,X.VIDEO,"delta_kbs_out",f),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},v={avg:dt(this._reports,X.VIDEO,"delta_KBytes_out",!1,f),min:at(this._reports,X.VIDEO,"delta_KBytes_out",f),max:ot(this._reports,X.VIDEO,"delta_KBytes_out",f),volatility:lt(this._reports,X.VIDEO,"delta_KBytes_out",f),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},T={avg:s0(this._reports,X.VIDEO,f),min:at(this._reports,X.VIDEO,"delta_rtt_ms_out",f),max:ot(this._reports,X.VIDEO,"delta_rtt_ms_out",f),volatility:lt(this._reports,X.VIDEO,"delta_rtt_ms_out",f),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},y=Ht(this._reports,X.VIDEO,"total_packets_lost_out",f),S=Ht(this._reports,X.VIDEO,"total_packets_out",f),A={lost:y,avg:Math.round((y/(y+S)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};s[f].jitter=d,s[f].rtt=T,s[f].traffic=v,s[f].bitrate=p,s[f].loss=A}})),{version:VA,configuration:{frequency:this._cfg.refreshEvery},started:this._start,ended:this._end,ua:{agent:navigator.userAgent,pname:this._cfg.pname,user_id:this._cfg.uid},call:{call_id:this._cfg.cid,events:this._events},details:{count:this._reports.length,reports:this._cfg.record?this._reports:[],reference:this._referenceReport||null},ssrc:s,data:{rtt:{avg:BA(this._reports,"data"),min:at(this._reports,"data","delta_rtt_connectivity_ms"),max:ot(this._reports,"data","delta_rtt_connectivity_ms"),volatility:lt(this._reports,"data","delta_rtt_connectivity_ms"),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},packetsLost:{audio:{in:{avg:Math.round((e/(e+t)*100||0)*100)/100}},video:{in:{avg:Math.round((r/(r+l)*100||0)*100)/100}},unit:{avg:"percent"}},bitrate:{in:{avg:dt(this._reports,"data","delta_kbs_in"),min:at(this._reports,"data","delta_kbs_in"),max:ot(this._reports,"data","delta_kbs_in"),volatility:lt(this._reports,"data","delta_kbs_in")},out:{avg:dt(this._reports,"data","delta_kbs_out"),min:at(this._reports,"data","delta_kbs_out"),max:ot(this._reports,"data","delta_kbs_out"),volatility:lt(this._reports,"data","delta_kbs_out")},unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},traffic:{in:{avg:dt(this._reports,"data","delta_KBytes_in"),min:at(this._reports,"data","delta_KBytes_in"),max:ot(this._reports,"data","delta_KBytes_in"),volatility:lt(this._reports,"data","delta_KBytes_in")},out:{avg:dt(this._reports,"data","delta_KBytes_out"),min:at(this._reports,"data","delta_KBytes_out"),max:ot(this._reports,"data","delta_KBytes_out"),volatility:lt(this._reports,"data","delta_KBytes_out")},unit:{avg:"KBytes",min:"KBytes",max:"KBytes",volatility:"percent"}},network:{localConnection:jA(this._reports),remoteConnection:qA(this._reports)}}}}updateConfig(e){this._cfg=e}getLastReport(){return this._reports.slice().pop()||null}getBeforeLastReport(){const e=this._reports.slice();return e.pop(),e.pop()||null}getReportsNumber(){return this._reports.length}}const bn="extractor ",n0=(u,e,t,r)=>{let l=!1;const s=r[e].total_rtt_ms_out,i=r[e].total_rtt_measure_out,f=t?t[e].total_rtt_ms_out:0,h=t?t[e].total_rtt_measure_out:0,d={rtt:null,totalRTT:s,totalRTTMeasurements:i};if(u[te.TIMESTAMP]===r[e].timestamp_out||!Object.prototype.hasOwnProperty.call(u,te.ROUND_TRIP_TIME)||Object.prototype.hasOwnProperty.call(u,te.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS)&&(l=!0,Number(u[te.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])===0||Number(u[te.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])-h===i))return d;const p=1e3*Number(u[te.ROUND_TRIP_TIME]);let v=s+p,T=i+1;return l&&(v=1e3*Number(u[te.TOTAL_ROUND_TRIP_TIME])-f,T=Number(u[te.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])-h),{rtt:p,totalRTT:v,totalRTTMeasurements:T}},KA=(u,e,t,r)=>{if(!Object.prototype.hasOwnProperty.call(u,te.CURRENT_ROUND_TRIP_TIME))return{rtt:null,totalRTT:r[e].total_rtt_connectivity_ms,totalRTTMeasurements:r[e].total_rtt_connectivity_measure};const l=1e3*Number(u[te.CURRENT_ROUND_TRIP_TIME]);let s=r[e].total_rtt_connectivity_ms+l,i=r[e].total_rtt_connectivity_measure+1;return Object.prototype.hasOwnProperty.call(u,te.TOTAL_ROUND_TRIP_TIME)&&(s=1e3*Number(u[te.TOTAL_ROUND_TRIP_TIME])-(t?t[e].total_rtt_connectivity_ms:0)),Object.prototype.hasOwnProperty.call(u,te.RESPONSES_RECEIVED)&&(i=Number(u[te.RESPONSES_RECEIVED])-(t?t[e].total_rtt_connectivity_measure:0)),{rtt:l,totalRTT:s,totalRTTMeasurements:i}},Ju=(u,e,t)=>u[te.TIMESTAMP]===t[e].timestamp_out||!Object.prototype.hasOwnProperty.call(u,te.JITTER)?null:1e3*(Number(u[te.JITTER])||0),YA=(u,e)=>{if(!Object.prototype.hasOwnProperty.call(u,te.FRAMES_DECODED)||!Object.prototype.hasOwnProperty.call(u,te.TOTAL_DECODE_TIME))return{delta_ms_decode_frame:e[X.VIDEO].delta_ms_decode_frame_in,frames_decoded:e[X.VIDEO].total_frames_decoded_in,total_decode_time:e[X.VIDEO].total_time_decoded_in};const t=u[te.FRAMES_DECODED],r=u[te.TOTAL_DECODE_TIME],l=r-e[X.VIDEO].total_time_decoded_in,s=t-e[X.VIDEO].total_frames_decoded_in;return{delta_ms_decode_frame:s>0?l*1e3/s:0,frames_decoded:t,total_decode_time:r}},zA=(u,e)=>{if(!Object.prototype.hasOwnProperty.call(u,te.FRAMES_ENCODED)||!Object.prototype.hasOwnProperty.call(u,te.TOTAL_ENCODE_TIME))return{delta_ms_encode_frame:e[X.VIDEO].delta_ms_encode_frame_out,frames_encoded:e[X.VIDEO].total_frames_encoded_out,total_encode_time:e[X.VIDEO].total_time_encoded_out};const t=u[te.FRAMES_ENCODED],r=u[te.TOTAL_ENCODE_TIME],l=r-e[X.VIDEO].total_time_encoded_out,s=t-e[X.VIDEO].total_frames_encoded_out;return{delta_ms_encode_frame:s>0&&l?l*1e3/s:0,frames_encoded:t,total_encode_time:r}},i0=(u,e,t,r)=>{if(!Object.prototype.hasOwnProperty.call(u,te.PACKETS_SENT)||!Object.prototype.hasOwnProperty.call(u,te.BYTES_SENT))return{packetsSent:t[e].total_packets_out,packetsLost:t[e].total_packets_lost_out,bytesSent:t[e].total_KBytes_out};const l=Number(u[te.PACKETS_SENT])||0-(r?r[e].total_packets_out:0),s=l-t[e].total_packets_out,i=Number(u[te.BYTES_SENT])/1024-(r?r[e].total_KBytes_out:0),f=i-t[e].total_KBytes_out,h=u[te.TIMESTAMP]||Date.now(),d=r?r.timestamp:null;let p=t.timestamp;!p&&d&&(p=d);const v=p?h-p:0,T=v>0?f*.008*1024/v*1e3:0;return{packetsSent:l,deltaPacketsSent:s,KBytesSent:i,deltaKBytesSent:f,kbsSent:T}},r0=(u,e,t,r)=>{let l=t[e].total_packets_lost_out,s=0,i=0;return Object.prototype.hasOwnProperty.call(u,te.PACKETS_LOST)&&(l=Number(u[te.PACKETS_LOST])||0-(r?r[e].total_packets_lost_out:0),s=l-t[e].total_packets_lost_out),Object.prototype.hasOwnProperty.call(u,te.FRACTION_LOST)&&(i=Number(100*u[te.FRACTION_LOST])),{packetsLost:l,deltaPacketsLost:s,fractionLost:i}},l0=(u,e,t,r)=>{if(!Object.prototype.hasOwnProperty.call(u,te.PACKETS_RECEIVED)||!Object.prototype.hasOwnProperty.call(u,te.PACKETS_LOST)||!Object.prototype.hasOwnProperty.call(u,te.BYTES_RECEIVED))return{percent_packets_lost:t[e].percent_packets_lost_in,packetsReceived:t[e].total_packets_in,packetsLost:t[e].total_packets_lost_in,bytesReceived:t[e].total_KBytes_in};const l=Number(u[te.PACKETS_RECEIVED])||0-(r?r[e].total_packets_in:0),s=Number(u[te.PACKETS_LOST])||0-(r?r[e].total_packets_lost_in:0),i=s-t[e].total_packets_lost_in,f=l-t[e].total_packets_in,h=l!==t[e].total_packets_in?i*100/(i+f):0,d=Number(u[te.BYTES_RECEIVED])/1024-(r?r[e].total_KBytes_in:0),p=d-t[e].total_KBytes_in,v=u[te.TIMESTAMP]||Date.now(),T=r?r.timestamp:null;let y=t.timestamp;!y&&T&&(y=T);const S=y?v-y:0,A=S>0?p*.008*1024/S*1e3:0;return{percentPacketsLost:h,packetsReceived:l,deltaPacketsReceived:f,packetsLost:s,deltaPacketsLost:i,KBytesReceived:d,deltaKBytesReceived:p,kbsReceived:A}},XA=u=>u[te.CANDIDATE_TYPE]!=="relay"?"":u[te.RELAY_PROTOCOL]||"",JA=u=>{if(!Object.prototype.hasOwnProperty.call(u,te.NETWORK_TYPE))return wl.WIFI;switch(u[te.NETWORK_TYPE]){case Uf.ETHERNET:return wl.ETHERNET;case Uf.CELLULAR_4G:return wl.CELLULAR_4G;case Uf.WIFI:return wl.WIFI;default:return wl.CELLULAR}},a0=u=>!Object.prototype.hasOwnProperty.call(u,te.FRAME_HEIGHT)||!Object.prototype.hasOwnProperty.call(u,te.FRAME_WIDTH)?{width:null,height:null,framerate:null}:{width:u[te.FRAME_WIDTH]||null,height:u[te.FRAME_HEIGHT]||null,framerate:u[te.FRAMES_PER_SECOND]},QA=u=>{const e=Object.prototype.hasOwnProperty.call(u,te.QUALITY_LIMITATION_REASON)?u[te.QUALITY_LIMITATION_REASON]:null,t=Object.prototype.hasOwnProperty.call(u,te.QUALITY_LIMITATION_RESOLUTION_CHANGES)?u[te.QUALITY_LIMITATION_RESOLUTION_CHANGES]:null,r=Object.prototype.hasOwnProperty.call(u,te.QUALITY_LIMITATION_DURATIONS)?u[te.QUALITY_LIMITATION_DURATIONS]:null;return r&&Object.keys(r).forEach(l=>{r[l]>1e3&&(r[l]=Number(r[l]/1e3))}),{reason:e,durations:r,resolutionChanges:t}},ZA=(u,e,t)=>{if(!Object.prototype.hasOwnProperty.call(u,te.PLI)||!Object.prototype.hasOwnProperty.call(u,te.NACK))return{pliCount:e.total_pli_sent_in,nackCount:e.total_nack_sent_in,deltaPliCount:0,deltaNackCount:0};const r=(u[te.PLI]||0)-(t?t[X.VIDEO].total_pli_sent_in:0),l=(u[te.NACK]||0)-(t?t[X.VIDEO].total_nack_sent_in:0);return{pliCount:r,nackCount:l,deltaPliCount:r-e[X.VIDEO].total_pli_sent_in,deltaNackCount:l-e[X.VIDEO].total_nack_sent_in}},eb=(u,e,t)=>{if(!Object.prototype.hasOwnProperty.call(u,te.PLI)||!Object.prototype.hasOwnProperty.call(u,te.NACK))return{pliCount:e.total_pli_received_out,nackCount:e.total_nack_received_out,deltaPliCount:0,deltaNackCount:0};const r=(u[te.PLI]||0)-(t?t[X.VIDEO].total_pli_received_out:0),l=(u[te.NACK]||0)-(t?t[X.VIDEO].total_nack_received_out:0);return{pliCount:r,nackCount:l,deltaPliCount:r-e[X.VIDEO].total_pli_received_out,deltaNackCount:l-e[X.VIDEO].total_nack_received_out}},tb=u=>({channels:u[te.CHANNELS]||null,clock_rate:u[te.CLOCK_RATE]||null,mime_type:u[te.MIME_TYPE]||null,sdp_fmtp_line:u[te.SDP_FMTP_LINE]||null}),sb=u=>({clock_rate:u[te.CLOCK_RATE]||null,mime_type:u[te.MIME_TYPE]||null}),nb=(u,e,t)=>{const r=(u[te.BYTES_RECEIVED]||0)/1024-(t?t.data.total_KBytes_in:0),l=(u[te.BYTES_SENT]||0)/1024-(t?t.data.total_KBytes_out:0),s=u[te.TIMESTAMP]||Date.now(),i=r-e.data.total_KBytes_in,f=l-e.data.total_KBytes_out,h=t?t.timestamp:null;let d=e.timestamp;!d&&h&&(d=h);const p=d?s-d:0,v=p>0?i*.008*1024/p*1e3:0,T=p>0?f*.008*1024/p*1e3:0;return{total_KBytes_received:r,total_KBytes_sent:l,delta_KBytes_received:i,delta_KBytes_sent:f,kbs_speed_received:v,kbs_speed_sent:T}},ib=u=>{const e=u[te.AVAILABLE_INCOMING_BITRATE]/1024||0,t=u[te.AVAILABLE_OUTGOING_BITRATE]/1024||0;return{kbs_incoming_bandwidth:e,kbs_outgoing_bandwidth:t}},rb=(u,e,t,r)=>{if(!u)return[];switch(u[te.TYPE]){case Ss.CANDIDATE_PAIR:let l=!1;if(u[te.NOMINATED]&&u[te.STATE]===X.SUCCEEDED&&(l=!0,Be(bn,`analyze() - got stats ${u[te.TYPE]} for ${t}`,u),te.SELECTED in u&&!u[te.SELECTED]&&(l=!1)),l){const i=u[te.LOCAL_CANDIDATE_ID],f=u[te.REMOTE_CANDIDATE_ID],h=nb(u,e,r),d=ib(u),p=KA(u,"data",r,e);return[{type:he.NETWORK,value:{local_candidate_id:i}},{type:he.NETWORK,value:{remote_candidate_id:f}},{type:he.DATA,value:{total_KBytes_in:h.total_KBytes_received}},{type:he.DATA,value:{total_KBytes_out:h.total_KBytes_sent}},{type:he.DATA,value:{delta_KBytes_in:h.delta_KBytes_received}},{type:he.DATA,value:{delta_KBytes_out:h.delta_KBytes_sent}},{type:he.DATA,value:{delta_kbs_in:h.kbs_speed_received}},{type:he.DATA,value:{delta_kbs_out:h.kbs_speed_sent}},{type:he.DATA,value:{delta_kbs_bandwidth_in:d.kbs_incoming_bandwidth}},{type:he.DATA,value:{delta_kbs_bandwidth_out:d.kbs_outgoing_bandwidth}},{type:he.DATA,value:{delta_rtt_connectivity_ms:p.rtt}},{type:he.DATA,value:{total_rtt_connectivity_ms:p.totalRTT}},{type:he.DATA,value:{total_rtt_connectivity_measure:p.totalRTTMeasurements}}]}break;case Ss.LOCAL_CANDIDATE:if(u[te.ID]===e.network.local_candidate_id)return[{type:he.NETWORK,value:{infrastructure:JA(u)}},{type:he.NETWORK,value:{local_candidate_type:u[te.CANDIDATE_TYPE]||""}},{type:he.NETWORK,value:{local_candidate_protocol:u[te.PROTOCOL]||""}},{type:he.NETWORK,value:{local_candidate_relay_protocol:XA(u)}}];break;case Ss.REMOTE_CANDIDATE:if(u[te.ID]===e.network.remote_candidate_id)return[{type:he.NETWORK,value:{remote_candidate_type:u[te.CANDIDATE_TYPE]||""}},{type:he.NETWORK,value:{remote_candidate_protocol:u[te.PROTOCOL]||""}}];break;case Ss.INBOUND_RTP:{Be(bn,`analyze() - got stats ${u[te.TYPE]} for ${t}`,u);const i=u[te.SSRC],f=Ot(i,e,Xe.INBOUND);f&&(f.timestamp=e.timestamp);const h=Ot(i,r,Xe.INBOUND);if(h&&(h.timestamp=r.timestamp),u[te.MEDIA_TYPE]===X.AUDIO){const d=l0(u,X.AUDIO,f,h),p=Ju(u,X.AUDIO,f),v=u[te.CODEC_ID]||"";return[{ssrc:i,type:he.AUDIO,value:{codec_id_in:v}},{ssrc:i,type:he.AUDIO,value:{total_packets_in:d.packetsReceived}},{ssrc:i,type:he.AUDIO,value:{delta_packets_in:d.deltaPacketsReceived}},{ssrc:i,type:he.AUDIO,value:{total_packets_lost_in:d.packetsLost}},{ssrc:i,type:he.AUDIO,value:{delta_packets_lost_in:d.deltaPacketsLost}},{ssrc:i,type:he.AUDIO,value:{percent_packets_lost_in:d.percentPacketsLost}},{ssrc:i,type:he.AUDIO,value:{total_KBytes_in:d.KBytesReceived}},{ssrc:i,type:he.AUDIO,value:{delta_KBytes_in:d.deltaKBytesReceived}},{ssrc:i,type:he.AUDIO,value:{delta_kbs_in:d.kbsReceived}},{ssrc:i,type:he.AUDIO,value:{delta_jitter_ms_in:p}}]}if(u[te.MEDIA_TYPE]===X.VIDEO){const d=YA(u,f),p=l0(u,X.VIDEO,f,h),v=Ju(u,X.VIDEO,f),T=u[te.DECODER_IMPLEMENTATION]||null,y=u[te.CODEC_ID]||null,S=a0(u),A=ZA(u,f,h);return[{ssrc:i,type:he.VIDEO,value:{codec_id_in:y}},{ssrc:i,type:he.VIDEO,value:{total_packets_in:p.packetsReceived}},{ssrc:i,type:he.VIDEO,value:{delta_packets_in:p.deltaPacketsReceived}},{ssrc:i,type:he.VIDEO,value:{total_packets_lost_in:p.packetsLost}},{ssrc:i,type:he.VIDEO,value:{delta_packets_lost_in:p.deltaPacketsLost}},{ssrc:i,type:he.VIDEO,value:{percent_packets_lost_in:p.percentPacketsLost}},{ssrc:i,type:he.VIDEO,value:{total_KBytes_in:p.KBytesReceived}},{ssrc:i,type:he.VIDEO,value:{delta_KBytes_in:p.deltaKBytesReceived}},{ssrc:i,type:he.VIDEO,value:{delta_kbs_in:p.kbsReceived}},{ssrc:i,type:he.VIDEO,value:{delta_jitter_ms_in:v}},{ssrc:i,type:he.VIDEO,value:{decoder_in:T}},{ssrc:i,type:he.VIDEO,value:{delta_ms_decode_frame_in:d.delta_ms_decode_frame}},{ssrc:i,type:he.VIDEO,value:{total_frames_decoded_in:d.frames_decoded}},{ssrc:i,type:he.VIDEO,value:{total_time_decoded_in:d.total_decode_time}},{ssrc:i,type:he.VIDEO,value:{total_nack_sent_in:A.nackCount}},{ssrc:i,type:he.VIDEO,value:{delta_nack_sent_in:A.deltaNackCount}},{ssrc:i,type:he.VIDEO,value:{total_pli_sent_in:A.pliCount}},{ssrc:i,type:he.VIDEO,value:{delta_pli_sent_in:A.deltaPliCount}},{ssrc:i,type:he.VIDEO,value:{size_in:S}}]}break}case Ss.OUTBOUND_RTP:{Be(bn,`analyze() - got stats ${u[te.TYPE]} for ${t}`,u);const i=u[te.SSRC],f=Ot(i,e,Xe.OUTBOUND);f&&(f.timestamp=e.timestamp);const h=Ot(i,r,Xe.OUTBOUND);if(h&&(h.timestamp=r.timestamp),u[te.MEDIA_TYPE]===X.AUDIO){const d=u[te.CODEC_ID]||null,p=i0(u,X.AUDIO,f,h);return[{ssrc:i,type:he.AUDIO,value:{codec_id_out:d}},{ssrc:i,type:he.AUDIO,value:{total_packets_out:p.packetsSent}},{ssrc:i,type:he.AUDIO,value:{delta_packets_out:p.deltaPacketsSent}},{ssrc:i,type:he.AUDIO,value:{total_KBytes_out:p.KBytesSent}},{ssrc:i,type:he.AUDIO,value:{delta_KBytes_out:p.deltaKBytesSent}},{ssrc:i,type:he.AUDIO,value:{delta_kbs_out:p.kbsSent}}]}if(u[te.MEDIA_TYPE]===X.VIDEO){const d=u[te.ENCODER_IMPLEMENTATION]||null,p=u[te.CODEC_ID]||null,v=zA(u,f),T=a0(u),y=QA(u),S=eb(u,f,h),A=i0(u,X.VIDEO,f,h);return[{ssrc:i,type:he.VIDEO,value:{codec_id_out:p}},{ssrc:i,type:he.VIDEO,value:{total_packets_out:A.packetsSent}},{ssrc:i,type:he.VIDEO,value:{delta_packets_out:A.deltaPacketsSent}},{ssrc:i,type:he.VIDEO,value:{total_KBytes_out:A.KBytesSent}},{ssrc:i,type:he.VIDEO,value:{delta_KBytes_out:A.deltaKBytesSent}},{ssrc:i,type:he.VIDEO,value:{delta_kbs_out:A.kbsSent}},{ssrc:i,type:he.VIDEO,value:{encoder_out:d}},{ssrc:i,type:he.VIDEO,value:{delta_ms_encode_frame_out:v.delta_ms_encode_frame}},{ssrc:i,type:he.VIDEO,value:{total_frames_encoded_out:v.frames_encoded}},{ssrc:i,type:he.VIDEO,value:{total_time_encoded_out:v.total_encode_time}},{ssrc:i,type:he.VIDEO,value:{total_nack_received_out:S.nackCount}},{ssrc:i,type:he.VIDEO,value:{delta_nack_received_out:S.deltaNackCount}},{ssrc:i,type:he.VIDEO,value:{total_pli_received_out:S.pliCount}},{ssrc:i,type:he.VIDEO,value:{delta_pli_received_out:S.deltaPliCount}},{ssrc:i,type:he.VIDEO,value:{size_out:T}},{ssrc:i,type:he.VIDEO,value:{limitation_out:y}}]}break}case Ss.MEDIA_SOURCE:{Be(bn,`analyze() - got stats ${u[te.TYPE]} for ${t}`,u);break}case Ss.TRACK:{Be(bn,`analyze() - got stats ${u[te.TYPE]} for ${t}`,u);break}case Ss.CODEC:const s=[];return Object.keys(e[X.AUDIO]).forEach(i=>{const f=e[X.AUDIO][i];if(f.codec_id_in===u[te.ID]||f.codec_id_out===u[te.ID]){Be(bn,`analyze() - got stats ${u[te.TYPE]} for ${t}`,u);const h=tb(u);u[te.ID]===f.codec_id_in?s.push({ssrc:f.ssrc,type:he.AUDIO,value:{codec_in:h}}):s.push({ssrc:f.ssrc,type:he.AUDIO,value:{codec_out:h}})}}),Object.keys(e[X.VIDEO]).forEach(i=>{const f=e[X.VIDEO][i];if(f.codec_id_in===u[te.ID]||f.codec_id_out===u[te.ID]){Be(bn,`analyze() - got stats ${u[te.TYPE]} for ${t}`,u);const h=sb(u);u[te.ID]===f.codec_id_in?s.push({ssrc:f.ssrc,type:he.VIDEO,value:{codec_in:h}}):s.push({ssrc:f.ssrc,type:he.VIDEO,value:{codec_out:h}})}}),s;case Ss.REMOTE_INBOUND_RTP:{Be(bn,`analyze() - got stats ${u[te.TYPE]} for ${t}`,u);const i=u[te.SSRC],f=Ot(i,e,Xe.OUTBOUND),h=Ot(i,r,Xe.OUTBOUND);if(u[te.KIND]===X.AUDIO){const d=n0(u,X.AUDIO,h,f),p=Ju(u,X.AUDIO,f),v=r0(u,X.AUDIO,f,h);return[{ssrc:i,type:he.AUDIO,value:{delta_rtt_ms_out:d.rtt}},{ssrc:i,type:he.AUDIO,value:{total_rtt_ms_out:d.totalRTT}},{ssrc:i,type:he.AUDIO,value:{total_rtt_measure_out:d.totalRTTMeasurements}},{ssrc:i,type:he.AUDIO,value:{delta_jitter_ms_out:p}},{ssrc:i,type:he.AUDIO,value:{timestamp_out:u[te.TIMESTAMP]}},{ssrc:i,type:he.AUDIO,value:{total_packets_lost_out:v.packetsLost}},{ssrc:i,type:he.AUDIO,value:{delta_packets_lost_out:v.deltaPacketsLost}},{ssrc:i,type:he.AUDIO,value:{percent_packets_lost_out:v.fractionLost}}]}if(u[te.KIND]===X.VIDEO){const d=n0(u,X.VIDEO,h,f),p=Ju(u,X.VIDEO,f),v=r0(u,X.VIDEO,f,h);return[{ssrc:i,type:he.VIDEO,value:{delta_rtt_ms_out:d.rtt}},{ssrc:i,type:he.VIDEO,value:{total_rtt_ms_out:d.totalRTT}},{ssrc:i,type:he.VIDEO,value:{total_rtt_measure_out:d.totalRTTMeasurements}},{ssrc:i,type:he.VIDEO,value:{delta_jitter_ms_out:p}},{ssrc:i,type:he.VIDEO,value:{timestamp_out:u[te.TIMESTAMP]}},{ssrc:i,type:he.VIDEO,value:{total_packets_lost_out:v.packetsLost}},{ssrc:i,type:he.VIDEO,value:{delta_packets_lost_out:v.deltaPacketsLost}},{ssrc:i,type:he.VIDEO,value:{percent_packets_lost_out:v.fractionLost}}]}break}}return[]},Qu=u=>u<0?1:u>100?4.5:1+.035*u+7/1e6*u*(u-60)*(100-u),lb=(u,e=X.AUDIO,t,r,l)=>{const s=Ot(l,u,Xe.INBOUND),i=Ot(l,t,Xe.INBOUND),f=Ot(l,r,Xe.INBOUND),h=[],d=[],p=s[e].percent_packets_lost_in,v=s[e].delta_jitter_ms_in,T=i&&i[e].delta_jitter_ms_in||null,y=f&&f[e].delta_jitter_ms_in||null,S=u.data.delta_rtt_connectivity_ms,A=t&&t.data.delta_rtt_connectivity_ms||null,R=r&&r.data.delta_rtt_connectivity_ms||null;S&&h.push(S),A&&h.push(A),R&&h.push(R),v&&d.push(v),t&&T&&d.push(T),r&&y&&d.push(y);const O=h.length>0?An(h):100,N=d.length>0?An(d):10,C=93.2-p,b=.18*C*C-27.9*C+1126.62,w=(O+N)/2,F=w-177.3<0?0:1,q=.024*w+.11*(w-177.3)*F,D=b-q;return Qu(D)},ab=(u,e=X.AUDIO,t,r,l)=>{const s=Ot(l,u,Xe.OUTBOUND),i=Ot(l,t,Xe.OUTBOUND),f=Ot(l,r,Xe.OUTBOUND),h=[],d=[],p=s[e].percent_packets_lost_out,v=s[e].delta_rtt_ms_out,T=i&&i[e].delta_rtt_ms_out||null,y=f&&f[e].delta_rtt_ms_out||null,S=s[e].delta_jitter_ms_out,A=i&&i[e].delta_jitter_ms_out||null,R=f&&f[e].delta_jitter_ms_out||null,O=u.data.delta_rtt_connectivity_ms,N=t&&t.data.delta_rtt_connectivity_ms||null,C=r&&r.data.delta_rtt_connectivity_ms||null;v?h.push(v):O&&h.push(O),T?h.push(T):N&&h.push(N),y?h.push(y):C&&h.push(C),S&&d.push(S),t&&A&&d.push(A),r&&R&&d.push(R);const b=h.length>0?An(h):100,w=d.length>0?An(d):10,F=93.2-p,q=.18*F*F-27.9*F+1126.62,D=(b+w)/2,P=D-177.3<0?0:1,I=.024*D+.11*(D-177.3)*P,x=q-I;return Qu(x)},ob=(u,e=X.AUDIO,t,r,l)=>{const s=Ot(l,u,Xe.INBOUND),i=Ot(l,t,Xe.INBOUND),f=Ot(l,r,Xe.INBOUND),h=[],d=[],p=s[e].percent_packets_lost_in/100,v=s[e].delta_jitter_ms_in,T=i&&i[e].delta_jitter_ms_in||null,y=f&&f[e].delta_jitter_ms_in||null,S=u.data.delta_rtt_connectivity_ms,A=t&&t.data.delta_rtt_connectivity_ms||null,R=r&&r.data.delta_rtt_connectivity_ms||null;S&&h.push(S),A&&h.push(A),R&&h.push(R),v&&d.push(v),i&&T&&d.push(T),f&&y&&d.push(y);const O=h.length>0?An(h):100,N=d.length>0?An(d):10,C=0,b=19.8,w=29.7,F=30,q=(O+N)/2+F,D=q-177.3<0?0:1,P=.024*q+.11*(q-177.3)*D,x=93.2-(C+b*Math.log(1+w*p)+P);return Qu(x)},ub=(u,e=X.AUDIO,t,r,l)=>{const s=Ot(l,u,Xe.OUTBOUND),i=Ot(l,t,Xe.OUTBOUND),f=Ot(l,r,Xe.OUTBOUND),h=[],d=[],p=s[e].percent_packets_lost_out/100,v=s[e].delta_rtt_ms_out,T=i&&i[e].delta_rtt_ms_out||null,y=f&&f[e].delta_rtt_ms_out||null,S=s[e].delta_jitter_ms_out,A=i&&i[e].delta_jitter_ms_out||null,R=f&&f[e].delta_jitter_ms_out||null,O=u.data.delta_rtt_connectivity_ms,N=t&&t.data.delta_rtt_connectivity_ms||null,C=r&&r.data.delta_rtt_connectivity_ms||null;v?h.push(v):O&&h.push(O),T?h.push(T):N&&h.push(N),y?h.push(y):C&&h.push(C),S&&d.push(S),i&&A&&d.push(A),f&&R&&d.push(R);const b=h.length>0?An(h):100,w=d.length>0?An(d):10,F=0,q=19.8,D=29.7,P=30,I=(b+w)/2+P,x=I-177.3<0?0:1,U=.024*I+.11*(I-177.3)*x,z=93.2-(F+q*Math.log(1+D*p)+U);return Qu(z)};class cb{constructor(e,t){this._callbacks={onreport:null,onticket:null},this._id=HA(),this._moduleName=this._id,this._probeId=t,this._config=e,this._exporter=new WA(e),this._state=en.IDLE,this.registerToPCEvents(),ii(this._moduleName,`new collector created for probe ${this._probeId}`)}analyze(e,t,r,l){const s=(h,d)=>h===X.AUDIO?d===Ss.INBOUND_RTP?{...Jp}:{...Qp}:d===Ss.INBOUND_RTP?{...Zp}:{...e0},i=MA(t);i.pname=this._config.pname,i.call_id=this._config.cid,i.user_id=this._config.uid,i.count=t?t.count+1:1;let f=null;return e.forEach(h=>{!f&&h.timestamp&&(f=h.timestamp),rb(h,i,i.pname,l).forEach(p=>{if(p.value&&p.type)if(p.ssrc){let v=i[p.type][p.ssrc];v||(v=s(p.type,h.type),v.ssrc=p.ssrc,i[p.type][p.ssrc]=v),Object.keys(p.value).forEach(T=>{v[T]=p.value[T]})}else Object.keys(p.value).forEach(v=>{i[p.type][v]=p.value[v]})})}),i.timestamp=f,Object.keys(i[X.AUDIO]).forEach(h=>{const d=i[X.AUDIO][h];d.direction===Xe.INBOUND?(d.mos_emodel_in=lb(i,X.AUDIO,t,r,d.ssrc),d.mos_in=ob(i,X.AUDIO,t,r,d.ssrc)):(d.mos_emodel_out=ab(i,X.AUDIO,t,r,d.ssrc),d.mos_out=ub(i,X.AUDIO,t,r,d.ssrc))}),i}async takeReferenceStats(){return new Promise((e,t)=>{const r=Date.now();setTimeout(async()=>{try{const l=Date.now()-r,s=Date.now(),i=await this._config.pc.getStats(),f=this.analyze(i,null,null,null),h=Date.now();f.experimental.time_to_measure_ms=h-s,f.experimental.time_to_wait_ms=l,this._exporter.saveReferenceReport(f),Be(this._moduleName,`got reference report for probe ${this._probeId}`),e()}catch(l){t(l)}},this._config.startAfter)})}async collectStats(){try{if(this._state!==en.RUNNING||!this._config.pc)return Be(this._moduleName,`report discarded (too late) for probe ${this._probeId}`),null;const e=Date.now(),t=await this._config.pc.getStats(),r=this.analyze(t,this._exporter.getLastReport(),this._exporter.getBeforeLastReport(),this._exporter.getReferenceReport()),l=Date.now();return r.experimental.time_to_measure_ms=l-e,this._exporter.addReport(r),Be(this._moduleName,`got report for probe ${this._probeId}#${this._exporter.getReportsNumber()+1}`),this.fireOnReport(r),r}catch(e){return Zi(this._moduleName,`got error ${e}`),null}}async start(){Be(this._moduleName,"starting"),this.state=en.RUNNING,this._startedTime=this._exporter.start(),Be(this._moduleName,"started")}async mute(){this.state=en.MUTED,Be(this._moduleName,"muted")}async unmute(){this.state=en.RUNNING,Be(this._moduleName,"unmuted")}async stop(e){if(Be(this._moduleName,`stopping${e?" by watchdog":""}...`),this._stoppedTime=this._exporter.stop(),this.state=en.IDLE,this._config.ticket){const{ticket:t}=this._exporter;this.fireOnTicket(t)}this._exporter.reset(),Be(this._moduleName,"stopped")}registerCallback(e,t,r){e in this._callbacks?(this._callbacks[e]={callback:t,context:r},Be(this._moduleName,`registered callback '${e}'`)):Zi(this._moduleName,`can't register callback for '${e}' - not found`)}unregisterCallback(e){e in this._callbacks?(this._callbacks[e]=null,delete this._callbacks[e],Be(this._moduleName,`unregistered callback '${e}'`)):Zi(this._moduleName,`can't unregister callback for '${e}' - not found`)}fireOnReport(e){this._callbacks.onreport&&Ff(this._callbacks.onreport.callback,this._callbacks.onreport.context,e)}fireOnTicket(e){this._callbacks.onticket&&Ff(this._callbacks.onticket.callback,this._callbacks.onticket.context,e)}updateConfig(e){this._config=e,this._exporter.updateConfig(e)}get state(){return this._state}set state(e){this._state=e,Be(this._moduleName,`state changed to ${e}`)}addCustomEvent(e,t,r,l){this._exporter.addCustomEvent({at:typeof e=="object"?e.toJSON():e,category:t,name:r,description:l})}async registerToPCEvents(){const{pc:e}=this._config;if(navigator.mediaDevices.ondevicechange=async()=>{try{const t=await navigator.mediaDevices.enumerateDevices();this.addCustomEvent(new Date().toJSON(),"device",`${t.length} devices found`,"Media Devices state")}catch{Zi(this._moduleName,"can't get devices")}},e){e.oniceconnectionstatechange=()=>{const r=e.iceConnectionState;r===Rl.CONNECTED||r===Rl.COMPLETED?this.addCustomEvent(new Date().toJSON(),"call",r,"ICE connection state"):r===Rl.DISCONNECTED||r===Rl.FAILED?this.addCustomEvent(new Date().toJSON(),"call",r,"ICE connection state"):r===Rl.CLOSED&&this.addCustomEvent(new Date().toJSON(),"call","ended","ICE connection state")},e.onicegatheringstatechange=()=>{const r=e.iceGatheringState;this.addCustomEvent(new Date().toJSON(),"call",r,"ICE gathering state")},e.ontrack=r=>{this.addCustomEvent(new Date().toJSON(),"call",`${r.track.kind}track`,"MediaStreamTrack received")},e.onnegotiationneeded=()=>{this.addCustomEvent(new Date().toJSON(),"call","negotiation","Media changed")};const t=e.getReceivers();if(t&&t.length>0){const r=t[0],{transport:l}=r;if(l){const{iceTransport:s}=l;s&&(s.onselectedcandidatepairchange=()=>{this.addCustomEvent(new Date().toJSON(),"call","transport","Candidates Pair changed")})}}}}}class hb{constructor(e){this._id=e.pname&&e.pname.substr(0,12).padEnd(12," ")||$A(),this._moduleName=this._id,ii(this._moduleName,"probe created"),this._config=e,this._collector=new cb(this._config,this._id)}set onreport(e){e?this._collector.registerCallback("onreport",e):this._collector.unregisterCallback("onreport")}set onticket(e){e?this._collector.registerCallback("onticket",e):this._collector.unregisterCallback("onticket")}get id(){return this._id}get pname(){return this._config.pname}get cid(){return this._config.cid}get uid(){return this._config.uid}get state(){return this._collector.state}set state(e){this._collector.state=e}addCustomEvent(e,t,r,l=new Date().toJSON()){this._collector.addCustomEvent(l,t,e,r)}get isRunning(){return this._collector.state===en.RUNNING}get isIdle(){return this._collector.state===en.IDLE}updateUserId(e){this._config.uid=e,this._collector.updateConfig(this._config)}updateCallId(e){this._config.cid=e,this._collector.updateConfig(this._config)}start(){if(!this.isIdle){Xu(this._moduleName,"probe is already running");return}this._collector.start()}stop(e=!1){this.isRunning&&this._collector.stop(e)}async takeReferenceStats(){return this._collector.takeReferenceStats()}async collectStats(){return this._collector.collectStats()}}const qt="engine ";class fb{constructor(e){this._config=e,this._probes=[],this._startedTime=null,this._callbacks={onresult:null},ii(qt,`configured for probing every ${this._config.refreshEvery}ms`),ii(qt,`configured for starting after ${this._config.startAfter}ms`),ii(qt,`${!this._config.stopAfter||this._config.stopAfter!==-1?`configured for stopped after ${this._config.stopAfter}ms`:"configured for never stopped"}`),Be(qt,"engine initialized")}get probes(){return this._probes}get isRunning(){return this._probes.some(e=>e.isRunning)}get isIdle(){return this._probes.every(e=>e.isIdle)}addNewProbe(e,t){if(!e)throw new Error("undefined peer connection");const r=LA(e,t,this._config),l=new hb(r);return this._probes.push(l),Be(qt,`${this._probes.length} probes registered`),l}removeExistingProbe(e){if(!e)throw new Error("undefined probe");e.state===en.RUNNING&&e.stop(),this._probes=this._probes.filter(t=>e.id!==t.id)}async start(){const e=()=>{this._probes.forEach(s=>s.start())},t=async()=>Promise.all(this._probes.map(s=>s.takeReferenceStats())),r=()=>this.isIdle?!1:!this._config.stopAfter||this._config.stopAfter<0?!0:Date.now()<this._startedTime+this._config.stopAfter,l=async()=>{const s=kA(),i=this._probes.filter(f=>f.isRunning);for(const f of i){const h=await f.collectStats();h&&s.probes.push(h),Be(qt,`got probe ${f.id}`),await t0(0)}return s.delta_time_to_measure_probes_ms=ri(s.probes,"experimental","time_to_measure_ms"),s.delta_KBytes_in=ri(s.probes,"data","delta_KBytes_in"),s.delta_KBytes_out=ri(s.probes,"data","delta_KBytes_out"),s.delta_kbs_in=ri(s.probes,"data","delta_kbs_in"),s.delta_kbs_out=ri(s.probes,"data","delta_kbs_out"),s.total_time_decoded_in=ri(s.probes,"video","total_time_decoded_in"),s.total_time_encoded_out=ri(s.probes,"video","total_time_encoded_out"),s};for(Be(qt,"starting to collect"),e(),Be(qt,"generating reference reports..."),await t(),Be(qt,"reference reports generated"),this._startedTime=Date.now();r();)if(Be(qt,`wait ${this._config.refreshEvery}ms before collecting`),await t0(this._config.refreshEvery),r()){Be(qt,"collecting...");const s=Date.now(),i=await l(),f=Date.now();i.delta_time_consumed_to_measure_ms=f-s,this.fireOnReports(i),Be(qt,"collected")}Be(qt,"reaching end of the collecting period..."),this.isRunning&&setTimeout(()=>{this.stop()},0)}stop(e){const t=r=>{this._probes.forEach(l=>{l.stop(r)})};ii(qt,"stop collecting"),t(e)}registerCallback(e,t,r){e in this._callbacks?(this._callbacks[e]={callback:t,context:r},Be(qt,`registered callback '${e}'`)):Zi(qt,`can't register callback for '${e}' - not found`)}unregisterCallback(e){e in this._callbacks?(this._callbacks[e]=null,delete this._callbacks[e],Be(this._moduleName,`unregistered callback '${e}'`)):Zi(this._moduleName,`can't unregister callback for '${e}' - not found`)}fireOnReports(e){this._callbacks.onresult&&e.probes.length>0&&Ff(this._callbacks.onresult.callback,this._callbacks.onresult.context,e)}}const db="interface ";class _b{constructor(e){this._config=FA(e),ii(db,`welcome to ${this._config.name} version ${this._config.version}`),RA(this._config.verbose||!1),this._engine=new fb(this._config)}setupLogLevel(e){wA(e)}get version(){return this._config.version}get name(){return this._config.name}get probes(){return this._engine.probes}createProbe(e,t){return this._engine.addNewProbe(e,t)}startAllProbes(){this._engine.start()}stopAllProbes(){this._engine.stop()}get running(){return this._engine.isRunning}get idle(){return this._engine.isIdle}removeProbe(e){this._engine.removeExistingProbe(e)}set onresult(e){e?this._engine.registerCallback("onresult",e):this._engine.unregisterCallback("onresult")}}function gb(u,e){return Object.keys(u).filter(t=>e.includes(t)).reduce((t,r)=>{const l=r;return{...t,[l]:u[l]}},{})}const pb=["mos_in","codec_in","delta_KBytes_in","delta_kbs_in","delta_jitter_ms_in","delta_packets_lost_in"];class mb{constructor(e){this.intervals={},this.emitInterval=e.emitInterval||200,this.onChangeFunction=e.onChangeFunction}start(e,t){e&&e.getTracks().length&&requestAnimationFrame(()=>this.beginCalculation(e,t))}stop(e){this.clearVolumeInterval(e)}clearVolumeInterval(e){clearInterval(this.intervals[e]),delete this.intervals[e]}clearAllIntervals(){Object.keys(this.intervals).forEach(e=>{clearInterval(this.intervals[e])}),this.intervals={}}beginCalculation(e,t){this.clearVolumeInterval(t);const r=ni.createAnalyser(),l=ni.createMediaStreamSource(e),s=ni.createScriptProcessor(2048,1,1);r.smoothingTimeConstant=.8,r.fftSize=1024,l.connect(r),r.connect(s),s.connect(ni.destination),this.intervals[t]=setInterval(()=>{const i=new Uint8Array(r.frequencyBinCount);r.getByteFrequencyData(i);let f=0;const h=i.length;for(let p=0;p<h;p++)f+=i[p];const d=f/h;this.onChangeFunction(t,d)},this.emitInterval)}}const Zu={SELECTED_INPUT_DEVICE:"OpensipsJSInputDevice",SELECTED_OUTPUT_DEVICE:"OpensipsJSOutputDevice"},vb=0;class Tb{constructor(e){this.isAutoAnswer=!1,this.muteWhenJoinEnabled=!1,this.isDNDEnabled=!1,this.muted=!1,this.microphoneInputLevelValue=1,this.speakerVolumeValue=1,this.activeRooms={},this.activeCalls={},this.extendedCalls={},this.availableMediaDevices=[],this.selectedMediaDevices={input:"default",output:"default"},this.callStatus={},this.callTime={},this.callMetrics={},this.timeIntervals={},this.metricConfig={refreshEvery:1e3},this.activeStreamValue=null,this.initialStreamValue=null,this.context=e,this.context.on(this.context.newRTCSessionEventName,this.newRTCSessionCallback.bind(this)),this.VUMeter=new mb({onChangeFunction:this.emitVolumeChange.bind(this)}),this.initializeMediaDevices()}get sipOptions(){return{...this.context.options.sipOptions,mediaConstraints:this.getUserMediaConstraints}}get currentActiveRoomId(){return this.currentActiveRoomIdValue}set currentActiveRoomId(e){this.currentActiveRoomIdValue=e,this.context.emit("currentActiveRoomChanged",e)}get autoAnswer(){return this.isAutoAnswer}get callAddingInProgress(){return this.isCallAddingInProgress}set callAddingInProgress(e){this.isCallAddingInProgress=e,this.context.emit("callAddingInProgressChanged",e)}get muteWhenJoin(){return this.muteWhenJoinEnabled}get isDND(){return this.isDNDEnabled}get speakerVolume(){return this.speakerVolumeValue}get microphoneInputLevel(){return this.microphoneInputLevelValue}get getActiveCalls(){return this.activeCalls}get hasActiveCalls(){return Object.values(this.extendedCalls).length>0}get getActiveRooms(){return this.activeRooms}get isMuted(){return this.muted}get getInputDeviceList(){return this.availableMediaDevices.filter(e=>e.kind==="audioinput")}get getOutputDeviceList(){return this.availableMediaDevices.filter(e=>e.kind==="audiooutput")}get getUserMediaConstraints(){return Og()?{video:!1,audio:!0}:{audio:{deviceId:{exact:this.selectedMediaDevices.input}},video:!1}}get selectedInputDevice(){return this.selectedMediaDevices.input}get selectedOutputDevice(){return this.selectedMediaDevices.output}get activeStream(){return this.activeStreamValue}setAvailableMediaDevices(e){this.availableMediaDevices=e,this.context.emit("changeAvailableDeviceList",e)}async updateDeviceList(){await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints);const e=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(e)}async initializeMediaDevices(){const e=localStorage.getItem(Zu.SELECTED_INPUT_DEVICE)||"default",t=localStorage.getItem(Zu.SELECTED_OUTPUT_DEVICE)||"default";try{const r=await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints),l=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(l),await this.setMicrophone(e),await this.setSpeaker(t),navigator.mediaDevices.addEventListener("devicechange",async()=>{const s=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(s)}),r.getTracks().forEach(s=>s.stop())}catch(r){console.error(r)}}setCallTime(e){const t={...e};delete t.callId,this.callTime={...this.callTime,[e.callId]:t},this.context.emit("changeCallTime",this.callTime)}removeCallTime(e){const t={...this.callTime};delete t[e],this.callTime={...t},this.context.emit("changeCallTime",this.callTime)}setTimeInterval(e,t){this.timeIntervals={...this.timeIntervals,[e]:t}}removeTimeInterval(e){const t={...this.timeIntervals};t[e]&&(clearInterval(t[e]),delete t[e],this.timeIntervals={...t})}stopCallTimer(e){this.removeTimeInterval(e),this.removeCallTime(e)}emitVolumeChange(e,t){this.context.emit("changeCallVolume",{callId:e,volume:t})}setMetricsConfig(e){this.metricConfig={...this.metricConfig,...e}}sendDTMF(e,t){if(!/^[A-D0-9]+$/g.test(t))throw new Error("Not allowed character in DTMF input");this.extendedCalls[e].sendDTMF(t)}setIsMuted(e){this.muted=e,this.context.emit("changeIsMuted",e)}processMute(e){const t=this.currentActiveRoomId;this.setIsMuted(e),this.initialStreamValue.getTracks().forEach(r=>r.enabled=!e),this.roomReconfigure(t)}mute(){this.processMute(!0)}unmute(){this.processMute(!1)}async processHold({callId:e,toHold:t,automatic:r}){const l=this.extendedCalls[e];l._automaticHold=r??!1,await new Promise(f=>{const h=()=>{l.putOnHoldTimestamp=t?Date.now():void 0,f()};t?l.hold({},h):l.unhold({},h)}),this.updateCall(l);const i=Object.values(this.extendedCalls).filter(f=>f.roomId===this.currentActiveRoomId&&(t?e!==f._id:!0));i.length>1&&await this.doConference(i)}holdCall(e,t=!1){return this.processHold({callId:e,automatic:t,toHold:!0})}unholdCall(e){return this.processHold({callId:e,toHold:!1})}cancelAllOutgoingUnanswered(){Object.values(this.getActiveCalls).filter(e=>e.direction==="outgoing"&&e.status===vb).forEach(e=>this.terminateCall(e._id))}answerCall(e){const t=this.extendedCalls[e];this.cancelAllOutgoingUnanswered(),t.answer(this.sipOptions),this.updateCall(t),this.setActiveRoom(t.roomId),t.connection.addEventListener("track",r=>{this.triggerAddStream(r,t)})}async moveCall(e,t){this.updateCallStatus({callId:e,isMoving:!0}),await this.processRoomChange({callId:e,roomId:t}),this.updateCallStatus({callId:e,isMoving:!1})}updateCall(e){this.activeCalls[e._id]=Rg(e),this.context.emit("changeActiveCalls",this.activeCalls)}updateRoom(e){const r={...this.activeRooms[e.roomId],...e};this.activeRooms={...this.activeRooms,[e.roomId]:{...r}},this.context.emit("updateRoom",{room:r,roomList:this.activeRooms})}hasAutoAnswerHeaders(e){const t=/answer-after=0/,l=e.request.getHeader("Call-Info");return l&&t.test(l)}addCall(e,t=!0){this.activeCalls={...this.activeCalls,[e._id]:Rg(e)},this.extendedCalls[e._id]=e,t&&this.context.emit("changeActiveCalls",this.activeCalls)}addCallStatus(e){this.callStatus={...this.callStatus,[e]:{isMoving:!1,isTransferring:!1,isMerging:!1}},this.context.emit("changeCallStatus",this.callStatus)}updateCallStatus(e){const r={...{...this.callStatus[e.callId]}};e.isMoving!==void 0&&(r.isMoving=e.isMoving),e.isTransferring!==void 0&&(r.isTransferring=e.isTransferring),e.isMerging!==void 0&&(r.isMerging=e.isMerging),this.callStatus={...this.callStatus,[e.callId]:{...r}},this.context.emit("changeCallStatus",this.callStatus)}removeCallStatus(e){const t={...this.callStatus};delete t[e],this.callStatus={...t},this.context.emit("changeCallStatus",this.callStatus)}addRoom(e){this.activeRooms={...this.activeRooms,[e.roomId]:e},this.context.emit("addRoom",{room:e,roomList:this.activeRooms})}getActiveStream(){const e=Ig(this.initialStreamValue,this.microphoneInputLevel*2);return e.getTracks().forEach(t=>t.enabled=!this.isMuted),this.setActiveStream(e),e}async setMicrophone(e){if(!this.getInputDeviceList.find(({deviceId:r})=>r===e)||(this.setSelectedInputDevice(e),Object.keys(this.getActiveCalls).length===0))return;await this.setupStream();const t=Object.values(this.extendedCalls).filter(r=>r.roomId===this.currentActiveRoomId);t.length===1?Object.values(t).forEach(async r=>{const l=this.getActiveStream();r.connection.getSenders()[0].replaceTrack(l.getTracks()[0]),this.updateCall(r)}):await this.doConference(t)}setActiveStream(e){this.activeStream&&this.stopVUMeter("origin"),this.setupVUMeter(e,"origin"),this.activeStreamValue=e,this.context.emit("changeActiveStream",e)}async setSpeaker(e){if(!this.getOutputDeviceList.find(({deviceId:l})=>l===e))return;this.setSelectedOutputDevice(e);const t=Object.values(this.extendedCalls);if(t.length===0)return;const r=t.filter(l=>l.roomId===this.currentActiveRoomId);r.length===1?t.forEach(l=>{var s;(s=l.audioTag)==null||s.setSinkId(e),this.updateCall(l)}):await this.doConference(r)}removeRoom(e){const t={...this.activeRooms},r={...t[e]};delete t[e],this.activeRooms={...t},this.context.emit("removeRoom",{room:r,roomList:this.activeRooms})}deleteRoomIfEmpty(e){e!==void 0&&Object.values(this.extendedCalls).filter(t=>t.roomId===e).length===0&&(this.removeRoom(e),this.currentActiveRoomId===e&&(this.currentActiveRoomId=void 0))}checkInitialized(){if(!this.context.initialized)throw new Error("[OpenSIPSJS] You must call `start` method first!")}muteReconfigure(e){this.muted?e.mute({audio:!0}):e.unmute({audio:!0})}async roomReconfigure(e){var r;if(e===void 0)return;const t=Object.values(this.extendedCalls).filter(l=>l.roomId===e);if(this.currentActiveRoomId===e?t.forEach(l=>{l.audioTag&&(this.muteReconfigure(l),l.audioTag.muted=!1,this.updateCall(l))}):t.forEach(l=>{l.audioTag&&(l.audioTag.muted=!0,this.updateCall(l))}),t.length===0)this.deleteRoomIfEmpty(e);else if(t.length===1&&this.currentActiveRoomId!==e)t[0].isOnHold().local||await this.holdCall(t[0].id,!0);else if(t.length===1&&this.currentActiveRoomId===e){if(t[0].isOnHold().local&&t[0]._automaticHold&&await this.unholdCall(t[0].id),t[0].connection&&((r=t[0].connection)!=null&&r.getSenders()[0])){const l=this.getActiveStream();await t[0].connection.getSenders()[0].replaceTrack(l.getTracks()[0]),this.muteReconfigure(t[0])}}else t.length>1&&await this.doConference(t)}async doConference(e){const t=[];e.forEach(r=>{r!=null&&r.connection.getReceivers().forEach(l=>{t.push(l.track)})}),await AA.forEach(e,async r=>{var i;if(r==null)return;const l=new MediaStream,s=ni.createMediaStreamDestination();if(r.connection.getReceivers().forEach(f=>{t.forEach(h=>{l.addTrack(f.track),f.track.id!==h.id&&ni.createMediaStreamSource(new MediaStream([h])).connect(s)})}),e[0].roomId===this.currentActiveRoomId){const f=this.getActiveStream();ni.createMediaStreamSource(f).connect(s)}(i=r.connection)!=null&&i.getSenders()[0]&&(await r.connection.getSenders()[0].replaceTrack(s.stream.getTracks()[0]),this.muteReconfigure(r))})}processCallerMute(e,t){const r=this.extendedCalls[e];r&&r.connection.getReceivers().length&&(r.localMuted=t,r.connection.getReceivers().forEach(l=>{l.track.enabled=!t}),this.updateCall(r))}muteCaller(e){this.processCallerMute(e,!0)}unmuteCaller(e){this.processCallerMute(e,!1)}terminateCall(e){const t=this.extendedCalls[e];t._status!==8&&t.terminate()}transferCall(e,t){if(t.toString().length===0)return new Error("Target must be passed");const r=this.extendedCalls[e];if(!r._is_confirmed&&!r._is_canceled){const l=`sip:${t}@${this.context.sipDomain}`;r.terminate({status_code:302,reason_phrase:"Moved Temporarily",extraHeaders:[`Contact: ${l}`]});return}this.updateCallStatus({callId:e,isTransferring:!0}),r.refer(`sip:${t}@${this.context.sipDomain}`),this.updateCall(r)}mergeCall(e){const t=Object.values(this.extendedCalls).filter(s=>s.roomId===e);if(t.length!==2)return;const r=t[0],l=t[1];!r||!l||(this.updateCallStatus({callId:r._id,isMerging:!0}),this.updateCallStatus({callId:l._id,isMerging:!0}),r.refer(l.remote_identity.uri.toString(),{replaces:l}),this.updateCall(r))}mergeCallByIds(e,t){const r=Object.values(this.extendedCalls).find(s=>s._id===e),l=Object.values(this.extendedCalls).find(s=>s._id===t);if(!r||!l)throw new Error("Call ID is not provided");this.updateCallStatus({callId:e,isMerging:!0}),this.updateCallStatus({callId:t,isMerging:!0}),r.refer(l.remote_identity.uri.toString(),{replaces:l}),this.updateCall(r)}setDND(e){this.isDNDEnabled=e,this.context.emit("changeIsDND",e)}startCallTimer(e){this.removeTimeInterval(e);const t={callId:e,hours:0,minutes:0,seconds:0,formatted:""};this.setCallTime(t);const r=setInterval(()=>{const l={...this.callTime[e]},s=CA(l);this.setCallTime({callId:e,...s})},1e3);this.setTimeInterval(e,r)}async setActiveRoom(e){const t=this.currentActiveRoomId;e!==t&&(this.currentActiveRoomId=e,await this.roomReconfigure(t),await this.roomReconfigure(e))}getNewRoomId(){const e=Object.keys(this.activeRooms);return e.length===0?1:parseInt(e.sort()[e.length-1])+1}async setupCall(e){var d,p;const t=e.session;if(this.getActiveCalls[t.id]!==void 0)return;const l=this.getNewRoomId(),s={started:new Date,incomingInProgress:!1,roomId:l};t.direction==="incoming"?(this.context.logger.log("New incoming call from",(p=(d=t._remote_identity)==null?void 0:d._uri)==null?void 0:p._user),s.incomingInProgress=!0,this.context.subscribe(ys.CALL_CONFIRMED,v=>{t.id===v.id&&(this.updateRoom({incomingInProgress:!1,roomId:l}),this.startCallTimer(t.id))}),this.context.subscribe(ys.CALL_FAILED,v=>{t.id===v.id&&(this.updateRoom({incomingInProgress:!1,roomId:l}),this.deleteRoomIfEmpty(l))})):t.direction==="outgoing"&&(t.once("confirmed",()=>{this.startCallTimer(t.id)}),this.startCallTimer(t.id));const i=t,f=this.hasAutoAnswerHeaders(e),h=i.direction==="incoming"&&!this.hasActiveCalls&&(f||this.autoAnswer);i.roomId=l,i.localMuted=!1,i.autoAnswer=h,h?this.addCall(i,!1):this.addCall(i),this.addCallStatus(t.id),this.addRoom(s),h&&this.answerCall(i._id)}removeCall(e){const t={...this.activeCalls};delete t[e],this.activeCalls={...t};const r={...this.extendedCalls};delete r[e],this.extendedCalls={...r},this.context.emit("changeActiveCalls",this.activeCalls)}activeCallListRemove(e){var l;const t=this.extendedCalls[e._id];this.stopVUMeter("origin"),(l=t.connection)==null||l.getSenders().forEach(s=>{s.track.stop()});const r=t.roomId;this.removeCall(e._id),this.roomReconfigure(r)}async newRTCSessionCallback(e){const t=e.session;if(this.isDND){t.terminate({status_code:486,reason_phrase:"Do Not Disturb"});return}if(this.context.triggerListener({listenerType:ys.NEW_CALL,session:t,event:e}),t.on("ended",r=>{var s,i,f;this.stopVUMeter(t.id),this.context.logger.log("Session ended for",(i=(s=t._remote_identity)==null?void 0:s._uri)==null?void 0:i._user),this.context.triggerListener({listenerType:ys.CALL_ENDED,session:t,event:r});const l=this.getActiveCalls[t.id];l&&this.activeCallListRemove(l),this.stopCallTimer(t.id),this.removeCallStatus(t.id),this.removeCallMetrics(t.id),Object.keys(this.extendedCalls).length||(this.setIsMuted(!1),(f=this.initialStreamValue)==null||f.getTracks().forEach(h=>h.stop()),this.initialStreamValue=null)}),t.on("progress",r=>{var l,s;this.context.logger.log("Session in progress for",(s=(l=t._remote_identity)==null?void 0:l._uri)==null?void 0:s._user),this.context.triggerListener({listenerType:ys.CALL_PROGRESS,session:t,event:r})}),t.on("failed",r=>{var s,i,f;this.stopVUMeter(t.id),this.context.logger.log("Session failed for",(i=(s=t._remote_identity)==null?void 0:s._uri)==null?void 0:i._user),this.context.triggerListener({listenerType:ys.CALL_FAILED,session:t,event:r}),t.id===this.callAddingInProgress&&(this.callAddingInProgress=void 0);const l=this.getActiveCalls[t.id];l&&this.activeCallListRemove(l),this.stopCallTimer(t.id),this.removeCallStatus(t.id),this.removeCallMetrics(t.id),Object.keys(this.extendedCalls).length||(this.setIsMuted(!1),(f=this.initialStreamValue)==null||f.getTracks().forEach(h=>h.stop()),this.initialStreamValue=null)}),t.on("confirmed",r=>{var l,s;this.context.logger.log("Session confirmed for",(s=(l=t._remote_identity)==null?void 0:l._uri)==null?void 0:s._user),this.context.triggerListener({listenerType:ys.CALL_CONFIRMED,session:t,event:r}),this.updateCall(t),t.id===this.callAddingInProgress&&(this.callAddingInProgress=void 0)}),await this.setupCall(e),t.direction==="outgoing"){const r=this.getActiveCalls[t.id].roomId;this.setActiveRoom(r)}}setMuteWhenJoin(e){this.muteWhenJoinEnabled=e,this.context.emit("changeMuteWhenJoin",e)}setMicrophoneSensitivity(e){if(e<0||e>1)throw new Error("Value should be in range from 0 to 1!");this.microphoneInputLevelValue=e,this.roomReconfigure(this.currentActiveRoomId)}setSpeakerVolume(e){this.speakerVolumeValue=e,Object.values(this.extendedCalls).forEach(t=>{t.audioTag&&(t.audioTag.volume=e,this.updateCall(t))})}setAutoAnswer(e){this.isAutoAnswer=e}setSelectedInputDevice(e){localStorage.setItem(Zu.SELECTED_INPUT_DEVICE,e),this.selectedMediaDevices.input=e,this.context.emit("changeActiveInputMediaDevice",e)}setSelectedOutputDevice(e){localStorage.setItem(Zu.SELECTED_OUTPUT_DEVICE,e),this.selectedMediaDevices.output=e,this.context.emit("changeActiveOutputMediaDevice",e)}setCallMetrics(e){const t={...e};delete t.callId,this.callMetrics={...this.callMetrics,[e.callId]:t},this.context.emit("changeCallMetrics",this.callMetrics)}removeCallMetrics(e){const t={...this.callMetrics};delete t[e],this.callMetrics={...t},this.context.emit("changeCallMetrics",this.callMetrics)}getCallQuality(e){const t=new _b(this.metricConfig),r=t.createProbe(e.connection,{cid:e._id}),l=[];let s;r.onreport=i=>{Object.entries(i.audio).forEach(([d,p])=>{p.direction==="inbound"&&!l.includes(d)&&(l.push(d),s=d)});const f=i.audio[s];if(!f)return;const h=gb(f,pb);h.callId=e._id,this.setCallMetrics(h)},this.context.subscribe(ys.CALL_ENDED,i=>{i._id===e._id&&t.stopAllProbes()}),t.startAllProbes()}setupVUMeter(e,t){this.VUMeter.start(e,t)}stopVUMeter(e){this.VUMeter.stop(e)}async setupStream(){const e=await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints);this.initialStreamValue&&(this.initialStreamValue.getTracks().forEach(t=>t.stop()),this.initialStreamValue=null),this.initialStreamValue=e}async triggerAddStream(e,t){this.setIsMuted(this.muteWhenJoin||this.isMuted),this.initialStreamValue||await this.setupStream();const r=Ig(this.initialStreamValue,this.microphoneInputLevel*2),l=this.isMuted||this.muteWhenJoin;r.getTracks().forEach(i=>i.enabled=!l),this.setActiveStream(r),await t.connection.getSenders()[0].replaceTrack(r.getTracks()[0]);const s=new MediaStream([e.track]);iS(s,t,this.selectedOutputDevice,this.speakerVolume),this.setupVUMeter(s,t._id),this.getCallQuality(t),this.updateCall(t)}initCall(e,t,r=!1){if(e.length===0)return console.error("Target must be a valid string");this.context.logger.log(`Calling sip:${e}@${this.context.sipDomain}...`);const l=this.context.call(`sip:${e}@${this.context.sipDomain}`,this.sipOptions);if(this.callAddingInProgress=l.id,t&&this.currentActiveRoomId!==void 0&&(this.processRoomChange({callId:l.id,roomId:this.currentActiveRoomId}),r)){const s=Object.values(this.extendedCalls).filter(i=>i.roomId===this.currentActiveRoomId&&i._id!==l.id);for(const i of s)this.holdCall(i._id,!0)}l.connection.addEventListener("track",s=>{this.triggerAddStream(s,l)})}async processRoomChange({callId:e,roomId:t}){const r=this.extendedCalls[e].roomId;this.extendedCalls[e].roomId=t;const l=this.extendedCalls[e];return this.updateCall(l),await this.setActiveRoom(t),Promise.all([this.roomReconfigure(r),this.roomReconfigure(t)]).then(()=>{this.deleteRoomIfEmpty(r),this.deleteRoomIfEmpty(t)})}}class yb{constructor(e){this.context=e}get sipOptions(){return{...this.context.options.sipOptions}}initCall(e,t){if(e.length===0)return console.error("Target must be a valid string");this.context.logger.log(`Calling sip:${e}@${this.context.sipDomain}...`),this.context.joinVideoCall(`sip:${e}@${this.context.sipDomain}`,t,this.sipOptions)}stop(e={}){this.context.terminateJanusSessions(e)}startAudio(){this.context.enableJanusAudio(!0)}stopAudio(){this.context.enableJanusAudio(!1)}startVideo(){this.context.enableJanusVideo(!0)}stopVideo(){this.context.enableJanusVideo(!1)}changeMediaConstraints(e){this.context.changeMediaConstraints(e)}startScreenShare(){this.context.startScreenShare()}startBlur(){this.context.startBlur()}stopBlur(){this.context.stopBlur()}}class Sb{constructor(e){this.activeMessages={},this.extendedMessages={},this.msrpHistory={},this.context=e,this.context.on(this.context.newMSRPSessionEventName,this.newMSRPSessionCallback.bind(this.context))}get isMSRPInitializing(){return this.isMSRPInitializingValue}get getActiveMessages(){return this.activeMessages}msrpAnswer(e){const t=this.extendedMessages[e];this.updateMSRPSession(t)}updateMSRPSession(e){this.activeMessages[e._id]=wg(e),this.context.emit("changeActiveMessages",this.activeMessages)}addMMSRPSession(e){this.activeMessages={...this.activeMessages,[e._id]:wg(e)},this.extendedMessages[e._id]=e,this.context.emit("changeActiveMessages",this.activeMessages)}addMSRPMessage(e,t){const r=this.msrpHistory[t.id]||[];r.push(e),this.msrpHistory={...this.msrpHistory,[t.id]:[...r]},this.context.emit("newMSRPMessage",{message:e,session:t})}messageTerminate(e){const t=this.extendedMessages[e];t._status!==8&&t.terminate()}addMessageSession(e){if(!e._id||this.getActiveMessages[e._id]!==void 0)return;const r=e;this.addMMSRPSession(r)}triggerMSRPListener({listenerType:e,session:t,event:r}){const l=this.context.listenersList[e];!l||!l.length||l.forEach(s=>{s(t,r)})}removeMMSRPSession(e){const t={...this.activeMessages};delete t[e],this.activeMessages={...t};const r={...this.extendedMessages};delete r[e],this.extendedMessages={...r},this.context.emit("changeActiveMessages",this.activeMessages)}activeMessageListRemove(e){this.removeMMSRPSession(e._id)}newMSRPSessionCallback(e){const t=e.session;t.on("ended",r=>{this.triggerMSRPListener({listenerType:ys.CALL_ENDED,session:t,event:r});const l=this.getActiveMessages[t.id];this.activeMessageListRemove(l)}),t.on("failed",r=>{this.triggerMSRPListener({listenerType:ys.CALL_FAILED,session:t,event:r});const l=this.getActiveMessages[t.id];this.activeMessageListRemove(l)}),t.on("confirmed",r=>{this.triggerMSRPListener({listenerType:ys.CALL_CONFIRMED,session:t,event:r}),this.updateMSRPSession(t)}),t.on("newMessage",r=>{this.addMSRPMessage(r,t)}),this.addMessageSession(t)}setIsMSRPInitializing(e){this.isMSRPInitializingValue=e,this.context.emit("isMSRPInitializingChanged",e)}initMSRP(e,t,r){if(e.length===0)return console.error("Target must be a valid string");const l=this.context.startMSRP(e,r);l.on("active",()=>{this.addMessageSession(l),l.sendMSRP(t),this.setIsMSRPInitializing(!1)}),this.setIsMSRPInitializing(!0)}sendMSRP(e,t){const r=this.extendedMessages[e];if(!r)throw new Error(`MSRP session with id ${e} doesn't exist!`);r.sendMSRP(t)}}const $f={AUDIO:"audio",VIDEO:"video",MSRP:"msrp"};class Eb extends Jy{constructor(e,t){if(!e.modules.length)throw new Error("options.modules should include at least 1 module");const r={...e.configuration,sockets:e.socketInterfaces.map(l=>new EA.WebSocketInterface(l))};super(r),this.initialized=!1,this.connected=!1,this.logger=console,this.newRTCSessionEventName="newRTCSession",this.registeredEventName="registered",this.unregisteredEventName="unregistered",this.disconnectedEventName="disconnected",this.connectedEventName="connected",this.newMSRPSessionEventName="newMSRPSession",this.isReconnecting=!1,this.activeConnection=!1,this.audio=null,this.msrp=null,this.video=null,this.listenersList={},this.modules=[],e.pnExtraHeaders&&Object.keys(e.pnExtraHeaders).length&&this.registrator().setExtraContactUriParams(e.pnExtraHeaders),this.options=e,this.modules=e.modules,t&&rS(t)&&(this.logger=t)}on(e,t){return super.on(e,t)}off(e,t){return super.off(e,t)}emit(e,t){return super.emit(e,t)}get sipDomain(){return this.options.sipDomain}use(e){if(this.newStreamPlugins.find(t=>t.name===e.name)||this.processStreamPlugins.find(t=>t.name===e.name))throw new Error(`Plugin with name ${e.name} already exists`);if(e instanceof Wo)e.setOpensips(this),this.newStreamPlugins.push(e);else if(e instanceof Pf)e.setOpensips(this),this.processStreamPlugins.push(e);else throw new Error("Wrong plugin instance")}getPlugin(e){return this.newStreamPlugins.find(t=>t.name===e)||this.processStreamPlugins.find(t=>t.name===e)}begin(){if(this.isConnected()){console.error("Connection is already established");return}return this.modules.includes($f.AUDIO)&&(this.audio=new Tb(this)),this.modules.includes($f.MSRP)&&(this.msrp=new Sb(this)),this.modules.includes($f.VIDEO)&&(this.video=new yb(this)),this.on(this.registeredEventName,()=>{this.logger.log("Successfully registered to",this.options.socketInterfaces[0]),this.setInitialized(!0)}),this.on(this.unregisteredEventName,()=>{this.logger.log("Unregistered from",this.options.socketInterfaces[0]),this.setInitialized(!1)}),this.on(this.connectedEventName,()=>{this.logger.log("Connected to",this.options.socketInterfaces[0]),this.setConnected(!0),this.isReconnecting=!1,this.activeConnection=!0}),this.on(this.disconnectedEventName,()=>{this.isReconnecting||(this.isReconnecting=!0,this.logger.log("Disconnected from",this.options.socketInterfaces[0]),this.logger.log("Reconnecting to",this.options.socketInterfaces[0]),this.stop(),this.setInitialized(!1),this.setConnected(!1),this.activeConnection&&setTimeout(this.start.bind(this),5e3))}),this.logger.log("Connecting to",this.options.socketInterfaces[0]),this.start(),this}disconnect(){this.activeConnection=!1,this.stop()}subscribe(e,t){const l=!this.listenersList[e]||!this.listenersList[e].length?[t]:[...this.listenersList[e],t];this.listenersList={...this.listenersList,[e]:l}}removeIListener(e){const t={...this.listenersList};delete t[e],this.listenersList={...t}}triggerListener({listenerType:e,session:t,event:r}){const l=this.listenersList[e];!l||!l.length||l.forEach(s=>{s(t,r)})}setInitialized(e){this.initialized=e,this.emit("ready",e)}setConnected(e){this.connected=e,this.emit("connection",e)}}return zt.BaseNewStreamPlugin=Wo,zt.BaseProcessStreamPlugin=Pf,zt.ScreenSharePlugin=lS,zt.ScreenShareWhiteBoardPlugin=lA,zt.WhiteBoardPlugin=uA,zt.default=Eb,Object.defineProperties(zt,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}}),zt}({});