@voicenter-team/opensips-js 1.0.100 → 1.0.101

Sign up to get free protection for your applications and to get access to all the features.
@@ -18356,4 +18356,4 @@ a=path:${e.getHeader("Use-Path")} msrp://${this._ua._configuration.authorization
18356
18356
  `);if(i===-1){P0.warn("parseMessage() | no CRLF found, not a SIP message");return}const s=r.substring(0,i);let a=rw.parse(s,"Request_Response");if(a===-1){P0.warn(`parseMessage() | error parsing first line of SIP message: "${s}"`);return}else a.status_code?(t=new Zl.IncomingResponse,t.status_code=a.status_code,t.reason_phrase=a.reason_phrase):(t=new Zl.IncomingRequest(e),t.method=a.method,t.ruri=a.uri);t.data=r;let o=i+2;for(;;){if(i=Cue(r,o),i===-2){n=o+2;break}else if(i===-1){P0.warn("parseMessage() | malformed message");return}if(a=Eue(t,r,o,i),a!==!0){P0.warn("parseMessage() |",a.error);return}o=i+2}if(t.hasHeader("content-length")){const u=t.getHeader("content-length");t.body=r.substr(n,u)}else t.body=r.substring(n);return t};function Cue(r,e){let t=e,n=0,i=0;if(r.substring(t,t+2).match(/(^\r\n)/))return-2;for(;n===0;){if(i=r.indexOf(`\r
18357
18357
  `,t),i===-1)return i;!r.substring(i+2,i+4).match(/(^\r\n)/)&&r.charAt(i+2).match(/(^\s+)/)?t=i+2:n=i}return n}function Eue(r,e,t,n){let i;const s=e.indexOf(":",t),a=e.substring(t,s).trim(),o=e.substring(s+1,n).trim();switch(a.toLowerCase()){case"via":case"v":r.addHeader("via",o),r.getHeaders("via").length===1?(i=r.parseHeader("Via"),i&&(r.via=i,r.via_branch=i.branch)):i=0;break;case"from":case"f":r.setHeader("from",o),i=r.parseHeader("from"),i&&(r.from=i,r.from_tag=i.getParam("tag"));break;case"to":case"t":r.setHeader("to",o),i=r.parseHeader("to"),i&&(r.to=i,r.to_tag=i.getParam("tag"));break;case"record-route":if(i=rw.parse(o,"Record_Route"),i===-1)i=void 0;else for(const u of i)r.addHeader("record-route",o.substring(u.possition,u.offset)),r.headers["Record-Route"][r.getHeaders("record-route").length-1].parsed=u.parsed;break;case"call-id":case"i":r.setHeader("call-id",o),i=r.parseHeader("call-id"),i&&(r.call_id=o);break;case"contact":case"m":if(i=rw.parse(o,"Contact"),i===-1)i=void 0;else for(const u of i)r.addHeader("contact",o.substring(u.possition,u.offset)),r.headers.Contact[r.getHeaders("contact").length-1].parsed=u.parsed;break;case"content-length":case"l":r.setHeader("content-length",o),i=r.parseHeader("content-length");break;case"content-type":case"c":r.setHeader("content-type",o),i=r.parseHeader("content-type");break;case"cseq":r.setHeader("cseq",o),i=r.parseHeader("cseq"),i&&(r.cseq=i.value),r instanceof Zl.IncomingResponse&&(r.method=i.method);break;case"max-forwards":r.setHeader("max-forwards",o),i=r.parseHeader("max-forwards");break;case"www-authenticate":r.setHeader("www-authenticate",o),i=r.parseHeader("www-authenticate");break;case"proxy-authenticate":r.setHeader("proxy-authenticate",o),i=r.parseHeader("proxy-authenticate");break;case"session-expires":case"x":r.setHeader("session-expires",o),i=r.parseHeader("session-expires"),i&&(r.session_expires=i.expires,r.session_expires_refresher=i.refresher);break;case"refer-to":case"r":r.setHeader("refer-to",o),i=r.parseHeader("refer-to"),i&&(r.refer_to=i);break;case"replaces":r.setHeader("replaces",o),i=r.parseHeader("replaces"),i&&(r.replaces=i);break;case"event":case"o":r.setHeader("event",o),i=r.parseHeader("event"),i&&(r.event=i);break;default:r.addHeader(a,o),i=0}return i===void 0?{error:`error parsing header "${a}"`}:!0}const xue={parseMessage:wue},np=new fm("Registrator"),F0=10;class Iue{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=so.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 n=this._contact.indexOf(">");if(n!==-1){const i=this._contact.slice(0,n)+this._contact.slice(n+1,this._contact.length);this._contact=i}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 n=e[t];this._extraContactParams+=`;${t}`,n&&(this._extraContactParams+=`=${n}`)}}setExtraContactUriParams(e){e instanceof Object||(e={}),this._extraContactParams="";for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)){const n=e[t];this._extraContactParams+=`;${t}`,n&&(this._extraContactParams+=`=${n}`)}}register(){if(this._registering){np.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 As.OutgoingRequest(ye.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},e),n=new mc(this._ua,t,{onRequestTimeout:()=>{this._registrationFailure(null,ye.causes.REQUEST_TIMEOUT)},onTransportError:()=>{this._registrationFailure(null,ye.causes.CONNECTION_ERROR)},onAuthenticated:()=>{this._cseq+=1},onReceiveResponse:i=>{if(i.cseq===this._cseq)switch(this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null),!0){case/^1[0-9]{2}$/.test(i.status_code):break;case/^2[0-9]{2}$/.test(i.status_code):{if(this._registering=!1,!i.hasHeader("Contact")){np.debug("no Contact header in response to REGISTER, response ignored");break}const s=i.headers.Contact.reduce((c,d)=>c.concat(d.parsed),[]);let a=s.find(c=>this._sipInstance===c.getParam("+sip.instance")&&this._reg_id===parseInt(c.getParam("reg-id")));if(a||(a=s.find(c=>c.uri.user===this._ua.contact.uri.user)),!a){np.debug("no Contact header pointing to us, response ignored");break}let o=a.getParam("expires");!o&&i.hasHeader("expires")&&(o=i.getHeader("expires")),o||(o=this._expires),o=Number(o),o<F0&&(o=F0);const u=o>64?o*1e3/2+Math.floor((o/2-32)*1e3*Math.random()):o*1e3-5e3;this._registrationTimer=setTimeout(()=>{this._registrationTimer=null,this._ua.listeners("registrationExpiring").length===0?this.register():this._ua.emit("registrationExpiring")},u),a.hasParam("temp-gruu")&&(this._ua.contact.temp_gruu=a.getParam("temp-gruu").replace(/"/g,"")),a.hasParam("pub-gruu")&&(this._ua.contact.pub_gruu=a.getParam("pub-gruu").replace(/"/g,"")),this._registered||(this._registered=!0,this._ua.registered({response:i}));break}case/^423$/.test(i.status_code):{i.hasHeader("min-expires")?(this._expires=Number(i.getHeader("min-expires")),this._expires<F0&&(this._expires=F0),this.register()):(np.debug("423 response received for REGISTER without Min-Expires"),this._registrationFailure(i,ye.causes.SIP_FAILURE_CODE));break}default:{const s=so.sipErrorCause(i.status_code);this._registrationFailure(i,s)}}}});this._registering=!0,n.send()}unregister(e={}){if(!this._registered){np.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 n=new As.OutgoingRequest(ye.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},t);new mc(this._ua,n,{onRequestTimeout:()=>{this._unregistered(null,ye.causes.REQUEST_TIMEOUT)},onTransportError:()=>{this._unregistered(null,ye.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 a=so.sipErrorCause(s.status_code);this._unregistered(s,a)}}}}).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 ns=console,Cl={STATUS_INIT:0,STATUS_READY:1,STATUS_USER_CLOSED:2,STATUS_NOT_READY:3,CONFIGURATION_ERROR:1,NETWORK_ERROR:2},Aue=a8;class Rue extends Aue{constructor(e){super(e),this._msrp_sessions=[],this._transactions={nist:{},nict:{},ist:{},ict:{}},this._janus_sessions=[],this.newStreamPlugins=[],this.processStreamPlugins=[],this._registrator=new Iue(this)}call(e,t){return super.call(e,t)}joinVideoCall(e,t,n){ns.debug("call()");const i=new D0(this);return i.configureMedia({audio:!0,video:!0}),i.connect(e,t,n),i}startScreenShare(){ns.debug("startScreenShare()");for(const e in this._janus_sessions)this._janus_sessions[e].connectScreenShare()}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{eh.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=so.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+=" "+kt.USER_AGENT,this._configuration.user_agent=e.overrideUserAgent&&typeof e.overrideUserAgent=="function"?e.overrideUserAgent(t):t,this._configuration.jssip_id=so.createRandomToken(5);const n=this._configuration.uri.clone();n.user=null,this._configuration.hostport_params=n.toString().replace(/^sip:/i,"");try{this._transport=new OF(this._configuration.sockets,{max_interval:this._configuration.connection_recovery_max_interval,min_interval:this._configuration.connection_recovery_min_interval}),this._transport.onconnecting=Nue.bind(this),this._transport.onconnect=kue.bind(this),this._transport.ondisconnect=Oue.bind(this),this._transport.ondata=$ue.bind(this)}catch(s){throw ns.warn(s),new Xo.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 Zo("sip",so.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 a=s.anonymous||null,o=s.outbound||null;let u="<";return a?u+=this.temp_gruu||"sip:anonymous@anonymous.invalid;transport=ws":u+=this.pub_gruu||this.uri.toString(),o&&(a?!this.temp_gruu:!this.pub_gruu)&&(u+=";ob"),u+=">",u}};const i=["authorization_user","password","realm","ha1","authorization_jwt","display_name","register"];for(const s in this._configuration)Object.prototype.hasOwnProperty.call(this._configuration,s)&&(i.indexOf(s)!==-1?Object.defineProperty(this._configuration,s,{writable:!0,configurable:!1}):Object.defineProperty(this._configuration,s,{writable:!1,configurable:!1}));ns.debug("configuration parameters after validation:");for(const s in this._configuration)if(Object.prototype.hasOwnProperty.call(eh.settings,s))switch(s){case"uri":case"registrar_server":ns.debug(`- ${s}: ${this._configuration[s]}`);break;case"password":case"ha1":case"authorization_jwt":ns.debug(`- ${s}: NOT SHOWN`);break;default:ns.debug(`- ${s}: ${JSON.stringify(this._configuration[s])}`)}}newMSRPSession(e,t){e.on("msgHistoryUpdate",n=>{console.log(n)}),this._msrp_sessions[e.id]=e,this.emit("newMSRPSession",t)}newJanusSession(e,t){this._janus_sessions[e.id]=e,this.newStreamPlugins.forEach(n=>{n.setSession(e)}),this.processStreamPlugins.forEach(n=>{n.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,a,o,u;const t=e.method;if(console.log("-----------"),e.ruri.user!==this._configuration.uri.user&&e.ruri.user!==this._contact.uri.user){ns.debug("Request-URI does not point to us"),e.method!==kt.ACK&&e.reply_sl(404);return}if(e.ruri.scheme===kt.SIPS){e.reply_sl(416);return}if(_i.checkTransaction(this,e))return;if(t===kt.INVITE?new _i.InviteServerTransaction(this,this._transport,e):t!==kt.ACK&&t!==kt.CANCEL&&new _i.NonInviteServerTransaction(this,this._transport,e),t===kt.OPTIONS){if(this.listeners("newOptions").length===0){e.reply(200);return}new xC.Options(this).init_incoming(e)}else if(t===kt.MESSAGE){if(this.listeners("newMessage").length===0){e.reply(405);return}new xC.Message(this).init_incoming(e)}else if(t===kt.INVITE&&!e.to_tag&&this.listeners("newRTCSession").length===0){e.reply(405);return}let n,i;if(e.to_tag)if(n=this._findDialog(e.call_id,e.from_tag,e.to_tag),n)n.receiveRequest(e);else if(t===kt.NOTIFY)if(i=this._findSession(e),i)i.receiveRequest(e);else{if(e.body)try{const c=JSON.parse(e.body)||{};(a=(s=c.plugindata)==null?void 0:s.data)!=null&&a.publishers&&Object.values(this._janus_sessions)[0].receivePublishers(c),(u=(o=c.plugindata)==null?void 0:o.data)!=null&&u.unpublished&&Object.values(this._janus_sessions)[0].receiveUnpublished(c.plugindata.data.unpublished)}catch(c){console.error(c)}e.reply(200)}else t!==kt.ACK&&e.reply(481);else switch(t){case kt.INVITE:if(window.RTCPeerConnection)if(e.hasHeader("replaces")){const c=e.replaces;n=this._findDialog(c.call_id,c.from_tag,c.to_tag),n?(i=n.owner,i.isEnded()?e.reply(603):i.receiveRequest(e)):e.reply(481)}else e.body.search(/MSRP/ig)>-1?(i=new sw(this),i.init_incoming(e)):e.body.search(/JANUS/ig)>-1||(i=new gF(this),i.init_incoming(e));else ns.warn("INVITE received but WebRTC is not supported"),e.reply(488);break;case kt.BYE:e.reply(481);break;case kt.CANCEL:i=this._findSession(e),i?i.receiveRequest(e):ns.debug("received CANCEL request for a non existent session");break;case kt.ACK:break;case kt.NOTIFY:this.emit("sipEvent",{event:e.event,request:e}),e.reply(200);break;default:e.reply(405);break}}startMSRP(e,t){ns.debug("startMSRP()",t);const n=new sw(this);return n.connect(e),n}startJanus(e,t){ns.debug("startJanus()",t);const n=new sw(this);return n.connect(e),n}terminateMSRPSessions(e){ns.debug("terminateSessions()");for(const t in this._msrp_sessions)this._msrp_sessions[t].isEnded()||this._msrp_sessions[t].terminate(e)}terminateJanusSessions(e){ns.debug("terminateSessions()");for(const t in this._janus_sessions)this._janus_sessions[t].isEnded()||this._janus_sessions[t].terminate(e)}enableJanusAudio(e){ns.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){ns.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(ns.debug("stop()"),this._dynConfiguration={},this._status===Cl.STATUS_USER_CLOSED){ns.debug("UA already closed");return}this._registrator.close();const e=Object.keys(this._sessions).length;for(const n in this._sessions)if(Object.prototype.hasOwnProperty.call(this._sessions,n)){ns.debug(`closing session ${n}`);try{this._sessions[n].terminate()}catch(i){console.error(i)}}for(const n in this._msrp_sessions)if(Object.prototype.hasOwnProperty.call(this._msrp_sessions,n)){ns.debug(`closing session ${n}`);try{this._msrp_sessions[n].terminate()}catch(i){console.error(i)}}for(const n in this._janus_sessions)if(Object.prototype.hasOwnProperty.call(this._janus_sessions,n)){ns.debug(`closing session ${n}`);try{this._janus_sessions[n].terminate()}catch(i){console.error(i)}}for(const n in this._applicants)if(Object.prototype.hasOwnProperty.call(this._applicants,n))try{this._applicants[n].close()}catch(i){console.error(i)}this._status=Cl.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 Nue(r){this.emit("connecting",r)}function kue(r){this._status!==Cl.STATUS_USER_CLOSED&&(this._status=Cl.STATUS_READY,this._error=null,this.emit("connected",r),this._dynConfiguration.register&&this._registrator.register())}function Oue(r){const e=["nict","ict","nist","ist"];for(const t of e)for(const n in this._transactions[t])Object.prototype.hasOwnProperty.call(this._transactions[t],n)&&this._transactions[t][n].onTransportError();this.emit("disconnected",r),this._registrator.onTransportClosed(),this._status!==Cl.STATUS_USER_CLOSED&&(this._status=Cl.STATUS_NOT_READY,this._error=Cl.NETWORK_ERROR)}function $ue(r){console.log("onTransportData",r);const e=r.transport;let t=r.message;if(t=xue.parseMessage(t,this),!t){console.log("if 1 return");return}if(this._status===Cl.STATUS_USER_CLOSED&&t instanceof Zl.IncomingRequest){console.log("if 2 return");return}if(!qF(t,this,e)){console.log("if 3 return");return}if(console.log("onTransportData message",t),console.log("onTransportData instanceof",t instanceof Zl.IncomingRequest),t instanceof Zl.IncomingRequest)t.transport=e,console.log("onTransportData receiveRequest"),this.receiveRequest(t);else if(t instanceof Zl.IncomingResponse){let n;switch(t.method){case kt.INVITE:n=this._transactions.ict[t.via_branch],n&&n.receiveResponse(t);break;case kt.ACK:break;default:n=this._transactions.nict[t.via_branch],n&&n.receiveResponse(t);break}}}const Due=["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"],Pue=["_cancel_reason","_contact","direction","_end_time","_eventsCount","_from_tag","_id","_is_canceled","_is_confirmed","_late_sdp","status","start_time","_remote_identity","target_addr"];function YO(r){const e={};return Due.forEach(t=>{r[t]!==void 0&&(e[t]=r[t])}),e.localHold=r._localHold,e}function JO(r){const e={};return Pue.forEach(t=>{r[t]!==void 0&&(e[t]=r[t])}),e}function QO(r,e){const t=new AudioContext,n=t.createMediaStreamSource(r),i=t.createMediaStreamDestination(),s=t.createGain();return n.connect(s),s.connect(i),s.gain.value=e,i.stream}function Fue(r,e,t,n){const i=document.createElement("audio");i.id=e._id,i.className="audioTag",i.srcObject=r,ZO()||(i.setSinkId(t),i.volume=n),i.play(),e.audioTag=i}function Mue(r){if(r&&typeof r.log=="function"&&typeof r.warn=="function"&&typeof r.error=="function")return!0}function ZO(){return/Mobi|Android|iPhone/i.test(navigator.userAgent)}class M0 extends XO{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=Xt.cloneArray(e.extraHeaders),n={from_tag:this.session._from_tag};e.fromUserName&&(n.from_uri=new Zo("sip",e.fromUserName,this.session._ua.configuration.uri.host),t.push(`P-Preferred-Identity: ${this.session._ua.configuration.uri.toString()}`)),e.fromDisplayName&&(n.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 As.InitialOutgoingInviteRequest(this.session.target,this.session._ua,n,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 mc(this.session._ua,this._request,{onRequestTimeout:()=>{this.session.onRequestTimeout()},onTransportError:()=>{this.session.onTransportError()},onAuthenticated:s=>{this._request=s},onReceiveResponse:s=>{this._receiveInviteResponse(s)}});await this.generateStream(),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 n={janus:"attach",plugin:"janus.plugin.videoroom",opaque_id:this.opaqueId},i=JSON.stringify(n);this._request.body=i,e.send()}_receiveInviteResponse(e){if(this._publisherSubscribeSent||!e.body)return;const t=JSON.parse(e.body);this.handleId=t.data.id;const n={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},i=[this.session.getPTypeHeader(or.PUBLISHER)];this.session.sendRequest(ye.SUBSCRIBE,{extraHeaders:i,body:JSON.stringify(n),eventHandlers:{onSuccessResponse:async s=>{var a,o,u,c;if(s.status_code===200){if(this._subscribeSent=!0,s.body)try{const d=JSON.parse(s.body)||{};((o=(a=d.plugindata)==null?void 0:a.data)==null?void 0:o.videoroom)==="joined"&&this.session.myFeedList.push(d.plugindata.data.id),(c=(u=d.plugindata)==null?void 0:u.data)!=null&&c.publishers&&this.session.receivePublishers(d)}catch(d){console.error(d)}this._lastTrickleReceived&&!this._configureSent&&this._sendConfigureMessage({audio:!0,video:!0})}}}}),this._publisherSubscribeSent=!0}async _sendConfigureMessage(e){const t=this._candidates.map(a=>({janus:"trickle",candidate:a,handle_id:this.handleId,session_id:this.session.session_id})),i={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(or.ICE)];this.session.sendRequest(ye.INFO,{extraHeaders:s,body:JSON.stringify(i),eventHandlers:{onSuccessResponse:async a=>{this._configureSent=!0;const u=a.data.split(`\r
18358
18358
  `),c=u[u.length-1],d=JSON.parse(c);await this._connection.setRemoteDescription(d.jsep),this._candidates=[]}}})}_sendDetach(){const e={janus:"detach",handle_id:this.handleId,session_id:this.session.session_id},t=[this.session.getPTypeHeader(or.DETACH)];this.session.sendRequest(ye.INFO,{extraHeaders:t,body:JSON.stringify(e)}),this.session._ua.emit("pluginDetach",this.name)}async stopMedia(){this._connection&&(this._connection.close(),this._connection=null)}async stop(){await this.session.stopProcessPlugins(this.type);const e=this._connection.getSenders();e.forEach(t=>{const n=t.track;n&&n.stop()}),e.forEach(t=>{this._connection.removeTrack(t)}),await this.stopMedia(),this._sendDetach()}async generateStream(){throw new Error("generateStream method is not implemented")}}class Lue extends M0{constructor(){super("ScreenShare","screen")}async generateStream(){try{this.stream=await navigator.mediaDevices.getDisplayMedia(),this.stream.getVideoTracks()[0].onended=()=>{this.stopMedia()},this.session._ua.emit("startScreenShare",{stream:this.stream})}catch(e){await this.stopMedia(),console.error(e)}return this.stream}async kill(){await this.stop(),this.session._ua.emit("stopScreenShare")}}var iw={exports:{}},L0={},e$={},$t={};(function(r){Object.defineProperty(r,"__esModule",{value:!0}),r._registerNode=r.Konva=r.glob=void 0;const e=Math.PI/180;function t(){return typeof window<"u"&&({}.toString.call(window)==="[object Window]"||{}.toString.call(window)==="[object global]")}r.glob=typeof Qn<"u"?Qn:typeof window<"u"?window:typeof WorkerGlobalScope<"u"?self:{},r.Konva={_global:r.glob,version:"9.3.16",isBrowser:t(),isUnminified:/param/.test((function(i){}).toString()),dblClickWindow:400,getAngle(i){return r.Konva.angleDeg?i*e:i},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 r.Konva.DD.isDragging},isTransforming(){var i;return(i=r.Konva.Transformer)===null||i===void 0?void 0:i.isTransforming()},isDragReady(){return!!r.Konva.DD.node},releaseCanvasOnDestroy:!0,document:r.glob.document,_injectGlobal(i){r.glob.Konva=i}};const n=i=>{r.Konva[i.prototype.getClassName()]=i};r._registerNode=n,r.Konva._injectGlobal(r.Konva)})($t);var Un={};(function(r){Object.defineProperty(r,"__esModule",{value:!0}),r.Util=r.Transform=void 0;const e=$t;class t{constructor(I=[1,0,0,1,0,0]){this.dirty=!1,this.m=I&&I.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(I){I.m[0]=this.m[0],I.m[1]=this.m[1],I.m[2]=this.m[2],I.m[3]=this.m[3],I.m[4]=this.m[4],I.m[5]=this.m[5]}point(I){const R=this.m;return{x:R[0]*I.x+R[2]*I.y+R[4],y:R[1]*I.x+R[3]*I.y+R[5]}}translate(I,R){return this.m[4]+=this.m[0]*I+this.m[2]*R,this.m[5]+=this.m[1]*I+this.m[3]*R,this}scale(I,R){return this.m[0]*=I,this.m[1]*=I,this.m[2]*=R,this.m[3]*=R,this}rotate(I){const R=Math.cos(I),P=Math.sin(I),B=this.m[0]*R+this.m[2]*P,O=this.m[1]*R+this.m[3]*P,F=this.m[0]*-P+this.m[2]*R,D=this.m[1]*-P+this.m[3]*R;return this.m[0]=B,this.m[1]=O,this.m[2]=F,this.m[3]=D,this}getTranslation(){return{x:this.m[4],y:this.m[5]}}skew(I,R){const P=this.m[0]+this.m[2]*R,B=this.m[1]+this.m[3]*R,O=this.m[2]+this.m[0]*I,F=this.m[3]+this.m[1]*I;return this.m[0]=P,this.m[1]=B,this.m[2]=O,this.m[3]=F,this}multiply(I){const R=this.m[0]*I.m[0]+this.m[2]*I.m[1],P=this.m[1]*I.m[0]+this.m[3]*I.m[1],B=this.m[0]*I.m[2]+this.m[2]*I.m[3],O=this.m[1]*I.m[2]+this.m[3]*I.m[3],F=this.m[0]*I.m[4]+this.m[2]*I.m[5]+this.m[4],D=this.m[1]*I.m[4]+this.m[3]*I.m[5]+this.m[5];return this.m[0]=R,this.m[1]=P,this.m[2]=B,this.m[3]=O,this.m[4]=F,this.m[5]=D,this}invert(){const I=1/(this.m[0]*this.m[3]-this.m[1]*this.m[2]),R=this.m[3]*I,P=-this.m[1]*I,B=-this.m[2]*I,O=this.m[0]*I,F=I*(this.m[2]*this.m[5]-this.m[3]*this.m[4]),D=I*(this.m[1]*this.m[4]-this.m[0]*this.m[5]);return this.m[0]=R,this.m[1]=P,this.m[2]=B,this.m[3]=O,this.m[4]=F,this.m[5]=D,this}getMatrix(){return this.m}decompose(){const I=this.m[0],R=this.m[1],P=this.m[2],B=this.m[3],O=this.m[4],F=this.m[5],D=I*B-R*P,L={x:O,y:F,rotation:0,scaleX:0,scaleY:0,skewX:0,skewY:0};if(I!=0||R!=0){const G=Math.sqrt(I*I+R*R);L.rotation=R>0?Math.acos(I/G):-Math.acos(I/G),L.scaleX=G,L.scaleY=D/G,L.skewX=(I*P+R*B)/D,L.skewY=0}else if(P!=0||B!=0){const G=Math.sqrt(P*P+B*B);L.rotation=Math.PI/2-(B>0?Math.acos(-P/G):-Math.acos(P/G)),L.scaleX=D/G,L.scaleY=G,L.skewX=0,L.skewY=(I*P+R*B)/D}return L.rotation=r.Util._getRotation(L.rotation),L}}r.Transform=t;let n="[object Array]",i="[object Number]",s="[object String]",a="[object Boolean]",o=Math.PI/180,u=180/Math.PI,c="#",d="",p="0",m="Konva warning: ",_="Konva error: ",y="rgb(",b={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]},S=/rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)/,w=[];const x=typeof requestAnimationFrame<"u"&&requestAnimationFrame||function(E){setTimeout(E,60)};r.Util={_isElement(E){return!!(E&&E.nodeType==1)},_isFunction(E){return!!(E&&E.constructor&&E.call&&E.apply)},_isPlainObject(E){return!!E&&E.constructor===Object},_isArray(E){return Object.prototype.toString.call(E)===n},_isNumber(E){return Object.prototype.toString.call(E)===i&&!isNaN(E)&&isFinite(E)},_isString(E){return Object.prototype.toString.call(E)===s},_isBoolean(E){return Object.prototype.toString.call(E)===a},isObject(E){return E instanceof Object},isValidSelector(E){if(typeof E!="string")return!1;const I=E[0];return I==="#"||I==="."||I===I.toUpperCase()},_sign(E){return E===0||E>0?1:-1},requestAnimFrame(E){w.push(E),w.length===1&&x(function(){const I=w;w=[],I.forEach(function(R){R()})})},createCanvasElement(){const E=document.createElement("canvas");try{E.style=E.style||{}}catch{}return E},createImageElement(){return document.createElement("img")},_isInDocument(E){for(;E=E.parentNode;)if(E==document)return!0;return!1},_urlToImage(E,I){const R=r.Util.createImageElement();R.onload=function(){I(R)},R.src=E},_rgbToHex(E,I,R){return(16777216+(E<<16)+(I<<8)+R).toString(16).slice(1)},_hexToRgb(E){E=E.replace(c,d);const I=parseInt(E,16);return{r:I>>16&255,g:I>>8&255,b:I&255}},getRandomColor(){let E=(Math.random()*16777215<<0).toString(16);for(;E.length<6;)E=p+E;return c+E},getRGB(E){let I;return E in b?(I=b[E],{r:I[0],g:I[1],b:I[2]}):E[0]===c?this._hexToRgb(E.substring(1)):E.substr(0,4)===y?(I=S.exec(E.replace(/ /g,"")),{r:parseInt(I[1],10),g:parseInt(I[2],10),b:parseInt(I[3],10)}):{r:0,g:0,b:0}},colorToRGBA(E){return E=E||"black",r.Util._namedColorToRBA(E)||r.Util._hex3ColorToRGBA(E)||r.Util._hex4ColorToRGBA(E)||r.Util._hex6ColorToRGBA(E)||r.Util._hex8ColorToRGBA(E)||r.Util._rgbColorToRGBA(E)||r.Util._rgbaColorToRGBA(E)||r.Util._hslColorToRGBA(E)},_namedColorToRBA(E){const I=b[E.toLowerCase()];return I?{r:I[0],g:I[1],b:I[2],a:1}:null},_rgbColorToRGBA(E){if(E.indexOf("rgb(")===0){E=E.match(/rgb\(([^)]+)\)/)[1];const I=E.split(/ *, */).map(Number);return{r:I[0],g:I[1],b:I[2],a:1}}},_rgbaColorToRGBA(E){if(E.indexOf("rgba(")===0){E=E.match(/rgba\(([^)]+)\)/)[1];const I=E.split(/ *, */).map((R,P)=>R.slice(-1)==="%"?P===3?parseInt(R)/100:parseInt(R)/100*255:Number(R));return{r:I[0],g:I[1],b:I[2],a:I[3]}}},_hex8ColorToRGBA(E){if(E[0]==="#"&&E.length===9)return{r:parseInt(E.slice(1,3),16),g:parseInt(E.slice(3,5),16),b:parseInt(E.slice(5,7),16),a:parseInt(E.slice(7,9),16)/255}},_hex6ColorToRGBA(E){if(E[0]==="#"&&E.length===7)return{r:parseInt(E.slice(1,3),16),g:parseInt(E.slice(3,5),16),b:parseInt(E.slice(5,7),16),a:1}},_hex4ColorToRGBA(E){if(E[0]==="#"&&E.length===5)return{r:parseInt(E[1]+E[1],16),g:parseInt(E[2]+E[2],16),b:parseInt(E[3]+E[3],16),a:parseInt(E[4]+E[4],16)/255}},_hex3ColorToRGBA(E){if(E[0]==="#"&&E.length===4)return{r:parseInt(E[1]+E[1],16),g:parseInt(E[2]+E[2],16),b:parseInt(E[3]+E[3],16),a:1}},_hslColorToRGBA(E){if(/hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)/g.test(E)){const[I,...R]=/hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)/g.exec(E),P=Number(R[0])/360,B=Number(R[1])/100,O=Number(R[2])/100;let F,D,L;if(B===0)return L=O*255,{r:Math.round(L),g:Math.round(L),b:Math.round(L),a:1};O<.5?F=O*(1+B):F=O+B-O*B;const G=2*O-F,j=[0,0,0];for(let te=0;te<3;te++)D=P+.3333333333333333*-(te-1),D<0&&D++,D>1&&D--,6*D<1?L=G+(F-G)*6*D:2*D<1?L=F:3*D<2?L=G+(F-G)*(.6666666666666666-D)*6:L=G,j[te]=L*255;return{r:Math.round(j[0]),g:Math.round(j[1]),b:Math.round(j[2]),a:1}}},haveIntersection(E,I){return!(I.x>E.x+E.width||I.x+I.width<E.x||I.y>E.y+E.height||I.y+I.height<E.y)},cloneObject(E){const I={};for(const R in E)this._isPlainObject(E[R])?I[R]=this.cloneObject(E[R]):this._isArray(E[R])?I[R]=this.cloneArray(E[R]):I[R]=E[R];return I},cloneArray(E){return E.slice(0)},degToRad(E){return E*o},radToDeg(E){return E*u},_degToRad(E){return r.Util.warn("Util._degToRad is removed. Please use public Util.degToRad instead."),r.Util.degToRad(E)},_radToDeg(E){return r.Util.warn("Util._radToDeg is removed. Please use public Util.radToDeg instead."),r.Util.radToDeg(E)},_getRotation(E){return e.Konva.angleDeg?r.Util.radToDeg(E):E},_capitalize(E){return E.charAt(0).toUpperCase()+E.slice(1)},throw(E){throw new Error(_+E)},error(E){console.error(_+E)},warn(E){e.Konva.showWarnings&&console.warn(m+E)},each(E,I){for(const R in E)I(R,E[R])},_inRange(E,I,R){return I<=E&&E<R},_getProjectionToSegment(E,I,R,P,B,O){let F,D,L;const G=(E-R)*(E-R)+(I-P)*(I-P);if(G==0)F=E,D=I,L=(B-R)*(B-R)+(O-P)*(O-P);else{const j=((B-E)*(R-E)+(O-I)*(P-I))/G;j<0?(F=E,D=I,L=(E-B)*(E-B)+(I-O)*(I-O)):j>1?(F=R,D=P,L=(R-B)*(R-B)+(P-O)*(P-O)):(F=E+j*(R-E),D=I+j*(P-I),L=(F-B)*(F-B)+(D-O)*(D-O))}return[F,D,L]},_getProjectionToLine(E,I,R){const P=r.Util.cloneObject(E);let B=Number.MAX_VALUE;return I.forEach(function(O,F){if(!R&&F===I.length-1)return;const D=I[(F+1)%I.length],L=r.Util._getProjectionToSegment(O.x,O.y,D.x,D.y,E.x,E.y),G=L[0],j=L[1],te=L[2];te<B&&(P.x=G,P.y=j,B=te)}),P},_prepareArrayForTween(E,I,R){let P,B=[],O=[];if(E.length>I.length){const D=I;I=E,E=D}for(P=0;P<E.length;P+=2)B.push({x:E[P],y:E[P+1]});for(P=0;P<I.length;P+=2)O.push({x:I[P],y:I[P+1]});const F=[];return O.forEach(function(D){const L=r.Util._getProjectionToLine(D,B,R);F.push(L.x),F.push(L.y)}),F},_prepareToStringify(E){let I;E.visitedByCircularReferenceRemoval=!0;for(const R in E)if(E.hasOwnProperty(R)&&E[R]&&typeof E[R]=="object"){if(I=Object.getOwnPropertyDescriptor(E,R),E[R].visitedByCircularReferenceRemoval||r.Util._isElement(E[R]))if(I.configurable)delete E[R];else return null;else if(r.Util._prepareToStringify(E[R])===null)if(I.configurable)delete E[R];else return null}return delete E.visitedByCircularReferenceRemoval,E},_assign(E,I){for(const R in I)E[R]=I[R];return E},_getFirstPointerId(E){return E.touches?E.changedTouches[0].identifier:E.pointerId||999},releaseCanvas(...E){e.Konva.releaseCanvasOnDestroy&&E.forEach(I=>{I.width=0,I.height=0})},drawRoundedRectPath(E,I,R,P){let B=0,O=0,F=0,D=0;typeof P=="number"?B=O=F=D=Math.min(P,I/2,R/2):(B=Math.min(P[0]||0,I/2,R/2),O=Math.min(P[1]||0,I/2,R/2),D=Math.min(P[2]||0,I/2,R/2),F=Math.min(P[3]||0,I/2,R/2)),E.moveTo(B,0),E.lineTo(I-O,0),E.arc(I-O,O,O,Math.PI*3/2,0,!1),E.lineTo(I,R-D),E.arc(I-D,R-D,D,0,Math.PI/2,!1),E.lineTo(F,R),E.arc(F,R-F,F,Math.PI/2,Math.PI,!1),E.lineTo(0,B),E.arc(B,B,B,Math.PI,Math.PI*3/2,!1)}}})(Un);var Mn={},Dt={},Ct={};Object.defineProperty(Ct,"__esModule",{value:!0}),Ct.RGBComponent=Uue,Ct.alphaComponent=Bue,Ct.getNumberValidator=Hue,Ct.getNumberOrArrayOfNumbersValidator=Vue,Ct.getNumberOrAutoValidator=Gue,Ct.getStringValidator=Wue,Ct.getStringOrGradientValidator=zue,Ct.getFunctionValidator=jue,Ct.getNumberArrayValidator=que,Ct.getBooleanValidator=Kue,Ct.getComponentValidator=Xue;const So=$t,Wn=Un;function To(r){return Wn.Util._isString(r)?'"'+r+'"':Object.prototype.toString.call(r)==="[object Number]"||Wn.Util._isBoolean(r)?r:Object.prototype.toString.call(r)}function Uue(r){return r>255?255:r<0?0:Math.round(r)}function Bue(r){return r>1?1:r<1e-4?1e-4:r}function Hue(){if(So.Konva.isUnminified)return function(r,e){return Wn.Util._isNumber(r)||Wn.Util.warn(To(r)+' is a not valid value for "'+e+'" attribute. The value should be a number.'),r}}function Vue(r){if(So.Konva.isUnminified)return function(e,t){const n=Wn.Util._isNumber(e),i=Wn.Util._isArray(e)&&e.length==r;return!n&&!i&&Wn.Util.warn(To(e)+' is a not valid value for "'+t+'" attribute. The value should be a number or Array<number>('+r+")"),e}}function Gue(){if(So.Konva.isUnminified)return function(r,e){return Wn.Util._isNumber(r)||r==="auto"||Wn.Util.warn(To(r)+' is a not valid value for "'+e+'" attribute. The value should be a number or "auto".'),r}}function Wue(){if(So.Konva.isUnminified)return function(r,e){return Wn.Util._isString(r)||Wn.Util.warn(To(r)+' is a not valid value for "'+e+'" attribute. The value should be a string.'),r}}function zue(){if(So.Konva.isUnminified)return function(r,e){const t=Wn.Util._isString(r),n=Object.prototype.toString.call(r)==="[object CanvasGradient]"||r&&r.addColorStop;return t||n||Wn.Util.warn(To(r)+' is a not valid value for "'+e+'" attribute. The value should be a string or a native gradient.'),r}}function jue(){if(So.Konva.isUnminified)return function(r,e){return Wn.Util._isFunction(r)||Wn.Util.warn(To(r)+' is a not valid value for "'+e+'" attribute. The value should be a function.'),r}}function que(){if(So.Konva.isUnminified)return function(r,e){const t=Int8Array?Object.getPrototypeOf(Int8Array):null;return t&&r instanceof t||(Wn.Util._isArray(r)?r.forEach(function(n){Wn.Util._isNumber(n)||Wn.Util.warn('"'+e+'" attribute has non numeric element '+n+". Make sure that all elements are numbers.")}):Wn.Util.warn(To(r)+' is a not valid value for "'+e+'" attribute. The value should be a array of numbers.')),r}}function Kue(){if(So.Konva.isUnminified)return function(r,e){return r===!0||r===!1||Wn.Util.warn(To(r)+' is a not valid value for "'+e+'" attribute. The value should be a boolean.'),r}}function Xue(r){if(So.Konva.isUnminified)return function(e,t){return e==null||Wn.Util.isObject(e)||Wn.Util.warn(To(e)+' is a not valid value for "'+t+'" attribute. The value should be an object with properties '+r),e}}(function(r){Object.defineProperty(r,"__esModule",{value:!0}),r.Factory=void 0;const e=Un,t=Ct,n="get",i="set";r.Factory={addGetterSetter(s,a,o,u,c){r.Factory.addGetter(s,a,o),r.Factory.addSetter(s,a,u,c),r.Factory.addOverloadedGetterSetter(s,a)},addGetter(s,a,o){const u=n+e.Util._capitalize(a);s.prototype[u]=s.prototype[u]||function(){const c=this.attrs[a];return c===void 0?o:c}},addSetter(s,a,o,u){const c=i+e.Util._capitalize(a);s.prototype[c]||r.Factory.overWriteSetter(s,a,o,u)},overWriteSetter(s,a,o,u){const c=i+e.Util._capitalize(a);s.prototype[c]=function(d){return o&&d!==void 0&&d!==null&&(d=o.call(this,d,a)),this._setAttr(a,d),u&&u.call(this),this}},addComponentsGetterSetter(s,a,o,u,c){let d=o.length,p=e.Util._capitalize,m=n+p(a),_=i+p(a),y,b;s.prototype[m]=function(){const w={};for(y=0;y<d;y++)b=o[y],w[b]=this.getAttr(a+p(b));return w};const S=(0,t.getComponentValidator)(o);s.prototype[_]=function(w){let x=this.attrs[a],E;u&&(w=u.call(this,w)),S&&S.call(this,w,a);for(E in w)w.hasOwnProperty(E)&&this._setAttr(a+p(E),w[E]);return w||o.forEach(I=>{this._setAttr(a+p(I),void 0)}),this._fireChangeEvent(a,x,w),c&&c.call(this),this},r.Factory.addOverloadedGetterSetter(s,a)},addOverloadedGetterSetter(s,a){const o=e.Util._capitalize(a),u=i+o,c=n+o;s.prototype[a]=function(){return arguments.length?(this[u](arguments[0]),this):this[c]()}},addDeprecatedGetterSetter(s,a,o,u){e.Util.error("Adding deprecated "+a);const c=n+e.Util._capitalize(a),d=a+" property is deprecated and will be removed soon. Look at Konva change log for more information.";s.prototype[c]=function(){e.Util.error(d);const p=this.attrs[a];return p===void 0?o:p},r.Factory.addSetter(s,a,u,function(){e.Util.error(d)}),r.Factory.addOverloadedGetterSetter(s,a)},backCompat(s,a){e.Util.each(a,function(o,u){const c=s.prototype[u],d=n+e.Util._capitalize(o),p=i+e.Util._capitalize(o);function m(){c.apply(this,arguments),e.Util.error('"'+o+'" method is deprecated and will be removed soon. Use ""'+u+'" instead.')}s.prototype[o]=m,s.prototype[d]=m,s.prototype[p]=m})},afterSetFilter(){this._filterUpToDate=!1}}})(Dt);var ia={},wo={};Object.defineProperty(wo,"__esModule",{value:!0}),wo.HitContext=wo.SceneContext=wo.Context=void 0;const t$=Un,Yue=$t;function Jue(r){let e=[],t=r.length,n=t$.Util,i,s;for(i=0;i<t;i++)s=r[i],n._isNumber(s)?s=Math.round(s*1e3)/1e3:n._isString(s)||(s=s+""),e.push(s);return e}const n$=",",Que="(",Zue=")",ece="([",tce="])",nce=";",sce="()",rce="=",s$=["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"],ice=["fillStyle","strokeStyle","shadowColor","shadowBlur","shadowOffsetX","shadowOffsetY","letterSpacing","lineCap","lineDashOffset","lineJoin","lineWidth","miterLimit","direction","font","textAlign","textBaseline","globalAlpha","globalCompositeOperation","imageSmoothingEnabled"],ace=100;class U0{constructor(e){this.canvas=e,Yue.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 n=this.traceArr,i=n.length,s="",a,o,u,c;for(a=0;a<i;a++)o=n[a],u=o.method,u?(c=o.args,s+=u,e?s+=sce:t$.Util._isArray(c[0])?s+=ece+c.join(n$)+tce:(t&&(c=c.map(d=>typeof d=="number"?Math.floor(d):d)),s+=Que+c.join(n$)+Zue)):(s+=o.property,e||(s+=rce+o.val)),s+=nce;return s}clearTrace(){this.traceArr=[]}_trace(e){let t=this.traceArr,n;t.push(e),n=t.length,n>=ace&&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,n,i,s,a){this._context.arc(e,t,n,i,s,a)}arcTo(e,t,n,i,s){this._context.arcTo(e,t,n,i,s)}beginPath(){this._context.beginPath()}bezierCurveTo(e,t,n,i,s,a){this._context.bezierCurveTo(e,t,n,i,s,a)}clearRect(e,t,n,i){this._context.clearRect(e,t,n,i)}clip(...e){this._context.clip.apply(this._context,e)}closePath(){this._context.closePath()}createImageData(e,t){const n=arguments;if(n.length===2)return this._context.createImageData(e,t);if(n.length===1)return this._context.createImageData(e)}createLinearGradient(e,t,n,i){return this._context.createLinearGradient(e,t,n,i)}createPattern(e,t){return this._context.createPattern(e,t)}createRadialGradient(e,t,n,i,s,a){return this._context.createRadialGradient(e,t,n,i,s,a)}drawImage(e,t,n,i,s,a,o,u,c){const d=arguments,p=this._context;d.length===3?p.drawImage(e,t,n):d.length===5?p.drawImage(e,t,n,i,s):d.length===9&&p.drawImage(e,t,n,i,s,a,o,u,c)}ellipse(e,t,n,i,s,a,o,u){this._context.ellipse(e,t,n,i,s,a,o,u)}isPointInPath(e,t,n,i){return n?this._context.isPointInPath(n,e,t,i):this._context.isPointInPath(e,t,i)}fill(...e){this._context.fill.apply(this._context,e)}fillRect(e,t,n,i){this._context.fillRect(e,t,n,i)}strokeRect(e,t,n,i){this._context.strokeRect(e,t,n,i)}fillText(e,t,n,i){i?this._context.fillText(e,t,n,i):this._context.fillText(e,t,n)}measureText(e){return this._context.measureText(e)}getImageData(e,t,n,i){return this._context.getImageData(e,t,n,i)}lineTo(e,t){this._context.lineTo(e,t)}moveTo(e,t){this._context.moveTo(e,t)}rect(e,t,n,i){this._context.rect(e,t,n,i)}roundRect(e,t,n,i,s){this._context.roundRect(e,t,n,i,s)}putImageData(e,t,n){this._context.putImageData(e,t,n)}quadraticCurveTo(e,t,n,i){this._context.quadraticCurveTo(e,t,n,i)}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,n,i,s,a){this._context.setTransform(e,t,n,i,s,a)}stroke(e){e?this._context.stroke(e):this._context.stroke()}strokeText(e,t,n,i){this._context.strokeText(e,t,n,i)}transform(e,t,n,i,s,a){this._context.transform(e,t,n,i,s,a)}translate(e,t){this._context.translate(e,t)}_enableTrace(){let e=this,t=s$.length,n=this.setAttr,i,s;const a=function(o){let u=e[o],c;e[o]=function(){return s=Jue(Array.prototype.slice.call(arguments,0)),c=u.apply(e,arguments),e._trace({method:o,args:s}),c}};for(i=0;i<t;i++)a(s$[i]);e.setAttr=function(){n.apply(e,arguments);const o=arguments[0];let u=arguments[1];(o==="shadowOffsetX"||o==="shadowOffsetY"||o==="shadowBlur")&&(u=u/this.canvas.getPixelRatio()),e._trace({property:o,val:u})}}_applyGlobalCompositeOperation(e){const t=e.attrs.globalCompositeOperation;!t||t==="source-over"||this.setAttr("globalCompositeOperation",t)}}wo.Context=U0,ice.forEach(function(r){Object.defineProperty(U0.prototype,r,{get(){return this._context[r]},set(e){this._context[r]=e}})});class oce extends U0{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(),n=e.getFillPriority();if(t&&n==="color"){this._fillColor(e);return}const i=e.getFillPatternImage();if(i&&n==="pattern"){this._fillPattern(e);return}const s=e.getFillLinearGradientColorStops();if(s&&n==="linear-gradient"){this._fillLinearGradient(e);return}const a=e.getFillRadialGradientColorStops();if(a&&n==="radial-gradient"){this._fillRadialGradient(e);return}t?this._fillColor(e):i?this._fillPattern(e):s?this._fillLinearGradient(e):a&&this._fillRadialGradient(e)}_strokeLinearGradient(e){const t=e.getStrokeLinearGradientStartPoint(),n=e.getStrokeLinearGradientEndPoint(),i=e.getStrokeLinearGradientColorStops(),s=this.createLinearGradient(t.x,t.y,n.x,n.y);if(i){for(let a=0;a<i.length;a+=2)s.addColorStop(i[a],i[a+1]);this.setAttr("strokeStyle",s)}}_stroke(e){const t=e.dash(),n=e.getStrokeScaleEnabled();if(e.hasStroke()){if(!n){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),n||this.restore()}}_applyShadow(e){var t,n,i;const s=(t=e.getShadowRGBA())!==null&&t!==void 0?t:"black",a=(n=e.getShadowBlur())!==null&&n!==void 0?n:5,o=(i=e.getShadowOffset())!==null&&i!==void 0?i:{x:0,y:0},u=e.getAbsoluteScale(),c=this.canvas.getPixelRatio(),d=u.x*c,p=u.y*c;this.setAttr("shadowColor",s),this.setAttr("shadowBlur",a*Math.min(Math.abs(d),Math.abs(p))),this.setAttr("shadowOffsetX",o.x*d),this.setAttr("shadowOffsetY",o.y*p)}}wo.SceneContext=oce;class lce extends U0{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 n=e.hitStrokeWidth(),i=n==="auto"?e.strokeWidth():n;this.setAttr("lineWidth",i),this.setAttr("strokeStyle",e.colorKey),e._strokeFuncHit(this),t||this.restore()}}}wo.HitContext=lce,Object.defineProperty(ia,"__esModule",{value:!0}),ia.HitCanvas=ia.SceneCanvas=ia.Canvas=void 0;const B0=Un,r$=wo,i$=$t,uce=Dt,cce=Ct;let H0;function dce(){if(H0)return H0;const r=B0.Util.createCanvasElement(),e=r.getContext("2d");return H0=function(){const t=i$.Konva._global.devicePixelRatio||1,n=e.webkitBackingStorePixelRatio||e.mozBackingStorePixelRatio||e.msBackingStorePixelRatio||e.oBackingStorePixelRatio||e.backingStorePixelRatio||1;return t/n}(),B0.Util.releaseCanvas(r),H0}class V0{constructor(e){this.pixelRatio=1,this.width=0,this.height=0,this.isCache=!1;const n=(e||{}).pixelRatio||i$.Konva.pixelRatio||dce();this.pixelRatio=n,this._canvas=B0.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(i){return B0.Util.error("Unable to get data URL. "+i.message+" For more info read https://konvajs.org/docs/posts/Tainted_Canvas.html."),""}}}}ia.Canvas=V0,uce.Factory.addGetterSetter(V0,"pixelRatio",void 0,(0,cce.getNumberValidator)());class hce extends V0{constructor(e={width:0,height:0,willReadFrequently:!1}){super(e),this.context=new r$.SceneContext(this,{willReadFrequently:e.willReadFrequently}),this.setSize(e.width,e.height)}}ia.SceneCanvas=hce;class fce extends V0{constructor(e={width:0,height:0}){super(e),this.hitCanvas=!0,this.context=new r$.HitContext(this),this.setSize(e.width,e.height)}}ia.HitCanvas=fce;var G0={};(function(r){Object.defineProperty(r,"__esModule",{value:!0}),r.DD=void 0;const e=$t,t=Un;r.DD={get isDragging(){let n=!1;return r.DD._dragElements.forEach(i=>{i.dragStatus==="dragging"&&(n=!0)}),n},justDragged:!1,get node(){let n;return r.DD._dragElements.forEach(i=>{n=i.node}),n},_dragElements:new Map,_drag(n){const i=[];r.DD._dragElements.forEach((s,a)=>{const{node:o}=s,u=o.getStage();u.setPointersPositions(n),s.pointerId===void 0&&(s.pointerId=t.Util._getFirstPointerId(n));const c=u._changedPointerPositions.find(d=>d.id===s.pointerId);if(c){if(s.dragStatus!=="dragging"){const d=o.dragDistance();if(Math.max(Math.abs(c.x-s.startPointerPos.x),Math.abs(c.y-s.startPointerPos.y))<d||(o.startDrag({evt:n}),!o.isDragging()))return}o._setDragPosition(n,s),i.push(o)}}),i.forEach(s=>{s.fire("dragmove",{type:"dragmove",target:s,evt:n},!0)})},_endDragBefore(n){const i=[];r.DD._dragElements.forEach(s=>{const{node:a}=s,o=a.getStage();if(n&&o.setPointersPositions(n),!o._changedPointerPositions.find(d=>d.id===s.pointerId))return;(s.dragStatus==="dragging"||s.dragStatus==="stopped")&&(r.DD.justDragged=!0,e.Konva._mouseListenClick=!1,e.Konva._touchListenClick=!1,e.Konva._pointerListenClick=!1,s.dragStatus="stopped");const c=s.node.getLayer()||s.node instanceof e.Konva.Stage&&s.node;c&&i.indexOf(c)===-1&&i.push(c)}),i.forEach(s=>{s.draw()})},_endDragAfter(n){r.DD._dragElements.forEach((i,s)=>{i.dragStatus==="stopped"&&i.node.fire("dragend",{type:"dragend",target:i.node,evt:n},!0),i.dragStatus!=="dragging"&&r.DD._dragElements.delete(s)})}},e.Konva.isBrowser&&(window.addEventListener("mouseup",r.DD._endDragBefore,!0),window.addEventListener("touchend",r.DD._endDragBefore,!0),window.addEventListener("touchcancel",r.DD._endDragBefore,!0),window.addEventListener("mousemove",r.DD._drag),window.addEventListener("touchmove",r.DD._drag),window.addEventListener("mouseup",r.DD._endDragAfter,!1),window.addEventListener("touchend",r.DD._endDragAfter,!1),window.addEventListener("touchcancel",r.DD._endDragAfter,!1))})(G0),Object.defineProperty(Mn,"__esModule",{value:!0}),Mn.Node=void 0;const Vt=Un,sp=Dt,rp=ia,El=$t,Oi=G0,ss=Ct,W0="absoluteOpacity",z0="allEventListeners",Co="absoluteTransform",a$="absoluteScale",Hu="canvas",pce="Change",mce="children",gce="konva",aw="listening",o$="mouseenter",l$="mouseleave",u$="set",c$="Shape",j0=" ",d$="stage",xl="transform",_ce="Stage",ow="visible",yce=["xChange.konva","yChange.konva","scaleXChange.konva","scaleYChange.konva","skewXChange.konva","skewYChange.konva","rotationChange.konva","offsetXChange.konva","offsetYChange.konva","transformsEnabledChange.konva"].join(j0);let vce=1;class Et{constructor(e){this._id=vce++,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===xl||e===Co)&&this._cache.get(e)?this._cache.get(e).dirty=!0:e?this._cache.delete(e):this._cache.clear()}_getCache(e,t){let n=this._cache.get(e);return(n===void 0||(e===xl||e===Co)&&n.dirty===!0)&&(n=t.call(this),this._cache.set(e,n)),n}_calculate(e,t,n){if(!this._attachedDepsListeners.get(e)){const i=t.map(s=>s+"Change.konva").join(j0);this.on(i,()=>{this._clearCache(e)}),this._attachedDepsListeners.set(e,!0)}return this._getCache(e,n)}_getCanvasCache(){return this._cache.get(Hu)}_clearSelfAndDescendantCache(e){this._clearCache(e),e===Co&&this.fire("absoluteTransformChange")}clearCache(){if(this._cache.has(Hu)){const{scene:e,filter:t,hit:n}=this._cache.get(Hu);Vt.Util.releaseCanvas(e,t,n),this._cache.delete(Hu)}return this._clearSelfAndDescendantCache(),this._requestDraw(),this}cache(e){const t=e||{};let n={};(t.x===void 0||t.y===void 0||t.width===void 0||t.height===void 0)&&(n=this.getClientRect({skipTransform:!0,relativeTo:this.getParent()||void 0}));let i=Math.ceil(t.width||n.width),s=Math.ceil(t.height||n.height),a=t.pixelRatio,o=t.x===void 0?Math.floor(n.x):t.x,u=t.y===void 0?Math.floor(n.y):t.y,c=t.offset||0,d=t.drawBorder||!1,p=t.hitCanvasPixelRatio||1;if(!i||!s){Vt.Util.error("Can not cache the node. Width or height of the node equals 0. Caching is skipped.");return}const m=Math.abs(Math.round(n.x)-o)>.5?1:0,_=Math.abs(Math.round(n.y)-u)>.5?1:0;i+=c*2+m,s+=c*2+_,o-=c,u-=c;const y=new rp.SceneCanvas({pixelRatio:a,width:i,height:s}),b=new rp.SceneCanvas({pixelRatio:a,width:0,height:0,willReadFrequently:!0}),S=new rp.HitCanvas({pixelRatio:p,width:i,height:s}),w=y.getContext(),x=S.getContext();return S.isCache=!0,y.isCache=!0,this._cache.delete(Hu),this._filterUpToDate=!1,t.imageSmoothingEnabled===!1&&(y.getContext()._context.imageSmoothingEnabled=!1,b.getContext()._context.imageSmoothingEnabled=!1),w.save(),x.save(),w.translate(-o,-u),x.translate(-o,-u),this._isUnderCache=!0,this._clearSelfAndDescendantCache(W0),this._clearSelfAndDescendantCache(a$),this.drawScene(y,this),this.drawHit(S,this),this._isUnderCache=!1,w.restore(),x.restore(),d&&(w.save(),w.beginPath(),w.rect(0,0,i,s),w.closePath(),w.setAttr("strokeStyle","red"),w.setAttr("lineWidth",5),w.stroke(),w.restore()),this._cache.set(Hu,{scene:y,filter:b,hit:S,x:o,y:u}),this._requestDraw(),this}isCached(){return this._cache.has(Hu)}getClientRect(e){throw new Error('abstract "getClientRect" method call')}_transformedRect(e,t){const n=[{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 i=1/0,s=1/0,a=-1/0,o=-1/0;const u=this.getAbsoluteTransform(t);return n.forEach(function(c){const d=u.point(c);i===void 0&&(i=a=d.x,s=o=d.y),i=Math.min(i,d.x),s=Math.min(s,d.y),a=Math.max(a,d.x),o=Math.max(o,d.y)}),{x:i,y:s,width:a-i,height:o-s}}_drawCachedSceneCanvas(e){e.save(),e._applyOpacity(this),e._applyGlobalCompositeOperation(this);const t=this._getCanvasCache();e.translate(t.x,t.y);const n=this._getCachedSceneCanvas(),i=n.pixelRatio;e.drawImage(n._canvas,0,0,n.width/i,n.height/i),e.restore()}_drawCachedHitCanvas(e){const t=this._getCanvasCache(),n=t.hit;e.save(),e.translate(t.x,t.y),e.drawImage(n._canvas,0,0,n.width/n.pixelRatio,n.height/n.pixelRatio),e.restore()}_getCachedSceneCanvas(){let e=this.filters(),t=this._getCanvasCache(),n=t.scene,i=t.filter,s=i.getContext(),a,o,u,c;if(e){if(!this._filterUpToDate){const d=n.pixelRatio;i.setSize(n.width/n.pixelRatio,n.height/n.pixelRatio);try{for(a=e.length,s.clear(),s.drawImage(n._canvas,0,0,n.getWidth()/d,n.getHeight()/d),o=s.getImageData(0,0,i.getWidth(),i.getHeight()),u=0;u<a;u++){if(c=e[u],typeof c!="function"){Vt.Util.error("Filter should be type of function, but got "+typeof c+" instead. Please check correct filters");continue}c.call(this,o),s.putImageData(o,0,0)}}catch(p){Vt.Util.error("Unable to apply filter. "+p.message+" This post my help you https://konvajs.org/docs/posts/Tainted_Canvas.html.")}this._filterUpToDate=!0}return i}return n}on(e,t){if(this._cache&&this._cache.delete(z0),arguments.length===3)return this._delegate.apply(this,arguments);let n=e.split(j0),i=n.length,s,a,o,u,c;for(s=0;s<i;s++)a=n[s],o=a.split("."),u=o[0],c=o[1]||"",this.eventListeners[u]||(this.eventListeners[u]=[]),this.eventListeners[u].push({name:c,handler:t});return this}off(e,t){let n=(e||"").split(j0),i=n.length,s,a,o,u,c,d;if(this._cache&&this._cache.delete(z0),!e)for(a in this.eventListeners)this._off(a);for(s=0;s<i;s++)if(o=n[s],u=o.split("."),c=u[0],d=u[1],c)this.eventListeners[c]&&this._off(c,d,t);else for(a in this.eventListeners)this._off(a,d,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(n){t.call(this,n.evt)}),this}removeEventListener(e){return this.off(e),this}_delegate(e,t,n){const i=this;this.on(e,function(s){const a=s.target.findAncestors(t,!0,i);for(let o=0;o<a.length;o++)s=Vt.Util.cloneObject(s),s.currentTarget=a[o],n.call(a[o],s)})}remove(){return this.isDragging()&&this.stopDrag(),Oi.DD._dragElements.delete(this._id),this._remove(),this}_clearCaches(){this._clearSelfAndDescendantCache(Co),this._clearSelfAndDescendantCache(W0),this._clearSelfAndDescendantCache(a$),this._clearSelfAndDescendantCache(d$),this._clearSelfAndDescendantCache(ow),this._clearSelfAndDescendantCache(aw)}_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"+Vt.Util._capitalize(e);return Vt.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,n;if(!e)return this;for(t in e)t!==mce&&(n=u$+Vt.Util._capitalize(t),Vt.Util._isFunction(this[n])?this[n](e[t]):this._setAttr(t,e[t]))}),this}isListening(){return this._getCache(aw,this._isListening)}_isListening(e){if(!this.listening())return!1;const n=this.getParent();return n&&n!==e&&this!==e?n._isListening(e):!0}isVisible(){return this._getCache(ow,this._isVisible)}_isVisible(e){if(!this.visible())return!1;const n=this.getParent();return n&&n!==e&&this!==e?n._isVisible(e):!0}shouldDrawHit(e,t=!1){if(e)return this._isVisible(e)&&this._isListening(e);const n=this.getLayer();let i=!1;Oi.DD._dragElements.forEach(a=>{a.dragStatus==="dragging"&&(a.node.nodeType==="Stage"||a.node.getLayer()===n)&&(i=!0)});const s=!t&&!El.Konva.hitOnDragEnabled&&(i||El.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,n=0,i,s,a,o;function u(d){for(i=[],s=d.length,a=0;a<s;a++)o=d[a],n++,o.nodeType!==c$&&(i=i.concat(o.getChildren().slice())),o._id===t._id&&(a=s);i.length>0&&i[0].getDepth()<=e&&u(i)}const c=this.getStage();return t.nodeType!==_ce&&c&&u(c.getChildren()),n}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(xl),this._clearSelfAndDescendantCache(Co)),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 n=this.getAbsoluteTransform().copy();return n.invert(),n.point(t)}getAbsolutePosition(e){let t=!1,n=this.parent;for(;n;){if(n.isCached()){t=!0;break}n=n.parent}t&&!e&&(e=!0);const i=this.getAbsoluteTransform(e).getMatrix(),s=new Vt.Transform,a=this.offset();return s.m=i.slice(),s.translate(a.x,a.y),s.getTranslation()}setAbsolutePosition(e){const{x:t,y:n,...i}=this._clearTransform();this.attrs.x=t,this.attrs.y=n,this._clearCache(xl);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(i),this.setPosition({x:e.x,y:e.y}),this._clearCache(xl),this._clearSelfAndDescendantCache(Co),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,n=e.y,i=this.x(),s=this.y();return t!==void 0&&(i+=t),n!==void 0&&(s+=n),this.setPosition({x:i,y:s}),this}_eachAncestorReverse(e,t){let n=[],i=this.getParent(),s,a;if(!(t&&t._id===this._id)){for(n.unshift(this);i&&(!t||i._id!==t._id);)n.unshift(i),i=i.parent;for(s=n.length,a=0;a<s;a++)e(n[a])}}rotate(e){return this.rotation(this.rotation()+e),this}moveToTop(){if(!this.parent)return Vt.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 Vt.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 Vt.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 Vt.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 Vt.Util.warn("Node has no parent. zIndex parameter is ignored."),this;(e<0||e>=this.parent.children.length)&&Vt.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(W0,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,n,i,s,a;const o={attrs:{},className:this.getClassName()};for(t in e)n=e[t],a=Vt.Util.isObject(n)&&!Vt.Util._isPlainObject(n)&&!Vt.Util._isArray(n),!a&&(i=typeof this[t]=="function"&&this[t],delete e[t],s=i?i.call(this):null,e[t]=n,s!==n&&(o.attrs[t]=n));return Vt.Util._prepareToStringify(o)}toJSON(){return JSON.stringify(this.toObject())}getParent(){return this.parent}findAncestors(e,t,n){const i=[];t&&this._isMatch(e)&&i.push(this);let s=this.parent;for(;s;){if(s===n)return i;s._isMatch(e)&&i.push(s),s=s.parent}return i}isAncestorOf(e){return!1}findAncestor(e,t,n){return this.findAncestors(e,t,n)[0]}_isMatch(e){if(!e)return!1;if(typeof e=="function")return e(this);let t=e.replace(/ /g,"").split(","),n=t.length,i,s;for(i=0;i<n;i++)if(s=t[i],Vt.Util.isValidSelector(s)||(Vt.Util.warn('Selector "'+s+'" is invalid. Allowed selectors examples are "#foo", ".bar" or "Group".'),Vt.Util.warn('If you have a custom shape with such className, please change it to start with upper letter like "Triangle".'),Vt.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(d$,this._getStage)}_getStage(){const e=this.getParent();return e?e.getStage():null}fire(e,t={},n){return t.target=t.target||this,n?this._fireAndBubble(e,t):this._fire(e,t),this}getAbsoluteTransform(e){return e?this._getAbsoluteTransform(e):this._getCache(Co,this._getAbsoluteTransform)}_getAbsoluteTransform(e){let t;if(e)return t=new Vt.Transform,this._eachAncestorReverse(function(n){const i=n.transformsEnabled();i==="all"?t.multiply(n.getTransform()):i==="position"&&t.translate(n.x()-n.offsetX(),n.y()-n.offsetY())},e),t;{t=this._cache.get(Co)||new Vt.Transform,this.parent?this.parent.getAbsoluteTransform().copyInto(t):t.reset();const n=this.transformsEnabled();if(n==="all")t.multiply(this.getTransform());else if(n==="position"){const i=this.attrs.x||0,s=this.attrs.y||0,a=this.attrs.offsetX||0,o=this.attrs.offsetY||0;t.translate(i-a,s-o)}return t.dirty=!1,t}}getAbsoluteScale(e){let t=this;for(;t;)t._isUnderCache&&(e=t),t=t.getParent();const i=this.getAbsoluteTransform(e).decompose();return{x:i.scaleX,y:i.scaleY}}getAbsoluteRotation(){return this.getAbsoluteTransform().decompose().rotation}getTransform(){return this._getCache(xl,this._getTransform)}_getTransform(){var e,t;const n=this._cache.get(xl)||new Vt.Transform;n.reset();const i=this.x(),s=this.y(),a=El.Konva.getAngle(this.rotation()),o=(e=this.attrs.scaleX)!==null&&e!==void 0?e:1,u=(t=this.attrs.scaleY)!==null&&t!==void 0?t:1,c=this.attrs.skewX||0,d=this.attrs.skewY||0,p=this.attrs.offsetX||0,m=this.attrs.offsetY||0;return(i!==0||s!==0)&&n.translate(i,s),a!==0&&n.rotate(a),(c!==0||d!==0)&&n.skew(c,d),(o!==1||u!==1)&&n.scale(o,u),(p!==0||m!==0)&&n.translate(-1*p,-1*m),n.dirty=!1,n}clone(e){let t=Vt.Util.cloneObject(this.attrs),n,i,s,a,o;for(n in e)t[n]=e[n];const u=new this.constructor(t);for(n in this.eventListeners)for(i=this.eventListeners[n],s=i.length,a=0;a<s;a++)o=i[a],o.name.indexOf(gce)<0&&(u.eventListeners[n]||(u.eventListeners[n]=[]),u.eventListeners[n].push(o));return u}_toKonvaCanvas(e){e=e||{};const t=this.getClientRect(),n=this.getStage(),i=e.x!==void 0?e.x:Math.floor(t.x),s=e.y!==void 0?e.y:Math.floor(t.y),a=e.pixelRatio||1,o=new rp.SceneCanvas({width:e.width||Math.ceil(t.width)||(n?n.width():0),height:e.height||Math.ceil(t.height)||(n?n.height():0),pixelRatio:a}),u=o.getContext(),c=new rp.SceneCanvas({width:o.width/o.pixelRatio+Math.abs(i),height:o.height/o.pixelRatio+Math.abs(s),pixelRatio:o.pixelRatio});return e.imageSmoothingEnabled===!1&&(u._context.imageSmoothingEnabled=!1),u.save(),(i||s)&&u.translate(-1*i,-1*s),this.drawScene(o,void 0,c),u.restore(),o}toCanvas(e){return this._toKonvaCanvas(e)._canvas}toDataURL(e){e=e||{};const t=e.mimeType||null,n=e.quality||null,i=this._toKonvaCanvas(e).toDataURL(t,n);return e.callback&&e.callback(i),i}toImage(e){return new Promise((t,n)=>{try{const i=e==null?void 0:e.callback;i&&delete e.callback,Vt.Util._urlToImage(this.toDataURL(e),function(s){t(s),i==null||i(s)})}catch(i){n(i)}})}toBlob(e){return new Promise((t,n)=>{try{const i=e==null?void 0:e.callback;i&&delete e.callback,this.toCanvas(e).toBlob(s=>{t(s),i==null||i(s)},e==null?void 0:e.mimeType,e==null?void 0:e.quality)}catch(i){n(i)}})}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():El.Konva.dragDistance}_off(e,t,n){let i=this.eventListeners[e],s,a,o;for(s=0;s<i.length;s++)if(a=i[s].name,o=i[s].handler,(a!=="konva"||t==="konva")&&(!t||a===t)&&(!n||n===o)){if(i.splice(s,1),i.length===0){delete this.eventListeners[e];break}s--}}_fireChangeEvent(e,t,n){this._fire(e+pce,{oldVal:t,newVal:n})}addName(e){if(!this.hasName(e)){const t=this.name(),n=t?t+" "+e:e;this.name(n)}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),n=t.indexOf(e);return n!==-1&&(t.splice(n,1),this.name(t.join(" "))),this}setAttr(e,t){const n=this[u$+Vt.Util._capitalize(e)];return Vt.Util._isFunction(n)?n.call(this,t):this._setAttr(e,t),this}_requestDraw(){if(El.Konva.autoDrawEnabled){const e=this.getLayer()||this.getStage();e==null||e.batchDraw()}}_setAttr(e,t){const n=this.attrs[e];n===t&&!Vt.Util.isObject(t)||(t==null?delete this.attrs[e]:this.attrs[e]=t,this._shouldFireChangeEvents&&this._fireChangeEvent(e,n,t),this._requestDraw())}_setComponentAttr(e,t,n){let i;n!==void 0&&(i=this.attrs[e],i||(this.attrs[e]=this.getAttr(e)),this.attrs[e][t]=n,this._fireChangeEvent(e,i,n))}_fireAndBubble(e,t,n){if(t&&this.nodeType===c$&&(t.target=this),!((e===o$||e===l$)&&(n&&(this===n||this.isAncestorOf&&this.isAncestorOf(n))||this.nodeType==="Stage"&&!n))){this._fire(e,t);const s=(e===o$||e===l$)&&n&&n.isAncestorOf&&n.isAncestorOf(this)&&!n.isAncestorOf(this.parent);(t&&!t.cancelBubble||!t)&&this.parent&&this.parent.isListening()&&!s&&(n&&n.parent?this._fireAndBubble.call(this.parent,e,t,n):this._fireAndBubble.call(this.parent,e,t))}}_getProtoListeners(e){var t,n,i;const s=(t=this._cache.get(z0))!==null&&t!==void 0?t:{};let a=s==null?void 0:s[e];if(a===void 0){a=[];let o=Object.getPrototypeOf(this);for(;o;){const u=(i=(n=o.eventListeners)===null||n===void 0?void 0:n[e])!==null&&i!==void 0?i:[];a.push(...u),o=Object.getPrototypeOf(o)}s[e]=a,this._cache.set(z0,s)}return a}_fire(e,t){t=t||{},t.currentTarget=this,t.type=e;const n=this._getProtoListeners(e);if(n)for(var i=0;i<n.length;i++)n[i].handler.call(this,t);const s=this.eventListeners[e];if(s)for(var i=0;i<s.length;i++)s[i].handler.call(this,t)}draw(){return this.drawScene(),this.drawHit(),this}_createDragElement(e){const t=e?e.pointerId:void 0,n=this.getStage(),i=this.getAbsolutePosition();if(!n)return;const s=n._getPointerById(t)||n._changedPointerPositions[0]||i;Oi.DD._dragElements.set(this._id,{node:this,startPointerPos:s,offset:{x:s.x-i.x,y:s.y-i.y},dragStatus:"ready",pointerId:t})}startDrag(e,t=!0){Oi.DD._dragElements.has(this._id)||this._createDragElement(e);const n=Oi.DD._dragElements.get(this._id);n.dragStatus="dragging",this.fire("dragstart",{type:"dragstart",target:this,evt:e&&e.evt},t)}_setDragPosition(e,t){const n=this.getStage()._getPointerById(t.pointerId);if(!n)return;let i={x:n.x-t.offset.x,y:n.y-t.offset.y};const s=this.dragBoundFunc();if(s!==void 0){const a=s.call(this,i,e);a?i=a:Vt.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!==i.x||this._lastPos.y!==i.y)&&(this.setAbsolutePosition(i),this._requestDraw()),this._lastPos=i}stopDrag(e){const t=Oi.DD._dragElements.get(this._id);t&&(t.dragStatus="stopped"),Oi.DD._endDragBefore(e),Oi.DD._endDragAfter(e)}setDraggable(e){this._setAttr("draggable",e),this._dragChange()}isDragging(){const e=Oi.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)||El.Konva.dragButtons.indexOf(e.evt.button)>=0)||this.isDragging())return;let i=!1;Oi.DD._dragElements.forEach(s=>{this.isAncestorOf(s.node)&&(i=!0)}),i||this._createDragElement(e)})}_dragChange(){if(this.attrs.draggable)this._listenDrag();else{if(this._dragCleanup(),!this.getStage())return;const t=Oi.DD._dragElements.get(this._id),n=t&&t.dragStatus==="dragging",i=t&&t.dragStatus==="ready";n?this.stopDrag():i&&Oi.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 n={x:-e.x,y:-e.y,width:t.width()+2*e.x,height:t.height()+2*e.y};return Vt.Util.haveIntersection(n,this.getClientRect())}static create(e,t){return Vt.Util._isString(e)&&(e=JSON.parse(e)),this._createNode(e,t)}static _createNode(e,t){let n=Et.prototype.getClassName.call(e),i=e.children,s,a,o;t&&(e.attrs.container=t),El.Konva[n]||(Vt.Util.warn('Can not find a node with class name "'+n+'". Fallback to "Shape".'),n="Shape");const u=El.Konva[n];if(s=new u(e.attrs),i)for(a=i.length,o=0;o<a;o++)s.add(Et._createNode(i[o]));return s}}Mn.Node=Et,Et.prototype.nodeType="Node",Et.prototype._attrsAffectingSize=[],Et.prototype.eventListeners={},Et.prototype.on.call(Et.prototype,yce,function(){if(this._batchingTransformChange){this._needClearTransformCache=!0;return}this._clearCache(xl),this._clearSelfAndDescendantCache(Co)}),Et.prototype.on.call(Et.prototype,"visibleChange.konva",function(){this._clearSelfAndDescendantCache(ow)}),Et.prototype.on.call(Et.prototype,"listeningChange.konva",function(){this._clearSelfAndDescendantCache(aw)}),Et.prototype.on.call(Et.prototype,"opacityChange.konva",function(){this._clearSelfAndDescendantCache(W0)});const yn=sp.Factory.addGetterSetter;yn(Et,"zIndex"),yn(Et,"absolutePosition"),yn(Et,"position"),yn(Et,"x",0,(0,ss.getNumberValidator)()),yn(Et,"y",0,(0,ss.getNumberValidator)()),yn(Et,"globalCompositeOperation","source-over",(0,ss.getStringValidator)()),yn(Et,"opacity",1,(0,ss.getNumberValidator)()),yn(Et,"name","",(0,ss.getStringValidator)()),yn(Et,"id","",(0,ss.getStringValidator)()),yn(Et,"rotation",0,(0,ss.getNumberValidator)()),sp.Factory.addComponentsGetterSetter(Et,"scale",["x","y"]),yn(Et,"scaleX",1,(0,ss.getNumberValidator)()),yn(Et,"scaleY",1,(0,ss.getNumberValidator)()),sp.Factory.addComponentsGetterSetter(Et,"skew",["x","y"]),yn(Et,"skewX",0,(0,ss.getNumberValidator)()),yn(Et,"skewY",0,(0,ss.getNumberValidator)()),sp.Factory.addComponentsGetterSetter(Et,"offset",["x","y"]),yn(Et,"offsetX",0,(0,ss.getNumberValidator)()),yn(Et,"offsetY",0,(0,ss.getNumberValidator)()),yn(Et,"dragDistance",null,(0,ss.getNumberValidator)()),yn(Et,"width",0,(0,ss.getNumberValidator)()),yn(Et,"height",0,(0,ss.getNumberValidator)()),yn(Et,"listening",!0,(0,ss.getBooleanValidator)()),yn(Et,"preventDefault",!0,(0,ss.getBooleanValidator)()),yn(Et,"filters",null,function(r){return this._filterUpToDate=!1,r}),yn(Et,"visible",!0,(0,ss.getBooleanValidator)()),yn(Et,"transformsEnabled","all",(0,ss.getStringValidator)()),yn(Et,"size"),yn(Et,"dragBoundFunc"),yn(Et,"draggable",!1,(0,ss.getBooleanValidator)()),sp.Factory.backCompat(Et,{rotateDeg:"rotate",setRotationDeg:"setRotation",getRotationDeg:"getRotation"});var Vu={};Object.defineProperty(Vu,"__esModule",{value:!0}),Vu.Container=void 0;const Qc=Dt,lw=Mn,q0=Ct;class Gu extends lw.Node{constructor(){super(...arguments),this.children=[]}getChildren(e){if(!e)return this.children||[];const t=this.children||[],n=[];return t.forEach(function(i){e(i)&&n.push(i)}),n}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 n=0;n<e.length;n++)this.add(e[n]);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 n=[];return this._descendants(i=>{const s=i._isMatch(e);return s&&n.push(i),!!(s&&t)}),n}_descendants(e){let t=!1;const n=this.getChildren();for(const i of n){if(t=e(i),t)return!0;if(i.hasChildren()&&(t=i._descendants(e),t))return!0}return!1}toObject(){const e=lw.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=lw.Node.prototype.clone.call(this,e);return this.getChildren().forEach(function(n){t.add(n.clone())}),t}getAllIntersections(e){const t=[];return this.find("Shape").forEach(n=>{n.isVisible()&&n.intersects(e)&&t.push(n)}),t}_clearSelfAndDescendantCache(e){var t;super._clearSelfAndDescendantCache(e),!this.isCached()&&((t=this.children)===null||t===void 0||t.forEach(function(n){n._clearSelfAndDescendantCache(e)}))}_setChildrenIndices(){var e;(e=this.children)===null||e===void 0||e.forEach(function(t,n){t.index=n}),this._requestDraw()}drawScene(e,t,n){const i=this.getLayer(),s=e||i&&i.getCanvas(),a=s&&s.getContext(),o=this._getCanvasCache(),u=o&&o.scene,c=s&&s.isCache;if(!this.isVisible()&&!c)return this;if(u){a.save();const d=this.getAbsoluteTransform(t).getMatrix();a.transform(d[0],d[1],d[2],d[3],d[4],d[5]),this._drawCachedSceneCanvas(a),a.restore()}else this._drawChildren("drawScene",s,t,n);return this}drawHit(e,t){if(!this.shouldDrawHit(t))return this;const n=this.getLayer(),i=e||n&&n.hitCanvas,s=i&&i.getContext(),a=this._getCanvasCache();if(a&&a.hit){s.save();const u=this.getAbsoluteTransform(t).getMatrix();s.transform(u[0],u[1],u[2],u[3],u[4],u[5]),this._drawCachedHitCanvas(s),s.restore()}else this._drawChildren("drawHit",i,t);return this}_drawChildren(e,t,n,i){var s;const a=t&&t.getContext(),o=this.clipWidth(),u=this.clipHeight(),c=this.clipFunc(),d=typeof o=="number"&&typeof u=="number"||c,p=n===this;if(d){a.save();const _=this.getAbsoluteTransform(n);let y=_.getMatrix();a.transform(y[0],y[1],y[2],y[3],y[4],y[5]),a.beginPath();let b;if(c)b=c.call(this,a,this);else{const S=this.clipX(),w=this.clipY();a.rect(S||0,w||0,o,u)}a.clip.apply(a,b),y=_.copy().invert().getMatrix(),a.transform(y[0],y[1],y[2],y[3],y[4],y[5])}const m=!p&&this.globalCompositeOperation()!=="source-over"&&e==="drawScene";m&&(a.save(),a._applyGlobalCompositeOperation(this)),(s=this.children)===null||s===void 0||s.forEach(function(_){_[e](t,n,i)}),m&&a.restore(),d&&a.restore()}getClientRect(e={}){var t;const n=e.skipTransform,i=e.relativeTo;let s,a,o,u,c={x:1/0,y:1/0,width:0,height:0};const d=this;(t=this.children)===null||t===void 0||t.forEach(function(_){if(!_.visible())return;const y=_.getClientRect({relativeTo:d,skipShadow:e.skipShadow,skipStroke:e.skipStroke});y.width===0&&y.height===0||(s===void 0?(s=y.x,a=y.y,o=y.x+y.width,u=y.y+y.height):(s=Math.min(s,y.x),a=Math.min(a,y.y),o=Math.max(o,y.x+y.width),u=Math.max(u,y.y+y.height)))});const p=this.find("Shape");let m=!1;for(let _=0;_<p.length;_++)if(p[_]._isVisible(this)){m=!0;break}return m&&s!==void 0?c={x:s,y:a,width:o-s,height:u-a}:c={x:0,y:0,width:0,height:0},n?c:this._transformedRect(c,i)}}Vu.Container=Gu,Qc.Factory.addComponentsGetterSetter(Gu,"clip",["x","y","width","height"]),Qc.Factory.addGetterSetter(Gu,"clipX",void 0,(0,q0.getNumberValidator)()),Qc.Factory.addGetterSetter(Gu,"clipY",void 0,(0,q0.getNumberValidator)()),Qc.Factory.addGetterSetter(Gu,"clipWidth",void 0,(0,q0.getNumberValidator)()),Qc.Factory.addGetterSetter(Gu,"clipHeight",void 0,(0,q0.getNumberValidator)()),Qc.Factory.addGetterSetter(Gu,"clipFunc");var h$={},Il={};Object.defineProperty(Il,"__esModule",{value:!0}),Il.getCapturedShape=Sce,Il.createEvent=uw,Il.hasPointerCapture=Tce,Il.setPointerCapture=wce,Il.releaseCapture=p$;const bce=$t,ip=new Map,f$=bce.Konva._global.PointerEvent!==void 0;function Sce(r){return ip.get(r)}function uw(r){return{evt:r,pointerId:r.pointerId}}function Tce(r,e){return ip.get(r)===e}function wce(r,e){p$(r),e.getStage()&&(ip.set(r,e),f$&&e._fire("gotpointercapture",uw(new PointerEvent("gotpointercapture"))))}function p$(r,e){const t=ip.get(r);if(!t)return;const n=t.getStage();n&&n.content,ip.delete(r),f$&&t._fire("lostpointercapture",uw(new PointerEvent("lostpointercapture")))}(function(r){Object.defineProperty(r,"__esModule",{value:!0}),r.Stage=r.stages=void 0;const e=Un,t=Dt,n=Vu,i=$t,s=ia,a=G0,o=$t,u=Il,c="Stage",d="string",p="px",m="mouseout",_="mouseleave",y="mouseover",b="mouseenter",S="mousemove",w="mousedown",x="mouseup",E="pointermove",I="pointerdown",R="pointerup",P="pointercancel",B="lostpointercapture",O="pointerout",F="pointerleave",D="pointerover",L="pointerenter",G="contextmenu",j="touchstart",te="touchend",W="touchmove",Q="touchcancel",oe="wheel",Ce=5,fe=[[b,"_pointerenter"],[w,"_pointerdown"],[S,"_pointermove"],[x,"_pointerup"],[_,"_pointerleave"],[j,"_pointerdown"],[W,"_pointermove"],[te,"_pointerup"],[Q,"_pointercancel"],[y,"_pointerover"],[oe,"_wheel"],[G,"_contextmenu"],[I,"_pointerdown"],[E,"_pointermove"],[R,"_pointerup"],[P,"_pointercancel"],[B,"_lostpointercapture"]],ne={mouse:{[O]:m,[F]:_,[D]:y,[L]:b,[E]:S,[I]:w,[R]:x,[P]:"mousecancel",pointerclick:"click",pointerdblclick:"dblclick"},touch:{[O]:"touchout",[F]:"touchleave",[D]:"touchover",[L]:"touchenter",[E]:W,[I]:j,[R]:te,[P]:Q,pointerclick:"tap",pointerdblclick:"dbltap"},pointer:{[O]:O,[F]:F,[D]:D,[L]:L,[E]:E,[I]:I,[R]:R,[P]:P,pointerclick:"pointerclick",pointerdblclick:"pointerdblclick"}},ae=Ve=>Ve.indexOf("pointer")>=0?"pointer":Ve.indexOf("touch")>=0?"touch":"mouse",be=Ve=>{const q=ae(Ve);if(q==="pointer")return i.Konva.pointerEventsEnabled&&ne.pointer;if(q==="touch")return ne.touch;if(q==="mouse")return ne.mouse};function Se(Ve={}){return(Ve.clipFunc||Ve.clipWidth||Ve.clipHeight)&&e.Util.warn("Stage does not support clipping. Please use clip for Layers or Groups."),Ve}const Me="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);";r.stages=[];class ot extends n.Container{constructor(q){super(Se(q)),this._pointerPositions=[],this._changedPointerPositions=[],this._buildDOM(),this._bindContentEvents(),r.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",()=>{Se(this.attrs)}),this._checkVisibility()}_validateAdd(q){const ue=q.getType()==="Layer",Ue=q.getType()==="FastLayer";ue||Ue||e.Util.throw("You may only add layers to the stage.")}_checkVisibility(){if(!this.content)return;const q=this.visible()?"":"none";this.content.style.display=q}setContainer(q){if(typeof q===d){if(q.charAt(0)==="."){const Ue=q.slice(1);q=document.getElementsByClassName(Ue)[0]}else{var ue;q.charAt(0)!=="#"?ue=q:ue=q.slice(1),q=document.getElementById(ue)}if(!q)throw"Can not find container in document with id "+ue}return this._setAttr("container",q),this.content&&(this.content.parentElement&&this.content.parentElement.removeChild(this.content),q.appendChild(this.content)),this}shouldDrawHit(){return!0}clear(){let q=this.children,ue=q.length,Ue;for(Ue=0;Ue<ue;Ue++)q[Ue].clear();return this}clone(q){return q||(q={}),q.container=typeof document<"u"&&document.createElement("div"),n.Container.prototype.clone.call(this,q)}destroy(){super.destroy();const q=this.content;q&&e.Util._isInDocument(q)&&this.container().removeChild(q);const ue=r.stages.indexOf(this);return ue>-1&&r.stages.splice(ue,1),e.Util.releaseCanvas(this.bufferCanvas._canvas,this.bufferHitCanvas._canvas),this}getPointerPosition(){const q=this._pointerPositions[0]||this._changedPointerPositions[0];return q?{x:q.x,y:q.y}:(e.Util.warn(Me),null)}_getPointerById(q){return this._pointerPositions.find(ue=>ue.id===q)}getPointersPositions(){return this._pointerPositions}getStage(){return this}getContent(){return this.content}_toKonvaCanvas(q){q=q||{},q.x=q.x||0,q.y=q.y||0,q.width=q.width||this.width(),q.height=q.height||this.height();const ue=new s.SceneCanvas({width:q.width,height:q.height,pixelRatio:q.pixelRatio||1}),Ue=ue.getContext()._context,mt=this.children;return(q.x||q.y)&&Ue.translate(-1*q.x,-1*q.y),mt.forEach(function($e){if(!$e.isVisible())return;const Be=$e._toKonvaCanvas(q);Ue.drawImage(Be._canvas,q.x,q.y,Be.getWidth()/Be.getPixelRatio(),Be.getHeight()/Be.getPixelRatio())}),ue}getIntersection(q){if(!q)return null;let ue=this.children,Ue=ue.length,mt=Ue-1,$e;for($e=mt;$e>=0;$e--){const Be=ue[$e].getIntersection(q);if(Be)return Be}return null}_resizeDOM(){const q=this.width(),ue=this.height();this.content&&(this.content.style.width=q+p,this.content.style.height=ue+p),this.bufferCanvas.setSize(q,ue),this.bufferHitCanvas.setSize(q,ue),this.children.forEach(Ue=>{Ue.setSize({width:q,height:ue}),Ue.draw()})}add(q,...ue){if(arguments.length>1){for(let mt=0;mt<arguments.length;mt++)this.add(arguments[mt]);return this}super.add(q);const Ue=this.children.length;return Ue>Ce&&e.Util.warn("The stage has "+Ue+" 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."),q.setSize({width:this.width(),height:this.height()}),q.draw(),i.Konva.isBrowser&&this.content.appendChild(q.canvas._canvas),this}getParent(){return null}getLayer(){return null}hasPointerCapture(q){return u.hasPointerCapture(q,this)}setPointerCapture(q){u.setPointerCapture(q,this)}releaseCapture(q){u.releaseCapture(q,this)}getLayers(){return this.children}_bindContentEvents(){i.Konva.isBrowser&&fe.forEach(([q,ue])=>{this.content.addEventListener(q,Ue=>{this[ue](Ue)},{passive:!1})})}_pointerenter(q){this.setPointersPositions(q);const ue=be(q.type);ue&&this._fire(ue.pointerenter,{evt:q,target:this,currentTarget:this})}_pointerover(q){this.setPointersPositions(q);const ue=be(q.type);ue&&this._fire(ue.pointerover,{evt:q,target:this,currentTarget:this})}_getTargetShape(q){let ue=this[q+"targetShape"];return ue&&!ue.getStage()&&(ue=null),ue}_pointerleave(q){const ue=be(q.type),Ue=ae(q.type);if(!ue)return;this.setPointersPositions(q);const mt=this._getTargetShape(Ue),$e=!(i.Konva.isDragging()||i.Konva.isTransforming())||i.Konva.hitOnDragEnabled;mt&&$e?(mt._fireAndBubble(ue.pointerout,{evt:q}),mt._fireAndBubble(ue.pointerleave,{evt:q}),this._fire(ue.pointerleave,{evt:q,target:this,currentTarget:this}),this[Ue+"targetShape"]=null):$e&&(this._fire(ue.pointerleave,{evt:q,target:this,currentTarget:this}),this._fire(ue.pointerout,{evt:q,target:this,currentTarget:this})),this.pointerPos=null,this._pointerPositions=[]}_pointerdown(q){const ue=be(q.type),Ue=ae(q.type);if(!ue)return;this.setPointersPositions(q);let mt=!1;this._changedPointerPositions.forEach($e=>{const Be=this.getIntersection($e);if(a.DD.justDragged=!1,i.Konva["_"+Ue+"ListenClick"]=!0,!Be||!Be.isListening()){this[Ue+"ClickStartShape"]=void 0;return}i.Konva.capturePointerEventsEnabled&&Be.setPointerCapture($e.id),this[Ue+"ClickStartShape"]=Be,Be._fireAndBubble(ue.pointerdown,{evt:q,pointerId:$e.id}),mt=!0;const ze=q.type.indexOf("touch")>=0;Be.preventDefault()&&q.cancelable&&ze&&q.preventDefault()}),mt||this._fire(ue.pointerdown,{evt:q,target:this,currentTarget:this,pointerId:this._pointerPositions[0].id})}_pointermove(q){const ue=be(q.type),Ue=ae(q.type);if(!ue||(i.Konva.isDragging()&&a.DD.node.preventDefault()&&q.cancelable&&q.preventDefault(),this.setPointersPositions(q),!(!(i.Konva.isDragging()||i.Konva.isTransforming())||i.Konva.hitOnDragEnabled)))return;const $e={};let Be=!1;const ze=this._getTargetShape(Ue);this._changedPointerPositions.forEach(et=>{const Ne=u.getCapturedShape(et.id)||this.getIntersection(et),De=et.id,Ge={evt:q,pointerId:De},ft=ze!==Ne;if(ft&&ze&&(ze._fireAndBubble(ue.pointerout,{...Ge},Ne),ze._fireAndBubble(ue.pointerleave,{...Ge},Ne)),Ne){if($e[Ne._id])return;$e[Ne._id]=!0}Ne&&Ne.isListening()?(Be=!0,ft&&(Ne._fireAndBubble(ue.pointerover,{...Ge},ze),Ne._fireAndBubble(ue.pointerenter,{...Ge},ze),this[Ue+"targetShape"]=Ne),Ne._fireAndBubble(ue.pointermove,{...Ge})):ze&&(this._fire(ue.pointerover,{evt:q,target:this,currentTarget:this,pointerId:De}),this[Ue+"targetShape"]=null)}),Be||this._fire(ue.pointermove,{evt:q,target:this,currentTarget:this,pointerId:this._changedPointerPositions[0].id})}_pointerup(q){const ue=be(q.type),Ue=ae(q.type);if(!ue)return;this.setPointersPositions(q);const mt=this[Ue+"ClickStartShape"],$e=this[Ue+"ClickEndShape"],Be={};let ze=!1;this._changedPointerPositions.forEach(et=>{const Ne=u.getCapturedShape(et.id)||this.getIntersection(et);if(Ne){if(Ne.releaseCapture(et.id),Be[Ne._id])return;Be[Ne._id]=!0}const De=et.id,Ge={evt:q,pointerId:De};let ft=!1;i.Konva["_"+Ue+"InDblClickWindow"]?(ft=!0,clearTimeout(this[Ue+"DblTimeout"])):a.DD.justDragged||(i.Konva["_"+Ue+"InDblClickWindow"]=!0,clearTimeout(this[Ue+"DblTimeout"])),this[Ue+"DblTimeout"]=setTimeout(function(){i.Konva["_"+Ue+"InDblClickWindow"]=!1},i.Konva.dblClickWindow),Ne&&Ne.isListening()?(ze=!0,this[Ue+"ClickEndShape"]=Ne,Ne._fireAndBubble(ue.pointerup,{...Ge}),i.Konva["_"+Ue+"ListenClick"]&&mt&&mt===Ne&&(Ne._fireAndBubble(ue.pointerclick,{...Ge}),ft&&$e&&$e===Ne&&Ne._fireAndBubble(ue.pointerdblclick,{...Ge}))):(this[Ue+"ClickEndShape"]=null,i.Konva["_"+Ue+"ListenClick"]&&this._fire(ue.pointerclick,{evt:q,target:this,currentTarget:this,pointerId:De}),ft&&this._fire(ue.pointerdblclick,{evt:q,target:this,currentTarget:this,pointerId:De}))}),ze||this._fire(ue.pointerup,{evt:q,target:this,currentTarget:this,pointerId:this._changedPointerPositions[0].id}),i.Konva["_"+Ue+"ListenClick"]=!1,q.cancelable&&Ue!=="touch"&&q.preventDefault()}_contextmenu(q){this.setPointersPositions(q);const ue=this.getIntersection(this.getPointerPosition());ue&&ue.isListening()?ue._fireAndBubble(G,{evt:q}):this._fire(G,{evt:q,target:this,currentTarget:this})}_wheel(q){this.setPointersPositions(q);const ue=this.getIntersection(this.getPointerPosition());ue&&ue.isListening()?ue._fireAndBubble(oe,{evt:q}):this._fire(oe,{evt:q,target:this,currentTarget:this})}_pointercancel(q){this.setPointersPositions(q);const ue=u.getCapturedShape(q.pointerId)||this.getIntersection(this.getPointerPosition());ue&&ue._fireAndBubble(R,u.createEvent(q)),u.releaseCapture(q.pointerId)}_lostpointercapture(q){u.releaseCapture(q.pointerId)}setPointersPositions(q){let ue=this._getContentPosition(),Ue=null,mt=null;q=q||window.event,q.touches!==void 0?(this._pointerPositions=[],this._changedPointerPositions=[],Array.prototype.forEach.call(q.touches,$e=>{this._pointerPositions.push({id:$e.identifier,x:($e.clientX-ue.left)/ue.scaleX,y:($e.clientY-ue.top)/ue.scaleY})}),Array.prototype.forEach.call(q.changedTouches||q.touches,$e=>{this._changedPointerPositions.push({id:$e.identifier,x:($e.clientX-ue.left)/ue.scaleX,y:($e.clientY-ue.top)/ue.scaleY})})):(Ue=(q.clientX-ue.left)/ue.scaleX,mt=(q.clientY-ue.top)/ue.scaleY,this.pointerPos={x:Ue,y:mt},this._pointerPositions=[{x:Ue,y:mt,id:e.Util._getFirstPointerId(q)}],this._changedPointerPositions=[{x:Ue,y:mt,id:e.Util._getFirstPointerId(q)}])}_setPointerPosition(q){e.Util.warn('Method _setPointerPosition is deprecated. Use "stage.setPointersPositions(event)" instead.'),this.setPointersPositions(q)}_getContentPosition(){if(!this.content||!this.content.getBoundingClientRect)return{top:0,left:0,scaleX:1,scaleY:1};const q=this.content.getBoundingClientRect();return{top:q.top,left:q.left,scaleX:q.width/this.content.clientWidth||1,scaleY:q.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()}),!i.Konva.isBrowser)return;const q=this.container();if(!q)throw"Stage has no container. A container is required.";q.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"),q.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(q){q.batchDraw()}),this}}r.Stage=ot,ot.prototype.nodeType=c,(0,o._registerNode)(ot),t.Factory.addGetterSetter(ot,"container"),i.Konva.isBrowser&&document.addEventListener("visibilitychange",()=>{r.stages.forEach(Ve=>{Ve.batchDraw()})})})(h$);var ap={},vs={};(function(r){Object.defineProperty(r,"__esModule",{value:!0}),r.Shape=r.shapes=void 0;const e=$t,t=Un,n=Dt,i=Mn,s=Ct,a=$t,o=Il,u="hasShadow",c="shadowRGBA",d="patternImage",p="linearGradient",m="radialGradient";let _;function y(){return _||(_=t.Util.createCanvasElement().getContext("2d"),_)}r.shapes={};function b(F){const D=this.attrs.fillRule;D?F.fill(D):F.fill()}function S(F){F.stroke()}function w(F){const D=this.attrs.fillRule;D?F.fill(D):F.fill()}function x(F){F.stroke()}function E(){this._clearCache(u)}function I(){this._clearCache(c)}function R(){this._clearCache(d)}function P(){this._clearCache(p)}function B(){this._clearCache(m)}class O extends i.Node{constructor(D){super(D);let L;for(;L=t.Util.getRandomColor(),!(L&&!(L in r.shapes)););this.colorKey=L,r.shapes[L]=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(u,this._hasShadow)}_hasShadow(){return this.shadowEnabled()&&this.shadowOpacity()!==0&&!!(this.shadowColor()||this.shadowBlur()||this.shadowOffsetX()||this.shadowOffsetY())}_getFillPattern(){return this._getCache(d,this.__getFillPattern)}__getFillPattern(){if(this.fillPatternImage()){const L=y().createPattern(this.fillPatternImage(),this.fillPatternRepeat()||"repeat");if(L&&L.setTransform){const G=new t.Transform;G.translate(this.fillPatternX(),this.fillPatternY()),G.rotate(e.Konva.getAngle(this.fillPatternRotation())),G.scale(this.fillPatternScaleX(),this.fillPatternScaleY()),G.translate(-1*this.fillPatternOffsetX(),-1*this.fillPatternOffsetY());const j=G.getMatrix(),te=typeof DOMMatrix>"u"?{a:j[0],b:j[1],c:j[2],d:j[3],e:j[4],f:j[5]}:new DOMMatrix(j);L.setTransform(te)}return L}}_getLinearGradient(){return this._getCache(p,this.__getLinearGradient)}__getLinearGradient(){const D=this.fillLinearGradientColorStops();if(D){const L=y(),G=this.fillLinearGradientStartPoint(),j=this.fillLinearGradientEndPoint(),te=L.createLinearGradient(G.x,G.y,j.x,j.y);for(let W=0;W<D.length;W+=2)te.addColorStop(D[W],D[W+1]);return te}}_getRadialGradient(){return this._getCache(m,this.__getRadialGradient)}__getRadialGradient(){const D=this.fillRadialGradientColorStops();if(D){const L=y(),G=this.fillRadialGradientStartPoint(),j=this.fillRadialGradientEndPoint(),te=L.createRadialGradient(G.x,G.y,this.fillRadialGradientStartRadius(),j.x,j.y,this.fillRadialGradientEndRadius());for(let W=0;W<D.length;W+=2)te.addColorStop(D[W],D[W+1]);return te}}getShadowRGBA(){return this._getCache(c,this._getShadowRGBA)}_getShadowRGBA(){if(!this.hasShadow())return;const D=t.Util.colorToRGBA(this.shadowColor());if(D)return"rgba("+D.r+","+D.g+","+D.b+","+D.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 D=this.hitStrokeWidth();return D==="auto"?this.hasStroke():this.strokeEnabled()&&!!D}intersects(D){const L=this.getStage();if(!L)return!1;const G=L.bufferHitCanvas;return G.getContext().clear(),this.drawHit(G,void 0,!0),G.context.getImageData(Math.round(D.x),Math.round(D.y),1,1).data[3]>0}destroy(){return i.Node.prototype.destroy.call(this),delete r.shapes[this.colorKey],delete this.colorKey,this}_useBufferCanvas(D){var L;if(!((L=this.attrs.perfectDrawEnabled)!==null&&L!==void 0?L:!0))return!1;const j=D||this.hasFill(),te=this.hasStroke(),W=this.getAbsoluteOpacity()!==1;if(j&&te&&W)return!0;const Q=this.hasShadow(),oe=this.shadowForStrokeEnabled();return!!(j&&te&&Q&&oe)}setStrokeHitEnabled(D){t.Util.warn("strokeHitEnabled property is deprecated. Please use hitStrokeWidth instead."),D?this.hitStrokeWidth("auto"):this.hitStrokeWidth(0)}getStrokeHitEnabled(){return this.hitStrokeWidth()!==0}getSelfRect(){const D=this.size();return{x:this._centroid?-D.width/2:0,y:this._centroid?-D.height/2:0,width:D.width,height:D.height}}getClientRect(D={}){let L=!1,G=this.getParent();for(;G;){if(G.isCached()){L=!0;break}G=G.getParent()}const j=D.skipTransform,te=D.relativeTo||L&&this.getStage()||void 0,W=this.getSelfRect(),oe=!D.skipStroke&&this.hasStroke()&&this.strokeWidth()||0,Ce=W.width+oe,fe=W.height+oe,ne=!D.skipShadow&&this.hasShadow(),ae=ne?this.shadowOffsetX():0,be=ne?this.shadowOffsetY():0,Se=Ce+Math.abs(ae),Me=fe+Math.abs(be),ot=ne&&this.shadowBlur()||0,Ve=Se+ot*2,q=Me+ot*2,ue={width:Ve,height:q,x:-(oe/2+ot)+Math.min(ae,0)+W.x,y:-(oe/2+ot)+Math.min(be,0)+W.y};return j?ue:this._transformedRect(ue,te)}drawScene(D,L,G){const j=this.getLayer();let te=D||j.getCanvas(),W=te.getContext(),Q=this._getCanvasCache(),oe=this.getSceneFunc(),Ce=this.hasShadow(),fe,ne;const ae=te.isCache,be=L===this;if(!this.isVisible()&&!be)return this;if(Q){W.save();const Me=this.getAbsoluteTransform(L).getMatrix();return W.transform(Me[0],Me[1],Me[2],Me[3],Me[4],Me[5]),this._drawCachedSceneCanvas(W),W.restore(),this}if(!oe)return this;if(W.save(),this._useBufferCanvas()&&!ae){fe=this.getStage();const Me=G||fe.bufferCanvas;ne=Me.getContext(),ne.clear(),ne.save(),ne._applyLineJoin(this);var Se=this.getAbsoluteTransform(L).getMatrix();ne.transform(Se[0],Se[1],Se[2],Se[3],Se[4],Se[5]),oe.call(this,ne,this),ne.restore();const ot=Me.pixelRatio;Ce&&W._applyShadow(this),W._applyOpacity(this),W._applyGlobalCompositeOperation(this),W.drawImage(Me._canvas,0,0,Me.width/ot,Me.height/ot)}else{if(W._applyLineJoin(this),!be){var Se=this.getAbsoluteTransform(L).getMatrix();W.transform(Se[0],Se[1],Se[2],Se[3],Se[4],Se[5]),W._applyOpacity(this),W._applyGlobalCompositeOperation(this)}Ce&&W._applyShadow(this),oe.call(this,W,this)}return W.restore(),this}drawHit(D,L,G=!1){if(!this.shouldDrawHit(L,G))return this;const j=this.getLayer(),te=D||j.hitCanvas,W=te&&te.getContext(),Q=this.hitFunc()||this.sceneFunc(),oe=this._getCanvasCache(),Ce=oe&&oe.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()"),Ce){W.save();const ne=this.getAbsoluteTransform(L).getMatrix();return W.transform(ne[0],ne[1],ne[2],ne[3],ne[4],ne[5]),this._drawCachedHitCanvas(W),W.restore(),this}if(!Q)return this;if(W.save(),W._applyLineJoin(this),!(this===L)){const ne=this.getAbsoluteTransform(L).getMatrix();W.transform(ne[0],ne[1],ne[2],ne[3],ne[4],ne[5])}return Q.call(this,W,this),W.restore(),this}drawHitFromCache(D=0){let L=this._getCanvasCache(),G=this._getCachedSceneCanvas(),j=L.hit,te=j.getContext(),W=j.getWidth(),Q=j.getHeight(),oe,Ce,fe,ne,ae,be;te.clear(),te.drawImage(G._canvas,0,0,W,Q);try{for(oe=te.getImageData(0,0,W,Q),Ce=oe.data,fe=Ce.length,ne=t.Util._hexToRgb(this.colorKey),ae=0;ae<fe;ae+=4)be=Ce[ae+3],be>D?(Ce[ae]=ne.r,Ce[ae+1]=ne.g,Ce[ae+2]=ne.b,Ce[ae+3]=255):Ce[ae+3]=0;te.putImageData(oe,0,0)}catch(Se){t.Util.error("Unable to draw hit graph from cached scene canvas. "+Se.message)}return this}hasPointerCapture(D){return o.hasPointerCapture(D,this)}setPointerCapture(D){o.setPointerCapture(D,this)}releaseCapture(D){o.releaseCapture(D,this)}}r.Shape=O,O.prototype._fillFunc=b,O.prototype._strokeFunc=S,O.prototype._fillFuncHit=w,O.prototype._strokeFuncHit=x,O.prototype._centroid=!1,O.prototype.nodeType="Shape",(0,a._registerNode)(O),O.prototype.eventListeners={},O.prototype.on.call(O.prototype,"shadowColorChange.konva shadowBlurChange.konva shadowOffsetChange.konva shadowOpacityChange.konva shadowEnabledChange.konva",E),O.prototype.on.call(O.prototype,"shadowColorChange.konva shadowOpacityChange.konva shadowEnabledChange.konva",I),O.prototype.on.call(O.prototype,"fillPriorityChange.konva fillPatternImageChange.konva fillPatternRepeatChange.konva fillPatternScaleXChange.konva fillPatternScaleYChange.konva fillPatternOffsetXChange.konva fillPatternOffsetYChange.konva fillPatternXChange.konva fillPatternYChange.konva fillPatternRotationChange.konva",R),O.prototype.on.call(O.prototype,"fillPriorityChange.konva fillLinearGradientColorStopsChange.konva fillLinearGradientStartPointXChange.konva fillLinearGradientStartPointYChange.konva fillLinearGradientEndPointXChange.konva fillLinearGradientEndPointYChange.konva",P),O.prototype.on.call(O.prototype,"fillPriorityChange.konva fillRadialGradientColorStopsChange.konva fillRadialGradientStartPointXChange.konva fillRadialGradientStartPointYChange.konva fillRadialGradientEndPointXChange.konva fillRadialGradientEndPointYChange.konva fillRadialGradientStartRadiusChange.konva fillRadialGradientEndRadiusChange.konva",B),n.Factory.addGetterSetter(O,"stroke",void 0,(0,s.getStringOrGradientValidator)()),n.Factory.addGetterSetter(O,"strokeWidth",2,(0,s.getNumberValidator)()),n.Factory.addGetterSetter(O,"fillAfterStrokeEnabled",!1),n.Factory.addGetterSetter(O,"hitStrokeWidth","auto",(0,s.getNumberOrAutoValidator)()),n.Factory.addGetterSetter(O,"strokeHitEnabled",!0,(0,s.getBooleanValidator)()),n.Factory.addGetterSetter(O,"perfectDrawEnabled",!0,(0,s.getBooleanValidator)()),n.Factory.addGetterSetter(O,"shadowForStrokeEnabled",!0,(0,s.getBooleanValidator)()),n.Factory.addGetterSetter(O,"lineJoin"),n.Factory.addGetterSetter(O,"lineCap"),n.Factory.addGetterSetter(O,"sceneFunc"),n.Factory.addGetterSetter(O,"hitFunc"),n.Factory.addGetterSetter(O,"dash"),n.Factory.addGetterSetter(O,"dashOffset",0,(0,s.getNumberValidator)()),n.Factory.addGetterSetter(O,"shadowColor",void 0,(0,s.getStringValidator)()),n.Factory.addGetterSetter(O,"shadowBlur",0,(0,s.getNumberValidator)()),n.Factory.addGetterSetter(O,"shadowOpacity",1,(0,s.getNumberValidator)()),n.Factory.addComponentsGetterSetter(O,"shadowOffset",["x","y"]),n.Factory.addGetterSetter(O,"shadowOffsetX",0,(0,s.getNumberValidator)()),n.Factory.addGetterSetter(O,"shadowOffsetY",0,(0,s.getNumberValidator)()),n.Factory.addGetterSetter(O,"fillPatternImage"),n.Factory.addGetterSetter(O,"fill",void 0,(0,s.getStringOrGradientValidator)()),n.Factory.addGetterSetter(O,"fillPatternX",0,(0,s.getNumberValidator)()),n.Factory.addGetterSetter(O,"fillPatternY",0,(0,s.getNumberValidator)()),n.Factory.addGetterSetter(O,"fillLinearGradientColorStops"),n.Factory.addGetterSetter(O,"strokeLinearGradientColorStops"),n.Factory.addGetterSetter(O,"fillRadialGradientStartRadius",0),n.Factory.addGetterSetter(O,"fillRadialGradientEndRadius",0),n.Factory.addGetterSetter(O,"fillRadialGradientColorStops"),n.Factory.addGetterSetter(O,"fillPatternRepeat","repeat"),n.Factory.addGetterSetter(O,"fillEnabled",!0),n.Factory.addGetterSetter(O,"strokeEnabled",!0),n.Factory.addGetterSetter(O,"shadowEnabled",!0),n.Factory.addGetterSetter(O,"dashEnabled",!0),n.Factory.addGetterSetter(O,"strokeScaleEnabled",!0),n.Factory.addGetterSetter(O,"fillPriority","color"),n.Factory.addComponentsGetterSetter(O,"fillPatternOffset",["x","y"]),n.Factory.addGetterSetter(O,"fillPatternOffsetX",0,(0,s.getNumberValidator)()),n.Factory.addGetterSetter(O,"fillPatternOffsetY",0,(0,s.getNumberValidator)()),n.Factory.addComponentsGetterSetter(O,"fillPatternScale",["x","y"]),n.Factory.addGetterSetter(O,"fillPatternScaleX",1,(0,s.getNumberValidator)()),n.Factory.addGetterSetter(O,"fillPatternScaleY",1,(0,s.getNumberValidator)()),n.Factory.addComponentsGetterSetter(O,"fillLinearGradientStartPoint",["x","y"]),n.Factory.addComponentsGetterSetter(O,"strokeLinearGradientStartPoint",["x","y"]),n.Factory.addGetterSetter(O,"fillLinearGradientStartPointX",0),n.Factory.addGetterSetter(O,"strokeLinearGradientStartPointX",0),n.Factory.addGetterSetter(O,"fillLinearGradientStartPointY",0),n.Factory.addGetterSetter(O,"strokeLinearGradientStartPointY",0),n.Factory.addComponentsGetterSetter(O,"fillLinearGradientEndPoint",["x","y"]),n.Factory.addComponentsGetterSetter(O,"strokeLinearGradientEndPoint",["x","y"]),n.Factory.addGetterSetter(O,"fillLinearGradientEndPointX",0),n.Factory.addGetterSetter(O,"strokeLinearGradientEndPointX",0),n.Factory.addGetterSetter(O,"fillLinearGradientEndPointY",0),n.Factory.addGetterSetter(O,"strokeLinearGradientEndPointY",0),n.Factory.addComponentsGetterSetter(O,"fillRadialGradientStartPoint",["x","y"]),n.Factory.addGetterSetter(O,"fillRadialGradientStartPointX",0),n.Factory.addGetterSetter(O,"fillRadialGradientStartPointY",0),n.Factory.addComponentsGetterSetter(O,"fillRadialGradientEndPoint",["x","y"]),n.Factory.addGetterSetter(O,"fillRadialGradientEndPointX",0),n.Factory.addGetterSetter(O,"fillRadialGradientEndPointY",0),n.Factory.addGetterSetter(O,"fillPatternRotation",0),n.Factory.addGetterSetter(O,"fillRule",void 0,(0,s.getStringValidator)()),n.Factory.backCompat(O,{dashArray:"dash",getDashArray:"getDash",setDashArray:"getDash",drawFunc:"sceneFunc",getDrawFunc:"getSceneFunc",setDrawFunc:"setSceneFunc",drawHitFunc:"hitFunc",getDrawHitFunc:"getHitFunc",setDrawHitFunc:"setHitFunc"})})(vs),Object.defineProperty(ap,"__esModule",{value:!0}),ap.Layer=void 0;const Eo=Un,cw=Vu,Zc=Mn,dw=Dt,m$=ia,Cce=Ct,Ece=vs,xce=$t,Ice="#",Ace="beforeDraw",Rce="draw",g$=[{x:0,y:0},{x:-1,y:-1},{x:1,y:-1},{x:1,y:1},{x:-1,y:1}],Nce=g$.length;class ed extends cw.Container{constructor(e){super(e),this.canvas=new m$.SceneCanvas,this.hitCanvas=new m$.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(){Zc.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(!Zc.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(Zc.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(Zc.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 Zc.Node.prototype.remove.call(this),e&&e.parentNode&&Eo.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"&&Eo.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(),Zc.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(){Eo.Util.warn('Can not change width of layer. Use "stage.width(value)" function instead.')}getHeight(){if(this.parent)return this.parent.height()}setHeight(){Eo.Util.warn('Can not change height of layer. Use "stage.height(value)" function instead.')}batchDraw(){return this._waitingForDraw||(this._waitingForDraw=!0,Eo.Util.requestAnimFrame(()=>{this.draw(),this._waitingForDraw=!1})),this}getIntersection(e){if(!this.isListening()||!this.isVisible())return null;let t=1,n=!1;for(;;){for(let i=0;i<Nce;i++){const s=g$[i],a=this._getIntersection({x:e.x+s.x*t,y:e.y+s.y*t}),o=a.shape;if(o)return o;if(n=!!a.antialiased,!a.antialiased)break}if(n)t+=1;else return null}}_getIntersection(e){const t=this.hitCanvas.pixelRatio,n=this.hitCanvas.context.getImageData(Math.round(e.x*t),Math.round(e.y*t),1,1).data,i=n[3];if(i===255){const s=Eo.Util._rgbToHex(n[0],n[1],n[2]),a=Ece.shapes[Ice+s];return a?{shape:a}:{antialiased:!0}}else if(i>0)return{antialiased:!0};return{}}drawScene(e,t){const n=this.getLayer(),i=e||n&&n.getCanvas();return this._fire(Ace,{node:this}),this.clearBeforeDraw()&&i.getContext().clear(),cw.Container.prototype.drawScene.call(this,i,t),this._fire(Rce,{node:this}),this}drawHit(e,t){const n=this.getLayer(),i=e||n&&n.hitCanvas;return n&&n.clearBeforeDraw()&&n.getHitCanvas().getContext().clear(),cw.Container.prototype.drawHit.call(this,i,t),this}enableHitGraph(){return this.hitGraphEnabled(!0),this}disableHitGraph(){return this.hitGraphEnabled(!1),this}setHitGraphEnabled(e){Eo.Util.warn("hitGraphEnabled method is deprecated. Please use layer.listening() instead."),this.listening(e)}getHitGraphEnabled(e){return Eo.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 Eo.Util.releaseCanvas(this.getNativeCanvasElement(),this.getHitCanvas()._canvas),super.destroy()}}ap.Layer=ed,ed.prototype.nodeType="Layer",(0,xce._registerNode)(ed),dw.Factory.addGetterSetter(ed,"imageSmoothingEnabled",!0),dw.Factory.addGetterSetter(ed,"clearBeforeDraw",!0),dw.Factory.addGetterSetter(ed,"hitGraphEnabled",!0,(0,Cce.getBooleanValidator)());var K0={};Object.defineProperty(K0,"__esModule",{value:!0}),K0.FastLayer=void 0;const kce=Un,Oce=ap,$ce=$t;class hw extends Oce.Layer{constructor(e){super(e),this.listening(!1),kce.Util.warn('Konva.Fast layer is deprecated. Please use "new Konva.Layer({ listening: false })" instead.')}}K0.FastLayer=hw,hw.prototype.nodeType="FastLayer",(0,$ce._registerNode)(hw);var td={};Object.defineProperty(td,"__esModule",{value:!0}),td.Group=void 0;const Dce=Un,Pce=Vu,Fce=$t;class fw extends Pce.Container{_validateAdd(e){const t=e.getType();t!=="Group"&&t!=="Shape"&&Dce.Util.throw("You may only add groups and shapes to groups.")}}td.Group=fw,fw.prototype.nodeType="Group",(0,Fce._registerNode)(fw);var nd={};Object.defineProperty(nd,"__esModule",{value:!0}),nd.Animation=void 0;const pw=$t,_$=Un,mw=function(){return pw.glob.performance&&pw.glob.performance.now?function(){return pw.glob.performance.now()}:function(){return new Date().getTime()}}();class La{constructor(e,t){this.id=La.animIdCounter++,this.frame={time:0,timeDiff:0,lastTime:mw(),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,n=t.length;for(let i=0;i<n;i++)if(t[i]._id===e._id)return!1;return this.layers.push(e),!0}isRunning(){const t=La.animations,n=t.length;for(let i=0;i<n;i++)if(t[i].id===this.id)return!0;return!1}start(){return this.stop(),this.frame.timeDiff=0,this.frame.lastTime=mw(),La._addAnimation(this),this}stop(){return La._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,n=this.animations,i=n.length;for(let s=0;s<i;s++)if(n[s].id===t){this.animations.splice(s,1);break}}static _runFrames(){const e={},t=this.animations;for(let n=0;n<t.length;n++){const i=t[n],s=i.layers,a=i.func;i._updateFrameObject(mw());const o=s.length;let u;if(a?u=a.call(i,i.frame)!==!1:u=!0,!!u)for(let c=0;c<o;c++){const d=s[c];d._id!==void 0&&(e[d._id]=d)}}for(const n in e)e.hasOwnProperty(n)&&e[n].batchDraw()}static _animationLoop(){const e=La;e.animations.length?(e._runFrames(),_$.Util.requestAnimFrame(e._animationLoop)):e.animRunning=!1}static _handleAnimation(){this.animRunning||(this.animRunning=!0,_$.Util.requestAnimFrame(this._animationLoop))}}nd.Animation=La,La.animations=[],La.animIdCounter=0,La.animRunning=!1;var y$={};(function(r){Object.defineProperty(r,"__esModule",{value:!0}),r.Easings=r.Tween=void 0;const e=Un,t=nd,n=Mn,i=$t;let s={node:1,duration:1,easing:1,onFinish:1,yoyo:1},a=1,o=2,u=3,c=0,d=["fill","stroke","shadowColor"];class p{constructor(y,b,S,w,x,E,I){this.prop=y,this.propFunc=b,this.begin=w,this._pos=w,this.duration=E,this._change=0,this.prevPos=0,this.yoyo=I,this._time=0,this._position=0,this._startTime=0,this._finish=0,this.func=S,this._change=x-this.begin,this.pause()}fire(y){const b=this[y];b&&b()}setTime(y){y>this.duration?this.yoyo?(this._time=this.duration,this.reverse()):this.finish():y<0?this.yoyo?(this._time=0,this.play()):this.reset():(this._time=y,this.update())}getTime(){return this._time}setPosition(y){this.prevPos=this._pos,this.propFunc(y),this._pos=y}getPosition(y){return y===void 0&&(y=this._time),this.func(y,this.begin,this._change,this.duration)}play(){this.state=o,this._startTime=this.getTimer()-this._time,this.onEnterFrame(),this.fire("onPlay")}reverse(){this.state=u,this._time=this.duration-this._time,this._startTime=this.getTimer()-this._time,this.onEnterFrame(),this.fire("onReverse")}seek(y){this.pause(),this._time=y,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 y=this.getTimer()-this._startTime;this.state===o?this.setTime(y):this.state===u&&this.setTime(this.duration-y)}pause(){this.state=a,this.fire("onPause")}getTimer(){return new Date().getTime()}}class m{constructor(y){let b=this,S=y.node,w=S._id,x,E=y.easing||r.Easings.Linear,I=!!y.yoyo,R;typeof y.duration>"u"?x=.3:y.duration===0?x=.001:x=y.duration,this.node=S,this._id=c++;const P=S.getLayer()||(S instanceof i.Konva.Stage?S.getLayers():null);P||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(){b.tween.onEnterFrame()},P),this.tween=new p(R,function(B){b._tweenFunc(B)},E,0,1,x*1e3,I),this._addListeners(),m.attrs[w]||(m.attrs[w]={}),m.attrs[w][this._id]||(m.attrs[w][this._id]={}),m.tweens[w]||(m.tweens[w]={});for(R in y)s[R]===void 0&&this._addAttr(R,y[R]);this.reset(),this.onFinish=y.onFinish,this.onReset=y.onReset,this.onUpdate=y.onUpdate}_addAttr(y,b){let S=this.node,w=S._id,x,E,I,R,P,B,O,F;if(I=m.tweens[w][y],I&&delete m.attrs[w][I][y],x=S.getAttr(y),e.Util._isArray(b))if(E=[],P=Math.max(b.length,x.length),y==="points"&&b.length!==x.length&&(b.length>x.length?(O=x,x=e.Util._prepareArrayForTween(x,b,S.closed())):(B=b,b=e.Util._prepareArrayForTween(b,x,S.closed()))),y.indexOf("fill")===0)for(R=0;R<P;R++)if(R%2===0)E.push(b[R]-x[R]);else{const D=e.Util.colorToRGBA(x[R]);F=e.Util.colorToRGBA(b[R]),x[R]=D,E.push({r:F.r-D.r,g:F.g-D.g,b:F.b-D.b,a:F.a-D.a})}else for(R=0;R<P;R++)E.push(b[R]-x[R]);else d.indexOf(y)!==-1?(x=e.Util.colorToRGBA(x),F=e.Util.colorToRGBA(b),E={r:F.r-x.r,g:F.g-x.g,b:F.b-x.b,a:F.a-x.a}):E=b-x;m.attrs[w][this._id][y]={start:x,diff:E,end:b,trueEnd:B,trueStart:O},m.tweens[w][y]=this._id}_tweenFunc(y){let b=this.node,S=m.attrs[b._id][this._id],w,x,E,I,R,P,B,O;for(w in S){if(x=S[w],E=x.start,I=x.diff,O=x.end,e.Util._isArray(E))if(R=[],B=Math.max(E.length,O.length),w.indexOf("fill")===0)for(P=0;P<B;P++)P%2===0?R.push((E[P]||0)+I[P]*y):R.push("rgba("+Math.round(E[P].r+I[P].r*y)+","+Math.round(E[P].g+I[P].g*y)+","+Math.round(E[P].b+I[P].b*y)+","+(E[P].a+I[P].a*y)+")");else for(P=0;P<B;P++)R.push((E[P]||0)+I[P]*y);else d.indexOf(w)!==-1?R="rgba("+Math.round(E.r+I.r*y)+","+Math.round(E.g+I.g*y)+","+Math.round(E.b+I.b*y)+","+(E.a+I.a*y)+")":R=E+I*y;b.setAttr(w,R)}}_addListeners(){this.tween.onPlay=()=>{this.anim.start()},this.tween.onReverse=()=>{this.anim.start()},this.tween.onPause=()=>{this.anim.stop()},this.tween.onFinish=()=>{const y=this.node,b=m.attrs[y._id][this._id];b.points&&b.points.trueEnd&&y.setAttr("points",b.points.trueEnd),this.onFinish&&this.onFinish.call(this)},this.tween.onReset=()=>{const y=this.node,b=m.attrs[y._id][this._id];b.points&&b.points.trueStart&&y.points(b.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(y){return this.tween.seek(y*1e3),this}pause(){return this.tween.pause(),this}finish(){return this.tween.finish(),this}destroy(){let y=this.node._id,b=this._id,S=m.tweens[y],w;this.pause();for(w in S)delete m.tweens[y][w];delete m.attrs[y][b]}}r.Tween=m,m.attrs={},m.tweens={},n.Node.prototype.to=function(_){const y=_.onFinish;_.node=this,_.onFinish=function(){this.destroy(),y&&y()},new m(_).play()},r.Easings={BackEaseIn(_,y,b,S){return b*(_/=S)*_*(2.70158*_-1.70158)+y},BackEaseOut(_,y,b,S){return b*((_=_/S-1)*_*(2.70158*_+1.70158)+1)+y},BackEaseInOut(_,y,b,S){let w=1.70158;return(_/=S/2)<1?b/2*(_*_*(((w*=1.525)+1)*_-w))+y:b/2*((_-=2)*_*(((w*=1.525)+1)*_+w)+2)+y},ElasticEaseIn(_,y,b,S,w,x){let E=0;return _===0?y:(_/=S)===1?y+b:(x||(x=S*.3),!w||w<Math.abs(b)?(w=b,E=x/4):E=x/(2*Math.PI)*Math.asin(b/w),-(w*Math.pow(2,10*(_-=1))*Math.sin((_*S-E)*(2*Math.PI)/x))+y)},ElasticEaseOut(_,y,b,S,w,x){let E=0;return _===0?y:(_/=S)===1?y+b:(x||(x=S*.3),!w||w<Math.abs(b)?(w=b,E=x/4):E=x/(2*Math.PI)*Math.asin(b/w),w*Math.pow(2,-10*_)*Math.sin((_*S-E)*(2*Math.PI)/x)+b+y)},ElasticEaseInOut(_,y,b,S,w,x){let E=0;return _===0?y:(_/=S/2)===2?y+b:(x||(x=S*.44999999999999996),!w||w<Math.abs(b)?(w=b,E=x/4):E=x/(2*Math.PI)*Math.asin(b/w),_<1?-.5*(w*Math.pow(2,10*(_-=1))*Math.sin((_*S-E)*(2*Math.PI)/x))+y:w*Math.pow(2,-10*(_-=1))*Math.sin((_*S-E)*(2*Math.PI)/x)*.5+b+y)},BounceEaseOut(_,y,b,S){return(_/=S)<.36363636363636365?b*(7.5625*_*_)+y:_<.7272727272727273?b*(7.5625*(_-=.5454545454545454)*_+.75)+y:_<.9090909090909091?b*(7.5625*(_-=.8181818181818182)*_+.9375)+y:b*(7.5625*(_-=.9545454545454546)*_+.984375)+y},BounceEaseIn(_,y,b,S){return b-r.Easings.BounceEaseOut(S-_,0,b,S)+y},BounceEaseInOut(_,y,b,S){return _<S/2?r.Easings.BounceEaseIn(_*2,0,b,S)*.5+y:r.Easings.BounceEaseOut(_*2-S,0,b,S)*.5+b*.5+y},EaseIn(_,y,b,S){return b*(_/=S)*_+y},EaseOut(_,y,b,S){return-b*(_/=S)*(_-2)+y},EaseInOut(_,y,b,S){return(_/=S/2)<1?b/2*_*_+y:-b/2*(--_*(_-2)-1)+y},StrongEaseIn(_,y,b,S){return b*(_/=S)*_*_*_*_+y},StrongEaseOut(_,y,b,S){return b*((_=_/S-1)*_*_*_*_+1)+y},StrongEaseInOut(_,y,b,S){return(_/=S/2)<1?b/2*_*_*_*_*_+y:b/2*((_-=2)*_*_*_*_+2)+y},Linear(_,y,b,S){return b*_/S+y}}})(y$),function(r){Object.defineProperty(r,"__esModule",{value:!0}),r.Konva=void 0;const e=$t,t=Un,n=Mn,i=Vu,s=h$,a=ap,o=K0,u=td,c=G0,d=vs,p=nd,m=y$,_=wo,y=ia;r.Konva=t.Util._assign(e.Konva,{Util:t.Util,Transform:t.Transform,Node:n.Node,Container:i.Container,Stage:s.Stage,stages:s.stages,Layer:a.Layer,FastLayer:o.FastLayer,Group:u.Group,DD:c.DD,Shape:d.Shape,shapes:d.shapes,Animation:p.Animation,Tween:m.Tween,Easings:m.Easings,Context:_.Context,Canvas:y.Canvas}),r.default=r.Konva}(e$);var X0={};Object.defineProperty(X0,"__esModule",{value:!0}),X0.Arc=void 0;const Y0=Dt,Mce=vs,v$=$t,J0=Ct,Lce=$t;class xo extends Mce.Shape{_sceneFunc(e){const t=v$.Konva.getAngle(this.angle()),n=this.clockwise();e.beginPath(),e.arc(0,0,this.outerRadius(),0,t,n),e.arc(0,0,this.innerRadius(),t,0,!n),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(),n=this.clockwise(),i=v$.Konva.getAngle(n?360-this.angle():this.angle()),s=Math.cos(Math.min(i,Math.PI)),a=1,o=Math.sin(Math.min(Math.max(Math.PI,i),3*Math.PI/2)),u=Math.sin(Math.min(i,Math.PI/2)),c=s*(s>0?e:t),d=a*t,p=o*(o>0?e:t),m=u*(u>0?t:e);return{x:c,y:n?-1*m:p,width:d-c,height:m-p}}}X0.Arc=xo,xo.prototype._centroid=!0,xo.prototype.className="Arc",xo.prototype._attrsAffectingSize=["innerRadius","outerRadius"],(0,Lce._registerNode)(xo),Y0.Factory.addGetterSetter(xo,"innerRadius",0,(0,J0.getNumberValidator)()),Y0.Factory.addGetterSetter(xo,"outerRadius",0,(0,J0.getNumberValidator)()),Y0.Factory.addGetterSetter(xo,"angle",0,(0,J0.getNumberValidator)()),Y0.Factory.addGetterSetter(xo,"clockwise",!1,(0,J0.getBooleanValidator)());var Q0={},op={};Object.defineProperty(op,"__esModule",{value:!0}),op.Line=void 0;const Z0=Dt,Uce=$t,Bce=vs,b$=Ct;function gw(r,e,t,n,i,s,a){const o=Math.sqrt(Math.pow(t-r,2)+Math.pow(n-e,2)),u=Math.sqrt(Math.pow(i-t,2)+Math.pow(s-n,2)),c=a*o/(o+u),d=a*u/(o+u),p=t-c*(i-r),m=n-c*(s-e),_=t+d*(i-r),y=n+d*(s-e);return[p,m,_,y]}function S$(r,e){const t=r.length,n=[];for(let i=2;i<t-2;i+=2){const s=gw(r[i-2],r[i-1],r[i],r[i+1],r[i+2],r[i+3],e);isNaN(s[0])||(n.push(s[0]),n.push(s[1]),n.push(r[i]),n.push(r[i+1]),n.push(s[2]),n.push(s[3]))}return n}class Al extends Bce.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(),n=t.length,i=this.tension(),s=this.closed(),a=this.bezier(),o,u,c;if(n){if(e.beginPath(),e.moveTo(t[0],t[1]),i!==0&&n>4){for(o=this.getTensionPoints(),u=o.length,c=s?0:4,s||e.quadraticCurveTo(o[0],o[1],o[2],o[3]);c<u-2;)e.bezierCurveTo(o[c++],o[c++],o[c++],o[c++],o[c++],o[c++]);s||e.quadraticCurveTo(o[u-2],o[u-1],t[n-2],t[n-1])}else if(a)for(c=2;c<n;)e.bezierCurveTo(t[c++],t[c++],t[c++],t[c++],t[c++],t[c++]);else for(c=2;c<n;c+=2)e.lineTo(t[c],t[c+1]);s?(e.closePath(),e.fillStrokeShape(this)):e.strokeShape(this)}}getTensionPoints(){return this._getCache("tensionPoints",this._getTensionPoints)}_getTensionPoints(){return this.closed()?this._getTensionPointsClosed():S$(this.points(),this.tension())}_getTensionPointsClosed(){const e=this.points(),t=e.length,n=this.tension(),i=gw(e[t-2],e[t-1],e[0],e[1],e[2],e[3],n),s=gw(e[t-4],e[t-3],e[t-2],e[t-1],e[0],e[1],n),a=S$(e,n);return[i[2],i[3]].concat(a).concat([s[0],s[1],e[t-2],e[t-1],s[2],s[3],i[0],i[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],n=e[0],i=e[1],s=e[1],a,o;for(let u=0;u<e.length/2;u++)a=e[u*2],o=e[u*2+1],t=Math.min(t,a),n=Math.max(n,a),i=Math.min(i,o),s=Math.max(s,o);return{x:t,y:i,width:n-t,height:s-i}}}op.Line=Al,Al.prototype.className="Line",Al.prototype._attrsAffectingSize=["points","bezier","tension"],(0,Uce._registerNode)(Al),Z0.Factory.addGetterSetter(Al,"closed",!1),Z0.Factory.addGetterSetter(Al,"bezier",!1),Z0.Factory.addGetterSetter(Al,"tension",0,(0,b$.getNumberValidator)()),Z0.Factory.addGetterSetter(Al,"points",[],(0,b$.getNumberArrayValidator)());var sd={},T$={};(function(r){Object.defineProperty(r,"__esModule",{value:!0}),r.t2length=r.getQuadraticArcLength=r.getCubicArcLength=r.binomialCoefficients=r.cValues=r.tValues=void 0,r.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]],r.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]],r.binomialCoefficients=[[1],[1,1],[1,2,1],[1,3,3,1]];const e=(a,o,u)=>{let c,d;const m=u/2;c=0;for(let _=0;_<20;_++)d=m*r.tValues[20][_]+m,c+=r.cValues[20][_]*n(a,o,d);return m*c};r.getCubicArcLength=e;const t=(a,o,u)=>{u===void 0&&(u=1);const c=a[0]-2*a[1]+a[2],d=o[0]-2*o[1]+o[2],p=2*a[1]-2*a[0],m=2*o[1]-2*o[0],_=4*(c*c+d*d),y=4*(c*p+d*m),b=p*p+m*m;if(_===0)return u*Math.sqrt(Math.pow(a[2]-a[0],2)+Math.pow(o[2]-o[0],2));const S=y/(2*_),w=b/_,x=u+S,E=w-S*S,I=x*x+E>0?Math.sqrt(x*x+E):0,R=S*S+E>0?Math.sqrt(S*S+E):0,P=S+Math.sqrt(S*S+E)!==0?E*Math.log(Math.abs((x+I)/(S+R))):0;return Math.sqrt(_)/2*(x*I-S*R+P)};r.getQuadraticArcLength=t;function n(a,o,u){const c=i(1,u,a),d=i(1,u,o),p=c*c+d*d;return Math.sqrt(p)}const i=(a,o,u)=>{const c=u.length-1;let d,p;if(c===0)return 0;if(a===0){p=0;for(let m=0;m<=c;m++)p+=r.binomialCoefficients[c][m]*Math.pow(1-o,c-m)*Math.pow(o,m)*u[m];return p}else{d=new Array(c);for(let m=0;m<c;m++)d[m]=c*(u[m+1]-u[m]);return i(a-1,o,d)}},s=(a,o,u)=>{let c=1,d=a/o,p=(a-u(d))/o,m=0;for(;c>.001;){const _=u(d+p),y=Math.abs(a-_)/o;if(y<c)c=y,d+=p;else{const b=u(d-p),S=Math.abs(a-b)/o;S<c?(c=S,d-=p):p/=2}if(m++,m>500)break}return d};r.t2length=s})(T$),Object.defineProperty(sd,"__esModule",{value:!0}),sd.Path=void 0;const Hce=Dt,Vce=vs,Gce=$t,rd=T$;class bs extends Vce.Shape{constructor(e){super(e),this.dataArray=[],this.pathLength=0,this._readDataAttribute(),this.on("dataChange.konva",function(){this._readDataAttribute()})}_readDataAttribute(){this.dataArray=bs.parsePathData(this.data()),this.pathLength=bs.getPathLength(this.dataArray)}_sceneFunc(e){const t=this.dataArray;e.beginPath();let n=!1;for(let b=0;b<t.length;b++){const S=t[b].command,w=t[b].points;switch(S){case"L":e.lineTo(w[0],w[1]);break;case"M":e.moveTo(w[0],w[1]);break;case"C":e.bezierCurveTo(w[0],w[1],w[2],w[3],w[4],w[5]);break;case"Q":e.quadraticCurveTo(w[0],w[1],w[2],w[3]);break;case"A":var i=w[0],s=w[1],a=w[2],o=w[3],u=w[4],c=w[5],d=w[6],p=w[7],m=a>o?a:o,_=a>o?1:a/o,y=a>o?o/a:1;e.translate(i,s),e.rotate(d),e.scale(_,y),e.arc(0,0,m,u,u+c,1-p),e.scale(1/_,1/y),e.rotate(-d),e.translate(-i,-s);break;case"z":n=!0,e.closePath();break}}!n&&!this.hasFill()?e.strokeShape(this):e.fillStrokeShape(this)}getSelfRect(){let e=[];this.dataArray.forEach(function(u){if(u.command==="A"){const c=u.points[4],d=u.points[5],p=u.points[4]+d;let m=Math.PI/180;if(Math.abs(c-p)<m&&(m=Math.abs(c-p)),d<0)for(let _=c-m;_>p;_-=m){const y=bs.getPointOnEllipticalArc(u.points[0],u.points[1],u.points[2],u.points[3],_,0);e.push(y.x,y.y)}else for(let _=c+m;_<p;_+=m){const y=bs.getPointOnEllipticalArc(u.points[0],u.points[1],u.points[2],u.points[3],_,0);e.push(y.x,y.y)}}else if(u.command==="C")for(let c=0;c<=1;c+=.01){const d=bs.getPointOnCubicBezier(c,u.start.x,u.start.y,u.points[0],u.points[1],u.points[2],u.points[3],u.points[4],u.points[5]);e.push(d.x,d.y)}else e=e.concat(u.points)});let t=e[0],n=e[0],i=e[1],s=e[1],a,o;for(let u=0;u<e.length/2;u++)a=e[u*2],o=e[u*2+1],isNaN(a)||(t=Math.min(t,a),n=Math.max(n,a)),isNaN(o)||(i=Math.min(i,o),s=Math.max(s,o));return{x:t,y:i,width:n-t,height:s-i}}getLength(){return this.pathLength}getPointAtLength(e){return bs.getPointAtLengthOfDataArray(e,this.dataArray)}static getLineLength(e,t,n,i){return Math.sqrt((n-e)*(n-e)+(i-t)*(i-t))}static getPathLength(e){let t=0;for(let n=0;n<e.length;++n)t+=e[n].pathLength;return t}static getPointAtLengthOfDataArray(e,t){let n,i=0,s=t.length;if(!s)return null;for(;i<s&&e>t[i].pathLength;)e-=t[i].pathLength,++i;if(i===s)return n=t[i-1].points.slice(-2),{x:n[0],y:n[1]};if(e<.01)return n=t[i].points.slice(0,2),{x:n[0],y:n[1]};const a=t[i],o=a.points;switch(a.command){case"L":return bs.getPointOnLine(e,a.start.x,a.start.y,o[0],o[1]);case"C":return bs.getPointOnCubicBezier((0,rd.t2length)(e,bs.getPathLength(t),b=>(0,rd.getCubicArcLength)([a.start.x,o[0],o[2],o[4]],[a.start.y,o[1],o[3],o[5]],b)),a.start.x,a.start.y,o[0],o[1],o[2],o[3],o[4],o[5]);case"Q":return bs.getPointOnQuadraticBezier((0,rd.t2length)(e,bs.getPathLength(t),b=>(0,rd.getQuadraticArcLength)([a.start.x,o[0],o[2]],[a.start.y,o[1],o[3]],b)),a.start.x,a.start.y,o[0],o[1],o[2],o[3]);case"A":var u=o[0],c=o[1],d=o[2],p=o[3],m=o[4],_=o[5],y=o[6];return m+=_*e/a.pathLength,bs.getPointOnEllipticalArc(u,c,d,p,m,y)}return null}static getPointOnLine(e,t,n,i,s,a,o){a=a??t,o=o??n;const u=this.getLineLength(t,n,i,s);if(u<1e-10)return{x:t,y:n};if(i===t)return{x:a,y:o+(s>n?e:-e)};const c=(s-n)/(i-t),d=Math.sqrt(e*e/(1+c*c))*(i<t?-1:1),p=c*d;if(Math.abs(o-n-c*(a-t))<1e-10)return{x:a+d,y:o+p};const m=((a-t)*(i-t)+(o-n)*(s-n))/(u*u),_=t+m*(i-t),y=n+m*(s-n),b=this.getLineLength(a,o,_,y),S=Math.sqrt(e*e-b*b),w=Math.sqrt(S*S/(1+c*c))*(i<t?-1:1),x=c*w;return{x:_+w,y:y+x}}static getPointOnCubicBezier(e,t,n,i,s,a,o,u,c){function d(S){return S*S*S}function p(S){return 3*S*S*(1-S)}function m(S){return 3*S*(1-S)*(1-S)}function _(S){return(1-S)*(1-S)*(1-S)}const y=u*d(e)+a*p(e)+i*m(e)+t*_(e),b=c*d(e)+o*p(e)+s*m(e)+n*_(e);return{x:y,y:b}}static getPointOnQuadraticBezier(e,t,n,i,s,a,o){function u(_){return _*_}function c(_){return 2*_*(1-_)}function d(_){return(1-_)*(1-_)}const p=a*u(e)+i*c(e)+t*d(e),m=o*u(e)+s*c(e)+n*d(e);return{x:p,y:m}}static getPointOnEllipticalArc(e,t,n,i,s,a){const o=Math.cos(a),u=Math.sin(a),c={x:n*Math.cos(s),y:i*Math.sin(s)};return{x:e+(c.x*o-c.y*u),y:t+(c.x*u+c.y*o)}}static parsePathData(e){if(!e)return[];let t=e;const n=["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 i=0;i<n.length;i++)t=t.replace(new RegExp(n[i],"g"),"|"+n[i]);const s=t.split("|"),a=[],o=[];let u=0,c=0;const d=/([-+]?((\d+\.\d+)|((\d+)|(\.\d+)))(?:e[-+]?\d+)?)/gi;let p;for(i=1;i<s.length;i++){let O=s[i],F=O.charAt(0);for(O=O.slice(1),o.length=0;p=d.exec(O);)o.push(p[0]);const D=[];for(let L=0,G=o.length;L<G;L++){if(o[L]==="00"){D.push(0,0);continue}const j=parseFloat(o[L]);isNaN(j)?D.push(0):D.push(j)}for(;D.length>0&&!isNaN(D[0]);){let L="",G=[];const j=u,te=c;var m,_,y,b,S,w,x,E,I,R;switch(F){case"l":u+=D.shift(),c+=D.shift(),L="L",G.push(u,c);break;case"L":u=D.shift(),c=D.shift(),G.push(u,c);break;case"m":var P=D.shift(),B=D.shift();if(u+=P,c+=B,L="M",a.length>2&&a[a.length-1].command==="z"){for(let W=a.length-2;W>=0;W--)if(a[W].command==="M"){u=a[W].points[0]+P,c=a[W].points[1]+B;break}}G.push(u,c),F="l";break;case"M":u=D.shift(),c=D.shift(),L="M",G.push(u,c),F="L";break;case"h":u+=D.shift(),L="L",G.push(u,c);break;case"H":u=D.shift(),L="L",G.push(u,c);break;case"v":c+=D.shift(),L="L",G.push(u,c);break;case"V":c=D.shift(),L="L",G.push(u,c);break;case"C":G.push(D.shift(),D.shift(),D.shift(),D.shift()),u=D.shift(),c=D.shift(),G.push(u,c);break;case"c":G.push(u+D.shift(),c+D.shift(),u+D.shift(),c+D.shift()),u+=D.shift(),c+=D.shift(),L="C",G.push(u,c);break;case"S":_=u,y=c,m=a[a.length-1],m.command==="C"&&(_=u+(u-m.points[2]),y=c+(c-m.points[3])),G.push(_,y,D.shift(),D.shift()),u=D.shift(),c=D.shift(),L="C",G.push(u,c);break;case"s":_=u,y=c,m=a[a.length-1],m.command==="C"&&(_=u+(u-m.points[2]),y=c+(c-m.points[3])),G.push(_,y,u+D.shift(),c+D.shift()),u+=D.shift(),c+=D.shift(),L="C",G.push(u,c);break;case"Q":G.push(D.shift(),D.shift()),u=D.shift(),c=D.shift(),G.push(u,c);break;case"q":G.push(u+D.shift(),c+D.shift()),u+=D.shift(),c+=D.shift(),L="Q",G.push(u,c);break;case"T":_=u,y=c,m=a[a.length-1],m.command==="Q"&&(_=u+(u-m.points[0]),y=c+(c-m.points[1])),u=D.shift(),c=D.shift(),L="Q",G.push(_,y,u,c);break;case"t":_=u,y=c,m=a[a.length-1],m.command==="Q"&&(_=u+(u-m.points[0]),y=c+(c-m.points[1])),u+=D.shift(),c+=D.shift(),L="Q",G.push(_,y,u,c);break;case"A":b=D.shift(),S=D.shift(),w=D.shift(),x=D.shift(),E=D.shift(),I=u,R=c,u=D.shift(),c=D.shift(),L="A",G=this.convertEndpointToCenterParameterization(I,R,u,c,x,E,b,S,w);break;case"a":b=D.shift(),S=D.shift(),w=D.shift(),x=D.shift(),E=D.shift(),I=u,R=c,u+=D.shift(),c+=D.shift(),L="A",G=this.convertEndpointToCenterParameterization(I,R,u,c,x,E,b,S,w);break}a.push({command:L||F,points:G,start:{x:j,y:te},pathLength:this.calcLength(j,te,L||F,G)})}(F==="z"||F==="Z")&&a.push({command:"z",points:[],start:void 0,pathLength:0})}return a}static calcLength(e,t,n,i){let s,a,o,u;const c=bs;switch(n){case"L":return c.getLineLength(e,t,i[0],i[1]);case"C":return(0,rd.getCubicArcLength)([e,i[0],i[2],i[4]],[t,i[1],i[3],i[5]],1);case"Q":return(0,rd.getQuadraticArcLength)([e,i[0],i[2]],[t,i[1],i[3]],1);case"A":s=0;var d=i[4],p=i[5],m=i[4]+p,_=Math.PI/180;if(Math.abs(d-m)<_&&(_=Math.abs(d-m)),a=c.getPointOnEllipticalArc(i[0],i[1],i[2],i[3],d,0),p<0)for(u=d-_;u>m;u-=_)o=c.getPointOnEllipticalArc(i[0],i[1],i[2],i[3],u,0),s+=c.getLineLength(a.x,a.y,o.x,o.y),a=o;else for(u=d+_;u<m;u+=_)o=c.getPointOnEllipticalArc(i[0],i[1],i[2],i[3],u,0),s+=c.getLineLength(a.x,a.y,o.x,o.y),a=o;return o=c.getPointOnEllipticalArc(i[0],i[1],i[2],i[3],m,0),s+=c.getLineLength(a.x,a.y,o.x,o.y),s}return 0}static convertEndpointToCenterParameterization(e,t,n,i,s,a,o,u,c){const d=c*(Math.PI/180),p=Math.cos(d)*(e-n)/2+Math.sin(d)*(t-i)/2,m=-1*Math.sin(d)*(e-n)/2+Math.cos(d)*(t-i)/2,_=p*p/(o*o)+m*m/(u*u);_>1&&(o*=Math.sqrt(_),u*=Math.sqrt(_));let y=Math.sqrt((o*o*(u*u)-o*o*(m*m)-u*u*(p*p))/(o*o*(m*m)+u*u*(p*p)));s===a&&(y*=-1),isNaN(y)&&(y=0);const b=y*o*m/u,S=y*-u*p/o,w=(e+n)/2+Math.cos(d)*b-Math.sin(d)*S,x=(t+i)/2+Math.sin(d)*b+Math.cos(d)*S,E=function(D){return Math.sqrt(D[0]*D[0]+D[1]*D[1])},I=function(D,L){return(D[0]*L[0]+D[1]*L[1])/(E(D)*E(L))},R=function(D,L){return(D[0]*L[1]<D[1]*L[0]?-1:1)*Math.acos(I(D,L))},P=R([1,0],[(p-b)/o,(m-S)/u]),B=[(p-b)/o,(m-S)/u],O=[(-1*p-b)/o,(-1*m-S)/u];let F=R(B,O);return I(B,O)<=-1&&(F=Math.PI),I(B,O)>=1&&(F=0),a===0&&F>0&&(F=F-2*Math.PI),a===1&&F<0&&(F=F+2*Math.PI),[w,x,o,u,P,F,d,a]}}sd.Path=bs,bs.prototype.className="Path",bs.prototype._attrsAffectingSize=["data"],(0,Gce._registerNode)(bs),Hce.Factory.addGetterSetter(bs,"data"),Object.defineProperty(Q0,"__esModule",{value:!0}),Q0.Arrow=void 0;const ey=Dt,Wce=op,w$=Ct,zce=$t,C$=sd;class Wu extends Wce.Line{_sceneFunc(e){super._sceneFunc(e);const t=Math.PI*2,n=this.points();let i=n;const s=this.tension()!==0&&n.length>4;s&&(i=this.getTensionPoints());const a=this.pointerLength(),o=n.length;let u,c;if(s){const m=[i[i.length-4],i[i.length-3],i[i.length-2],i[i.length-1],n[o-2],n[o-1]],_=C$.Path.calcLength(i[i.length-4],i[i.length-3],"C",m),y=C$.Path.getPointOnQuadraticBezier(Math.min(1,1-a/_),m[0],m[1],m[2],m[3],m[4],m[5]);u=n[o-2]-y.x,c=n[o-1]-y.y}else u=n[o-2]-n[o-4],c=n[o-1]-n[o-3];const d=(Math.atan2(c,u)+t)%t,p=this.pointerWidth();this.pointerAtEnding()&&(e.save(),e.beginPath(),e.translate(n[o-2],n[o-1]),e.rotate(d),e.moveTo(0,0),e.lineTo(-a,p/2),e.lineTo(-a,-p/2),e.closePath(),e.restore(),this.__fillStroke(e)),this.pointerAtBeginning()&&(e.save(),e.beginPath(),e.translate(n[0],n[1]),s?(u=(i[0]+i[2])/2-n[0],c=(i[1]+i[3])/2-n[1]):(u=n[2]-n[0],c=n[3]-n[1]),e.rotate((Math.atan2(-c,-u)+t)%t),e.moveTo(0,0),e.lineTo(-a,p/2),e.lineTo(-a,-p/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}}}Q0.Arrow=Wu,Wu.prototype.className="Arrow",(0,zce._registerNode)(Wu),ey.Factory.addGetterSetter(Wu,"pointerLength",10,(0,w$.getNumberValidator)()),ey.Factory.addGetterSetter(Wu,"pointerWidth",10,(0,w$.getNumberValidator)()),ey.Factory.addGetterSetter(Wu,"pointerAtBeginning",!1),ey.Factory.addGetterSetter(Wu,"pointerAtEnding",!0);var ty={};Object.defineProperty(ty,"__esModule",{value:!0}),ty.Circle=void 0;const jce=Dt,qce=vs,Kce=Ct,Xce=$t;class id extends qce.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)}}ty.Circle=id,id.prototype._centroid=!0,id.prototype.className="Circle",id.prototype._attrsAffectingSize=["radius"],(0,Xce._registerNode)(id),jce.Factory.addGetterSetter(id,"radius",0,(0,Kce.getNumberValidator)());var ny={};Object.defineProperty(ny,"__esModule",{value:!0}),ny.Ellipse=void 0;const _w=Dt,Yce=vs,E$=Ct,Jce=$t;class Rl extends Yce.Shape{_sceneFunc(e){const t=this.radiusX(),n=this.radiusY();e.beginPath(),e.save(),t!==n&&e.scale(1,n/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)}}ny.Ellipse=Rl,Rl.prototype.className="Ellipse",Rl.prototype._centroid=!0,Rl.prototype._attrsAffectingSize=["radiusX","radiusY"],(0,Jce._registerNode)(Rl),_w.Factory.addComponentsGetterSetter(Rl,"radius",["x","y"]),_w.Factory.addGetterSetter(Rl,"radiusX",0,(0,E$.getNumberValidator)()),_w.Factory.addGetterSetter(Rl,"radiusY",0,(0,E$.getNumberValidator)());var sy={};Object.defineProperty(sy,"__esModule",{value:!0}),sy.Image=void 0;const yw=Un,zu=Dt,Qce=vs,Zce=$t,lp=Ct;let Ua=class $4 extends Qce.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(),n=this.getHeight(),i=this.cornerRadius(),s=this.attrs.image;let a;if(s){const o=this.attrs.cropWidth,u=this.attrs.cropHeight;o&&u?a=[s,this.cropX(),this.cropY(),o,u,0,0,t,n]:a=[s,0,0,t,n]}(this.hasFill()||this.hasStroke()||i)&&(e.beginPath(),i?yw.Util.drawRoundedRectPath(e,t,n,i):e.rect(0,0,t,n),e.closePath(),e.fillStrokeShape(this)),s&&(i&&e.clip(),e.drawImage.apply(e,a))}_hitFunc(e){const t=this.width(),n=this.height(),i=this.cornerRadius();e.beginPath(),i?yw.Util.drawRoundedRectPath(e,t,n,i):e.rect(0,0,t,n),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,n=null){const i=yw.Util.createImageElement();i.onload=function(){const s=new $4({image:i});t(s)},i.onerror=n,i.crossOrigin="Anonymous",i.src=e}};sy.Image=Ua,Ua.prototype.className="Image",(0,Zce._registerNode)(Ua),zu.Factory.addGetterSetter(Ua,"cornerRadius",0,(0,lp.getNumberOrArrayOfNumbersValidator)(4)),zu.Factory.addGetterSetter(Ua,"image"),zu.Factory.addComponentsGetterSetter(Ua,"crop",["x","y","width","height"]),zu.Factory.addGetterSetter(Ua,"cropX",0,(0,lp.getNumberValidator)()),zu.Factory.addGetterSetter(Ua,"cropY",0,(0,lp.getNumberValidator)()),zu.Factory.addGetterSetter(Ua,"cropWidth",0,(0,lp.getNumberValidator)()),zu.Factory.addGetterSetter(Ua,"cropHeight",0,(0,lp.getNumberValidator)());var ad={};Object.defineProperty(ad,"__esModule",{value:!0}),ad.Tag=ad.Label=void 0;const ry=Dt,ede=vs,tde=td,vw=Ct,x$=$t,I$=["fontFamily","fontSize","fontStyle","padding","lineHeight","text","width","height","pointerDirection","pointerWidth","pointerHeight"],nde="Change.konva",sde="none",bw="up",Sw="right",Tw="down",ww="left",rde=I$.length;class Cw extends tde.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,n;const i=function(){t._sync()};for(n=0;n<rde;n++)e.on(I$[n]+nde,i)}getWidth(){return this.getText().width()}getHeight(){return this.getText().height()}_sync(){let e=this.getText(),t=this.getTag(),n,i,s,a,o,u,c;if(e&&t){switch(n=e.width(),i=e.height(),s=t.pointerDirection(),a=t.pointerWidth(),c=t.pointerHeight(),o=0,u=0,s){case bw:o=n/2,u=-1*c;break;case Sw:o=n+a,u=i/2;break;case Tw:o=n/2,u=i+c;break;case ww:o=-1*a,u=i/2;break}t.setAttrs({x:-1*o,y:-1*u,width:n,height:i}),e.setAttrs({x:-1*o,y:-1*u})}}}ad.Label=Cw,Cw.prototype.className="Label",(0,x$._registerNode)(Cw);class ju extends ede.Shape{_sceneFunc(e){const t=this.width(),n=this.height(),i=this.pointerDirection(),s=this.pointerWidth(),a=this.pointerHeight(),o=this.cornerRadius();let u=0,c=0,d=0,p=0;typeof o=="number"?u=c=d=p=Math.min(o,t/2,n/2):(u=Math.min(o[0]||0,t/2,n/2),c=Math.min(o[1]||0,t/2,n/2),p=Math.min(o[2]||0,t/2,n/2),d=Math.min(o[3]||0,t/2,n/2)),e.beginPath(),e.moveTo(u,0),i===bw&&(e.lineTo((t-s)/2,0),e.lineTo(t/2,-1*a),e.lineTo((t+s)/2,0)),e.lineTo(t-c,0),e.arc(t-c,c,c,Math.PI*3/2,0,!1),i===Sw&&(e.lineTo(t,(n-a)/2),e.lineTo(t+s,n/2),e.lineTo(t,(n+a)/2)),e.lineTo(t,n-p),e.arc(t-p,n-p,p,0,Math.PI/2,!1),i===Tw&&(e.lineTo((t+s)/2,n),e.lineTo(t/2,n+a),e.lineTo((t-s)/2,n)),e.lineTo(d,n),e.arc(d,n-d,d,Math.PI/2,Math.PI,!1),i===ww&&(e.lineTo(0,(n+a)/2),e.lineTo(-1*s,n/2),e.lineTo(0,(n-a)/2)),e.lineTo(0,u),e.arc(u,u,u,Math.PI,Math.PI*3/2,!1),e.closePath(),e.fillStrokeShape(this)}getSelfRect(){let e=0,t=0,n=this.pointerWidth(),i=this.pointerHeight(),s=this.pointerDirection(),a=this.width(),o=this.height();return s===bw?(t-=i,o+=i):s===Tw?o+=i:s===ww?(e-=n*1.5,a+=n):s===Sw&&(a+=n*1.5),{x:e,y:t,width:a,height:o}}}ad.Tag=ju,ju.prototype.className="Tag",(0,x$._registerNode)(ju),ry.Factory.addGetterSetter(ju,"pointerDirection",sde),ry.Factory.addGetterSetter(ju,"pointerWidth",0,(0,vw.getNumberValidator)()),ry.Factory.addGetterSetter(ju,"pointerHeight",0,(0,vw.getNumberValidator)()),ry.Factory.addGetterSetter(ju,"cornerRadius",0,(0,vw.getNumberOrArrayOfNumbersValidator)(4));var up={};Object.defineProperty(up,"__esModule",{value:!0}),up.Rect=void 0;const ide=Dt,ade=vs,ode=$t,lde=Un,ude=Ct;class iy extends ade.Shape{_sceneFunc(e){const t=this.cornerRadius(),n=this.width(),i=this.height();e.beginPath(),t?lde.Util.drawRoundedRectPath(e,n,i,t):e.rect(0,0,n,i),e.closePath(),e.fillStrokeShape(this)}}up.Rect=iy,iy.prototype.className="Rect",(0,ode._registerNode)(iy),ide.Factory.addGetterSetter(iy,"cornerRadius",0,(0,ude.getNumberOrArrayOfNumbersValidator)(4));var ay={};Object.defineProperty(ay,"__esModule",{value:!0}),ay.RegularPolygon=void 0;const A$=Dt,cde=vs,R$=Ct,dde=$t;class qu extends cde.Shape{_sceneFunc(e){const t=this._getPoints();e.beginPath(),e.moveTo(t[0].x,t[0].y);for(let n=1;n<t.length;n++)e.lineTo(t[n].x,t[n].y);e.closePath(),e.fillStrokeShape(this)}_getPoints(){const e=this.attrs.sides,t=this.attrs.radius||0,n=[];for(let i=0;i<e;i++)n.push({x:t*Math.sin(i*2*Math.PI/e),y:-1*t*Math.cos(i*2*Math.PI/e)});return n}getSelfRect(){const e=this._getPoints();let t=e[0].x,n=e[0].y,i=e[0].x,s=e[0].y;return e.forEach(a=>{t=Math.min(t,a.x),n=Math.max(n,a.x),i=Math.min(i,a.y),s=Math.max(s,a.y)}),{x:t,y:i,width:n-t,height:s-i}}getWidth(){return this.radius()*2}getHeight(){return this.radius()*2}setWidth(e){this.radius(e/2)}setHeight(e){this.radius(e/2)}}ay.RegularPolygon=qu,qu.prototype.className="RegularPolygon",qu.prototype._centroid=!0,qu.prototype._attrsAffectingSize=["radius"],(0,dde._registerNode)(qu),A$.Factory.addGetterSetter(qu,"radius",0,(0,R$.getNumberValidator)()),A$.Factory.addGetterSetter(qu,"sides",0,(0,R$.getNumberValidator)());var oy={};Object.defineProperty(oy,"__esModule",{value:!0}),oy.Ring=void 0;const N$=Dt,hde=vs,k$=Ct,fde=$t,O$=Math.PI*2;class Ku extends hde.Shape{_sceneFunc(e){e.beginPath(),e.arc(0,0,this.innerRadius(),0,O$,!1),e.moveTo(this.outerRadius(),0),e.arc(0,0,this.outerRadius(),O$,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)}}oy.Ring=Ku,Ku.prototype.className="Ring",Ku.prototype._centroid=!0,Ku.prototype._attrsAffectingSize=["innerRadius","outerRadius"],(0,fde._registerNode)(Ku),N$.Factory.addGetterSetter(Ku,"innerRadius",0,(0,k$.getNumberValidator)()),N$.Factory.addGetterSetter(Ku,"outerRadius",0,(0,k$.getNumberValidator)());var ly={};Object.defineProperty(ly,"__esModule",{value:!0}),ly.Sprite=void 0;const Xu=Dt,pde=vs,mde=nd,$$=Ct,gde=$t;class Ba extends pde.Shape{constructor(e){super(e),this._updated=!0,this.anim=new mde.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(),n=this.frameIndex(),i=n*4,s=this.animations()[t],a=this.frameOffsets(),o=s[i+0],u=s[i+1],c=s[i+2],d=s[i+3],p=this.image();if((this.hasFill()||this.hasStroke())&&(e.beginPath(),e.rect(0,0,c,d),e.closePath(),e.fillStrokeShape(this)),p)if(a){const m=a[t],_=n*2;e.drawImage(p,o,u,c,d,m[_+0],m[_+1],c,d)}else e.drawImage(p,o,u,c,d,0,0,c,d)}_hitFunc(e){const t=this.animation(),n=this.frameIndex(),i=n*4,s=this.animations()[t],a=this.frameOffsets(),o=s[i+2],u=s[i+3];if(e.beginPath(),a){const c=a[t],d=n*2;e.rect(c[d+0],c[d+1],o,u)}else e.rect(0,0,o,u);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(),n=this.animations(),i=n[t],s=i.length/4;e<s-1?this.frameIndex(e+1):this.frameIndex(0)}}ly.Sprite=Ba,Ba.prototype.className="Sprite",(0,gde._registerNode)(Ba),Xu.Factory.addGetterSetter(Ba,"animation"),Xu.Factory.addGetterSetter(Ba,"animations"),Xu.Factory.addGetterSetter(Ba,"frameOffsets"),Xu.Factory.addGetterSetter(Ba,"image"),Xu.Factory.addGetterSetter(Ba,"frameIndex",0,(0,$$.getNumberValidator)()),Xu.Factory.addGetterSetter(Ba,"frameRate",17,(0,$$.getNumberValidator)()),Xu.Factory.backCompat(Ba,{index:"frameIndex",getIndex:"getFrameIndex",setIndex:"setFrameIndex"});var uy={};Object.defineProperty(uy,"__esModule",{value:!0}),uy.Star=void 0;const Ew=Dt,_de=vs,xw=Ct,yde=$t;class Nl extends _de.Shape{_sceneFunc(e){const t=this.innerRadius(),n=this.outerRadius(),i=this.numPoints();e.beginPath(),e.moveTo(0,0-n);for(let s=1;s<i*2;s++){const a=s%2===0?n:t,o=a*Math.sin(s*Math.PI/i),u=-1*a*Math.cos(s*Math.PI/i);e.lineTo(o,u)}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)}}uy.Star=Nl,Nl.prototype.className="Star",Nl.prototype._centroid=!0,Nl.prototype._attrsAffectingSize=["innerRadius","outerRadius"],(0,yde._registerNode)(Nl),Ew.Factory.addGetterSetter(Nl,"numPoints",5,(0,xw.getNumberValidator)()),Ew.Factory.addGetterSetter(Nl,"innerRadius",0,(0,xw.getNumberValidator)()),Ew.Factory.addGetterSetter(Nl,"outerRadius",0,(0,xw.getNumberValidator)());var od={};Object.defineProperty(od,"__esModule",{value:!0}),od.Text=void 0,od.stringToArray=D$;const Iw=Un,gr=Dt,vde=vs,Aw=$t,kl=Ct,bde=$t;function D$(r){return[...r].reduce((e,t,n,i)=>(/\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?(?:\u200D\p{Emoji_Presentation})+/u.test(t)?e.push(t):/\p{Regional_Indicator}{2}/u.test(t+(i[n+1]||""))?e.push(t+i[n+1]):n>0&&/\p{Mn}|\p{Me}|\p{Mc}/u.test(t)?e[e.length-1]+=t:e.push(t),e),[])}const ld="auto",Sde="center",P$="inherit",cp="justify",Tde="Change.konva",wde="2d",F$="-",M$="left",Cde="text",Ede="Text",xde="top",Ide="bottom",L$="middle",U$="normal",Ade="px ",cy=" ",Rde="right",B$="rtl",Nde="word",kde="char",H$="none",Rw="…",V$=["direction","fontFamily","fontSize","fontStyle","fontVariant","padding","align","verticalAlign","lineHeight","text","width","height","wrap","ellipsis","letterSpacing"],Ode=V$.length;function $de(r){return r.split(",").map(e=>{e=e.trim();const t=e.indexOf(" ")>=0,n=e.indexOf('"')>=0||e.indexOf("'")>=0;return t&&!n&&(e=`"${e}"`),e}).join(", ")}let dy;function Nw(){return dy||(dy=Iw.Util.createCanvasElement().getContext(wde),dy)}function Dde(r){r.fillText(this._partialText,this._partialTextX,this._partialTextY)}function Pde(r){r.setAttr("miterLimit",2),r.strokeText(this._partialText,this._partialTextX,this._partialTextY)}function Fde(r){return r=r||{},!r.fillLinearGradientColorStops&&!r.fillRadialGradientColorStops&&!r.fillPatternImage&&(r.fill=r.fill||"black"),r}class zn extends vde.Shape{constructor(e){super(Fde(e)),this._partialTextX=0,this._partialTextY=0;for(let t=0;t<Ode;t++)this.on(V$[t]+Tde,this._setTextData);this._setTextData()}_sceneFunc(e){const t=this.textArr,n=t.length;if(!this.text())return;let i=this.padding(),s=this.fontSize(),a=this.lineHeight()*s,o=this.verticalAlign(),u=this.direction(),c=0,d=this.align(),p=this.getWidth(),m=this.letterSpacing(),_=this.fill(),y=this.textDecoration(),b=y.indexOf("underline")!==-1,S=y.indexOf("line-through")!==-1,w;u=u===P$?e.direction:u;let x=a/2,E=L$;if(Aw.Konva._fixTextRendering){const j=this.measureSize("M");E="alphabetic",x=(j.fontBoundingBoxAscent-j.fontBoundingBoxDescent)/2+a/2}var I=0,R=0;for(u===B$&&e.setAttr("direction",u),e.setAttr("font",this._getContextFont()),e.setAttr("textBaseline",E),e.setAttr("textAlign",M$),o===L$?c=(this.getHeight()-n*a-i*2)/2:o===Ide&&(c=this.getHeight()-n*a-i*2),e.translate(i,c+i),w=0;w<n;w++){var I=0,R=0,P=t[w],B=P.text,O=P.width,F=P.lastInParagraph,D,L,G;if(e.save(),d===Rde?I+=p-O-i*2:d===Sde&&(I+=(p-O-i*2)/2),b){e.save(),e.beginPath();const W=Aw.Konva._fixTextRendering?Math.round(s/4):Math.round(s/2),Q=I,oe=x+R+W;e.moveTo(Q,oe),D=B.split(" ").length-1,L=D===0,G=d===cp&&!F?p-i*2:O,e.lineTo(Q+Math.round(G),oe),e.lineWidth=s/15;const Ce=this._getLinearGradient();e.strokeStyle=Ce||_,e.stroke(),e.restore()}if(S){e.save(),e.beginPath();const W=Aw.Konva._fixTextRendering?-Math.round(s/4):0;e.moveTo(I,x+R+W),D=B.split(" ").length-1,L=D===0,G=d===cp&&F&&!L?p-i*2:O,e.lineTo(I+Math.round(G),x+R+W),e.lineWidth=s/15;const Q=this._getLinearGradient();e.strokeStyle=Q||_,e.stroke(),e.restore()}if(u!==B$&&(m!==0||d===cp)){D=B.split(" ").length-1;const W=D$(B);for(let Q=0;Q<W.length;Q++){const oe=W[Q];oe===" "&&!F&&d===cp&&(I+=(p-i*2-O)/D),this._partialTextX=I,this._partialTextY=x+R,this._partialText=oe,e.fillStrokeShape(this),I+=this.measureSize(oe).width+m}}else m!==0&&e.setAttr("letterSpacing",`${m}px`),this._partialTextX=I,this._partialTextY=x+R,this._partialText=B,e.fillStrokeShape(this);e.restore(),n>1&&(x+=a)}}_hitFunc(e){const t=this.getWidth(),n=this.getHeight();e.beginPath(),e.rect(0,0,t,n),e.closePath(),e.fillStrokeShape(this)}setText(e){const t=Iw.Util._isString(e)?e:e==null?"":e+"";return this._setAttr(Cde,t),this}getWidth(){return this.attrs.width===ld||this.attrs.width===void 0?this.getTextWidth()+this.padding()*2:this.attrs.width}getHeight(){return this.attrs.height===ld||this.attrs.height===void 0?this.fontSize()*this.textArr.length*this.lineHeight()+this.padding()*2:this.attrs.height}getTextWidth(){return this.textWidth}getTextHeight(){return Iw.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,n,i,s,a,o,u,c,d,p,m;let _=Nw(),y=this.fontSize(),b;_.save(),_.font=this._getContextFont(),b=_.measureText(e),_.restore();const S=y/100;return{actualBoundingBoxAscent:(t=b.actualBoundingBoxAscent)!==null&&t!==void 0?t:71.58203125*S,actualBoundingBoxDescent:(n=b.actualBoundingBoxDescent)!==null&&n!==void 0?n:0,actualBoundingBoxLeft:(i=b.actualBoundingBoxLeft)!==null&&i!==void 0?i:-7.421875*S,actualBoundingBoxRight:(s=b.actualBoundingBoxRight)!==null&&s!==void 0?s:75.732421875*S,alphabeticBaseline:(a=b.alphabeticBaseline)!==null&&a!==void 0?a:0,emHeightAscent:(o=b.emHeightAscent)!==null&&o!==void 0?o:100*S,emHeightDescent:(u=b.emHeightDescent)!==null&&u!==void 0?u:-20*S,fontBoundingBoxAscent:(c=b.fontBoundingBoxAscent)!==null&&c!==void 0?c:91*S,fontBoundingBoxDescent:(d=b.fontBoundingBoxDescent)!==null&&d!==void 0?d:21*S,hangingBaseline:(p=b.hangingBaseline)!==null&&p!==void 0?p:72.80000305175781*S,ideographicBaseline:(m=b.ideographicBaseline)!==null&&m!==void 0?m:-21*S,width:b.width,height:y}}_getContextFont(){return this.fontStyle()+cy+this.fontVariant()+cy+(this.fontSize()+Ade)+$de(this.fontFamily())}_addTextLine(e){this.align()===cp&&(e=e.trim());const n=this._getTextWidth(e);return this.textArr.push({text:e,width:n,lastInParagraph:!1})}_getTextWidth(e){const t=this.letterSpacing(),n=e.length;return Nw().measureText(e).width+(n?t*(n-1):0)}_setTextData(){let e=this.text().split(`
18359
- `),t=+this.fontSize(),n=0,i=this.lineHeight()*t,s=this.attrs.width,a=this.attrs.height,o=s!==ld&&s!==void 0,u=a!==ld&&a!==void 0,c=this.padding(),d=s-c*2,p=a-c*2,m=0,_=this.wrap(),y=_!==H$,b=_!==kde&&y,S=this.ellipsis();this.textArr=[],Nw().font=this._getContextFont();const w=S?this._getTextWidth(Rw):0;for(let E=0,I=e.length;E<I;++E){let R=e[E],P=this._getTextWidth(R);if(o&&P>d)for(;R.length>0;){let B=0,O=R.length,F="",D=0;for(;B<O;){const L=B+O>>>1,G=R.slice(0,L+1),j=this._getTextWidth(G)+w;j<=d?(B=L+1,F=G,D=j):O=L}if(F){if(b){var x;const G=R[F.length];(G===cy||G===F$)&&D<=d?x=F.length:x=Math.max(F.lastIndexOf(cy),F.lastIndexOf(F$))+1,x>0&&(B=x,F=F.slice(0,B),D=this._getTextWidth(F))}if(F=F.trimRight(),this._addTextLine(F),n=Math.max(n,D),m+=i,this._shouldHandleEllipsis(m)){this._tryToAddEllipsisToLastLine();break}if(R=R.slice(B),R=R.trimLeft(),R.length>0&&(P=this._getTextWidth(R),P<=d)){this._addTextLine(R),m+=i,n=Math.max(n,P);break}}else break}else this._addTextLine(R),m+=i,n=Math.max(n,P),this._shouldHandleEllipsis(m)&&E<I-1&&this._tryToAddEllipsisToLastLine();if(this.textArr[this.textArr.length-1]&&(this.textArr[this.textArr.length-1].lastInParagraph=!0),u&&m+i>p)break}this.textHeight=t,this.textWidth=n}_shouldHandleEllipsis(e){const t=+this.fontSize(),n=this.lineHeight()*t,i=this.attrs.height,s=i!==ld&&i!==void 0,a=this.padding(),o=i-a*2;return!(this.wrap()!==H$)||s&&e+n>o}_tryToAddEllipsisToLastLine(){const e=this.attrs.width,t=e!==ld&&e!==void 0,n=this.padding(),i=e-n*2,s=this.ellipsis(),a=this.textArr[this.textArr.length-1];!a||!s||(t&&(this._getTextWidth(a.text+Rw)<i||(a.text=a.text.slice(0,a.text.length-3))),this.textArr.splice(this.textArr.length-1,1),this._addTextLine(a.text+Rw))}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()}}od.Text=zn,zn.prototype._fillFunc=Dde,zn.prototype._strokeFunc=Pde,zn.prototype.className=Ede,zn.prototype._attrsAffectingSize=["text","fontSize","padding","wrap","lineHeight","letterSpacing"],(0,bde._registerNode)(zn),gr.Factory.overWriteSetter(zn,"width",(0,kl.getNumberOrAutoValidator)()),gr.Factory.overWriteSetter(zn,"height",(0,kl.getNumberOrAutoValidator)()),gr.Factory.addGetterSetter(zn,"direction",P$),gr.Factory.addGetterSetter(zn,"fontFamily","Arial"),gr.Factory.addGetterSetter(zn,"fontSize",12,(0,kl.getNumberValidator)()),gr.Factory.addGetterSetter(zn,"fontStyle",U$),gr.Factory.addGetterSetter(zn,"fontVariant",U$),gr.Factory.addGetterSetter(zn,"padding",0,(0,kl.getNumberValidator)()),gr.Factory.addGetterSetter(zn,"align",M$),gr.Factory.addGetterSetter(zn,"verticalAlign",xde),gr.Factory.addGetterSetter(zn,"lineHeight",1,(0,kl.getNumberValidator)()),gr.Factory.addGetterSetter(zn,"wrap",Nde),gr.Factory.addGetterSetter(zn,"ellipsis",!1,(0,kl.getBooleanValidator)()),gr.Factory.addGetterSetter(zn,"letterSpacing",0,(0,kl.getNumberValidator)()),gr.Factory.addGetterSetter(zn,"text","",(0,kl.getStringValidator)()),gr.Factory.addGetterSetter(zn,"textDecoration","");var hy={};Object.defineProperty(hy,"__esModule",{value:!0}),hy.TextPath=void 0;const kw=Un,aa=Dt,Mde=vs,dp=sd,Ow=od,G$=Ct,Lde=$t,Ude="",W$="normal";function z$(r){r.fillText(this.partialText,0,0)}function j$(r){r.strokeText(this.partialText,0,0)}class Ss extends Mde.Shape{constructor(e){super(e),this.dummyCanvas=kw.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 dp.Path.getPathLength(this.dataArray)}_getPointAtLength(e){if(!this.attrs.data)return null;const t=this.pathLength;return e-1>t?null:dp.Path.getPointAtLengthOfDataArray(e,this.dataArray)}_readDataAttribute(){this.dataArray=dp.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(),n=this.fill(),i=this.fontSize(),s=this.glyphInfo;t==="underline"&&e.beginPath();for(let a=0;a<s.length;a++){e.save();const o=s[a].p0;e.translate(o.x,o.y),e.rotate(s[a].rotation),this.partialText=s[a].text,e.fillStrokeShape(this),t==="underline"&&(a===0&&e.moveTo(0,i/2+1),e.lineTo(i,i/2+1)),e.restore()}t==="underline"&&(e.strokeStyle=n,e.lineWidth=i/20,e.stroke()),e.restore()}_hitFunc(e){e.beginPath();const t=this.glyphInfo;if(t.length>=1){const n=t[0].p0;e.moveTo(n.x,n.y)}for(let n=0;n<t.length;n++){const i=t[n].p1;e.lineTo(i.x,i.y)}e.setAttr("lineWidth",this.fontSize()),e.setAttr("strokeStyle",this.colorKey),e.stroke()}getTextWidth(){return this.textWidth}getTextHeight(){return kw.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 Ow.Text.prototype.setText.call(this,e)}_getContextFont(){return Ow.Text.prototype._getContextFont.call(this)}_getTextSize(e){const n=this.dummyCanvas.getContext("2d");n.save(),n.font=this._getContextFont();const i=n.measureText(e);return n.restore(),{width:i.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 n=this.letterSpacing(),i=this.align(),s=this.kerningFunc(),a=Math.max(this.textWidth+((this.attrs.text||"").length-1)*n,0);let o=0;i==="center"&&(o=Math.max(0,this.pathLength/2-a/2)),i==="right"&&(o=Math.max(0,this.pathLength-a));const u=(0,Ow.stringToArray)(this.text());let c=o;for(let d=0;d<u.length;d++){const p=this._getPointAtLength(c);if(!p)return;let m=this._getTextSize(u[d]).width+n;if(u[d]===" "&&i==="justify"){const x=this.text().split(" ").length-1;m+=(this.pathLength-a)/x}const _=this._getPointAtLength(c+m);if(!_)return;const y=dp.Path.getLineLength(p.x,p.y,_.x,_.y);let b=0;if(s)try{b=s(u[d-1],u[d])*this.fontSize()}catch{b=0}p.x+=b,_.x+=b,this.textWidth+=b;const S=dp.Path.getPointOnLine(b+y/2,p.x,p.y,_.x,_.y),w=Math.atan2(_.y-p.y,_.x-p.x);this.glyphInfo.push({transposeX:S.x,transposeY:S.y,text:u[d],rotation:w,p0:p,p1:_}),c+=m}}getSelfRect(){if(!this.glyphInfo.length)return{x:0,y:0,width:0,height:0};const e=[];this.glyphInfo.forEach(function(c){e.push(c.p0.x),e.push(c.p0.y),e.push(c.p1.x),e.push(c.p1.y)});let t=e[0]||0,n=e[0]||0,i=e[1]||0,s=e[1]||0,a,o;for(let c=0;c<e.length/2;c++)a=e[c*2],o=e[c*2+1],t=Math.min(t,a),n=Math.max(n,a),i=Math.min(i,o),s=Math.max(s,o);const u=this.fontSize();return{x:t-u/2,y:i-u/2,width:n-t+u,height:s-i+u}}destroy(){return kw.Util.releaseCanvas(this.dummyCanvas),super.destroy()}}hy.TextPath=Ss,Ss.prototype._fillFunc=z$,Ss.prototype._strokeFunc=j$,Ss.prototype._fillFuncHit=z$,Ss.prototype._strokeFuncHit=j$,Ss.prototype.className="TextPath",Ss.prototype._attrsAffectingSize=["text","fontSize","data"],(0,Lde._registerNode)(Ss),aa.Factory.addGetterSetter(Ss,"data"),aa.Factory.addGetterSetter(Ss,"fontFamily","Arial"),aa.Factory.addGetterSetter(Ss,"fontSize",12,(0,G$.getNumberValidator)()),aa.Factory.addGetterSetter(Ss,"fontStyle",W$),aa.Factory.addGetterSetter(Ss,"align","left"),aa.Factory.addGetterSetter(Ss,"letterSpacing",0,(0,G$.getNumberValidator)()),aa.Factory.addGetterSetter(Ss,"textBaseline","middle"),aa.Factory.addGetterSetter(Ss,"fontVariant",W$),aa.Factory.addGetterSetter(Ss,"text",Ude),aa.Factory.addGetterSetter(Ss,"textDecoration",null),aa.Factory.addGetterSetter(Ss,"kerningFunc",null);var fy={};Object.defineProperty(fy,"__esModule",{value:!0}),fy.Transformer=void 0;const pn=Un,rn=Dt,q$=Mn,Bde=vs,Hde=up,K$=td,oa=$t,Ol=Ct,Vde=$t,X$="tr-konva",Gde=["resizeEnabledChange","rotateAnchorOffsetChange","rotateEnabledChange","enabledAnchorsChange","anchorSizeChange","borderEnabledChange","borderStrokeChange","borderStrokeWidthChange","borderDashChange","anchorStrokeChange","anchorStrokeWidthChange","anchorFillChange","anchorCornerRadiusChange","ignoreStrokeChange","anchorStyleFuncChange"].map(r=>r+`.${X$}`).join(" "),Y$="nodesRect",Wde=["widthChange","heightChange","scaleXChange","scaleYChange","skewXChange","skewYChange","rotationChange","offsetXChange","offsetYChange","transformsEnabledChange","strokeWidthChange"],zde={"top-left":-45,"top-center":0,"top-right":45,"middle-right":-90,"middle-left":90,"bottom-left":-135,"bottom-center":180,"bottom-right":135},jde="ontouchstart"in oa.Konva._global;function qde(r,e,t){if(r==="rotater")return t;e+=pn.Util.degToRad(zde[r]||0);const n=(pn.Util.radToDeg(e)%360+360)%360;return pn.Util._inRange(n,337.5,360)||pn.Util._inRange(n,0,22.5)?"ns-resize":pn.Util._inRange(n,22.5,67.5)?"nesw-resize":pn.Util._inRange(n,67.5,112.5)?"ew-resize":pn.Util._inRange(n,112.5,157.5)?"nwse-resize":pn.Util._inRange(n,157.5,202.5)?"ns-resize":pn.Util._inRange(n,202.5,247.5)?"nesw-resize":pn.Util._inRange(n,247.5,292.5)?"ew-resize":pn.Util._inRange(n,292.5,337.5)?"nwse-resize":(pn.Util.error("Transformer has unknown angle for cursor detection: "+n),"pointer")}const py=["top-left","top-center","top-right","middle-right","middle-left","bottom-left","bottom-center","bottom-right"],J$=1e8;function Kde(r){return{x:r.x+r.width/2*Math.cos(r.rotation)+r.height/2*Math.sin(-r.rotation),y:r.y+r.height/2*Math.cos(r.rotation)+r.width/2*Math.sin(r.rotation)}}function Q$(r,e,t){const n=t.x+(r.x-t.x)*Math.cos(e)-(r.y-t.y)*Math.sin(e),i=t.y+(r.x-t.x)*Math.sin(e)+(r.y-t.y)*Math.cos(e);return{...r,rotation:r.rotation+e,x:n,y:i}}function Xde(r,e){const t=Kde(r);return Q$(r,e,t)}function Yde(r,e,t){let n=e;for(let i=0;i<r.length;i++){const s=oa.Konva.getAngle(r[i]),a=Math.abs(s-e)%(Math.PI*2);Math.min(a,Math.PI*2-a)<t&&(n=s)}return n}let $w=0;class qt extends K$.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(Gde,this.update),this.getNode()&&this.update()}attachTo(e){return this.setNode(e),this}setNode(e){return pn.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 X$+this._id}setNodes(e=[]){this._nodes&&this._nodes.length&&this.detach();const t=e.filter(i=>i.isAncestorOf(this)?(pn.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(i=>{const s=()=>{this.nodes().length===1&&this.useSingleNodeRotation()&&this.rotation(this.nodes()[0].getAbsoluteRotation()),this._resetTransformCache(),!this._transforming&&!this.isDragging()&&this.update()},a=i._attrsAffectingSize.map(o=>o+"Change."+this._getEventNamespace()).join(" ");i.on(a,s),i.on(Wde.map(o=>o+`.${this._getEventNamespace()}`).join(" "),s),i.on(`absoluteTransformChange.${this._getEventNamespace()}`,s),this._proxyDrag(i)}),this._resetTransformCache(),!!this.findOne(".top-left")&&this.update(),this}_proxyDrag(e){let t;e.on(`dragstart.${this._getEventNamespace()}`,n=>{t=e.getAbsolutePosition(),!this.isDragging()&&e!==this.findOne(".back")&&this.startDrag(n,!1)}),e.on(`dragmove.${this._getEventNamespace()}`,n=>{if(!t)return;const i=e.getAbsolutePosition(),s=i.x-t.x,a=i.y-t.y;this.nodes().forEach(o=>{if(o===e||o.isDragging())return;const u=o.getAbsolutePosition();o.setAbsolutePosition({x:u.x+s,y:u.y+a}),o.startDrag(n)}),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(Y$),this._clearCache("transform"),this._clearSelfAndDescendantCache("absoluteTransform")}_getNodeRect(){return this._getCache(Y$,this.__getNodeRect)}__getNodeShape(e,t=this.rotation(),n){const i=e.getClientRect({skipTransform:!0,skipShadow:!0,skipStroke:this.ignoreStroke()}),s=e.getAbsoluteScale(n),a=e.getAbsolutePosition(n),o=i.x*s.x-e.offsetX()*s.x,u=i.y*s.y-e.offsetY()*s.y,c=(oa.Konva.getAngle(e.getAbsoluteRotation())+Math.PI*2)%(Math.PI*2),d={x:a.x+o*Math.cos(c)+u*Math.sin(-c),y:a.y+u*Math.cos(c)+o*Math.sin(c),width:i.width*s.x,height:i.height*s.y,rotation:c};return Q$(d,-oa.Konva.getAngle(t),{x:0,y:0})}__getNodeRect(){if(!this.getNode())return{x:-J$,y:-J$,width:0,height:0,rotation:0};const t=[];this.nodes().map(c=>{const d=c.getClientRect({skipTransform:!0,skipShadow:!0,skipStroke:this.ignoreStroke()}),p=[{x:d.x,y:d.y},{x:d.x+d.width,y:d.y},{x:d.x+d.width,y:d.y+d.height},{x:d.x,y:d.y+d.height}],m=c.getAbsoluteTransform();p.forEach(function(_){const y=m.point(_);t.push(y)})});const n=new pn.Transform;n.rotate(-oa.Konva.getAngle(this.rotation()));let i=1/0,s=1/0,a=-1/0,o=-1/0;t.forEach(function(c){const d=n.point(c);i===void 0&&(i=a=d.x,s=o=d.y),i=Math.min(i,d.x),s=Math.min(s,d.y),a=Math.max(a,d.x),o=Math.max(o,d.y)}),n.invert();const u=n.point({x:i,y:s});return{x:u.x,y:u.y,width:a-i,height:o-s,rotation:oa.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(),py.forEach(e=>{this._createAnchor(e)}),this._createAnchor("rotater")}_createAnchor(e){const t=new Hde.Rect({stroke:"rgb(0, 161, 255)",fill:"white",strokeWidth:1,name:e+" _anchor",dragDistance:0,draggable:!0,hitStrokeWidth:jde?10:"auto"}),n=this;t.on("mousedown touchstart",function(i){n._handleMouseDown(i)}),t.on("dragstart",i=>{t.stopDrag(),i.cancelBubble=!0}),t.on("dragend",i=>{i.cancelBubble=!0}),t.on("mouseenter",()=>{const i=oa.Konva.getAngle(this.rotation()),s=this.rotateAnchorCursor(),a=qde(e,i,s);t.getStage().content&&(t.getStage().content.style.cursor=a),this._cursorChange=!0}),t.on("mouseout",()=>{t.getStage().content&&(t.getStage().content.style.cursor=""),this._cursorChange=!1}),this.add(t)}_createBack(){const e=new Bde.Shape({name:"back",width:0,height:0,draggable:!0,sceneFunc(t,n){const i=n.getParent(),s=i.padding();t.beginPath(),t.rect(-s,-s,n.width()+s*2,n.height()+s*2),t.moveTo(n.width()/2,-s),i.rotateEnabled()&&i.rotateLineVisible()&&t.lineTo(n.width()/2,-i.rotateAnchorOffset()*pn.Util._sign(n.height())-s),t.fillStrokeShape(n)},hitFunc:(t,n)=>{if(!this.shouldOverdrawWholeArea())return;const i=this.padding();t.beginPath(),t.rect(-i,-i,n.width()+i*2,n.height()+i*2),t.fillStrokeShape(n)}});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(),n=t.width,i=t.height,s=Math.sqrt(Math.pow(n,2)+Math.pow(i,2));this.sin=Math.abs(i/s),this.cos=Math.abs(n/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 a=e.target.getAbsolutePosition(),o=e.target.getStage().getPointerPosition();this._anchorDragOffset={x:o.x-a.x,y:o.y-a.y},$w++,this._fire("transformstart",{evt:e.evt,target:this.getNode()}),this._nodes.forEach(u=>{u._fire("transformstart",{evt:e.evt,target:u})})}_handleMouseMove(e){let t,n,i;const s=this.findOne("."+this._movingAnchorName),a=s.getStage();a.setPointersPositions(e);const o=a.getPointerPosition();let u={x:o.x-this._anchorDragOffset.x,y:o.y-this._anchorDragOffset.y};const c=s.getAbsolutePosition();this.anchorDragBoundFunc()&&(u=this.anchorDragBoundFunc()(c,u,e)),s.setAbsolutePosition(u);const d=s.getAbsolutePosition();if(c.x===d.x&&c.y===d.y)return;if(this._movingAnchorName==="rotater"){const R=this._getNodeRect();t=s.x()-R.width/2,n=-s.y()+R.height/2;let P=Math.atan2(-n,t)+Math.PI/2;R.height<0&&(P-=Math.PI);const O=oa.Konva.getAngle(this.rotation())+P,F=oa.Konva.getAngle(this.rotationSnapTolerance()),L=Yde(this.rotationSnaps(),O,F)-R.rotation,G=Xde(R,L);this._fitNodesInto(G,e);return}const p=this.shiftBehavior();let m;p==="inverted"?m=this.keepRatio()&&!e.shiftKey:p==="none"?m=this.keepRatio():m=this.keepRatio()||e.shiftKey;var w=this.centeredScaling()||e.altKey;if(this._movingAnchorName==="top-left"){if(m){var _=w?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".bottom-right").x(),y:this.findOne(".bottom-right").y()};i=Math.sqrt(Math.pow(_.x-s.x(),2)+Math.pow(_.y-s.y(),2));var y=this.findOne(".top-left").x()>_.x?-1:1,b=this.findOne(".top-left").y()>_.y?-1:1;t=i*this.cos*y,n=i*this.sin*b,this.findOne(".top-left").x(_.x-t),this.findOne(".top-left").y(_.y-n)}}else if(this._movingAnchorName==="top-center")this.findOne(".top-left").y(s.y());else if(this._movingAnchorName==="top-right"){if(m){var _=w?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".bottom-left").x(),y:this.findOne(".bottom-left").y()};i=Math.sqrt(Math.pow(s.x()-_.x,2)+Math.pow(_.y-s.y(),2));var y=this.findOne(".top-right").x()<_.x?-1:1,b=this.findOne(".top-right").y()>_.y?-1:1;t=i*this.cos*y,n=i*this.sin*b,this.findOne(".top-right").x(_.x+t),this.findOne(".top-right").y(_.y-n)}var S=s.position();this.findOne(".top-left").y(S.y),this.findOne(".bottom-right").x(S.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(m){var _=w?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".top-right").x(),y:this.findOne(".top-right").y()};i=Math.sqrt(Math.pow(_.x-s.x(),2)+Math.pow(s.y()-_.y,2));var y=_.x<s.x()?-1:1,b=s.y()<_.y?-1:1;t=i*this.cos*y,n=i*this.sin*b,s.x(_.x-t),s.y(_.y+n)}S=s.position(),this.findOne(".top-left").x(S.x),this.findOne(".bottom-right").y(S.y)}else if(this._movingAnchorName==="bottom-center")this.findOne(".bottom-right").y(s.y());else if(this._movingAnchorName==="bottom-right"){if(m){var _=w?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".top-left").x(),y:this.findOne(".top-left").y()};i=Math.sqrt(Math.pow(s.x()-_.x,2)+Math.pow(s.y()-_.y,2));var y=this.findOne(".bottom-right").x()<_.x?-1:1,b=this.findOne(".bottom-right").y()<_.y?-1:1;t=i*this.cos*y,n=i*this.sin*b,this.findOne(".bottom-right").x(_.x+t),this.findOne(".bottom-right").y(_.y+n)}}else console.error(new Error("Wrong position argument of selection resizer: "+this._movingAnchorName));var w=this.centeredScaling()||e.altKey;if(w){const R=this.findOne(".top-left"),P=this.findOne(".bottom-right"),B=R.x(),O=R.y(),F=this.getWidth()-P.x(),D=this.getHeight()-P.y();P.move({x:-B,y:-O}),R.move({x:F,y:D})}const x=this.findOne(".top-left").getAbsolutePosition();t=x.x,n=x.y;const E=this.findOne(".bottom-right").x()-this.findOne(".top-left").x(),I=this.findOne(".bottom-right").y()-this.findOne(".top-left").y();this._fitNodesInto({x:t,y:n,width:E,height:I,rotation:oa.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 n=this.getNode();$w--,this._fire("transformend",{evt:e,target:n}),(t=this.getLayer())===null||t===void 0||t.batchDraw(),n&&this._nodes.forEach(i=>{var s;i._fire("transformend",{evt:e,target:i}),(s=i.getLayer())===null||s===void 0||s.batchDraw()}),this._movingAnchorName=null}}_fitNodesInto(e,t){const n=this._getNodeRect(),i=1;if(pn.Util._inRange(e.width,-this.padding()*2-i,i)){this.update();return}if(pn.Util._inRange(e.height,-this.padding()*2-i,i)){this.update();return}const s=new pn.Transform;if(s.rotate(oa.Konva.getAngle(this.rotation())),this._movingAnchorName&&e.width<0&&this._movingAnchorName.indexOf("left")>=0){const m=s.point({x:-this.padding()*2,y:0});e.x+=m.x,e.y+=m.y,e.width+=this.padding()*2,this._movingAnchorName=this._movingAnchorName.replace("left","right"),this._anchorDragOffset.x-=m.x,this._anchorDragOffset.y-=m.y}else if(this._movingAnchorName&&e.width<0&&this._movingAnchorName.indexOf("right")>=0){const m=s.point({x:this.padding()*2,y:0});this._movingAnchorName=this._movingAnchorName.replace("right","left"),this._anchorDragOffset.x-=m.x,this._anchorDragOffset.y-=m.y,e.width+=this.padding()*2}if(this._movingAnchorName&&e.height<0&&this._movingAnchorName.indexOf("top")>=0){const m=s.point({x:0,y:-this.padding()*2});e.x+=m.x,e.y+=m.y,this._movingAnchorName=this._movingAnchorName.replace("top","bottom"),this._anchorDragOffset.x-=m.x,this._anchorDragOffset.y-=m.y,e.height+=this.padding()*2}else if(this._movingAnchorName&&e.height<0&&this._movingAnchorName.indexOf("bottom")>=0){const m=s.point({x:0,y:this.padding()*2});this._movingAnchorName=this._movingAnchorName.replace("bottom","top"),this._anchorDragOffset.x-=m.x,this._anchorDragOffset.y-=m.y,e.height+=this.padding()*2}if(this.boundBoxFunc()){const m=this.boundBoxFunc()(n,e);m?e=m:pn.Util.warn("boundBoxFunc returned falsy. You should return new bound rect from it!")}const a=1e7,o=new pn.Transform;o.translate(n.x,n.y),o.rotate(n.rotation),o.scale(n.width/a,n.height/a);const u=new pn.Transform,c=e.width/a,d=e.height/a;this.flipEnabled()===!1?(u.translate(e.x,e.y),u.rotate(e.rotation),u.translate(e.width<0?e.width:0,e.height<0?e.height:0),u.scale(Math.abs(c),Math.abs(d))):(u.translate(e.x,e.y),u.rotate(e.rotation),u.scale(c,d));const p=u.multiply(o.invert());this._nodes.forEach(m=>{var _;const y=m.getParent().getAbsoluteTransform(),b=m.getTransform().copy();b.translate(m.offsetX(),m.offsetY());const S=new pn.Transform;S.multiply(y.copy().invert()).multiply(p).multiply(y).multiply(b);const w=S.decompose();m.setAttrs(w),(_=m.getLayer())===null||_===void 0||_.batchDraw()}),this.rotation(pn.Util._getRotation(e.rotation)),this._nodes.forEach(m=>{this._fire("transform",{evt:t,target:m}),m._fire("transform",{evt:t,target:m})}),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(pn.Util._getRotation(t.rotation));const n=t.width,i=t.height,s=this.enabledAnchors(),a=this.resizeEnabled(),o=this.padding(),u=this.anchorSize(),c=this.find("._anchor");c.forEach(p=>{p.setAttrs({width:u,height:u,offsetX:u/2,offsetY:u/2,stroke:this.anchorStroke(),strokeWidth:this.anchorStrokeWidth(),fill:this.anchorFill(),cornerRadius:this.anchorCornerRadius()})}),this._batchChangeChild(".top-left",{x:0,y:0,offsetX:u/2+o,offsetY:u/2+o,visible:a&&s.indexOf("top-left")>=0}),this._batchChangeChild(".top-center",{x:n/2,y:0,offsetY:u/2+o,visible:a&&s.indexOf("top-center")>=0}),this._batchChangeChild(".top-right",{x:n,y:0,offsetX:u/2-o,offsetY:u/2+o,visible:a&&s.indexOf("top-right")>=0}),this._batchChangeChild(".middle-left",{x:0,y:i/2,offsetX:u/2+o,visible:a&&s.indexOf("middle-left")>=0}),this._batchChangeChild(".middle-right",{x:n,y:i/2,offsetX:u/2-o,visible:a&&s.indexOf("middle-right")>=0}),this._batchChangeChild(".bottom-left",{x:0,y:i,offsetX:u/2+o,offsetY:u/2-o,visible:a&&s.indexOf("bottom-left")>=0}),this._batchChangeChild(".bottom-center",{x:n/2,y:i,offsetY:u/2-o,visible:a&&s.indexOf("bottom-center")>=0}),this._batchChangeChild(".bottom-right",{x:n,y:i,offsetX:u/2-o,offsetY:u/2-o,visible:a&&s.indexOf("bottom-right")>=0}),this._batchChangeChild(".rotater",{x:n/2,y:-this.rotateAnchorOffset()*pn.Util._sign(i)-o,visible:this.rotateEnabled()}),this._batchChangeChild(".back",{width:n,height:i,visible:this.borderEnabled(),stroke:this.borderStroke(),strokeWidth:this.borderStrokeWidth(),dash:this.borderDash(),x:0,y:0});const d=this.anchorStyleFunc();d&&c.forEach(p=>{d(p)}),(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=""),K$.Group.prototype.destroy.call(this),this.detach(),this._removeEvents(),this}toObject(){return q$.Node.prototype.toObject.call(this)}clone(e){return q$.Node.prototype.clone.call(this,e)}getClientRect(){return this.nodes().length>0?super.getClientRect():{x:0,y:0,width:0,height:0}}}fy.Transformer=qt,qt.isTransforming=()=>$w>0;function Jde(r){return r instanceof Array||pn.Util.warn("enabledAnchors value should be an array"),r instanceof Array&&r.forEach(function(e){py.indexOf(e)===-1&&pn.Util.warn("Unknown anchor name: "+e+". Available names are: "+py.join(", "))}),r||[]}qt.prototype.className="Transformer",(0,Vde._registerNode)(qt),rn.Factory.addGetterSetter(qt,"enabledAnchors",py,Jde),rn.Factory.addGetterSetter(qt,"flipEnabled",!0,(0,Ol.getBooleanValidator)()),rn.Factory.addGetterSetter(qt,"resizeEnabled",!0),rn.Factory.addGetterSetter(qt,"anchorSize",10,(0,Ol.getNumberValidator)()),rn.Factory.addGetterSetter(qt,"rotateEnabled",!0),rn.Factory.addGetterSetter(qt,"rotateLineVisible",!0),rn.Factory.addGetterSetter(qt,"rotationSnaps",[]),rn.Factory.addGetterSetter(qt,"rotateAnchorOffset",50,(0,Ol.getNumberValidator)()),rn.Factory.addGetterSetter(qt,"rotateAnchorCursor","crosshair"),rn.Factory.addGetterSetter(qt,"rotationSnapTolerance",5,(0,Ol.getNumberValidator)()),rn.Factory.addGetterSetter(qt,"borderEnabled",!0),rn.Factory.addGetterSetter(qt,"anchorStroke","rgb(0, 161, 255)"),rn.Factory.addGetterSetter(qt,"anchorStrokeWidth",1,(0,Ol.getNumberValidator)()),rn.Factory.addGetterSetter(qt,"anchorFill","white"),rn.Factory.addGetterSetter(qt,"anchorCornerRadius",0,(0,Ol.getNumberValidator)()),rn.Factory.addGetterSetter(qt,"borderStroke","rgb(0, 161, 255)"),rn.Factory.addGetterSetter(qt,"borderStrokeWidth",1,(0,Ol.getNumberValidator)()),rn.Factory.addGetterSetter(qt,"borderDash"),rn.Factory.addGetterSetter(qt,"keepRatio",!0),rn.Factory.addGetterSetter(qt,"shiftBehavior","default"),rn.Factory.addGetterSetter(qt,"centeredScaling",!1),rn.Factory.addGetterSetter(qt,"ignoreStroke",!1),rn.Factory.addGetterSetter(qt,"padding",0,(0,Ol.getNumberValidator)()),rn.Factory.addGetterSetter(qt,"node"),rn.Factory.addGetterSetter(qt,"nodes"),rn.Factory.addGetterSetter(qt,"boundBoxFunc"),rn.Factory.addGetterSetter(qt,"anchorDragBoundFunc"),rn.Factory.addGetterSetter(qt,"anchorStyleFunc"),rn.Factory.addGetterSetter(qt,"shouldOverdrawWholeArea",!1),rn.Factory.addGetterSetter(qt,"useSingleNodeRotation",!0),rn.Factory.backCompat(qt,{lineEnabled:"borderEnabled",rotateHandlerOffset:"rotateAnchorOffset",enabledHandlers:"enabledAnchors"});var my={};Object.defineProperty(my,"__esModule",{value:!0}),my.Wedge=void 0;const gy=Dt,Qde=vs,Zde=$t,Z$=Ct,ehe=$t;class Io extends Qde.Shape{_sceneFunc(e){e.beginPath(),e.arc(0,0,this.radius(),0,Zde.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)}}my.Wedge=Io,Io.prototype.className="Wedge",Io.prototype._centroid=!0,Io.prototype._attrsAffectingSize=["radius"],(0,ehe._registerNode)(Io),gy.Factory.addGetterSetter(Io,"radius",0,(0,Z$.getNumberValidator)()),gy.Factory.addGetterSetter(Io,"angle",0,(0,Z$.getNumberValidator)()),gy.Factory.addGetterSetter(Io,"clockwise",!1),gy.Factory.backCompat(Io,{angleDeg:"angle",getAngleDeg:"getAngle",setAngleDeg:"setAngle"});var _y={};Object.defineProperty(_y,"__esModule",{value:!0}),_y.Blur=void 0;const e4=Dt,the=Mn,nhe=Ct;function t4(){this.r=0,this.g=0,this.b=0,this.a=0,this.next=null}const she=[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],rhe=[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 ihe(r,e){const t=r.data,n=r.width,i=r.height;let s,a,o,u,c,d,p,m,_,y,b,S,w,x,E,I,R,P,B,O,F,D,L,G,j=e+e+1,te=n-1,W=i-1,Q=e+1,oe=Q*(Q+1)/2,Ce=new t4,fe=null,ne=Ce,ae=null,be=null,Se=she[e],Me=rhe[e];for(o=1;o<j;o++)ne=ne.next=new t4,o===Q&&(fe=ne);for(ne.next=Ce,p=d=0,a=0;a<i;a++){for(I=R=P=B=m=_=y=b=0,S=Q*(O=t[d]),w=Q*(F=t[d+1]),x=Q*(D=t[d+2]),E=Q*(L=t[d+3]),m+=oe*O,_+=oe*F,y+=oe*D,b+=oe*L,ne=Ce,o=0;o<Q;o++)ne.r=O,ne.g=F,ne.b=D,ne.a=L,ne=ne.next;for(o=1;o<Q;o++)u=d+((te<o?te:o)<<2),m+=(ne.r=O=t[u])*(G=Q-o),_+=(ne.g=F=t[u+1])*G,y+=(ne.b=D=t[u+2])*G,b+=(ne.a=L=t[u+3])*G,I+=O,R+=F,P+=D,B+=L,ne=ne.next;for(ae=Ce,be=fe,s=0;s<n;s++)t[d+3]=L=b*Se>>Me,L!==0?(L=255/L,t[d]=(m*Se>>Me)*L,t[d+1]=(_*Se>>Me)*L,t[d+2]=(y*Se>>Me)*L):t[d]=t[d+1]=t[d+2]=0,m-=S,_-=w,y-=x,b-=E,S-=ae.r,w-=ae.g,x-=ae.b,E-=ae.a,u=p+((u=s+e+1)<te?u:te)<<2,I+=ae.r=t[u],R+=ae.g=t[u+1],P+=ae.b=t[u+2],B+=ae.a=t[u+3],m+=I,_+=R,y+=P,b+=B,ae=ae.next,S+=O=be.r,w+=F=be.g,x+=D=be.b,E+=L=be.a,I-=O,R-=F,P-=D,B-=L,be=be.next,d+=4;p+=n}for(s=0;s<n;s++){for(R=P=B=I=_=y=b=m=0,d=s<<2,S=Q*(O=t[d]),w=Q*(F=t[d+1]),x=Q*(D=t[d+2]),E=Q*(L=t[d+3]),m+=oe*O,_+=oe*F,y+=oe*D,b+=oe*L,ne=Ce,o=0;o<Q;o++)ne.r=O,ne.g=F,ne.b=D,ne.a=L,ne=ne.next;for(c=n,o=1;o<=e;o++)d=c+s<<2,m+=(ne.r=O=t[d])*(G=Q-o),_+=(ne.g=F=t[d+1])*G,y+=(ne.b=D=t[d+2])*G,b+=(ne.a=L=t[d+3])*G,I+=O,R+=F,P+=D,B+=L,ne=ne.next,o<W&&(c+=n);for(d=s,ae=Ce,be=fe,a=0;a<i;a++)u=d<<2,t[u+3]=L=b*Se>>Me,L>0?(L=255/L,t[u]=(m*Se>>Me)*L,t[u+1]=(_*Se>>Me)*L,t[u+2]=(y*Se>>Me)*L):t[u]=t[u+1]=t[u+2]=0,m-=S,_-=w,y-=x,b-=E,S-=ae.r,w-=ae.g,x-=ae.b,E-=ae.a,u=s+((u=a+Q)<W?u:W)*n<<2,m+=I+=ae.r=t[u],_+=R+=ae.g=t[u+1],y+=P+=ae.b=t[u+2],b+=B+=ae.a=t[u+3],ae=ae.next,S+=O=be.r,w+=F=be.g,x+=D=be.b,E+=L=be.a,I-=O,R-=F,P-=D,B-=L,be=be.next,d+=n}}const ahe=function(e){const t=Math.round(this.blurRadius());t>0&&ihe(e,t)};_y.Blur=ahe,e4.Factory.addGetterSetter(the.Node,"blurRadius",0,(0,nhe.getNumberValidator)(),e4.Factory.afterSetFilter);var yy={};Object.defineProperty(yy,"__esModule",{value:!0}),yy.Brighten=void 0;const n4=Dt,ohe=Mn,lhe=Ct,uhe=function(r){let e=this.brightness()*255,t=r.data,n=t.length,i;for(i=0;i<n;i+=4)t[i]+=e,t[i+1]+=e,t[i+2]+=e};yy.Brighten=uhe,n4.Factory.addGetterSetter(ohe.Node,"brightness",0,(0,lhe.getNumberValidator)(),n4.Factory.afterSetFilter);var vy={};Object.defineProperty(vy,"__esModule",{value:!0}),vy.Contrast=void 0;const s4=Dt,che=Mn,dhe=Ct,hhe=function(r){const e=Math.pow((this.contrast()+100)/100,2);let t=r.data,n=t.length,i=150,s=150,a=150,o;for(o=0;o<n;o+=4)i=t[o],s=t[o+1],a=t[o+2],i/=255,i-=.5,i*=e,i+=.5,i*=255,s/=255,s-=.5,s*=e,s+=.5,s*=255,a/=255,a-=.5,a*=e,a+=.5,a*=255,i=i<0?0:i>255?255:i,s=s<0?0:s>255?255:s,a=a<0?0:a>255?255:a,t[o]=i,t[o+1]=s,t[o+2]=a};vy.Contrast=hhe,s4.Factory.addGetterSetter(che.Node,"contrast",0,(0,dhe.getNumberValidator)(),s4.Factory.afterSetFilter);var by={};Object.defineProperty(by,"__esModule",{value:!0}),by.Emboss=void 0;const $l=Dt,Sy=Mn,fhe=Un,r4=Ct,phe=function(r){let e=this.embossStrength()*10,t=this.embossWhiteLevel()*255,n=this.embossDirection(),i=this.embossBlend(),s=0,a=0,o=r.data,u=r.width,c=r.height,d=u*4,p=c;switch(n){case"top-left":s=-1,a=-1;break;case"top":s=-1,a=0;break;case"top-right":s=-1,a=1;break;case"right":s=0,a=1;break;case"bottom-right":s=1,a=1;break;case"bottom":s=1,a=0;break;case"bottom-left":s=1,a=-1;break;case"left":s=0,a=-1;break;default:fhe.Util.error("Unknown emboss direction: "+n)}do{const m=(p-1)*d;let _=s;p+_<1&&(_=0),p+_>c&&(_=0);const y=(p-1+_)*u*4;let b=u;do{const S=m+(b-1)*4;let w=a;b+w<1&&(w=0),b+w>u&&(w=0);const x=y+(b-1+w)*4,E=o[S]-o[x],I=o[S+1]-o[x+1],R=o[S+2]-o[x+2];let P=E;const B=P>0?P:-P,O=I>0?I:-I,F=R>0?R:-R;if(O>B&&(P=I),F>B&&(P=R),P*=e,i){const D=o[S]+P,L=o[S+1]+P,G=o[S+2]+P;o[S]=D>255?255:D<0?0:D,o[S+1]=L>255?255:L<0?0:L,o[S+2]=G>255?255:G<0?0:G}else{let D=t-P;D<0?D=0:D>255&&(D=255),o[S]=o[S+1]=o[S+2]=D}}while(--b)}while(--p)};by.Emboss=phe,$l.Factory.addGetterSetter(Sy.Node,"embossStrength",.5,(0,r4.getNumberValidator)(),$l.Factory.afterSetFilter),$l.Factory.addGetterSetter(Sy.Node,"embossWhiteLevel",.5,(0,r4.getNumberValidator)(),$l.Factory.afterSetFilter),$l.Factory.addGetterSetter(Sy.Node,"embossDirection","top-left",null,$l.Factory.afterSetFilter),$l.Factory.addGetterSetter(Sy.Node,"embossBlend",!1,null,$l.Factory.afterSetFilter);var Ty={};Object.defineProperty(Ty,"__esModule",{value:!0}),Ty.Enhance=void 0;const i4=Dt,mhe=Mn,ghe=Ct;function Dw(r,e,t,n,i){let s=t-e,a=i-n,o;return s===0?n+a/2:a===0?n:(o=(r-e)/s,o=a*o+n,o)}const _he=function(r){let e=r.data,t=e.length,n=e[0],i=n,s,a=e[1],o=a,u,c=e[2],d=c,p,m;const _=this.enhance();if(_===0)return;for(m=0;m<t;m+=4)s=e[m+0],s<n?n=s:s>i&&(i=s),u=e[m+1],u<a?a=u:u>o&&(o=u),p=e[m+2],p<c?c=p:p>d&&(d=p);i===n&&(i=255,n=0),o===a&&(o=255,a=0),d===c&&(d=255,c=0);let y,b,S,w,x,E,I,R,P;for(_>0?(b=i+_*(255-i),S=n-_*(n-0),x=o+_*(255-o),E=a-_*(a-0),R=d+_*(255-d),P=c-_*(c-0)):(y=(i+n)*.5,b=i+_*(i-y),S=n+_*(n-y),w=(o+a)*.5,x=o+_*(o-w),E=a+_*(a-w),I=(d+c)*.5,R=d+_*(d-I),P=c+_*(c-I)),m=0;m<t;m+=4)e[m+0]=Dw(e[m+0],n,i,S,b),e[m+1]=Dw(e[m+1],a,o,E,x),e[m+2]=Dw(e[m+2],c,d,P,R)};Ty.Enhance=_he,i4.Factory.addGetterSetter(mhe.Node,"enhance",0,(0,ghe.getNumberValidator)(),i4.Factory.afterSetFilter);var wy={};Object.defineProperty(wy,"__esModule",{value:!0}),wy.Grayscale=void 0;const yhe=function(r){let e=r.data,t=e.length,n,i;for(n=0;n<t;n+=4)i=.34*e[n]+.5*e[n+1]+.16*e[n+2],e[n]=i,e[n+1]=i,e[n+2]=i};wy.Grayscale=yhe;var Cy={};Object.defineProperty(Cy,"__esModule",{value:!0}),Cy.HSL=void 0;const ud=Dt,Pw=Mn,Fw=Ct;ud.Factory.addGetterSetter(Pw.Node,"hue",0,(0,Fw.getNumberValidator)(),ud.Factory.afterSetFilter),ud.Factory.addGetterSetter(Pw.Node,"saturation",0,(0,Fw.getNumberValidator)(),ud.Factory.afterSetFilter),ud.Factory.addGetterSetter(Pw.Node,"luminance",0,(0,Fw.getNumberValidator)(),ud.Factory.afterSetFilter);const vhe=function(r){let e=r.data,t=e.length,n=1,i=Math.pow(2,this.saturation()),s=Math.abs(this.hue()+360)%360,a=this.luminance()*127,o;const u=n*i*Math.cos(s*Math.PI/180),c=n*i*Math.sin(s*Math.PI/180),d=.299*n+.701*u+.167*c,p=.587*n-.587*u+.33*c,m=.114*n-.114*u-.497*c,_=.299*n-.299*u-.328*c,y=.587*n+.413*u+.035*c,b=.114*n-.114*u+.293*c,S=.299*n-.3*u+1.25*c,w=.587*n-.586*u-1.05*c,x=.114*n+.886*u-.2*c;let E,I,R,P;for(o=0;o<t;o+=4)E=e[o+0],I=e[o+1],R=e[o+2],P=e[o+3],e[o+0]=d*E+p*I+m*R+a,e[o+1]=_*E+y*I+b*R+a,e[o+2]=S*E+w*I+x*R+a,e[o+3]=P};Cy.HSL=vhe;var Ey={};Object.defineProperty(Ey,"__esModule",{value:!0}),Ey.HSV=void 0;const cd=Dt,Mw=Mn,Lw=Ct,bhe=function(r){const e=r.data,t=e.length,n=Math.pow(2,this.value()),i=Math.pow(2,this.saturation()),s=Math.abs(this.hue()+360)%360,a=n*i*Math.cos(s*Math.PI/180),o=n*i*Math.sin(s*Math.PI/180),u=.299*n+.701*a+.167*o,c=.587*n-.587*a+.33*o,d=.114*n-.114*a-.497*o,p=.299*n-.299*a-.328*o,m=.587*n+.413*a+.035*o,_=.114*n-.114*a+.293*o,y=.299*n-.3*a+1.25*o,b=.587*n-.586*a-1.05*o,S=.114*n+.886*a-.2*o;let w,x,E,I;for(let R=0;R<t;R+=4)w=e[R+0],x=e[R+1],E=e[R+2],I=e[R+3],e[R+0]=u*w+c*x+d*E,e[R+1]=p*w+m*x+_*E,e[R+2]=y*w+b*x+S*E,e[R+3]=I};Ey.HSV=bhe,cd.Factory.addGetterSetter(Mw.Node,"hue",0,(0,Lw.getNumberValidator)(),cd.Factory.afterSetFilter),cd.Factory.addGetterSetter(Mw.Node,"saturation",0,(0,Lw.getNumberValidator)(),cd.Factory.afterSetFilter),cd.Factory.addGetterSetter(Mw.Node,"value",0,(0,Lw.getNumberValidator)(),cd.Factory.afterSetFilter);var xy={};Object.defineProperty(xy,"__esModule",{value:!0}),xy.Invert=void 0;const She=function(r){let e=r.data,t=e.length,n;for(n=0;n<t;n+=4)e[n]=255-e[n],e[n+1]=255-e[n+1],e[n+2]=255-e[n+2]};xy.Invert=She;var Iy={};Object.defineProperty(Iy,"__esModule",{value:!0}),Iy.Kaleidoscope=void 0;const Ay=Dt,a4=Mn,o4=Un,l4=Ct,The=function(r,e,t){let n=r.data,i=e.data,s=r.width,a=r.height,o=t.polarCenterX||s/2,u=t.polarCenterY||a/2,c,d,p,m=0,_=0,y=0,b=0,S,w=Math.sqrt(o*o+u*u);d=s-o,p=a-u,S=Math.sqrt(d*d+p*p),w=S>w?S:w;let x=a,E=s,I,R,P=360/E*Math.PI/180,B,O;for(R=0;R<E;R+=1)for(B=Math.sin(R*P),O=Math.cos(R*P),I=0;I<x;I+=1)d=Math.floor(o+w*I/x*O),p=Math.floor(u+w*I/x*B),c=(p*s+d)*4,m=n[c+0],_=n[c+1],y=n[c+2],b=n[c+3],c=(R+I*s)*4,i[c+0]=m,i[c+1]=_,i[c+2]=y,i[c+3]=b},whe=function(r,e,t){let n=r.data,i=e.data,s=r.width,a=r.height,o=t.polarCenterX||s/2,u=t.polarCenterY||a/2,c,d,p,m,_,y=0,b=0,S=0,w=0,x,E=Math.sqrt(o*o+u*u);d=s-o,p=a-u,x=Math.sqrt(d*d+p*p),E=x>E?x:E;let I=a,R=s,P,B,O=t.polarRotation||0,F,D;for(d=0;d<s;d+=1)for(p=0;p<a;p+=1)m=d-o,_=p-u,P=Math.sqrt(m*m+_*_)*I/E,B=(Math.atan2(_,m)*180/Math.PI+360+O)%360,B=B*R/360,F=Math.floor(B),D=Math.floor(P),c=(D*s+F)*4,y=n[c+0],b=n[c+1],S=n[c+2],w=n[c+3],c=(p*s+d)*4,i[c+0]=y,i[c+1]=b,i[c+2]=S,i[c+3]=w},Che=function(r){const e=r.width,t=r.height;let n,i,s,a,o,u,c,d,p,m,_=Math.round(this.kaleidoscopePower());const y=Math.round(this.kaleidoscopeAngle()),b=Math.floor(e*(y%360)/360);if(_<1)return;const S=o4.Util.createCanvasElement();S.width=e,S.height=t;const w=S.getContext("2d").getImageData(0,0,e,t);o4.Util.releaseCanvas(S),The(r,w,{polarCenterX:e/2,polarCenterY:t/2});let x=e/Math.pow(2,_);for(;x<=8;)x=x*2,_-=1;x=Math.ceil(x);let E=x,I=0,R=E,P=1;for(b+x>e&&(I=E,R=0,P=-1),i=0;i<t;i+=1)for(n=I;n!==R;n+=P)s=Math.round(n+b)%e,p=(e*i+s)*4,o=w.data[p+0],u=w.data[p+1],c=w.data[p+2],d=w.data[p+3],m=(e*i+n)*4,w.data[m+0]=o,w.data[m+1]=u,w.data[m+2]=c,w.data[m+3]=d;for(i=0;i<t;i+=1)for(E=Math.floor(x),a=0;a<_;a+=1){for(n=0;n<E+1;n+=1)p=(e*i+n)*4,o=w.data[p+0],u=w.data[p+1],c=w.data[p+2],d=w.data[p+3],m=(e*i+E*2-n-1)*4,w.data[m+0]=o,w.data[m+1]=u,w.data[m+2]=c,w.data[m+3]=d;E*=2}whe(w,r,{polarRotation:0})};Iy.Kaleidoscope=Che,Ay.Factory.addGetterSetter(a4.Node,"kaleidoscopePower",2,(0,l4.getNumberValidator)(),Ay.Factory.afterSetFilter),Ay.Factory.addGetterSetter(a4.Node,"kaleidoscopeAngle",0,(0,l4.getNumberValidator)(),Ay.Factory.afterSetFilter);var Ry={};Object.defineProperty(Ry,"__esModule",{value:!0}),Ry.Mask=void 0;const u4=Dt,Ehe=Mn,xhe=Ct;function Ny(r,e,t){let n=(t*r.width+e)*4;const i=[];return i.push(r.data[n++],r.data[n++],r.data[n++],r.data[n++]),i}function hp(r,e){return Math.sqrt(Math.pow(r[0]-e[0],2)+Math.pow(r[1]-e[1],2)+Math.pow(r[2]-e[2],2))}function Ihe(r){const e=[0,0,0];for(let t=0;t<r.length;t++)e[0]+=r[t][0],e[1]+=r[t][1],e[2]+=r[t][2];return e[0]/=r.length,e[1]/=r.length,e[2]/=r.length,e}function Ahe(r,e){const t=Ny(r,0,0),n=Ny(r,r.width-1,0),i=Ny(r,0,r.height-1),s=Ny(r,r.width-1,r.height-1),a=e||10;if(hp(t,n)<a&&hp(n,s)<a&&hp(s,i)<a&&hp(i,t)<a){const o=Ihe([n,t,s,i]),u=[];for(let c=0;c<r.width*r.height;c++){const d=hp(o,[r.data[c*4],r.data[c*4+1],r.data[c*4+2]]);u[c]=d<a?0:255}return u}}function Rhe(r,e){for(let t=0;t<r.width*r.height;t++)r.data[4*t+3]=e[t]}function Nhe(r,e,t){const n=[1,1,1,1,0,1,1,1,1],i=Math.round(Math.sqrt(n.length)),s=Math.floor(i/2),a=[];for(let o=0;o<t;o++)for(let u=0;u<e;u++){const c=o*e+u;let d=0;for(let p=0;p<i;p++)for(let m=0;m<i;m++){const _=o+p-s,y=u+m-s;if(_>=0&&_<t&&y>=0&&y<e){const b=_*e+y,S=n[p*i+m];d+=r[b]*S}}a[c]=d===2040?255:0}return a}function khe(r,e,t){const n=[1,1,1,1,1,1,1,1,1],i=Math.round(Math.sqrt(n.length)),s=Math.floor(i/2),a=[];for(let o=0;o<t;o++)for(let u=0;u<e;u++){const c=o*e+u;let d=0;for(let p=0;p<i;p++)for(let m=0;m<i;m++){const _=o+p-s,y=u+m-s;if(_>=0&&_<t&&y>=0&&y<e){const b=_*e+y,S=n[p*i+m];d+=r[b]*S}}a[c]=d>=1020?255:0}return a}function Ohe(r,e,t){const n=[.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111],i=Math.round(Math.sqrt(n.length)),s=Math.floor(i/2),a=[];for(let o=0;o<t;o++)for(let u=0;u<e;u++){const c=o*e+u;let d=0;for(let p=0;p<i;p++)for(let m=0;m<i;m++){const _=o+p-s,y=u+m-s;if(_>=0&&_<t&&y>=0&&y<e){const b=_*e+y,S=n[p*i+m];d+=r[b]*S}}a[c]=d}return a}const $he=function(r){let e=this.threshold(),t=Ahe(r,e);return t&&(t=Nhe(t,r.width,r.height),t=khe(t,r.width,r.height),t=Ohe(t,r.width,r.height),Rhe(r,t)),r};Ry.Mask=$he,u4.Factory.addGetterSetter(Ehe.Node,"threshold",0,(0,xhe.getNumberValidator)(),u4.Factory.afterSetFilter);var ky={};Object.defineProperty(ky,"__esModule",{value:!0}),ky.Noise=void 0;const c4=Dt,Dhe=Mn,Phe=Ct,Fhe=function(r){const e=this.noise()*255,t=r.data,n=t.length,i=e/2;for(let s=0;s<n;s+=4)t[s+0]+=i-2*i*Math.random(),t[s+1]+=i-2*i*Math.random(),t[s+2]+=i-2*i*Math.random()};ky.Noise=Fhe,c4.Factory.addGetterSetter(Dhe.Node,"noise",.2,(0,Phe.getNumberValidator)(),c4.Factory.afterSetFilter);var Oy={};Object.defineProperty(Oy,"__esModule",{value:!0}),Oy.Pixelate=void 0;const d4=Dt,Mhe=Un,Lhe=Mn,Uhe=Ct,Bhe=function(r){let e=Math.ceil(this.pixelSize()),t=r.width,n=r.height,i,s,a,o,u,c,d,p=Math.ceil(t/e),m=Math.ceil(n/e),_,y,b,S,w,x,E,I=r.data;if(e<=0){Mhe.Util.error("pixelSize value can not be <= 0");return}for(w=0;w<p;w+=1)for(x=0;x<m;x+=1){for(o=0,u=0,c=0,d=0,_=w*e,y=_+e,b=x*e,S=b+e,E=0,i=_;i<y;i+=1)if(!(i>=t))for(s=b;s<S;s+=1)s>=n||(a=(t*s+i)*4,o+=I[a+0],u+=I[a+1],c+=I[a+2],d+=I[a+3],E+=1);for(o=o/E,u=u/E,c=c/E,d=d/E,i=_;i<y;i+=1)if(!(i>=t))for(s=b;s<S;s+=1)s>=n||(a=(t*s+i)*4,I[a+0]=o,I[a+1]=u,I[a+2]=c,I[a+3]=d)}};Oy.Pixelate=Bhe,d4.Factory.addGetterSetter(Lhe.Node,"pixelSize",8,(0,Uhe.getNumberValidator)(),d4.Factory.afterSetFilter);var $y={};Object.defineProperty($y,"__esModule",{value:!0}),$y.Posterize=void 0;const h4=Dt,Hhe=Mn,Vhe=Ct,Ghe=function(r){let e=Math.round(this.levels()*254)+1,t=r.data,n=t.length,i=255/e,s;for(s=0;s<n;s+=1)t[s]=Math.floor(t[s]/i)*i};$y.Posterize=Ghe,h4.Factory.addGetterSetter(Hhe.Node,"levels",.5,(0,Vhe.getNumberValidator)(),h4.Factory.afterSetFilter);var Dy={};Object.defineProperty(Dy,"__esModule",{value:!0}),Dy.RGB=void 0;const Py=Dt,Uw=Mn,Whe=Ct,zhe=function(r){let e=r.data,t=e.length,n=this.red(),i=this.green(),s=this.blue(),a,o;for(a=0;a<t;a+=4)o=(.34*e[a]+.5*e[a+1]+.16*e[a+2])/255,e[a]=o*n,e[a+1]=o*i,e[a+2]=o*s,e[a+3]=e[a+3]};Dy.RGB=zhe,Py.Factory.addGetterSetter(Uw.Node,"red",0,function(r){return this._filterUpToDate=!1,r>255?255:r<0?0:Math.round(r)}),Py.Factory.addGetterSetter(Uw.Node,"green",0,function(r){return this._filterUpToDate=!1,r>255?255:r<0?0:Math.round(r)}),Py.Factory.addGetterSetter(Uw.Node,"blue",0,Whe.RGBComponent,Py.Factory.afterSetFilter);var Fy={};Object.defineProperty(Fy,"__esModule",{value:!0}),Fy.RGBA=void 0;const fp=Dt,My=Mn,jhe=Ct,qhe=function(r){const e=r.data,t=e.length,n=this.red(),i=this.green(),s=this.blue(),a=this.alpha();for(let o=0;o<t;o+=4){const u=1-a;e[o]=n*a+e[o]*u,e[o+1]=i*a+e[o+1]*u,e[o+2]=s*a+e[o+2]*u}};Fy.RGBA=qhe,fp.Factory.addGetterSetter(My.Node,"red",0,function(r){return this._filterUpToDate=!1,r>255?255:r<0?0:Math.round(r)}),fp.Factory.addGetterSetter(My.Node,"green",0,function(r){return this._filterUpToDate=!1,r>255?255:r<0?0:Math.round(r)}),fp.Factory.addGetterSetter(My.Node,"blue",0,jhe.RGBComponent,fp.Factory.afterSetFilter),fp.Factory.addGetterSetter(My.Node,"alpha",1,function(r){return this._filterUpToDate=!1,r>1?1:r<0?0:r});var Ly={};Object.defineProperty(Ly,"__esModule",{value:!0}),Ly.Sepia=void 0;const Khe=function(r){let e=r.data,t=e.length,n,i,s,a;for(n=0;n<t;n+=4)i=e[n+0],s=e[n+1],a=e[n+2],e[n+0]=Math.min(255,i*.393+s*.769+a*.189),e[n+1]=Math.min(255,i*.349+s*.686+a*.168),e[n+2]=Math.min(255,i*.272+s*.534+a*.131)};Ly.Sepia=Khe;var Uy={};Object.defineProperty(Uy,"__esModule",{value:!0}),Uy.Solarize=void 0;const Xhe=function(r){const e=r.data,t=r.width,n=r.height,i=t*4;let s=n;do{const a=(s-1)*i;let o=t;do{const u=a+(o-1)*4;let c=e[u],d=e[u+1],p=e[u+2];c>127&&(c=255-c),d>127&&(d=255-d),p>127&&(p=255-p),e[u]=c,e[u+1]=d,e[u+2]=p}while(--o)}while(--s)};Uy.Solarize=Xhe;var By={};Object.defineProperty(By,"__esModule",{value:!0}),By.Threshold=void 0;const f4=Dt,Yhe=Mn,Jhe=Ct,Qhe=function(r){const e=this.threshold()*255,t=r.data,n=t.length;for(let i=0;i<n;i+=1)t[i]=t[i]<e?0:255};By.Threshold=Qhe,f4.Factory.addGetterSetter(Yhe.Node,"threshold",.5,(0,Jhe.getNumberValidator)(),f4.Factory.afterSetFilter),Object.defineProperty(L0,"__esModule",{value:!0}),L0.Konva=void 0;const p4=e$,Zhe=X0,efe=Q0,tfe=ty,nfe=ny,sfe=sy,m4=ad,rfe=op,ife=sd,afe=up,ofe=ay,lfe=oy,ufe=ly,cfe=uy,dfe=od,hfe=hy,ffe=fy,pfe=my,mfe=_y,gfe=yy,_fe=vy,yfe=by,vfe=Ty,bfe=wy,Sfe=Cy,Tfe=Ey,wfe=xy,Cfe=Iy,Efe=Ry,xfe=ky,Ife=Oy,Afe=$y,Rfe=Dy,Nfe=Fy,kfe=Ly,Ofe=Uy,$fe=By;L0.Konva=p4.Konva.Util._assign(p4.Konva,{Arc:Zhe.Arc,Arrow:efe.Arrow,Circle:tfe.Circle,Ellipse:nfe.Ellipse,Image:sfe.Image,Label:m4.Label,Tag:m4.Tag,Line:rfe.Line,Path:ife.Path,Rect:afe.Rect,RegularPolygon:ofe.RegularPolygon,Ring:lfe.Ring,Sprite:ufe.Sprite,Star:cfe.Star,Text:dfe.Text,TextPath:hfe.TextPath,Transformer:ffe.Transformer,Wedge:pfe.Wedge,Filters:{Blur:mfe.Blur,Brighten:gfe.Brighten,Contrast:_fe.Contrast,Emboss:yfe.Emboss,Enhance:vfe.Enhance,Grayscale:bfe.Grayscale,HSL:Sfe.HSL,HSV:Tfe.HSV,Invert:wfe.Invert,Kaleidoscope:Cfe.Kaleidoscope,Mask:Efe.Mask,Noise:xfe.Noise,Pixelate:Ife.Pixelate,Posterize:Afe.Posterize,RGB:Rfe.RGB,RGBA:Nfe.RGBA,Sepia:kfe.Sepia,Solarize:Ofe.Solarize,Threshold:$fe.Threshold}});var Dfe=iw.exports;Object.defineProperty(Dfe,"__esModule",{value:!0});const Pfe=L0;iw.exports=Pfe.Konva;var Ffe=iw.exports;const dd=mn(Ffe),Bw={STROKE_WIDTH:5,STROKE_COLOR:"#f32",EMPTY_DRAWER_RECT_COLOR:"#fff"};class Hw{constructor(e){this.stage=null,this.strokeWidth=Bw.STROKE_WIDTH,this.strokeColor=Bw.STROKE_COLOR,this.emptyDrawerRectColor=Bw.EMPTY_DRAWER_RECT_COLOR,this.emptyDrawerRect=null;const{container:t,width:n,height:i}=e,s=new dd.Stage({container:t,width:n,height:i});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 dd.Layer;return this.stage.add(e),e}initFreeDrawing(e){let t=!1,n;this.stage.on("mousedown touchstart",i=>{t=!0;const s=this.stage.getPointerPosition();n=new dd.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(n)}),this.stage.on("mouseup touchend",()=>{t=!1}),this.stage.on("mousemove touchmove",i=>{if(!t)return;i.evt.preventDefault();const s=this.stage.getPointerPosition(),a=n.points().concat([s.x,s.y]);n.points(a)})}addRect(e,t,n){const i=new dd.Rect({width:t,height:n,fill:this.emptyDrawerRectColor});return e.add(i),this.emptyDrawerRect=i,i}addImage(e,t){const n=new dd.Image({image:t,x:(this.stage.width()-t.width)/2,y:(this.stage.height()-t.height)/2});return e.add(n),n}addWakeupLine(e){const t=new dd.Line({stroke:"#ffffff",strokeWidth:1,globalCompositeOperation:"source-over",lineCap:"round",lineJoin:"round",points:[0,0,0,0]});e.add(t)}}const Mfe={container:"screen-share-video-container",compositeCanvasContainer:"composite-canvas-container",compositeCanvas:"composite-canvas",drawerContainer:"container",videoElement:"whiteboard-source-video",videoElementContainer:"whiteboard-wrapper"};class pp extends O0{constructor(e,t={}){super("ScreenShareWhiteboard","screen"),this.imageSrc=null,this.konvaDrawer=null,this.mode=void 0,this.screenSharePlugin=null,this.selectors={},this.screenSharePlugin=e,this.selectors={...Mfe,...t.selectors||{}}}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,document.body.appendChild(t)}getAspectRatioDimensions(e,t){const n=e.getTracks()[0].getSettings(),i=t.clientWidth,s=t.clientHeight,a=n.width,o=n.height,u=a/o,c=i/s;let d=0,p=0;return u>c?(d=i,p=i/u):(p=s,d=s*u),{width:d,height:p}}async start(e){this.createVideoElement(),this.initialStream=e,this.video.srcObject=e;const t=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 n=document.getElementById(this.selectors.compositeCanvasContainer);n.style.setProperty("position","relative"),n.style.setProperty("margin","auto 0");const{width:i,height:s}=this.getAspectRatioDimensions(e,t);let a=i,o=s;this.screenShareKonvaDrawer=new Hw({container:this.selectors.drawerContainer,width:a,height:o});const u=this.screenShareKonvaDrawer.addLayer();this.screenShareKonvaDrawer.initFreeDrawing(u);const c=document.getElementById(this.selectors.drawerContainer),d=c.querySelector("canvas"),p=c.querySelector(".konvajs-content"),m=document.getElementById(this.selectors.compositeCanvas);m.style.setProperty("position","absolute"),m.style.setProperty("top","0"),m.style.setProperty("left","0");const _=m.getContext("2d"),y=()=>{const{width:w,height:x}=this.getAspectRatioDimensions(e,t);a=w,o=x,d.width=w,d.height=x,d.style.width=`${w}px`,d.style.height=`${x}px`,p.style.width=`${w}px`,p.style.height=`${x}px`,n.style.height=`${x}px`,m.width=w,m.height=x};y(),window.addEventListener("resize",()=>{y(),this.screenShareKonvaDrawer.addWakeupLine(u)});const b=this.video,S=()=>{_.drawImage(b,0,0,a,o),_.drawImage(d,0,0,a,o),requestAnimationFrame(S)};return S(),m.captureStream(30)}stop(){const e=this.initialStream;return this.initialStream=null,this.video=null,this.wrapperEl=null,this.screenShareKonvaDrawer=null,e}setupScreenShareDrawerOptions(e){this.screenShareKonvaDrawer&&this.screenShareKonvaDrawer.setupDrawerOptions(e)}}pp.video=null,pp.wrapperEl=null,pp.screenShareKonvaDrawer=null,pp.initialStream=null;const g4={WHITEBOARD:"whiteboard",IMAGE_WHITEBOARD:"imageWhiteboard"},Lfe={container:"presentation-video-container",drawerContainer:"presentationCanvasWrapper"};class Ufe extends M0{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={...Lfe,...e.selectors||{}}}setupDrawerOptions(e){this.konvaDrawer&&this.konvaDrawer.setupDrawerOptions(e)}setupDrawerImage(e){this.imageSrc=e}drawEmptyWhiteboard(){const e=document.getElementById(this.selectors.container);e.style.setProperty("min-width","100%"),e.style.setProperty("height","100%");const t=e.clientWidth,n=e.clientHeight;this.konvaDrawer=new Hw({container:this.selectors.drawerContainer,width:t,height:n});const i=this.konvaDrawer.addLayer();this.konvaDrawer.addRect(i,t,n),this.konvaDrawer.initFreeDrawing(i)}async drawImageWhiteboard(){const e=document.getElementById(this.selectors.container),t=e.clientWidth,n=e.clientHeight,i=await yue(this.imageSrc);this.konvaDrawer=new Hw({container:this.selectors.drawerContainer,width:t,height:n});const s=this.konvaDrawer.addLayer();this.konvaDrawer.addImage(s,i),s.batchDraw(),this.konvaDrawer.initFreeDrawing(s)}async generateStream(){if(this.mode===g4.WHITEBOARD)this.drawEmptyWhiteboard();else if(this.mode===g4.IMAGE_WHITEBOARD)await this.drawImageWhiteboard();else return;const t=document.getElementById(this.selectors.drawerContainer).querySelector("canvas"),n=t.getContext("2d");function i(){n.fillRect(0,0,1,1),requestAnimationFrame(i)}i();const s=t.captureStream(30);this.stream=s}async kill(){this.konvaDrawer=null,await this.stop(),this.session._ua.emit("stopWhiteboard")}}const Bfe=gs,Hfe=qi(),$r=new Bfe("WebSocketInterface");var Vfe=class{constructor(e){$r.debug('new() [url:"%s"]',e),this._url=e,this._sip_uri=null,this._via_transport=null,this._ws=null;const t=Hfe.parse(e,"absoluteURI");if(t===-1)throw $r.warn(`invalid WebSocket URI: ${e}`),new TypeError(`Invalid argument: ${e}`);if(t.scheme!=="wss"&&t.scheme!=="ws")throw $r.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($r.debug("connect()"),this.isConnected()){$r.debug(`WebSocket ${this._url} is already connected`);return}else if(this.isConnecting()){$r.debug(`WebSocket ${this._url} is connecting`);return}this._ws&&this.disconnect(),$r.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(){$r.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 $r.debug("send()"),this.isConnected()?(this._ws.send(e),!0):($r.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(){$r.debug(`WebSocket ${this._url} connected`),this.onconnect()}_onClose({wasClean:e,code:t,reason:n}){$r.debug(`WebSocket ${this._url} closed`),e===!1&&$r.debug("WebSocket abrupt disconnection"),this.ondisconnect(!e,t,n)}_onMessage({data:e}){$r.debug("received WebSocket message"),this.ondata(e)}_onError(e){$r.warn(`WebSocket ${this._url} error: `,e)}};const Vw=Ap,Gfe=kt,Wfe=no,zfe=zs(),jfe=yE,qfe=Za(),Kfe=V1(),Xfe=qi(),Yfe=Vfe;oc("JsSIP")("version %s",Vw.version);var Jfe={C:Gfe,Exceptions:Wfe,Utils:zfe,UA:jfe,URI:qfe,NameAddrHeader:Kfe,WebSocketInterface:Yfe,Grammar:Xfe,debug:oc,get name(){return Vw.title},get version(){return Vw.version}};const Qfe=mn(Jfe);function Gw(r){return r<10?`0${r}`:`${r}`}function Zfe(r){let e=r.hours||0,t=r.minutes||0,n=r.seconds||0;n++,n===60&&(n=0,t++,t===60&&(t=0,e++));const i=`${Gw(e)}:${Gw(t)}:${Gw(n)}`;return{seconds:n,minutes:t,hours:e,formatted:i}}var Zs={};Zs.forEach=async(r,e,t)=>{const n=[];for(let i=0;i<r.length;i++)if(i in r){const s=Promise.resolve(r[i]).then(a=>e.call(t||globalThis,a,i,r));n.push(s)}await Promise.all(n)},Zs.forEachSeries=async(r,e,t)=>{for(let n=0;n<r.length;n++)n in r&&await e.call(t||globalThis,await r[n],n,r)},Zs.map=async(r,e,t)=>{const n=[];for(let i=0;i<r.length;i++)i in r&&(n[i]=Promise.resolve(r[i]).then(s=>e.call(t||globalThis,s,i,r)));return Promise.all(n)},Zs.mapSeries=async(r,e,t)=>{const n=[];for(let i=0;i<r.length;i++)i in r&&(n[i]=await e.call(t||globalThis,await r[i],i,r));return n},Zs.find=(r,e,t)=>new Promise((n,i)=>{if(r.length===0)return n();let s=1;for(let a=0;a<r.length;a++){const o=u=>{u?n(r[a]):s===r.length&&n(),s++};Promise.resolve(r[a]).then(u=>e.call(t||globalThis,u,a,r)).then(o).catch(i)}}),Zs.findSeries=async(r,e,t)=>{for(let n=0;n<r.length;n++)if(await e.call(t||globalThis,await r[n],n,r))return r[n]},Zs.findIndex=(r,e,t)=>new Promise((n,i)=>{if(r.length===0)return n(-1);let s=1;for(let a=0;a<r.length;a++){const o=u=>{u?n(a):s===r.length&&n(-1),s++};Promise.resolve(r[a]).then(u=>e.call(t||globalThis,u,a,r)).then(o).catch(i)}}),Zs.findIndexSeries=async(r,e,t)=>{for(let n=0;n<r.length;n++)if(await e.call(t||globalThis,await r[n],n,r))return n},Zs.some=(r,e,t)=>new Promise((n,i)=>{if(r.length===0)return n(!1);let s=1;for(let a=0;a<r.length;a++){if(!(a in r)){s++;continue}const o=u=>{u?n(!0):s===r.length&&n(!1),s++};Promise.resolve(r[a]).then(u=>e.call(t||globalThis,u,a,r)).then(o).catch(i)}}),Zs.someSeries=async(r,e,t)=>{for(let n=0;n<r.length;n++)if(n in r&&await e.call(t||globalThis,await r[n],n,r))return!0;return!1},Zs.every=(r,e,t)=>new Promise((n,i)=>{if(r.length===0)return n(!0);let s=1;for(let a=0;a<r.length;a++){if(!(a in r)){s++;continue}const o=u=>{u?s===r.length&&n(!0):n(!1),s++};Promise.resolve(r[a]).then(u=>e.call(t||globalThis,u,a,r)).then(o).catch(i)}}),Zs.everySeries=async(r,e,t)=>{for(let n=0;n<r.length;n++)if(n in r&&!await e.call(t||globalThis,await r[n],n,r))return!1;return!0},Zs.filter=(r,e,t)=>new Promise(async(n,i)=>{const s=[];for(let o=0;o<r.length;o++)o in r&&(s[o]=Promise.resolve(r[o]).then(u=>e.call(t||globalThis,u,o,r)).catch(i));const a=[];for(let o=0;o<s.length;o++)await s[o]&&a.push(await r[o]);n(a)}),Zs.filterSeries=async(r,e,t)=>{const n=[];for(let i=0;i<r.length;i++)i in r&&await e.call(t||globalThis,await r[i],i,r)&&n.push(await r[i]);return n},Zs.reduce=async(r,e,t)=>{if(r.length===0&&t===void 0)throw TypeError("Reduce of empty array with no initial value");let n,i;for(t!==void 0?(i=t,n=0):(i=r[0],n=1),n;n<r.length;n++)n in r&&(i=await e(await i,await r[n],n,r));return i};var _4={};(function(r){const e=Zs;Object.keys(e).forEach(t=>{const n=t.charAt(0).toUpperCase()+t.slice(1);r[`async${n}`]=async function(...i){return e[t](this,...i)}})})(_4);var epe=Object.assign(Zs,{instanceMethods:_4});const Yu=new AudioContext,la={NEW_CALL:"new_call",CALL_CONFIRMED:"confirmed",CALL_FAILED:"failed",CALL_PROGRESS:"progress",CALL_ENDED:"ended"};var tpe={exports:{}};(function(r){var e=function(t){var n=Object.prototype,i=n.hasOwnProperty,s=Object.defineProperty||function(fe,ne,ae){fe[ne]=ae.value},a,o=typeof Symbol=="function"?Symbol:{},u=o.iterator||"@@iterator",c=o.asyncIterator||"@@asyncIterator",d=o.toStringTag||"@@toStringTag";function p(fe,ne,ae){return Object.defineProperty(fe,ne,{value:ae,enumerable:!0,configurable:!0,writable:!0}),fe[ne]}try{p({},"")}catch{p=function(ne,ae,be){return ne[ae]=be}}function m(fe,ne,ae,be){var Se=ne&&ne.prototype instanceof E?ne:E,Me=Object.create(Se.prototype),ot=new Q(be||[]);return s(Me,"_invoke",{value:G(fe,ae,ot)}),Me}t.wrap=m;function _(fe,ne,ae){try{return{type:"normal",arg:fe.call(ne,ae)}}catch(be){return{type:"throw",arg:be}}}var y="suspendedStart",b="suspendedYield",S="executing",w="completed",x={};function E(){}function I(){}function R(){}var P={};p(P,u,function(){return this});var B=Object.getPrototypeOf,O=B&&B(B(oe([])));O&&O!==n&&i.call(O,u)&&(P=O);var F=R.prototype=E.prototype=Object.create(P);I.prototype=R,s(F,"constructor",{value:R,configurable:!0}),s(R,"constructor",{value:I,configurable:!0}),I.displayName=p(R,d,"GeneratorFunction");function D(fe){["next","throw","return"].forEach(function(ne){p(fe,ne,function(ae){return this._invoke(ne,ae)})})}t.isGeneratorFunction=function(fe){var ne=typeof fe=="function"&&fe.constructor;return ne?ne===I||(ne.displayName||ne.name)==="GeneratorFunction":!1},t.mark=function(fe){return Object.setPrototypeOf?Object.setPrototypeOf(fe,R):(fe.__proto__=R,p(fe,d,"GeneratorFunction")),fe.prototype=Object.create(F),fe},t.awrap=function(fe){return{__await:fe}};function L(fe,ne){function ae(Me,ot,Ve,q){var ue=_(fe[Me],fe,ot);if(ue.type==="throw")q(ue.arg);else{var Ue=ue.arg,mt=Ue.value;return mt&&typeof mt=="object"&&i.call(mt,"__await")?ne.resolve(mt.__await).then(function($e){ae("next",$e,Ve,q)},function($e){ae("throw",$e,Ve,q)}):ne.resolve(mt).then(function($e){Ue.value=$e,Ve(Ue)},function($e){return ae("throw",$e,Ve,q)})}}var be;function Se(Me,ot){function Ve(){return new ne(function(q,ue){ae(Me,ot,q,ue)})}return be=be?be.then(Ve,Ve):Ve()}s(this,"_invoke",{value:Se})}D(L.prototype),p(L.prototype,c,function(){return this}),t.AsyncIterator=L,t.async=function(fe,ne,ae,be,Se){Se===void 0&&(Se=Promise);var Me=new L(m(fe,ne,ae,be),Se);return t.isGeneratorFunction(ne)?Me:Me.next().then(function(ot){return ot.done?ot.value:Me.next()})};function G(fe,ne,ae){var be=y;return function(Me,ot){if(be===S)throw new Error("Generator is already running");if(be===w){if(Me==="throw")throw ot;return Ce()}for(ae.method=Me,ae.arg=ot;;){var Ve=ae.delegate;if(Ve){var q=j(Ve,ae);if(q){if(q===x)continue;return q}}if(ae.method==="next")ae.sent=ae._sent=ae.arg;else if(ae.method==="throw"){if(be===y)throw be=w,ae.arg;ae.dispatchException(ae.arg)}else ae.method==="return"&&ae.abrupt("return",ae.arg);be=S;var ue=_(fe,ne,ae);if(ue.type==="normal"){if(be=ae.done?w:b,ue.arg===x)continue;return{value:ue.arg,done:ae.done}}else ue.type==="throw"&&(be=w,ae.method="throw",ae.arg=ue.arg)}}}function j(fe,ne){var ae=ne.method,be=fe.iterator[ae];if(be===a)return ne.delegate=null,ae==="throw"&&fe.iterator.return&&(ne.method="return",ne.arg=a,j(fe,ne),ne.method==="throw")||ae!=="return"&&(ne.method="throw",ne.arg=new TypeError("The iterator does not provide a '"+ae+"' method")),x;var Se=_(be,fe.iterator,ne.arg);if(Se.type==="throw")return ne.method="throw",ne.arg=Se.arg,ne.delegate=null,x;var Me=Se.arg;if(!Me)return ne.method="throw",ne.arg=new TypeError("iterator result is not an object"),ne.delegate=null,x;if(Me.done)ne[fe.resultName]=Me.value,ne.next=fe.nextLoc,ne.method!=="return"&&(ne.method="next",ne.arg=a);else return Me;return ne.delegate=null,x}D(F),p(F,d,"Generator"),p(F,u,function(){return this}),p(F,"toString",function(){return"[object Generator]"});function te(fe){var ne={tryLoc:fe[0]};1 in fe&&(ne.catchLoc=fe[1]),2 in fe&&(ne.finallyLoc=fe[2],ne.afterLoc=fe[3]),this.tryEntries.push(ne)}function W(fe){var ne=fe.completion||{};ne.type="normal",delete ne.arg,fe.completion=ne}function Q(fe){this.tryEntries=[{tryLoc:"root"}],fe.forEach(te,this),this.reset(!0)}t.keys=function(fe){var ne=Object(fe),ae=[];for(var be in ne)ae.push(be);return ae.reverse(),function Se(){for(;ae.length;){var Me=ae.pop();if(Me in ne)return Se.value=Me,Se.done=!1,Se}return Se.done=!0,Se}};function oe(fe){if(fe){var ne=fe[u];if(ne)return ne.call(fe);if(typeof fe.next=="function")return fe;if(!isNaN(fe.length)){var ae=-1,be=function Se(){for(;++ae<fe.length;)if(i.call(fe,ae))return Se.value=fe[ae],Se.done=!1,Se;return Se.value=a,Se.done=!0,Se};return be.next=be}}return{next:Ce}}t.values=oe;function Ce(){return{value:a,done:!0}}return Q.prototype={constructor:Q,reset:function(fe){if(this.prev=0,this.next=0,this.sent=this._sent=a,this.done=!1,this.delegate=null,this.method="next",this.arg=a,this.tryEntries.forEach(W),!fe)for(var ne in this)ne.charAt(0)==="t"&&i.call(this,ne)&&!isNaN(+ne.slice(1))&&(this[ne]=a)},stop:function(){this.done=!0;var fe=this.tryEntries[0],ne=fe.completion;if(ne.type==="throw")throw ne.arg;return this.rval},dispatchException:function(fe){if(this.done)throw fe;var ne=this;function ae(q,ue){return Me.type="throw",Me.arg=fe,ne.next=q,ue&&(ne.method="next",ne.arg=a),!!ue}for(var be=this.tryEntries.length-1;be>=0;--be){var Se=this.tryEntries[be],Me=Se.completion;if(Se.tryLoc==="root")return ae("end");if(Se.tryLoc<=this.prev){var ot=i.call(Se,"catchLoc"),Ve=i.call(Se,"finallyLoc");if(ot&&Ve){if(this.prev<Se.catchLoc)return ae(Se.catchLoc,!0);if(this.prev<Se.finallyLoc)return ae(Se.finallyLoc)}else if(ot){if(this.prev<Se.catchLoc)return ae(Se.catchLoc,!0)}else if(Ve){if(this.prev<Se.finallyLoc)return ae(Se.finallyLoc)}else throw new Error("try statement without catch or finally")}}},abrupt:function(fe,ne){for(var ae=this.tryEntries.length-1;ae>=0;--ae){var be=this.tryEntries[ae];if(be.tryLoc<=this.prev&&i.call(be,"finallyLoc")&&this.prev<be.finallyLoc){var Se=be;break}}Se&&(fe==="break"||fe==="continue")&&Se.tryLoc<=ne&&ne<=Se.finallyLoc&&(Se=null);var Me=Se?Se.completion:{};return Me.type=fe,Me.arg=ne,Se?(this.method="next",this.next=Se.finallyLoc,x):this.complete(Me)},complete:function(fe,ne){if(fe.type==="throw")throw fe.arg;return fe.type==="break"||fe.type==="continue"?this.next=fe.arg:fe.type==="return"?(this.rval=this.arg=fe.arg,this.method="return",this.next="end"):fe.type==="normal"&&ne&&(this.next=ne),x},finish:function(fe){for(var ne=this.tryEntries.length-1;ne>=0;--ne){var ae=this.tryEntries[ne];if(ae.finallyLoc===fe)return this.complete(ae.completion,ae.afterLoc),W(ae),x}},catch:function(fe){for(var ne=this.tryEntries.length-1;ne>=0;--ne){var ae=this.tryEntries[ne];if(ae.tryLoc===fe){var be=ae.completion;if(be.type==="throw"){var Se=be.arg;W(ae)}return Se}}throw new Error("illegal catch attempt")},delegateYield:function(fe,ne,ae){return this.delegate={iterator:oe(fe),resultName:ne,nextLoc:ae},this.method==="next"&&(this.arg=a),x}},t}(r.exports);try{regeneratorRuntime=e}catch{typeof globalThis=="object"?globalThis.regeneratorRuntime=e:Function("r","regeneratorRuntime = r")(e)}})(tpe);var y4={exports:{}};(function(r){(function(e,t){r.exports?r.exports=t():e.log=t()})(Qn,function(){var e=function(){},t="undefined",n=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),i=["trace","debug","info","warn","error"];function s(b,S){var w=b[S];if(typeof w.bind=="function")return w.bind(b);try{return Function.prototype.bind.call(w,b)}catch{return function(){return Function.prototype.apply.apply(w,[b,arguments])}}}function a(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function o(b){return b==="debug"&&(b="log"),typeof console===t?!1:b==="trace"&&n?a:console[b]!==void 0?s(console,b):console.log!==void 0?s(console,"log"):e}function u(b,S){for(var w=0;w<i.length;w++){var x=i[w];this[x]=w<b?e:this.methodFactory(x,b,S)}this.log=this.debug}function c(b,S,w){return function(){typeof console!==t&&(u.call(this,S,w),this[b].apply(this,arguments))}}function d(b,S,w){return o(b)||c.apply(this,arguments)}function p(b,S,w){var x=this,E;S=S??"WARN";var I="loglevel";typeof b=="string"?I+=":"+b:typeof b=="symbol"&&(I=void 0);function R(F){var D=(i[F]||"silent").toUpperCase();if(!(typeof window===t||!I)){try{window.localStorage[I]=D;return}catch{}try{window.document.cookie=encodeURIComponent(I)+"="+D+";"}catch{}}}function P(){var F;if(!(typeof window===t||!I)){try{F=window.localStorage[I]}catch{}if(typeof F===t)try{var D=window.document.cookie,L=D.indexOf(encodeURIComponent(I)+"=");L!==-1&&(F=/^([^;]+)/.exec(D.slice(L))[1])}catch{}return x.levels[F]===void 0&&(F=void 0),F}}function B(){if(!(typeof window===t||!I)){try{window.localStorage.removeItem(I);return}catch{}try{window.document.cookie=encodeURIComponent(I)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}x.name=b,x.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},x.methodFactory=w||d,x.getLevel=function(){return E},x.setLevel=function(F,D){if(typeof F=="string"&&x.levels[F.toUpperCase()]!==void 0&&(F=x.levels[F.toUpperCase()]),typeof F=="number"&&F>=0&&F<=x.levels.SILENT){if(E=F,D!==!1&&R(F),u.call(x,F,b),typeof console===t&&F<x.levels.SILENT)return"No console available for logging"}else throw"log.setLevel() called with invalid level: "+F},x.setDefaultLevel=function(F){S=F,P()||x.setLevel(F,!1)},x.resetLevel=function(){x.setLevel(S,!1),B()},x.enableAll=function(F){x.setLevel(x.levels.TRACE,F)},x.disableAll=function(F){x.setLevel(x.levels.SILENT,F)};var O=P();O==null&&(O=S),x.setLevel(O,!1)}var m=new p,_={};m.getLogger=function(S){if(typeof S!="symbol"&&typeof S!="string"||S==="")throw new TypeError("You must supply a name when creating a logger.");var w=_[S];return w||(w=_[S]=new p(S,m.getLevel(),m.methodFactory)),w};var y=typeof window!==t?window.log:void 0;return m.noConflict=function(){return typeof window!==t&&window.log===m&&(window.log=y),m},m.getLoggers=function(){return _},m.default=m,m})})(y4);var _r=y4.exports;const Ao=()=>`${new Date().toISOString()} | metrics`,Ro=(r,e,t)=>`${r} | ${e} | ${t}`;_r.setDefaultLevel(_r.levels.TRACE);const npe=r=>{_r.info(Ro(Ao(),"log ",`set log level to ${r?"verbose":"info"}`)),_r.setLevel(r?_r.levels.TRACE:_r.levels.INFO)},spe=r=>{const e=[...Object.keys(_r.levels)];e.includes(r)?(_r.info(Ro(Ao(),"log ",`update log level to ${r.toLowerCase()}`)),_r.setLevel(r)):_r.warn(Ro(Ao(),"log ","Incorrect log level please choose one of "),e)},Qt=(r,e,t)=>{t?_r.debug(Ro(Ao(),r,e),t):_r.debug(Ro(Ao(),r,e))},Ww=(r,e)=>{_r.info(Ro(Ao(),r,e))},Ju=(r,e)=>{_r.info(Ro(Ao(),r,e))},Hy=(r,e)=>{_r.warn(Ro(Ao(),r,e))},hd=(r,e)=>{_r.error(Ro(Ao(),r,e))};function rpe(r){return Math.floor(Math.random()*r).toString()}function v4(r,e){let t=e;return r.forEach(n=>{t=t.replace(n,"")}),t}function ipe(r,e){let t="";for(let n=0;n<e;n+=1)t+=r[rpe(r.length)];return t}function ape({length:r=20,useLetters:e=!0,useNumbers:t=!0,includeSymbols:n=[],excludeSymbols:i=[]}={}){let s="abcdefghijklmnopqrstuvwxyz",a="0123456789",o=[],u=[],c=[];return e&&(i.length&&(s=v4(i,s)),u=s.split("")),t&&(i.length&&(a=v4(i,a)),c=a.split("")),o=[...u,...c,...n],ipe(o,r)}var ope=ape;const mp=mn(ope),lpe=()=>"WebRTCMetrics",upe=()=>"5.0.3",vn={INBOUND:"inbound",OUTBOUND:"outbound"},No={IDLE:"idle",RUNNING:"running",MUTED:"muted"},gp={NEW:"new",CHECKING:"checking",CONNECTED:"connected",COMPLETED:"completed",DISCONNECTED:"disconnected",FAILED:"failed",CLOSED:"closed"},cpe=()=>({...{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:[]}}),b4={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:vn.INBOUND},S4={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:vn.OUTBOUND},T4={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:vn.INBOUND},w4={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:vn.OUTBOUND},dpe=r=>{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(r){const t={...r,audio:{},video:{},data:{...r.data},network:{...r.network},experimental:{...r.experimental}};return Object.keys(r.audio).forEach(n=>{t.audio[n]={...r.audio[n]}}),Object.keys(r.video).forEach(n=>{t.video[n]={...r.video[n]}}),t}return{...e,audio:{},video:{},data:{...e.data},network:{...e.network},experimental:{...e.experimental}}},hpe={refreshEvery:2e3,startAfter:0,stopAfter:-1,verbose:!1,pname:`p-${mp()}`,cid:`c-${mp()}`,uid:`u-${mp()}`,record:!1,ticket:!0},ua={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"},we={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"},_e={SUCCEEDED:"succeeded",AUDIO:"audio",VIDEO:"video"},_p={ETHERNET:0,CELLULAR_5G:2,WIFI:3,CELLULAR_4G:5,CELLULAR:10},zw={ETHERNET:"ethernet",CELLULAR_4G:"cellular",WIFI:"wifi"},Le={AUDIO:"audio",VIDEO:"video",NETWORK:"network",DATA:"data"},jw="config ",fpe=(r,e={},t)=>{const n={...t,...e};return e.pname||Hy(jw,`Argument [String] 'cfg.pname' for the peerConnection name or id is missing - use generated '${t.pname}'`),e.cid||Hy(jw,`Argument [String] 'cfg.cid' for the call name or id is missing - use generated '${t.cid}'`),e.uid||Hy(jw,`Argument [String] 'cfg.uid' for the user name or id is missing - use generated '${t.uid}'`),n.pc=r,n},ppe=(r={})=>{const e={...hpe,...r};return e.name=lpe(),e.version=upe(),e},yp=(r,e,t,n=!1,i)=>{let s=r.map(a=>{if(!t)return a[e];if(!i)return a[e][t];const o=a[e][i];return o?o[t]:null});return s=s.filter(a=>n?Number.isFinite(a)&&a>0:Number.isFinite(a)),s.length===0?[]:s},Dl=r=>r.reduce((e,t)=>e+t,0)/r.length,mpe=()=>`probe-${mp()}`,gpe=()=>`coltr-${mp()}`,C4=r=>new Promise(e=>setTimeout(e,r)),qw=(r,e,t)=>{e?r.call(e,t):r(t)},Bn=(r,e,t,n)=>{const i=yp(r,e,t,!0,n);if(i.length===0)return null;const s=i.reduce((c,d)=>c+d,0)/i.length;return s===0?null:i.map(c=>Math.abs(s-c)).reduce((c,d)=>c+d,0)/i.length*100/s},jn=(r,e,t,n=!1,i)=>{const s=yp(r,e,t,n,i);return s.length===0?null:s.reduce((a,o)=>a+o,0)/s.length},Qu=(r,e,t)=>yp(r,e,t).reduce((i,s)=>i+s,0),Hn=(r,e,t,n)=>{const i=yp(r,e,t,!0,n);return i.length===0?null:Math.min(...i)},Vn=(r,e,t,n)=>{const i=yp(r,e,t,!1,n);return i.length===0?null:Math.max(...i)},er=(r,e,t,n)=>{const i=r.slice().pop();if(!i)return null;if(!t)return i[e];if(!n)return i[e][t];const s=i[e][n];return s?s[t]:null},_pe=r=>r.slice().pop(),Fs=(r,e,t)=>{if(!e)return null;const n={};let i=e[_e.AUDIO][r];i||(i=t===vn.INBOUND?{...b4}:{...S4}),n[_e.AUDIO]=i;let s=e[_e.VIDEO][r];return s||(s=t===vn.INBOUND?{...T4}:{...w4}),n[_e.VIDEO]=s,n},vp="exporter ",ype="2.0",E4=(r,e,t)=>{if(!r||r.length===0)return 0;const n=r[r.length-1];if(!n)return 0;const i=n[e][t];if(i){const s=i.total_rtt_ms_out,a=i.total_rtt_measure_out;return!a||!s?jn(r,e,"delta_rtt_ms_out",!1,t):Number(s/a)}return null},vpe=(r,e)=>{if(!r||r.length===0)return 0;const t=r[r.length-1];if(!t)return 0;const n=t[e].total_rtt_connectivity_ms,i=t[e].total_rtt_connectivity_measure;return!i||!n?jn(r,e,"delta_rtt_connectivity_ms"):Number(n/i)},bpe=r=>er(r,"network","local_candidate_type")!=="relay"?`direct/${er(r,"network","local_candidate_protocol")}`:`turn/${er(r,"network","local_candidate_relay_protocol")}`,Spe=r=>{const e=er(r,"network","remote_candidate_type"),t=er(r,"network","remote_candidate_protocol");return e!=="relay"?`direct/${t}`:`turn/${t}`};class Tpe{constructor(e){this._start=null,this._end=null,this._cfg=e,this._referenceReport=null,this._reports=[],this._events=[]}start(){Ww(vp,"start() - start exporter...");const e=new Date;return this._start=e.toJSON(),e}stop(){Ww(vp,"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&&(Qt(vp,`addReport() - add report to exporter at ${e.timestamp}`),this._reports.push(e))}addCustomEvent(e){this._events.push(e)}reset(){Ww(vp,"resetReports() - reset reports"),this._reports=[],this._referenceReport=null,this._start=null,this._end=null}get ticket(){Qt(vp,"ticket() - generate ticket");const e=er(this._reports,"audio","total_packets_lost_in"),t=er(this._reports,"audio","total_packets_in"),n=er(this._reports,"video","total_packets_lost_in"),i=er(this._reports,"video","total_packets_in"),s={},a=_pe(this._reports);return a&&(Object.keys(a[_e.AUDIO]).forEach(o=>{const u=a[_e.AUDIO][o];if(s[u.ssrc]={type:_e.AUDIO,direction:u.direction},u.direction===vn.INBOUND){const c={avg:jn(this._reports,_e.AUDIO,"delta_jitter_ms_in",!1,o),min:Hn(this._reports,_e.AUDIO,"delta_jitter_ms_in",o),max:Vn(this._reports,_e.AUDIO,"delta_jitter_ms_in",o),volatility:Bn(this._reports,_e.AUDIO,"delta_jitter_ms_in",o),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},d={avg:jn(this._reports,_e.AUDIO,"delta_kbs_in",!1,o),min:Hn(this._reports,_e.AUDIO,"delta_kbs_in",o),max:Vn(this._reports,_e.AUDIO,"delta_kbs_in",o),volatility:Bn(this._reports,_e.AUDIO,"delta_kbs_in",o),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},p={avg:jn(this._reports,_e.AUDIO,"delta_KBytes_in",!1,o),min:Hn(this._reports,_e.AUDIO,"delta_KBytes_in",o),max:Vn(this._reports,_e.AUDIO,"delta_KBytes_in",o),volatility:Bn(this._reports,_e.AUDIO,"delta_KBytes_in",o),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},m={emodel:{avg:jn(this._reports,_e.AUDIO,"mos_emodel_in",!1,o),min:Hn(this._reports,_e.AUDIO,"mos_emodel_in",o),max:Vn(this._reports,_e.AUDIO,"mos_emodel_in",o),volatility:Bn(this._reports,_e.AUDIO,"mos_emodel_in",o)},effective:{avg:jn(this._reports,_e.AUDIO,"mos_in",!1,o),min:Hn(this._reports,_e.AUDIO,"mos_in",o),max:Vn(this._reports,_e.AUDIO,"mos_in",o),volatility:Bn(this._reports,_e.AUDIO,"mos_in",o)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}},_=er(this._reports,_e.AUDIO,"total_packets_lost_in",o),y=er(this._reports,_e.AUDIO,"total_packets_in",o),b={lost:_,avg:Math.round((_/(_+y)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};s[o].jitter=c,s[o].mos=m,s[o].traffic=p,s[o].bitrate=d,s[o].loss=b}else{const c={avg:jn(this._reports,_e.AUDIO,"delta_jitter_ms_out",!1,o),min:Hn(this._reports,_e.AUDIO,"delta_jitter_ms_out",o),max:Vn(this._reports,_e.AUDIO,"delta_jitter_ms_out",o),volatility:Bn(this._reports,_e.AUDIO,"delta_jitter_ms_out",o),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},d={avg:jn(this._reports,_e.AUDIO,"delta_kbs_out",!1,o),min:Hn(this._reports,_e.AUDIO,"delta_kbs_out",o),max:Vn(this._reports,_e.AUDIO,"delta_kbs_out",o),volatility:Bn(this._reports,_e.AUDIO,"delta_kbs_out",o),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},p={avg:jn(this._reports,_e.AUDIO,"delta_KBytes_out",!1,o),min:Hn(this._reports,_e.AUDIO,"delta_KBytes_out",o),max:Vn(this._reports,_e.AUDIO,"delta_KBytes_out",o),volatility:Bn(this._reports,_e.AUDIO,"delta_KBytes_out",o),_unit:{avg:"KB",min:"KB",max:"KB",bitrate:"kbs",volatility:"percent"}},m={avg:E4(this._reports,_e.AUDIO,o),min:Hn(this._reports,_e.AUDIO,"delta_rtt_ms_out",o),max:Vn(this._reports,_e.AUDIO,"delta_rtt_ms_out",o),volatility:Bn(this._reports,_e.AUDIO,"delta_rtt_ms_out",o),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},_=er(this._reports,_e.AUDIO,"total_packets_lost_out",o),y=er(this._reports,_e.AUDIO,"total_packets_out",o),b={lost:_,avg:Math.round((_/(_+y)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}},S={emodel:{avg:jn(this._reports,_e.AUDIO,"mos_emodel_out",!1,o),min:Hn(this._reports,_e.AUDIO,"mos_emodel_out",o),max:Vn(this._reports,_e.AUDIO,"mos_emodel_out",o),volatility:Bn(this._reports,_e.AUDIO,"mos_emodel_out",o)},effective:{avg:jn(this._reports,_e.AUDIO,"mos_out",!1,o),min:Hn(this._reports,_e.AUDIO,"mos_out",o),max:Vn(this._reports,_e.AUDIO,"mos_out",o),volatility:Bn(this._reports,_e.AUDIO,"mos_out",o)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}};s[o].jitter=c,s[o].rtt=m,s[o].traffic=p,s[o].bitrate=d,s[o].loss=b,s[o].mos=S}}),Object.keys(a[_e.VIDEO]).forEach(o=>{const u=a[_e.VIDEO][o];if(s[o]={type:_e.VIDEO,direction:u.direction},u.direction===vn.INBOUND){const c={avg:jn(this._reports,_e.VIDEO,"delta_jitter_ms_in",!1,o),min:Hn(this._reports,_e.VIDEO,"delta_jitter_ms_in",o),max:Vn(this._reports,_e.VIDEO,"delta_jitter_ms_in",o),volatility:Bn(this._reports,_e.VIDEO,"delta_jitter_ms_in",o),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},d={avg:jn(this._reports,_e.VIDEO,"delta_kbs_in",!1,o),min:Hn(this._reports,_e.VIDEO,"delta_kbs_in",o),max:Vn(this._reports,_e.VIDEO,"delta_kbs_in",o),volatility:Bn(this._reports,_e.VIDEO,"delta_kbs_in",o),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},p={avg:jn(this._reports,_e.VIDEO,"delta_KBytes_in",!1,o),min:Hn(this._reports,_e.VIDEO,"delta_KBytes_in",o),max:Vn(this._reports,_e.VIDEO,"delta_KBytes_in",o),volatility:Bn(this._reports,_e.VIDEO,"delta_KBytes_in",o),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},m=er(this._reports,_e.VIDEO,"total_packets_lost_in",o),_=er(this._reports,_e.VIDEO,"total_packets_in",o),y={lost:m,avg:Math.round((m/(m+_)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};s[o].jitter=c,s[o].traffic=p,s[o].bitrate=d,s[o].loss=y}else{const c={avg:jn(this._reports,_e.VIDEO,"delta_jitter_ms_out",!1,o),min:Hn(this._reports,_e.VIDEO,"delta_jitter_ms_out",o),max:Vn(this._reports,_e.VIDEO,"delta_jitter_ms_out",o),volatility:Bn(this._reports,_e.VIDEO,"delta_jitter_ms_out",o),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},d={avg:jn(this._reports,_e.VIDEO,"delta_kbs_out",!1,o),min:Hn(this._reports,_e.VIDEO,"delta_kbs_out",o),max:Vn(this._reports,_e.VIDEO,"delta_kbs_out",o),volatility:Bn(this._reports,_e.VIDEO,"delta_kbs_out",o),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},p={avg:jn(this._reports,_e.VIDEO,"delta_KBytes_out",!1,o),min:Hn(this._reports,_e.VIDEO,"delta_KBytes_out",o),max:Vn(this._reports,_e.VIDEO,"delta_KBytes_out",o),volatility:Bn(this._reports,_e.VIDEO,"delta_KBytes_out",o),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},m={avg:E4(this._reports,_e.VIDEO,o),min:Hn(this._reports,_e.VIDEO,"delta_rtt_ms_out",o),max:Vn(this._reports,_e.VIDEO,"delta_rtt_ms_out",o),volatility:Bn(this._reports,_e.VIDEO,"delta_rtt_ms_out",o),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},_=er(this._reports,_e.VIDEO,"total_packets_lost_out",o),y=er(this._reports,_e.VIDEO,"total_packets_out",o),b={lost:_,avg:Math.round((_/(_+y)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};s[o].jitter=c,s[o].rtt=m,s[o].traffic=p,s[o].bitrate=d,s[o].loss=b}})),{version:ype,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:vpe(this._reports,"data"),min:Hn(this._reports,"data","delta_rtt_connectivity_ms"),max:Vn(this._reports,"data","delta_rtt_connectivity_ms"),volatility:Bn(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((n/(n+i)*100||0)*100)/100}},unit:{avg:"percent"}},bitrate:{in:{avg:jn(this._reports,"data","delta_kbs_in"),min:Hn(this._reports,"data","delta_kbs_in"),max:Vn(this._reports,"data","delta_kbs_in"),volatility:Bn(this._reports,"data","delta_kbs_in")},out:{avg:jn(this._reports,"data","delta_kbs_out"),min:Hn(this._reports,"data","delta_kbs_out"),max:Vn(this._reports,"data","delta_kbs_out"),volatility:Bn(this._reports,"data","delta_kbs_out")},unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},traffic:{in:{avg:jn(this._reports,"data","delta_KBytes_in"),min:Hn(this._reports,"data","delta_KBytes_in"),max:Vn(this._reports,"data","delta_KBytes_in"),volatility:Bn(this._reports,"data","delta_KBytes_in")},out:{avg:jn(this._reports,"data","delta_KBytes_out"),min:Hn(this._reports,"data","delta_KBytes_out"),max:Vn(this._reports,"data","delta_KBytes_out"),volatility:Bn(this._reports,"data","delta_KBytes_out")},unit:{avg:"KBytes",min:"KBytes",max:"KBytes",volatility:"percent"}},network:{localConnection:bpe(this._reports),remoteConnection:Spe(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 Pl="extractor ",x4=(r,e,t,n)=>{let i=!1;const s=n[e].total_rtt_ms_out,a=n[e].total_rtt_measure_out,o=t?t[e].total_rtt_ms_out:0,u=t?t[e].total_rtt_measure_out:0,c={rtt:null,totalRTT:s,totalRTTMeasurements:a};if(r[we.TIMESTAMP]===n[e].timestamp_out||!Object.prototype.hasOwnProperty.call(r,we.ROUND_TRIP_TIME)||Object.prototype.hasOwnProperty.call(r,we.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS)&&(i=!0,Number(r[we.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])===0||Number(r[we.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])-u===a))return c;const d=1e3*Number(r[we.ROUND_TRIP_TIME]);let p=s+d,m=a+1;return i&&(p=1e3*Number(r[we.TOTAL_ROUND_TRIP_TIME])-o,m=Number(r[we.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])-u),{rtt:d,totalRTT:p,totalRTTMeasurements:m}},wpe=(r,e,t,n)=>{if(!Object.prototype.hasOwnProperty.call(r,we.CURRENT_ROUND_TRIP_TIME))return{rtt:null,totalRTT:n[e].total_rtt_connectivity_ms,totalRTTMeasurements:n[e].total_rtt_connectivity_measure};const i=1e3*Number(r[we.CURRENT_ROUND_TRIP_TIME]);let s=n[e].total_rtt_connectivity_ms+i,a=n[e].total_rtt_connectivity_measure+1;return Object.prototype.hasOwnProperty.call(r,we.TOTAL_ROUND_TRIP_TIME)&&(s=1e3*Number(r[we.TOTAL_ROUND_TRIP_TIME])-(t?t[e].total_rtt_connectivity_ms:0)),Object.prototype.hasOwnProperty.call(r,we.RESPONSES_RECEIVED)&&(a=Number(r[we.RESPONSES_RECEIVED])-(t?t[e].total_rtt_connectivity_measure:0)),{rtt:i,totalRTT:s,totalRTTMeasurements:a}},Vy=(r,e,t)=>r[we.TIMESTAMP]===t[e].timestamp_out||!Object.prototype.hasOwnProperty.call(r,we.JITTER)?null:1e3*(Number(r[we.JITTER])||0),Cpe=(r,e)=>{if(!Object.prototype.hasOwnProperty.call(r,we.FRAMES_DECODED)||!Object.prototype.hasOwnProperty.call(r,we.TOTAL_DECODE_TIME))return{delta_ms_decode_frame:e[_e.VIDEO].delta_ms_decode_frame_in,frames_decoded:e[_e.VIDEO].total_frames_decoded_in,total_decode_time:e[_e.VIDEO].total_time_decoded_in};const t=r[we.FRAMES_DECODED],n=r[we.TOTAL_DECODE_TIME],i=n-e[_e.VIDEO].total_time_decoded_in,s=t-e[_e.VIDEO].total_frames_decoded_in;return{delta_ms_decode_frame:s>0?i*1e3/s:0,frames_decoded:t,total_decode_time:n}},Epe=(r,e)=>{if(!Object.prototype.hasOwnProperty.call(r,we.FRAMES_ENCODED)||!Object.prototype.hasOwnProperty.call(r,we.TOTAL_ENCODE_TIME))return{delta_ms_encode_frame:e[_e.VIDEO].delta_ms_encode_frame_out,frames_encoded:e[_e.VIDEO].total_frames_encoded_out,total_encode_time:e[_e.VIDEO].total_time_encoded_out};const t=r[we.FRAMES_ENCODED],n=r[we.TOTAL_ENCODE_TIME],i=n-e[_e.VIDEO].total_time_encoded_out,s=t-e[_e.VIDEO].total_frames_encoded_out;return{delta_ms_encode_frame:s>0&&i?i*1e3/s:0,frames_encoded:t,total_encode_time:n}},I4=(r,e,t,n)=>{if(!Object.prototype.hasOwnProperty.call(r,we.PACKETS_SENT)||!Object.prototype.hasOwnProperty.call(r,we.BYTES_SENT))return{packetsSent:t[e].total_packets_out,packetsLost:t[e].total_packets_lost_out,bytesSent:t[e].total_KBytes_out};const i=Number(r[we.PACKETS_SENT])||0-(n?n[e].total_packets_out:0),s=i-t[e].total_packets_out,a=Number(r[we.BYTES_SENT])/1024-(n?n[e].total_KBytes_out:0),o=a-t[e].total_KBytes_out,u=r[we.TIMESTAMP]||Date.now(),c=n?n.timestamp:null;let d=t.timestamp;!d&&c&&(d=c);const p=d?u-d:0,m=p>0?o*.008*1024/p*1e3:0;return{packetsSent:i,deltaPacketsSent:s,KBytesSent:a,deltaKBytesSent:o,kbsSent:m}},A4=(r,e,t,n)=>{let i=t[e].total_packets_lost_out,s=0,a=0;return Object.prototype.hasOwnProperty.call(r,we.PACKETS_LOST)&&(i=Number(r[we.PACKETS_LOST])||0-(n?n[e].total_packets_lost_out:0),s=i-t[e].total_packets_lost_out),Object.prototype.hasOwnProperty.call(r,we.FRACTION_LOST)&&(a=Number(100*r[we.FRACTION_LOST])),{packetsLost:i,deltaPacketsLost:s,fractionLost:a}},R4=(r,e,t,n)=>{if(!Object.prototype.hasOwnProperty.call(r,we.PACKETS_RECEIVED)||!Object.prototype.hasOwnProperty.call(r,we.PACKETS_LOST)||!Object.prototype.hasOwnProperty.call(r,we.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 i=Number(r[we.PACKETS_RECEIVED])||0-(n?n[e].total_packets_in:0),s=Number(r[we.PACKETS_LOST])||0-(n?n[e].total_packets_lost_in:0),a=s-t[e].total_packets_lost_in,o=i-t[e].total_packets_in,u=i!==t[e].total_packets_in?a*100/(a+o):0,c=Number(r[we.BYTES_RECEIVED])/1024-(n?n[e].total_KBytes_in:0),d=c-t[e].total_KBytes_in,p=r[we.TIMESTAMP]||Date.now(),m=n?n.timestamp:null;let _=t.timestamp;!_&&m&&(_=m);const y=_?p-_:0,b=y>0?d*.008*1024/y*1e3:0;return{percentPacketsLost:u,packetsReceived:i,deltaPacketsReceived:o,packetsLost:s,deltaPacketsLost:a,KBytesReceived:c,deltaKBytesReceived:d,kbsReceived:b}},xpe=r=>r[we.CANDIDATE_TYPE]!=="relay"?"":r[we.RELAY_PROTOCOL]||"",Ipe=r=>{if(!Object.prototype.hasOwnProperty.call(r,we.NETWORK_TYPE))return _p.WIFI;switch(r[we.NETWORK_TYPE]){case zw.ETHERNET:return _p.ETHERNET;case zw.CELLULAR_4G:return _p.CELLULAR_4G;case zw.WIFI:return _p.WIFI;default:return _p.CELLULAR}},N4=r=>!Object.prototype.hasOwnProperty.call(r,we.FRAME_HEIGHT)||!Object.prototype.hasOwnProperty.call(r,we.FRAME_WIDTH)?{width:null,height:null,framerate:null}:{width:r[we.FRAME_WIDTH]||null,height:r[we.FRAME_HEIGHT]||null,framerate:r[we.FRAMES_PER_SECOND]},Ape=r=>{const e=Object.prototype.hasOwnProperty.call(r,we.QUALITY_LIMITATION_REASON)?r[we.QUALITY_LIMITATION_REASON]:null,t=Object.prototype.hasOwnProperty.call(r,we.QUALITY_LIMITATION_RESOLUTION_CHANGES)?r[we.QUALITY_LIMITATION_RESOLUTION_CHANGES]:null,n=Object.prototype.hasOwnProperty.call(r,we.QUALITY_LIMITATION_DURATIONS)?r[we.QUALITY_LIMITATION_DURATIONS]:null;return n&&Object.keys(n).forEach(i=>{n[i]>1e3&&(n[i]=Number(n[i]/1e3))}),{reason:e,durations:n,resolutionChanges:t}},Rpe=(r,e,t)=>{if(!Object.prototype.hasOwnProperty.call(r,we.PLI)||!Object.prototype.hasOwnProperty.call(r,we.NACK))return{pliCount:e.total_pli_sent_in,nackCount:e.total_nack_sent_in,deltaPliCount:0,deltaNackCount:0};const n=(r[we.PLI]||0)-(t?t[_e.VIDEO].total_pli_sent_in:0),i=(r[we.NACK]||0)-(t?t[_e.VIDEO].total_nack_sent_in:0);return{pliCount:n,nackCount:i,deltaPliCount:n-e[_e.VIDEO].total_pli_sent_in,deltaNackCount:i-e[_e.VIDEO].total_nack_sent_in}},Npe=(r,e,t)=>{if(!Object.prototype.hasOwnProperty.call(r,we.PLI)||!Object.prototype.hasOwnProperty.call(r,we.NACK))return{pliCount:e.total_pli_received_out,nackCount:e.total_nack_received_out,deltaPliCount:0,deltaNackCount:0};const n=(r[we.PLI]||0)-(t?t[_e.VIDEO].total_pli_received_out:0),i=(r[we.NACK]||0)-(t?t[_e.VIDEO].total_nack_received_out:0);return{pliCount:n,nackCount:i,deltaPliCount:n-e[_e.VIDEO].total_pli_received_out,deltaNackCount:i-e[_e.VIDEO].total_nack_received_out}},kpe=r=>({channels:r[we.CHANNELS]||null,clock_rate:r[we.CLOCK_RATE]||null,mime_type:r[we.MIME_TYPE]||null,sdp_fmtp_line:r[we.SDP_FMTP_LINE]||null}),Ope=r=>({clock_rate:r[we.CLOCK_RATE]||null,mime_type:r[we.MIME_TYPE]||null}),$pe=(r,e,t)=>{const n=(r[we.BYTES_RECEIVED]||0)/1024-(t?t.data.total_KBytes_in:0),i=(r[we.BYTES_SENT]||0)/1024-(t?t.data.total_KBytes_out:0),s=r[we.TIMESTAMP]||Date.now(),a=n-e.data.total_KBytes_in,o=i-e.data.total_KBytes_out,u=t?t.timestamp:null;let c=e.timestamp;!c&&u&&(c=u);const d=c?s-c:0,p=d>0?a*.008*1024/d*1e3:0,m=d>0?o*.008*1024/d*1e3:0;return{total_KBytes_received:n,total_KBytes_sent:i,delta_KBytes_received:a,delta_KBytes_sent:o,kbs_speed_received:p,kbs_speed_sent:m}},Dpe=r=>{const e=r[we.AVAILABLE_INCOMING_BITRATE]/1024||0,t=r[we.AVAILABLE_OUTGOING_BITRATE]/1024||0;return{kbs_incoming_bandwidth:e,kbs_outgoing_bandwidth:t}},Ppe=(r,e,t,n)=>{if(!r)return[];switch(r[we.TYPE]){case ua.CANDIDATE_PAIR:let i=!1;if(r[we.NOMINATED]&&r[we.STATE]===_e.SUCCEEDED&&(i=!0,Qt(Pl,`analyze() - got stats ${r[we.TYPE]} for ${t}`,r),we.SELECTED in r&&!r[we.SELECTED]&&(i=!1)),i){const a=r[we.LOCAL_CANDIDATE_ID],o=r[we.REMOTE_CANDIDATE_ID],u=$pe(r,e,n),c=Dpe(r),d=wpe(r,"data",n,e);return[{type:Le.NETWORK,value:{local_candidate_id:a}},{type:Le.NETWORK,value:{remote_candidate_id:o}},{type:Le.DATA,value:{total_KBytes_in:u.total_KBytes_received}},{type:Le.DATA,value:{total_KBytes_out:u.total_KBytes_sent}},{type:Le.DATA,value:{delta_KBytes_in:u.delta_KBytes_received}},{type:Le.DATA,value:{delta_KBytes_out:u.delta_KBytes_sent}},{type:Le.DATA,value:{delta_kbs_in:u.kbs_speed_received}},{type:Le.DATA,value:{delta_kbs_out:u.kbs_speed_sent}},{type:Le.DATA,value:{delta_kbs_bandwidth_in:c.kbs_incoming_bandwidth}},{type:Le.DATA,value:{delta_kbs_bandwidth_out:c.kbs_outgoing_bandwidth}},{type:Le.DATA,value:{delta_rtt_connectivity_ms:d.rtt}},{type:Le.DATA,value:{total_rtt_connectivity_ms:d.totalRTT}},{type:Le.DATA,value:{total_rtt_connectivity_measure:d.totalRTTMeasurements}}]}break;case ua.LOCAL_CANDIDATE:if(r[we.ID]===e.network.local_candidate_id)return[{type:Le.NETWORK,value:{infrastructure:Ipe(r)}},{type:Le.NETWORK,value:{local_candidate_type:r[we.CANDIDATE_TYPE]||""}},{type:Le.NETWORK,value:{local_candidate_protocol:r[we.PROTOCOL]||""}},{type:Le.NETWORK,value:{local_candidate_relay_protocol:xpe(r)}}];break;case ua.REMOTE_CANDIDATE:if(r[we.ID]===e.network.remote_candidate_id)return[{type:Le.NETWORK,value:{remote_candidate_type:r[we.CANDIDATE_TYPE]||""}},{type:Le.NETWORK,value:{remote_candidate_protocol:r[we.PROTOCOL]||""}}];break;case ua.INBOUND_RTP:{Qt(Pl,`analyze() - got stats ${r[we.TYPE]} for ${t}`,r);const a=r[we.SSRC],o=Fs(a,e,vn.INBOUND);o&&(o.timestamp=e.timestamp);const u=Fs(a,n,vn.INBOUND);if(u&&(u.timestamp=n.timestamp),r[we.MEDIA_TYPE]===_e.AUDIO){const c=R4(r,_e.AUDIO,o,u),d=Vy(r,_e.AUDIO,o),p=r[we.CODEC_ID]||"";return[{ssrc:a,type:Le.AUDIO,value:{codec_id_in:p}},{ssrc:a,type:Le.AUDIO,value:{total_packets_in:c.packetsReceived}},{ssrc:a,type:Le.AUDIO,value:{delta_packets_in:c.deltaPacketsReceived}},{ssrc:a,type:Le.AUDIO,value:{total_packets_lost_in:c.packetsLost}},{ssrc:a,type:Le.AUDIO,value:{delta_packets_lost_in:c.deltaPacketsLost}},{ssrc:a,type:Le.AUDIO,value:{percent_packets_lost_in:c.percentPacketsLost}},{ssrc:a,type:Le.AUDIO,value:{total_KBytes_in:c.KBytesReceived}},{ssrc:a,type:Le.AUDIO,value:{delta_KBytes_in:c.deltaKBytesReceived}},{ssrc:a,type:Le.AUDIO,value:{delta_kbs_in:c.kbsReceived}},{ssrc:a,type:Le.AUDIO,value:{delta_jitter_ms_in:d}}]}if(r[we.MEDIA_TYPE]===_e.VIDEO){const c=Cpe(r,o),d=R4(r,_e.VIDEO,o,u),p=Vy(r,_e.VIDEO,o),m=r[we.DECODER_IMPLEMENTATION]||null,_=r[we.CODEC_ID]||null,y=N4(r),b=Rpe(r,o,u);return[{ssrc:a,type:Le.VIDEO,value:{codec_id_in:_}},{ssrc:a,type:Le.VIDEO,value:{total_packets_in:d.packetsReceived}},{ssrc:a,type:Le.VIDEO,value:{delta_packets_in:d.deltaPacketsReceived}},{ssrc:a,type:Le.VIDEO,value:{total_packets_lost_in:d.packetsLost}},{ssrc:a,type:Le.VIDEO,value:{delta_packets_lost_in:d.deltaPacketsLost}},{ssrc:a,type:Le.VIDEO,value:{percent_packets_lost_in:d.percentPacketsLost}},{ssrc:a,type:Le.VIDEO,value:{total_KBytes_in:d.KBytesReceived}},{ssrc:a,type:Le.VIDEO,value:{delta_KBytes_in:d.deltaKBytesReceived}},{ssrc:a,type:Le.VIDEO,value:{delta_kbs_in:d.kbsReceived}},{ssrc:a,type:Le.VIDEO,value:{delta_jitter_ms_in:p}},{ssrc:a,type:Le.VIDEO,value:{decoder_in:m}},{ssrc:a,type:Le.VIDEO,value:{delta_ms_decode_frame_in:c.delta_ms_decode_frame}},{ssrc:a,type:Le.VIDEO,value:{total_frames_decoded_in:c.frames_decoded}},{ssrc:a,type:Le.VIDEO,value:{total_time_decoded_in:c.total_decode_time}},{ssrc:a,type:Le.VIDEO,value:{total_nack_sent_in:b.nackCount}},{ssrc:a,type:Le.VIDEO,value:{delta_nack_sent_in:b.deltaNackCount}},{ssrc:a,type:Le.VIDEO,value:{total_pli_sent_in:b.pliCount}},{ssrc:a,type:Le.VIDEO,value:{delta_pli_sent_in:b.deltaPliCount}},{ssrc:a,type:Le.VIDEO,value:{size_in:y}}]}break}case ua.OUTBOUND_RTP:{Qt(Pl,`analyze() - got stats ${r[we.TYPE]} for ${t}`,r);const a=r[we.SSRC],o=Fs(a,e,vn.OUTBOUND);o&&(o.timestamp=e.timestamp);const u=Fs(a,n,vn.OUTBOUND);if(u&&(u.timestamp=n.timestamp),r[we.MEDIA_TYPE]===_e.AUDIO){const c=r[we.CODEC_ID]||null,d=I4(r,_e.AUDIO,o,u);return[{ssrc:a,type:Le.AUDIO,value:{codec_id_out:c}},{ssrc:a,type:Le.AUDIO,value:{total_packets_out:d.packetsSent}},{ssrc:a,type:Le.AUDIO,value:{delta_packets_out:d.deltaPacketsSent}},{ssrc:a,type:Le.AUDIO,value:{total_KBytes_out:d.KBytesSent}},{ssrc:a,type:Le.AUDIO,value:{delta_KBytes_out:d.deltaKBytesSent}},{ssrc:a,type:Le.AUDIO,value:{delta_kbs_out:d.kbsSent}}]}if(r[we.MEDIA_TYPE]===_e.VIDEO){const c=r[we.ENCODER_IMPLEMENTATION]||null,d=r[we.CODEC_ID]||null,p=Epe(r,o),m=N4(r),_=Ape(r),y=Npe(r,o,u),b=I4(r,_e.VIDEO,o,u);return[{ssrc:a,type:Le.VIDEO,value:{codec_id_out:d}},{ssrc:a,type:Le.VIDEO,value:{total_packets_out:b.packetsSent}},{ssrc:a,type:Le.VIDEO,value:{delta_packets_out:b.deltaPacketsSent}},{ssrc:a,type:Le.VIDEO,value:{total_KBytes_out:b.KBytesSent}},{ssrc:a,type:Le.VIDEO,value:{delta_KBytes_out:b.deltaKBytesSent}},{ssrc:a,type:Le.VIDEO,value:{delta_kbs_out:b.kbsSent}},{ssrc:a,type:Le.VIDEO,value:{encoder_out:c}},{ssrc:a,type:Le.VIDEO,value:{delta_ms_encode_frame_out:p.delta_ms_encode_frame}},{ssrc:a,type:Le.VIDEO,value:{total_frames_encoded_out:p.frames_encoded}},{ssrc:a,type:Le.VIDEO,value:{total_time_encoded_out:p.total_encode_time}},{ssrc:a,type:Le.VIDEO,value:{total_nack_received_out:y.nackCount}},{ssrc:a,type:Le.VIDEO,value:{delta_nack_received_out:y.deltaNackCount}},{ssrc:a,type:Le.VIDEO,value:{total_pli_received_out:y.pliCount}},{ssrc:a,type:Le.VIDEO,value:{delta_pli_received_out:y.deltaPliCount}},{ssrc:a,type:Le.VIDEO,value:{size_out:m}},{ssrc:a,type:Le.VIDEO,value:{limitation_out:_}}]}break}case ua.MEDIA_SOURCE:{Qt(Pl,`analyze() - got stats ${r[we.TYPE]} for ${t}`,r);break}case ua.TRACK:{Qt(Pl,`analyze() - got stats ${r[we.TYPE]} for ${t}`,r);break}case ua.CODEC:const s=[];return Object.keys(e[_e.AUDIO]).forEach(a=>{const o=e[_e.AUDIO][a];if(o.codec_id_in===r[we.ID]||o.codec_id_out===r[we.ID]){Qt(Pl,`analyze() - got stats ${r[we.TYPE]} for ${t}`,r);const u=kpe(r);r[we.ID]===o.codec_id_in?s.push({ssrc:o.ssrc,type:Le.AUDIO,value:{codec_in:u}}):s.push({ssrc:o.ssrc,type:Le.AUDIO,value:{codec_out:u}})}}),Object.keys(e[_e.VIDEO]).forEach(a=>{const o=e[_e.VIDEO][a];if(o.codec_id_in===r[we.ID]||o.codec_id_out===r[we.ID]){Qt(Pl,`analyze() - got stats ${r[we.TYPE]} for ${t}`,r);const u=Ope(r);r[we.ID]===o.codec_id_in?s.push({ssrc:o.ssrc,type:Le.VIDEO,value:{codec_in:u}}):s.push({ssrc:o.ssrc,type:Le.VIDEO,value:{codec_out:u}})}}),s;case ua.REMOTE_INBOUND_RTP:{Qt(Pl,`analyze() - got stats ${r[we.TYPE]} for ${t}`,r);const a=r[we.SSRC],o=Fs(a,e,vn.OUTBOUND),u=Fs(a,n,vn.OUTBOUND);if(r[we.KIND]===_e.AUDIO){const c=x4(r,_e.AUDIO,u,o),d=Vy(r,_e.AUDIO,o),p=A4(r,_e.AUDIO,o,u);return[{ssrc:a,type:Le.AUDIO,value:{delta_rtt_ms_out:c.rtt}},{ssrc:a,type:Le.AUDIO,value:{total_rtt_ms_out:c.totalRTT}},{ssrc:a,type:Le.AUDIO,value:{total_rtt_measure_out:c.totalRTTMeasurements}},{ssrc:a,type:Le.AUDIO,value:{delta_jitter_ms_out:d}},{ssrc:a,type:Le.AUDIO,value:{timestamp_out:r[we.TIMESTAMP]}},{ssrc:a,type:Le.AUDIO,value:{total_packets_lost_out:p.packetsLost}},{ssrc:a,type:Le.AUDIO,value:{delta_packets_lost_out:p.deltaPacketsLost}},{ssrc:a,type:Le.AUDIO,value:{percent_packets_lost_out:p.fractionLost}}]}if(r[we.KIND]===_e.VIDEO){const c=x4(r,_e.VIDEO,u,o),d=Vy(r,_e.VIDEO,o),p=A4(r,_e.VIDEO,o,u);return[{ssrc:a,type:Le.VIDEO,value:{delta_rtt_ms_out:c.rtt}},{ssrc:a,type:Le.VIDEO,value:{total_rtt_ms_out:c.totalRTT}},{ssrc:a,type:Le.VIDEO,value:{total_rtt_measure_out:c.totalRTTMeasurements}},{ssrc:a,type:Le.VIDEO,value:{delta_jitter_ms_out:d}},{ssrc:a,type:Le.VIDEO,value:{timestamp_out:r[we.TIMESTAMP]}},{ssrc:a,type:Le.VIDEO,value:{total_packets_lost_out:p.packetsLost}},{ssrc:a,type:Le.VIDEO,value:{delta_packets_lost_out:p.deltaPacketsLost}},{ssrc:a,type:Le.VIDEO,value:{percent_packets_lost_out:p.fractionLost}}]}break}}return[]},Gy=r=>r<0?1:r>100?4.5:1+.035*r+7/1e6*r*(r-60)*(100-r),Fpe=(r,e=_e.AUDIO,t,n,i)=>{const s=Fs(i,r,vn.INBOUND),a=Fs(i,t,vn.INBOUND),o=Fs(i,n,vn.INBOUND),u=[],c=[],d=s[e].percent_packets_lost_in,p=s[e].delta_jitter_ms_in,m=a&&a[e].delta_jitter_ms_in||null,_=o&&o[e].delta_jitter_ms_in||null,y=r.data.delta_rtt_connectivity_ms,b=t&&t.data.delta_rtt_connectivity_ms||null,S=n&&n.data.delta_rtt_connectivity_ms||null;y&&u.push(y),b&&u.push(b),S&&u.push(S),p&&c.push(p),t&&m&&c.push(m),n&&_&&c.push(_);const w=u.length>0?Dl(u):100,x=c.length>0?Dl(c):10,E=93.2-d,I=.18*E*E-27.9*E+1126.62,R=(w+x)/2,P=R-177.3<0?0:1,B=.024*R+.11*(R-177.3)*P,O=I-B;return Gy(O)},Mpe=(r,e=_e.AUDIO,t,n,i)=>{const s=Fs(i,r,vn.OUTBOUND),a=Fs(i,t,vn.OUTBOUND),o=Fs(i,n,vn.OUTBOUND),u=[],c=[],d=s[e].percent_packets_lost_out,p=s[e].delta_rtt_ms_out,m=a&&a[e].delta_rtt_ms_out||null,_=o&&o[e].delta_rtt_ms_out||null,y=s[e].delta_jitter_ms_out,b=a&&a[e].delta_jitter_ms_out||null,S=o&&o[e].delta_jitter_ms_out||null,w=r.data.delta_rtt_connectivity_ms,x=t&&t.data.delta_rtt_connectivity_ms||null,E=n&&n.data.delta_rtt_connectivity_ms||null;p?u.push(p):w&&u.push(w),m?u.push(m):x&&u.push(x),_?u.push(_):E&&u.push(E),y&&c.push(y),t&&b&&c.push(b),n&&S&&c.push(S);const I=u.length>0?Dl(u):100,R=c.length>0?Dl(c):10,P=93.2-d,B=.18*P*P-27.9*P+1126.62,O=(I+R)/2,F=O-177.3<0?0:1,D=.024*O+.11*(O-177.3)*F,L=B-D;return Gy(L)},Lpe=(r,e=_e.AUDIO,t,n,i)=>{const s=Fs(i,r,vn.INBOUND),a=Fs(i,t,vn.INBOUND),o=Fs(i,n,vn.INBOUND),u=[],c=[],d=s[e].percent_packets_lost_in/100,p=s[e].delta_jitter_ms_in,m=a&&a[e].delta_jitter_ms_in||null,_=o&&o[e].delta_jitter_ms_in||null,y=r.data.delta_rtt_connectivity_ms,b=t&&t.data.delta_rtt_connectivity_ms||null,S=n&&n.data.delta_rtt_connectivity_ms||null;y&&u.push(y),b&&u.push(b),S&&u.push(S),p&&c.push(p),a&&m&&c.push(m),o&&_&&c.push(_);const w=u.length>0?Dl(u):100,x=c.length>0?Dl(c):10,E=0,I=19.8,R=29.7,P=30,B=(w+x)/2+P,O=B-177.3<0?0:1,F=.024*B+.11*(B-177.3)*O,L=93.2-(E+I*Math.log(1+R*d)+F);return Gy(L)},Upe=(r,e=_e.AUDIO,t,n,i)=>{const s=Fs(i,r,vn.OUTBOUND),a=Fs(i,t,vn.OUTBOUND),o=Fs(i,n,vn.OUTBOUND),u=[],c=[],d=s[e].percent_packets_lost_out/100,p=s[e].delta_rtt_ms_out,m=a&&a[e].delta_rtt_ms_out||null,_=o&&o[e].delta_rtt_ms_out||null,y=s[e].delta_jitter_ms_out,b=a&&a[e].delta_jitter_ms_out||null,S=o&&o[e].delta_jitter_ms_out||null,w=r.data.delta_rtt_connectivity_ms,x=t&&t.data.delta_rtt_connectivity_ms||null,E=n&&n.data.delta_rtt_connectivity_ms||null;p?u.push(p):w&&u.push(w),m?u.push(m):x&&u.push(x),_?u.push(_):E&&u.push(E),y&&c.push(y),a&&b&&c.push(b),o&&S&&c.push(S);const I=u.length>0?Dl(u):100,R=c.length>0?Dl(c):10,P=0,B=19.8,O=29.7,F=30,D=(I+R)/2+F,L=D-177.3<0?0:1,G=.024*D+.11*(D-177.3)*L,te=93.2-(P+B*Math.log(1+O*d)+G);return Gy(te)};class Bpe{constructor(e,t){this._callbacks={onreport:null,onticket:null},this._id=gpe(),this._moduleName=this._id,this._probeId=t,this._config=e,this._exporter=new Tpe(e),this._state=No.IDLE,this.registerToPCEvents(),Ju(this._moduleName,`new collector created for probe ${this._probeId}`)}analyze(e,t,n,i){const s=(u,c)=>u===_e.AUDIO?c===ua.INBOUND_RTP?{...b4}:{...S4}:c===ua.INBOUND_RTP?{...T4}:{...w4},a=dpe(t);a.pname=this._config.pname,a.call_id=this._config.cid,a.user_id=this._config.uid,a.count=t?t.count+1:1;let o=null;return e.forEach(u=>{!o&&u.timestamp&&(o=u.timestamp),Ppe(u,a,a.pname,i).forEach(d=>{if(d.value&&d.type)if(d.ssrc){let p=a[d.type][d.ssrc];p||(p=s(d.type,u.type),p.ssrc=d.ssrc,a[d.type][d.ssrc]=p),Object.keys(d.value).forEach(m=>{p[m]=d.value[m]})}else Object.keys(d.value).forEach(p=>{a[d.type][p]=d.value[p]})})}),a.timestamp=o,Object.keys(a[_e.AUDIO]).forEach(u=>{const c=a[_e.AUDIO][u];c.direction===vn.INBOUND?(c.mos_emodel_in=Fpe(a,_e.AUDIO,t,n,c.ssrc),c.mos_in=Lpe(a,_e.AUDIO,t,n,c.ssrc)):(c.mos_emodel_out=Mpe(a,_e.AUDIO,t,n,c.ssrc),c.mos_out=Upe(a,_e.AUDIO,t,n,c.ssrc))}),a}async takeReferenceStats(){return new Promise((e,t)=>{const n=Date.now();setTimeout(async()=>{try{const i=Date.now()-n,s=Date.now(),a=await this._config.pc.getStats(),o=this.analyze(a,null,null,null),u=Date.now();o.experimental.time_to_measure_ms=u-s,o.experimental.time_to_wait_ms=i,this._exporter.saveReferenceReport(o),Qt(this._moduleName,`got reference report for probe ${this._probeId}`),e()}catch(i){t(i)}},this._config.startAfter)})}async collectStats(){try{if(this._state!==No.RUNNING||!this._config.pc)return Qt(this._moduleName,`report discarded (too late) for probe ${this._probeId}`),null;const e=Date.now(),t=await this._config.pc.getStats(),n=this.analyze(t,this._exporter.getLastReport(),this._exporter.getBeforeLastReport(),this._exporter.getReferenceReport()),i=Date.now();return n.experimental.time_to_measure_ms=i-e,this._exporter.addReport(n),Qt(this._moduleName,`got report for probe ${this._probeId}#${this._exporter.getReportsNumber()+1}`),this.fireOnReport(n),n}catch(e){return hd(this._moduleName,`got error ${e}`),null}}async start(){Qt(this._moduleName,"starting"),this.state=No.RUNNING,this._startedTime=this._exporter.start(),Qt(this._moduleName,"started")}async mute(){this.state=No.MUTED,Qt(this._moduleName,"muted")}async unmute(){this.state=No.RUNNING,Qt(this._moduleName,"unmuted")}async stop(e){if(Qt(this._moduleName,`stopping${e?" by watchdog":""}...`),this._stoppedTime=this._exporter.stop(),this.state=No.IDLE,this._config.ticket){const{ticket:t}=this._exporter;this.fireOnTicket(t)}this._exporter.reset(),Qt(this._moduleName,"stopped")}registerCallback(e,t,n){e in this._callbacks?(this._callbacks[e]={callback:t,context:n},Qt(this._moduleName,`registered callback '${e}'`)):hd(this._moduleName,`can't register callback for '${e}' - not found`)}unregisterCallback(e){e in this._callbacks?(this._callbacks[e]=null,delete this._callbacks[e],Qt(this._moduleName,`unregistered callback '${e}'`)):hd(this._moduleName,`can't unregister callback for '${e}' - not found`)}fireOnReport(e){this._callbacks.onreport&&qw(this._callbacks.onreport.callback,this._callbacks.onreport.context,e)}fireOnTicket(e){this._callbacks.onticket&&qw(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,Qt(this._moduleName,`state changed to ${e}`)}addCustomEvent(e,t,n,i){this._exporter.addCustomEvent({at:typeof e=="object"?e.toJSON():e,category:t,name:n,description:i})}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{hd(this._moduleName,"can't get devices")}},e){e.oniceconnectionstatechange=()=>{const n=e.iceConnectionState;n===gp.CONNECTED||n===gp.COMPLETED?this.addCustomEvent(new Date().toJSON(),"call",n,"ICE connection state"):n===gp.DISCONNECTED||n===gp.FAILED?this.addCustomEvent(new Date().toJSON(),"call",n,"ICE connection state"):n===gp.CLOSED&&this.addCustomEvent(new Date().toJSON(),"call","ended","ICE connection state")},e.onicegatheringstatechange=()=>{const n=e.iceGatheringState;this.addCustomEvent(new Date().toJSON(),"call",n,"ICE gathering state")},e.ontrack=n=>{this.addCustomEvent(new Date().toJSON(),"call",`${n.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 n=t[0],{transport:i}=n;if(i){const{iceTransport:s}=i;s&&(s.onselectedcandidatepairchange=()=>{this.addCustomEvent(new Date().toJSON(),"call","transport","Candidates Pair changed")})}}}}}class Hpe{constructor(e){this._id=e.pname&&e.pname.substr(0,12).padEnd(12," ")||mpe(),this._moduleName=this._id,Ju(this._moduleName,"probe created"),this._config=e,this._collector=new Bpe(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,n,i=new Date().toJSON()){this._collector.addCustomEvent(i,t,e,n)}get isRunning(){return this._collector.state===No.RUNNING}get isIdle(){return this._collector.state===No.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){Hy(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 yr="engine ";class Vpe{constructor(e){this._config=e,this._probes=[],this._startedTime=null,this._callbacks={onresult:null},Ju(yr,`configured for probing every ${this._config.refreshEvery}ms`),Ju(yr,`configured for starting after ${this._config.startAfter}ms`),Ju(yr,`${!this._config.stopAfter||this._config.stopAfter!==-1?`configured for stopped after ${this._config.stopAfter}ms`:"configured for never stopped"}`),Qt(yr,"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 n=fpe(e,t,this._config),i=new Hpe(n);return this._probes.push(i),Qt(yr,`${this._probes.length} probes registered`),i}removeExistingProbe(e){if(!e)throw new Error("undefined probe");e.state===No.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())),n=()=>this.isIdle?!1:!this._config.stopAfter||this._config.stopAfter<0?!0:Date.now()<this._startedTime+this._config.stopAfter,i=async()=>{const s=cpe(),a=this._probes.filter(o=>o.isRunning);for(const o of a){const u=await o.collectStats();u&&s.probes.push(u),Qt(yr,`got probe ${o.id}`),await C4(0)}return s.delta_time_to_measure_probes_ms=Qu(s.probes,"experimental","time_to_measure_ms"),s.delta_KBytes_in=Qu(s.probes,"data","delta_KBytes_in"),s.delta_KBytes_out=Qu(s.probes,"data","delta_KBytes_out"),s.delta_kbs_in=Qu(s.probes,"data","delta_kbs_in"),s.delta_kbs_out=Qu(s.probes,"data","delta_kbs_out"),s.total_time_decoded_in=Qu(s.probes,"video","total_time_decoded_in"),s.total_time_encoded_out=Qu(s.probes,"video","total_time_encoded_out"),s};for(Qt(yr,"starting to collect"),e(),Qt(yr,"generating reference reports..."),await t(),Qt(yr,"reference reports generated"),this._startedTime=Date.now();n();)if(Qt(yr,`wait ${this._config.refreshEvery}ms before collecting`),await C4(this._config.refreshEvery),n()){Qt(yr,"collecting...");const s=Date.now(),a=await i(),o=Date.now();a.delta_time_consumed_to_measure_ms=o-s,this.fireOnReports(a),Qt(yr,"collected")}Qt(yr,"reaching end of the collecting period..."),this.isRunning&&setTimeout(()=>{this.stop()},0)}stop(e){const t=n=>{this._probes.forEach(i=>{i.stop(n)})};Ju(yr,"stop collecting"),t(e)}registerCallback(e,t,n){e in this._callbacks?(this._callbacks[e]={callback:t,context:n},Qt(yr,`registered callback '${e}'`)):hd(yr,`can't register callback for '${e}' - not found`)}unregisterCallback(e){e in this._callbacks?(this._callbacks[e]=null,delete this._callbacks[e],Qt(this._moduleName,`unregistered callback '${e}'`)):hd(this._moduleName,`can't unregister callback for '${e}' - not found`)}fireOnReports(e){this._callbacks.onresult&&e.probes.length>0&&qw(this._callbacks.onresult.callback,this._callbacks.onresult.context,e)}}const Gpe="interface ";class Wpe{constructor(e){this._config=ppe(e),Ju(Gpe,`welcome to ${this._config.name} version ${this._config.version}`),npe(this._config.verbose||!1),this._engine=new Vpe(this._config)}setupLogLevel(e){spe(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 zpe(r,e){return Object.keys(r).filter(t=>e.includes(t)).reduce((t,n)=>{const i=n;return{...t,[i]:r[i]}},{})}const jpe=["mos_in","codec_in","delta_KBytes_in","delta_kbs_in","delta_jitter_ms_in","delta_packets_lost_in"];class qpe{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){console.log("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 n=Yu.createAnalyser(),i=Yu.createMediaStreamSource(e),s=Yu.createScriptProcessor(2048,1,1);n.smoothingTimeConstant=.8,n.fftSize=1024,i.connect(n),n.connect(s),s.connect(Yu.destination),this.intervals[t]=setInterval(()=>{const a=new Uint8Array(n.frequencyBinCount);n.getByteFrequencyData(a);let o=0;const u=a.length;for(let d=0;d<u;d++)o+=a[d];const c=o/u;this.onChangeFunction(t,c)},this.emitInterval)}}const Wy={SELECTED_INPUT_DEVICE:"OpensipsJSInputDevice",SELECTED_OUTPUT_DEVICE:"OpensipsJSOutputDevice"},Kpe=0;class Xpe{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 qpe({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 ZO()?{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(Wy.SELECTED_INPUT_DEVICE)||"default",t=localStorage.getItem(Wy.SELECTED_OUTPUT_DEVICE)||"default";try{const n=await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints),i=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(i),await this.setMicrophone(e),await this.setSpeaker(t),navigator.mediaDevices.addEventListener("devicechange",async()=>{const s=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(s)}),n.getTracks().forEach(s=>s.stop())}catch(n){console.error(n)}}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");console.log("callId",e),console.log("value",t);const i=this.extendedCalls[e];console.log("call",i),i.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(n=>n.enabled=!e),this.roomReconfigure(t)}mute(){this.processMute(!0)}unmute(){this.processMute(!1)}async processHold({callId:e,toHold:t,automatic:n}){const i=this.extendedCalls[e];i._automaticHold=n??!1,await new Promise(o=>{const u=()=>{o()};t?i.hold({},u):i.unhold({},u)}),this.updateCall(i);const a=Object.values(this.extendedCalls).filter(o=>o.roomId===this.currentActiveRoomId&&(t?e!==o._id:!0));a.length>1&&await this.doConference(a)}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===Kpe).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",n=>{this.triggerAddStream(n,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]=YO(e),this.context.emit("changeActiveCalls",this.activeCalls)}updateRoom(e){const n={...this.activeRooms[e.roomId],...e};this.activeRooms={...this.activeRooms,[e.roomId]:{...n}},this.context.emit("updateRoom",{room:n,roomList:this.activeRooms})}hasAutoAnswerHeaders(e){const t=/answer-after=0/,i=e.request.getHeader("Call-Info");return i&&t.test(i)}addCall(e,t=!0){this.activeCalls={...this.activeCalls,[e._id]:YO(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 n={...{...this.callStatus[e.callId]}};e.isMoving!==void 0&&(n.isMoving=e.isMoving),e.isTransferring!==void 0&&(n.isTransferring=e.isTransferring),e.isMerging!==void 0&&(n.isMerging=e.isMerging),this.callStatus={...this.callStatus,[e.callId]:{...n}},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=QO(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:n})=>n===e)||(this.setSelectedInputDevice(e),Object.keys(this.getActiveCalls).length===0))return;await this.setupStream();const t=Object.values(this.extendedCalls).filter(n=>n.roomId===this.currentActiveRoomId);t.length===1?Object.values(t).forEach(async n=>{const i=this.getActiveStream();n.connection.getSenders()[0].replaceTrack(i.getTracks()[0]),this.updateCall(n)}):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:i})=>i===e))return;this.setSelectedOutputDevice(e);const t=Object.values(this.extendedCalls);if(t.length===0)return;const n=t.filter(i=>i.roomId===this.currentActiveRoomId);n.length===1?t.forEach(i=>{var s;(s=i.audioTag)==null||s.setSinkId(e),this.updateCall(i)}):await this.doConference(n)}removeRoom(e){const t={...this.activeRooms},n={...t[e]};delete t[e],this.activeRooms={...t},this.context.emit("removeRoom",{room:n,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 n;if(e===void 0)return;const t=Object.values(this.extendedCalls).filter(i=>i.roomId===e);if(this.currentActiveRoomId===e?t.forEach(i=>{i.audioTag&&(this.muteReconfigure(i),i.audioTag.muted=!1,this.updateCall(i))}):t.forEach(i=>{i.audioTag&&(i.audioTag.muted=!0,this.updateCall(i))}),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&&((n=t[0].connection)!=null&&n.getSenders()[0])){const i=this.getActiveStream();await t[0].connection.getSenders()[0].replaceTrack(i.getTracks()[0]),this.muteReconfigure(t[0])}}else t.length>1&&await this.doConference(t)}async doConference(e){const t=[];e.forEach(n=>{n!=null&&n.connection.getReceivers().forEach(i=>{t.push(i.track)})}),await epe.forEach(e,async n=>{var a;if(n==null)return;const i=new MediaStream,s=Yu.createMediaStreamDestination();if(n.connection.getReceivers().forEach(o=>{t.forEach(u=>{i.addTrack(o.track),o.track.id!==u.id&&Yu.createMediaStreamSource(new MediaStream([u])).connect(s)})}),e[0].roomId===this.currentActiveRoomId){const o=this.getActiveStream();Yu.createMediaStreamSource(o).connect(s)}(a=n.connection)!=null&&a.getSenders()[0]&&(await n.connection.getSenders()[0].replaceTrack(s.stream.getTracks()[0]),this.muteReconfigure(n))})}processCallerMute(e,t){const n=this.extendedCalls[e];n&&n.connection.getReceivers().length&&(n.localMuted=t,n.connection.getReceivers().forEach(i=>{i.track.enabled=!t}),this.updateCall(n))}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 n=this.extendedCalls[e];if(!n._is_confirmed&&!n._is_canceled){const i=`sip:${t}@${this.context.sipDomain}`;n.terminate({status_code:302,reason_phrase:"Moved Temporarily",extraHeaders:[`Contact: ${i}`]});return}this.updateCallStatus({callId:e,isTransferring:!0}),n.refer(`sip:${t}@${this.context.sipDomain}`),this.updateCall(n)}mergeCall(e){const t=Object.values(this.extendedCalls).filter(s=>s.roomId===e);if(t.length!==2)return;const n=t[0],i=t[1];!n||!i||(this.updateCallStatus({callId:n._id,isMerging:!0}),this.updateCallStatus({callId:i._id,isMerging:!0}),n.refer(i.remote_identity.uri.toString(),{replaces:i}),this.updateCall(n))}mergeCallByIds(e,t){const n=Object.values(this.extendedCalls).find(s=>s._id===e),i=Object.values(this.extendedCalls).find(s=>s._id===t);if(!n||!i)throw new Error("Call ID is not provided");this.updateCallStatus({callId:e,isMerging:!0}),this.updateCallStatus({callId:t,isMerging:!0}),n.refer(i.remote_identity.uri.toString(),{replaces:i}),this.updateCall(n)}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 n=setInterval(()=>{const i={...this.callTime[e]},s=Zfe(i);this.setCallTime({callId:e,...s})},1e3);this.setTimeInterval(e,n)}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 c,d;const t=e.session;if(this.getActiveCalls[t.id]!==void 0)return;const i=this.getNewRoomId(),s={started:new Date,incomingInProgress:!1,roomId:i};t.direction==="incoming"?(this.context.logger.log("New incoming call from",(d=(c=t._remote_identity)==null?void 0:c._uri)==null?void 0:d._user),s.incomingInProgress=!0,this.context.subscribe(la.CALL_CONFIRMED,p=>{t.id===p.id&&(this.updateRoom({incomingInProgress:!1,roomId:i}),this.startCallTimer(t.id))}),this.context.subscribe(la.CALL_FAILED,p=>{t.id===p.id&&(this.updateRoom({incomingInProgress:!1,roomId:i}),this.deleteRoomIfEmpty(i))})):t.direction==="outgoing"&&(t.once("confirmed",()=>{this.startCallTimer(t.id)}),this.startCallTimer(t.id));const a=t,o=this.hasAutoAnswerHeaders(e),u=a.direction==="incoming"&&!this.hasActiveCalls&&(o||this.autoAnswer);a.roomId=i,a.localMuted=!1,a.autoAnswer=u,u?this.addCall(a,!1):this.addCall(a),this.addCallStatus(t.id),this.addRoom(s),u&&this.answerCall(a._id)}removeCall(e){const t={...this.activeCalls};delete t[e],this.activeCalls={...t};const n={...this.extendedCalls};delete n[e],this.extendedCalls={...n},this.context.emit("changeActiveCalls",this.activeCalls)}activeCallListRemove(e){var i;const t=this.extendedCalls[e._id];this.stopVUMeter("origin"),(i=t.connection)==null||i.getSenders().forEach(s=>{s.track.stop()});const n=t.roomId;this.removeCall(e._id),this.roomReconfigure(n)}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:la.NEW_CALL,session:t,event:e}),t.on("ended",n=>{var s,a,o;this.stopVUMeter(t.id),this.context.logger.log("Session ended for",(a=(s=t._remote_identity)==null?void 0:s._uri)==null?void 0:a._user),this.context.triggerListener({listenerType:la.CALL_ENDED,session:t,event:n});const i=this.getActiveCalls[t.id];i&&this.activeCallListRemove(i),this.stopCallTimer(t.id),this.removeCallStatus(t.id),this.removeCallMetrics(t.id),Object.keys(this.extendedCalls).length||(this.setIsMuted(!1),(o=this.initialStreamValue)==null||o.getTracks().forEach(u=>u.stop()),this.initialStreamValue=null)}),t.on("progress",n=>{var i,s;this.context.logger.log("Session in progress for",(s=(i=t._remote_identity)==null?void 0:i._uri)==null?void 0:s._user),this.context.triggerListener({listenerType:la.CALL_PROGRESS,session:t,event:n})}),t.on("failed",n=>{var s,a,o;this.stopVUMeter(t.id),this.context.logger.log("Session failed for",(a=(s=t._remote_identity)==null?void 0:s._uri)==null?void 0:a._user),this.context.triggerListener({listenerType:la.CALL_FAILED,session:t,event:n}),t.id===this.callAddingInProgress&&(this.callAddingInProgress=void 0);const i=this.getActiveCalls[t.id];i&&this.activeCallListRemove(i),this.stopCallTimer(t.id),this.removeCallStatus(t.id),this.removeCallMetrics(t.id),Object.keys(this.extendedCalls).length||(this.setIsMuted(!1),(o=this.initialStreamValue)==null||o.getTracks().forEach(u=>u.stop()),this.initialStreamValue=null)}),t.on("confirmed",n=>{var i,s;this.context.logger.log("Session confirmed for",(s=(i=t._remote_identity)==null?void 0:i._uri)==null?void 0:s._user),this.context.triggerListener({listenerType:la.CALL_CONFIRMED,session:t,event:n}),this.updateCall(t),t.id===this.callAddingInProgress&&(this.callAddingInProgress=void 0)}),await this.setupCall(e),t.direction==="outgoing"){const n=this.getActiveCalls[t.id].roomId;this.setActiveRoom(n)}}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(Wy.SELECTED_INPUT_DEVICE,e),this.selectedMediaDevices.input=e,this.context.emit("changeActiveInputMediaDevice",e)}setSelectedOutputDevice(e){localStorage.setItem(Wy.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 Wpe(this.metricConfig),n=t.createProbe(e.connection,{cid:e._id}),i=[];let s;n.onreport=a=>{Object.entries(a.audio).forEach(([c,d])=>{d.direction==="inbound"&&!i.includes(c)&&(i.push(c),s=c)});const o=a.audio[s];if(!o)return;const u=zpe(o,jpe);u.callId=e._id,this.setCallMetrics(u)},this.context.subscribe(la.CALL_ENDED,a=>{a._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 n=QO(this.initialStreamValue,this.microphoneInputLevel*2),i=this.isMuted||this.muteWhenJoin;n.getTracks().forEach(a=>a.enabled=!i),this.setActiveStream(n),await t.connection.getSenders()[0].replaceTrack(n.getTracks()[0]);const s=new MediaStream([e.track]);Fue(s,t,this.selectedOutputDevice,this.speakerVolume),this.setupVUMeter(s,t._id),this.getCallQuality(t),this.updateCall(t)}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}...`);const n=this.context.call(`sip:${e}@${this.context.sipDomain}`,this.sipOptions);this.callAddingInProgress=n.id,t&&this.currentActiveRoomId!==void 0&&this.processRoomChange({callId:n.id,roomId:this.currentActiveRoomId}),n.connection.addEventListener("track",i=>{this.triggerAddStream(i,n)})}async processRoomChange({callId:e,roomId:t}){const n=this.extendedCalls[e].roomId;this.extendedCalls[e].roomId=t;const i=this.extendedCalls[e];return this.updateCall(i),await this.setActiveRoom(t),Promise.all([this.roomReconfigure(n),this.roomReconfigure(t)]).then(()=>{this.deleteRoomIfEmpty(n),this.deleteRoomIfEmpty(t)})}}class Ype{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)}startScreenShare(){this.context.startScreenShare()}startBlur(){this.context.startBlur()}stopBlur(){this.context.stopBlur()}}class Jpe{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]=JO(e),this.context.emit("changeActiveMessages",this.activeMessages)}addMMSRPSession(e){this.activeMessages={...this.activeMessages,[e._id]:JO(e)},this.extendedMessages[e._id]=e,this.context.emit("changeActiveMessages",this.activeMessages)}addMSRPMessage(e,t){const n=this.msrpHistory[t.id]||[];n.push(e),this.msrpHistory={...this.msrpHistory,[t.id]:[...n]},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 n=e;this.addMMSRPSession(n)}triggerMSRPListener({listenerType:e,session:t,event:n}){const i=this.context.listenersList[e];!i||!i.length||i.forEach(s=>{s(t,n)})}removeMMSRPSession(e){const t={...this.activeMessages};delete t[e],this.activeMessages={...t};const n={...this.extendedMessages};delete n[e],this.extendedMessages={...n},this.context.emit("changeActiveMessages",this.activeMessages)}activeMessageListRemove(e){this.removeMMSRPSession(e._id)}newMSRPSessionCallback(e){const t=e.session;t.on("ended",n=>{this.triggerMSRPListener({listenerType:la.CALL_ENDED,session:t,event:n});const i=this.getActiveMessages[t.id];this.activeMessageListRemove(i)}),t.on("failed",n=>{this.triggerMSRPListener({listenerType:la.CALL_FAILED,session:t,event:n});const i=this.getActiveMessages[t.id];this.activeMessageListRemove(i)}),t.on("confirmed",n=>{this.triggerMSRPListener({listenerType:la.CALL_CONFIRMED,session:t,event:n}),this.updateMSRPSession(t)}),t.on("newMessage",n=>{this.addMSRPMessage(n,t)}),this.addMessageSession(t)}setIsMSRPInitializing(e){this.isMSRPInitializingValue=e,this.context.emit("isMSRPInitializingChanged",e)}initMSRP(e,t,n){if(e.length===0)return console.error("Target must be a valid string");const i=this.context.startMSRP(e,n);i.on("active",()=>{this.addMessageSession(i),i.sendMSRP(t),this.setIsMSRPInitializing(!1)}),this.setIsMSRPInitializing(!0)}sendMSRP(e,t){const n=this.extendedMessages[e];if(!n)throw new Error(`MSRP session with id ${e} doesn't exist!`);n.sendMSRP(t)}}const Kw={AUDIO:"audio",VIDEO:"video",MSRP:"msrp"};class Qpe extends Rue{constructor(e,t){if(!e.modules.length)throw new Error("options.modules should include at least 1 module");const n={...e.configuration,sockets:e.socketInterfaces.map(i=>new Qfe.WebSocketInterface(i))};super(n),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&&Mue(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(console.log("RRR use",e),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 M0)e.setOpensips(this),console.log("RRR push to newStreamPlugins"),this.newStreamPlugins.push(e);else if(e instanceof O0)e.setOpensips(this),console.log("RRR push to processStreamPlugins"),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(Kw.AUDIO)&&(this.audio=new Xpe(this)),this.modules.includes(Kw.MSRP)&&(this.msrp=new Jpe(this)),this.modules.includes(Kw.VIDEO)&&(this.video=new Ype(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 i=!this.listenersList[e]||!this.listenersList[e].length?[t]:[...this.listenersList[e],t];this.listenersList={...this.listenersList,[e]:i}}removeIListener(e){const t={...this.listenersList};delete t[e],this.listenersList={...t}}triggerListener({listenerType:e,session:t,event:n}){const i=this.listenersList[e];!i||!i.length||i.forEach(s=>{s(t,n)})}setInitialized(e){this.initialized=e,this.emit("ready",e)}setConnected(e){this.connected=e,this.emit("connection",e)}}return Er.BaseNewStreamPlugin=M0,Er.BaseProcessStreamPlugin=O0,Er.ScreenSharePlugin=Lue,Er.ScreenShareWhiteBoardPlugin=pp,Er.StreamMaskPlugin=bue,Er.WhiteBoardPlugin=Ufe,Er.default=Qpe,Object.defineProperties(Er,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}}),Er}({});
18359
+ `),t=+this.fontSize(),n=0,i=this.lineHeight()*t,s=this.attrs.width,a=this.attrs.height,o=s!==ld&&s!==void 0,u=a!==ld&&a!==void 0,c=this.padding(),d=s-c*2,p=a-c*2,m=0,_=this.wrap(),y=_!==H$,b=_!==kde&&y,S=this.ellipsis();this.textArr=[],Nw().font=this._getContextFont();const w=S?this._getTextWidth(Rw):0;for(let E=0,I=e.length;E<I;++E){let R=e[E],P=this._getTextWidth(R);if(o&&P>d)for(;R.length>0;){let B=0,O=R.length,F="",D=0;for(;B<O;){const L=B+O>>>1,G=R.slice(0,L+1),j=this._getTextWidth(G)+w;j<=d?(B=L+1,F=G,D=j):O=L}if(F){if(b){var x;const G=R[F.length];(G===cy||G===F$)&&D<=d?x=F.length:x=Math.max(F.lastIndexOf(cy),F.lastIndexOf(F$))+1,x>0&&(B=x,F=F.slice(0,B),D=this._getTextWidth(F))}if(F=F.trimRight(),this._addTextLine(F),n=Math.max(n,D),m+=i,this._shouldHandleEllipsis(m)){this._tryToAddEllipsisToLastLine();break}if(R=R.slice(B),R=R.trimLeft(),R.length>0&&(P=this._getTextWidth(R),P<=d)){this._addTextLine(R),m+=i,n=Math.max(n,P);break}}else break}else this._addTextLine(R),m+=i,n=Math.max(n,P),this._shouldHandleEllipsis(m)&&E<I-1&&this._tryToAddEllipsisToLastLine();if(this.textArr[this.textArr.length-1]&&(this.textArr[this.textArr.length-1].lastInParagraph=!0),u&&m+i>p)break}this.textHeight=t,this.textWidth=n}_shouldHandleEllipsis(e){const t=+this.fontSize(),n=this.lineHeight()*t,i=this.attrs.height,s=i!==ld&&i!==void 0,a=this.padding(),o=i-a*2;return!(this.wrap()!==H$)||s&&e+n>o}_tryToAddEllipsisToLastLine(){const e=this.attrs.width,t=e!==ld&&e!==void 0,n=this.padding(),i=e-n*2,s=this.ellipsis(),a=this.textArr[this.textArr.length-1];!a||!s||(t&&(this._getTextWidth(a.text+Rw)<i||(a.text=a.text.slice(0,a.text.length-3))),this.textArr.splice(this.textArr.length-1,1),this._addTextLine(a.text+Rw))}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()}}od.Text=zn,zn.prototype._fillFunc=Dde,zn.prototype._strokeFunc=Pde,zn.prototype.className=Ede,zn.prototype._attrsAffectingSize=["text","fontSize","padding","wrap","lineHeight","letterSpacing"],(0,bde._registerNode)(zn),gr.Factory.overWriteSetter(zn,"width",(0,kl.getNumberOrAutoValidator)()),gr.Factory.overWriteSetter(zn,"height",(0,kl.getNumberOrAutoValidator)()),gr.Factory.addGetterSetter(zn,"direction",P$),gr.Factory.addGetterSetter(zn,"fontFamily","Arial"),gr.Factory.addGetterSetter(zn,"fontSize",12,(0,kl.getNumberValidator)()),gr.Factory.addGetterSetter(zn,"fontStyle",U$),gr.Factory.addGetterSetter(zn,"fontVariant",U$),gr.Factory.addGetterSetter(zn,"padding",0,(0,kl.getNumberValidator)()),gr.Factory.addGetterSetter(zn,"align",M$),gr.Factory.addGetterSetter(zn,"verticalAlign",xde),gr.Factory.addGetterSetter(zn,"lineHeight",1,(0,kl.getNumberValidator)()),gr.Factory.addGetterSetter(zn,"wrap",Nde),gr.Factory.addGetterSetter(zn,"ellipsis",!1,(0,kl.getBooleanValidator)()),gr.Factory.addGetterSetter(zn,"letterSpacing",0,(0,kl.getNumberValidator)()),gr.Factory.addGetterSetter(zn,"text","",(0,kl.getStringValidator)()),gr.Factory.addGetterSetter(zn,"textDecoration","");var hy={};Object.defineProperty(hy,"__esModule",{value:!0}),hy.TextPath=void 0;const kw=Un,aa=Dt,Mde=vs,dp=sd,Ow=od,G$=Ct,Lde=$t,Ude="",W$="normal";function z$(r){r.fillText(this.partialText,0,0)}function j$(r){r.strokeText(this.partialText,0,0)}class Ss extends Mde.Shape{constructor(e){super(e),this.dummyCanvas=kw.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 dp.Path.getPathLength(this.dataArray)}_getPointAtLength(e){if(!this.attrs.data)return null;const t=this.pathLength;return e-1>t?null:dp.Path.getPointAtLengthOfDataArray(e,this.dataArray)}_readDataAttribute(){this.dataArray=dp.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(),n=this.fill(),i=this.fontSize(),s=this.glyphInfo;t==="underline"&&e.beginPath();for(let a=0;a<s.length;a++){e.save();const o=s[a].p0;e.translate(o.x,o.y),e.rotate(s[a].rotation),this.partialText=s[a].text,e.fillStrokeShape(this),t==="underline"&&(a===0&&e.moveTo(0,i/2+1),e.lineTo(i,i/2+1)),e.restore()}t==="underline"&&(e.strokeStyle=n,e.lineWidth=i/20,e.stroke()),e.restore()}_hitFunc(e){e.beginPath();const t=this.glyphInfo;if(t.length>=1){const n=t[0].p0;e.moveTo(n.x,n.y)}for(let n=0;n<t.length;n++){const i=t[n].p1;e.lineTo(i.x,i.y)}e.setAttr("lineWidth",this.fontSize()),e.setAttr("strokeStyle",this.colorKey),e.stroke()}getTextWidth(){return this.textWidth}getTextHeight(){return kw.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 Ow.Text.prototype.setText.call(this,e)}_getContextFont(){return Ow.Text.prototype._getContextFont.call(this)}_getTextSize(e){const n=this.dummyCanvas.getContext("2d");n.save(),n.font=this._getContextFont();const i=n.measureText(e);return n.restore(),{width:i.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 n=this.letterSpacing(),i=this.align(),s=this.kerningFunc(),a=Math.max(this.textWidth+((this.attrs.text||"").length-1)*n,0);let o=0;i==="center"&&(o=Math.max(0,this.pathLength/2-a/2)),i==="right"&&(o=Math.max(0,this.pathLength-a));const u=(0,Ow.stringToArray)(this.text());let c=o;for(let d=0;d<u.length;d++){const p=this._getPointAtLength(c);if(!p)return;let m=this._getTextSize(u[d]).width+n;if(u[d]===" "&&i==="justify"){const x=this.text().split(" ").length-1;m+=(this.pathLength-a)/x}const _=this._getPointAtLength(c+m);if(!_)return;const y=dp.Path.getLineLength(p.x,p.y,_.x,_.y);let b=0;if(s)try{b=s(u[d-1],u[d])*this.fontSize()}catch{b=0}p.x+=b,_.x+=b,this.textWidth+=b;const S=dp.Path.getPointOnLine(b+y/2,p.x,p.y,_.x,_.y),w=Math.atan2(_.y-p.y,_.x-p.x);this.glyphInfo.push({transposeX:S.x,transposeY:S.y,text:u[d],rotation:w,p0:p,p1:_}),c+=m}}getSelfRect(){if(!this.glyphInfo.length)return{x:0,y:0,width:0,height:0};const e=[];this.glyphInfo.forEach(function(c){e.push(c.p0.x),e.push(c.p0.y),e.push(c.p1.x),e.push(c.p1.y)});let t=e[0]||0,n=e[0]||0,i=e[1]||0,s=e[1]||0,a,o;for(let c=0;c<e.length/2;c++)a=e[c*2],o=e[c*2+1],t=Math.min(t,a),n=Math.max(n,a),i=Math.min(i,o),s=Math.max(s,o);const u=this.fontSize();return{x:t-u/2,y:i-u/2,width:n-t+u,height:s-i+u}}destroy(){return kw.Util.releaseCanvas(this.dummyCanvas),super.destroy()}}hy.TextPath=Ss,Ss.prototype._fillFunc=z$,Ss.prototype._strokeFunc=j$,Ss.prototype._fillFuncHit=z$,Ss.prototype._strokeFuncHit=j$,Ss.prototype.className="TextPath",Ss.prototype._attrsAffectingSize=["text","fontSize","data"],(0,Lde._registerNode)(Ss),aa.Factory.addGetterSetter(Ss,"data"),aa.Factory.addGetterSetter(Ss,"fontFamily","Arial"),aa.Factory.addGetterSetter(Ss,"fontSize",12,(0,G$.getNumberValidator)()),aa.Factory.addGetterSetter(Ss,"fontStyle",W$),aa.Factory.addGetterSetter(Ss,"align","left"),aa.Factory.addGetterSetter(Ss,"letterSpacing",0,(0,G$.getNumberValidator)()),aa.Factory.addGetterSetter(Ss,"textBaseline","middle"),aa.Factory.addGetterSetter(Ss,"fontVariant",W$),aa.Factory.addGetterSetter(Ss,"text",Ude),aa.Factory.addGetterSetter(Ss,"textDecoration",null),aa.Factory.addGetterSetter(Ss,"kerningFunc",null);var fy={};Object.defineProperty(fy,"__esModule",{value:!0}),fy.Transformer=void 0;const pn=Un,rn=Dt,q$=Mn,Bde=vs,Hde=up,K$=td,oa=$t,Ol=Ct,Vde=$t,X$="tr-konva",Gde=["resizeEnabledChange","rotateAnchorOffsetChange","rotateEnabledChange","enabledAnchorsChange","anchorSizeChange","borderEnabledChange","borderStrokeChange","borderStrokeWidthChange","borderDashChange","anchorStrokeChange","anchorStrokeWidthChange","anchorFillChange","anchorCornerRadiusChange","ignoreStrokeChange","anchorStyleFuncChange"].map(r=>r+`.${X$}`).join(" "),Y$="nodesRect",Wde=["widthChange","heightChange","scaleXChange","scaleYChange","skewXChange","skewYChange","rotationChange","offsetXChange","offsetYChange","transformsEnabledChange","strokeWidthChange"],zde={"top-left":-45,"top-center":0,"top-right":45,"middle-right":-90,"middle-left":90,"bottom-left":-135,"bottom-center":180,"bottom-right":135},jde="ontouchstart"in oa.Konva._global;function qde(r,e,t){if(r==="rotater")return t;e+=pn.Util.degToRad(zde[r]||0);const n=(pn.Util.radToDeg(e)%360+360)%360;return pn.Util._inRange(n,337.5,360)||pn.Util._inRange(n,0,22.5)?"ns-resize":pn.Util._inRange(n,22.5,67.5)?"nesw-resize":pn.Util._inRange(n,67.5,112.5)?"ew-resize":pn.Util._inRange(n,112.5,157.5)?"nwse-resize":pn.Util._inRange(n,157.5,202.5)?"ns-resize":pn.Util._inRange(n,202.5,247.5)?"nesw-resize":pn.Util._inRange(n,247.5,292.5)?"ew-resize":pn.Util._inRange(n,292.5,337.5)?"nwse-resize":(pn.Util.error("Transformer has unknown angle for cursor detection: "+n),"pointer")}const py=["top-left","top-center","top-right","middle-right","middle-left","bottom-left","bottom-center","bottom-right"],J$=1e8;function Kde(r){return{x:r.x+r.width/2*Math.cos(r.rotation)+r.height/2*Math.sin(-r.rotation),y:r.y+r.height/2*Math.cos(r.rotation)+r.width/2*Math.sin(r.rotation)}}function Q$(r,e,t){const n=t.x+(r.x-t.x)*Math.cos(e)-(r.y-t.y)*Math.sin(e),i=t.y+(r.x-t.x)*Math.sin(e)+(r.y-t.y)*Math.cos(e);return{...r,rotation:r.rotation+e,x:n,y:i}}function Xde(r,e){const t=Kde(r);return Q$(r,e,t)}function Yde(r,e,t){let n=e;for(let i=0;i<r.length;i++){const s=oa.Konva.getAngle(r[i]),a=Math.abs(s-e)%(Math.PI*2);Math.min(a,Math.PI*2-a)<t&&(n=s)}return n}let $w=0;class qt extends K$.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(Gde,this.update),this.getNode()&&this.update()}attachTo(e){return this.setNode(e),this}setNode(e){return pn.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 X$+this._id}setNodes(e=[]){this._nodes&&this._nodes.length&&this.detach();const t=e.filter(i=>i.isAncestorOf(this)?(pn.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(i=>{const s=()=>{this.nodes().length===1&&this.useSingleNodeRotation()&&this.rotation(this.nodes()[0].getAbsoluteRotation()),this._resetTransformCache(),!this._transforming&&!this.isDragging()&&this.update()},a=i._attrsAffectingSize.map(o=>o+"Change."+this._getEventNamespace()).join(" ");i.on(a,s),i.on(Wde.map(o=>o+`.${this._getEventNamespace()}`).join(" "),s),i.on(`absoluteTransformChange.${this._getEventNamespace()}`,s),this._proxyDrag(i)}),this._resetTransformCache(),!!this.findOne(".top-left")&&this.update(),this}_proxyDrag(e){let t;e.on(`dragstart.${this._getEventNamespace()}`,n=>{t=e.getAbsolutePosition(),!this.isDragging()&&e!==this.findOne(".back")&&this.startDrag(n,!1)}),e.on(`dragmove.${this._getEventNamespace()}`,n=>{if(!t)return;const i=e.getAbsolutePosition(),s=i.x-t.x,a=i.y-t.y;this.nodes().forEach(o=>{if(o===e||o.isDragging())return;const u=o.getAbsolutePosition();o.setAbsolutePosition({x:u.x+s,y:u.y+a}),o.startDrag(n)}),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(Y$),this._clearCache("transform"),this._clearSelfAndDescendantCache("absoluteTransform")}_getNodeRect(){return this._getCache(Y$,this.__getNodeRect)}__getNodeShape(e,t=this.rotation(),n){const i=e.getClientRect({skipTransform:!0,skipShadow:!0,skipStroke:this.ignoreStroke()}),s=e.getAbsoluteScale(n),a=e.getAbsolutePosition(n),o=i.x*s.x-e.offsetX()*s.x,u=i.y*s.y-e.offsetY()*s.y,c=(oa.Konva.getAngle(e.getAbsoluteRotation())+Math.PI*2)%(Math.PI*2),d={x:a.x+o*Math.cos(c)+u*Math.sin(-c),y:a.y+u*Math.cos(c)+o*Math.sin(c),width:i.width*s.x,height:i.height*s.y,rotation:c};return Q$(d,-oa.Konva.getAngle(t),{x:0,y:0})}__getNodeRect(){if(!this.getNode())return{x:-J$,y:-J$,width:0,height:0,rotation:0};const t=[];this.nodes().map(c=>{const d=c.getClientRect({skipTransform:!0,skipShadow:!0,skipStroke:this.ignoreStroke()}),p=[{x:d.x,y:d.y},{x:d.x+d.width,y:d.y},{x:d.x+d.width,y:d.y+d.height},{x:d.x,y:d.y+d.height}],m=c.getAbsoluteTransform();p.forEach(function(_){const y=m.point(_);t.push(y)})});const n=new pn.Transform;n.rotate(-oa.Konva.getAngle(this.rotation()));let i=1/0,s=1/0,a=-1/0,o=-1/0;t.forEach(function(c){const d=n.point(c);i===void 0&&(i=a=d.x,s=o=d.y),i=Math.min(i,d.x),s=Math.min(s,d.y),a=Math.max(a,d.x),o=Math.max(o,d.y)}),n.invert();const u=n.point({x:i,y:s});return{x:u.x,y:u.y,width:a-i,height:o-s,rotation:oa.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(),py.forEach(e=>{this._createAnchor(e)}),this._createAnchor("rotater")}_createAnchor(e){const t=new Hde.Rect({stroke:"rgb(0, 161, 255)",fill:"white",strokeWidth:1,name:e+" _anchor",dragDistance:0,draggable:!0,hitStrokeWidth:jde?10:"auto"}),n=this;t.on("mousedown touchstart",function(i){n._handleMouseDown(i)}),t.on("dragstart",i=>{t.stopDrag(),i.cancelBubble=!0}),t.on("dragend",i=>{i.cancelBubble=!0}),t.on("mouseenter",()=>{const i=oa.Konva.getAngle(this.rotation()),s=this.rotateAnchorCursor(),a=qde(e,i,s);t.getStage().content&&(t.getStage().content.style.cursor=a),this._cursorChange=!0}),t.on("mouseout",()=>{t.getStage().content&&(t.getStage().content.style.cursor=""),this._cursorChange=!1}),this.add(t)}_createBack(){const e=new Bde.Shape({name:"back",width:0,height:0,draggable:!0,sceneFunc(t,n){const i=n.getParent(),s=i.padding();t.beginPath(),t.rect(-s,-s,n.width()+s*2,n.height()+s*2),t.moveTo(n.width()/2,-s),i.rotateEnabled()&&i.rotateLineVisible()&&t.lineTo(n.width()/2,-i.rotateAnchorOffset()*pn.Util._sign(n.height())-s),t.fillStrokeShape(n)},hitFunc:(t,n)=>{if(!this.shouldOverdrawWholeArea())return;const i=this.padding();t.beginPath(),t.rect(-i,-i,n.width()+i*2,n.height()+i*2),t.fillStrokeShape(n)}});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(),n=t.width,i=t.height,s=Math.sqrt(Math.pow(n,2)+Math.pow(i,2));this.sin=Math.abs(i/s),this.cos=Math.abs(n/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 a=e.target.getAbsolutePosition(),o=e.target.getStage().getPointerPosition();this._anchorDragOffset={x:o.x-a.x,y:o.y-a.y},$w++,this._fire("transformstart",{evt:e.evt,target:this.getNode()}),this._nodes.forEach(u=>{u._fire("transformstart",{evt:e.evt,target:u})})}_handleMouseMove(e){let t,n,i;const s=this.findOne("."+this._movingAnchorName),a=s.getStage();a.setPointersPositions(e);const o=a.getPointerPosition();let u={x:o.x-this._anchorDragOffset.x,y:o.y-this._anchorDragOffset.y};const c=s.getAbsolutePosition();this.anchorDragBoundFunc()&&(u=this.anchorDragBoundFunc()(c,u,e)),s.setAbsolutePosition(u);const d=s.getAbsolutePosition();if(c.x===d.x&&c.y===d.y)return;if(this._movingAnchorName==="rotater"){const R=this._getNodeRect();t=s.x()-R.width/2,n=-s.y()+R.height/2;let P=Math.atan2(-n,t)+Math.PI/2;R.height<0&&(P-=Math.PI);const O=oa.Konva.getAngle(this.rotation())+P,F=oa.Konva.getAngle(this.rotationSnapTolerance()),L=Yde(this.rotationSnaps(),O,F)-R.rotation,G=Xde(R,L);this._fitNodesInto(G,e);return}const p=this.shiftBehavior();let m;p==="inverted"?m=this.keepRatio()&&!e.shiftKey:p==="none"?m=this.keepRatio():m=this.keepRatio()||e.shiftKey;var w=this.centeredScaling()||e.altKey;if(this._movingAnchorName==="top-left"){if(m){var _=w?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".bottom-right").x(),y:this.findOne(".bottom-right").y()};i=Math.sqrt(Math.pow(_.x-s.x(),2)+Math.pow(_.y-s.y(),2));var y=this.findOne(".top-left").x()>_.x?-1:1,b=this.findOne(".top-left").y()>_.y?-1:1;t=i*this.cos*y,n=i*this.sin*b,this.findOne(".top-left").x(_.x-t),this.findOne(".top-left").y(_.y-n)}}else if(this._movingAnchorName==="top-center")this.findOne(".top-left").y(s.y());else if(this._movingAnchorName==="top-right"){if(m){var _=w?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".bottom-left").x(),y:this.findOne(".bottom-left").y()};i=Math.sqrt(Math.pow(s.x()-_.x,2)+Math.pow(_.y-s.y(),2));var y=this.findOne(".top-right").x()<_.x?-1:1,b=this.findOne(".top-right").y()>_.y?-1:1;t=i*this.cos*y,n=i*this.sin*b,this.findOne(".top-right").x(_.x+t),this.findOne(".top-right").y(_.y-n)}var S=s.position();this.findOne(".top-left").y(S.y),this.findOne(".bottom-right").x(S.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(m){var _=w?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".top-right").x(),y:this.findOne(".top-right").y()};i=Math.sqrt(Math.pow(_.x-s.x(),2)+Math.pow(s.y()-_.y,2));var y=_.x<s.x()?-1:1,b=s.y()<_.y?-1:1;t=i*this.cos*y,n=i*this.sin*b,s.x(_.x-t),s.y(_.y+n)}S=s.position(),this.findOne(".top-left").x(S.x),this.findOne(".bottom-right").y(S.y)}else if(this._movingAnchorName==="bottom-center")this.findOne(".bottom-right").y(s.y());else if(this._movingAnchorName==="bottom-right"){if(m){var _=w?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".top-left").x(),y:this.findOne(".top-left").y()};i=Math.sqrt(Math.pow(s.x()-_.x,2)+Math.pow(s.y()-_.y,2));var y=this.findOne(".bottom-right").x()<_.x?-1:1,b=this.findOne(".bottom-right").y()<_.y?-1:1;t=i*this.cos*y,n=i*this.sin*b,this.findOne(".bottom-right").x(_.x+t),this.findOne(".bottom-right").y(_.y+n)}}else console.error(new Error("Wrong position argument of selection resizer: "+this._movingAnchorName));var w=this.centeredScaling()||e.altKey;if(w){const R=this.findOne(".top-left"),P=this.findOne(".bottom-right"),B=R.x(),O=R.y(),F=this.getWidth()-P.x(),D=this.getHeight()-P.y();P.move({x:-B,y:-O}),R.move({x:F,y:D})}const x=this.findOne(".top-left").getAbsolutePosition();t=x.x,n=x.y;const E=this.findOne(".bottom-right").x()-this.findOne(".top-left").x(),I=this.findOne(".bottom-right").y()-this.findOne(".top-left").y();this._fitNodesInto({x:t,y:n,width:E,height:I,rotation:oa.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 n=this.getNode();$w--,this._fire("transformend",{evt:e,target:n}),(t=this.getLayer())===null||t===void 0||t.batchDraw(),n&&this._nodes.forEach(i=>{var s;i._fire("transformend",{evt:e,target:i}),(s=i.getLayer())===null||s===void 0||s.batchDraw()}),this._movingAnchorName=null}}_fitNodesInto(e,t){const n=this._getNodeRect(),i=1;if(pn.Util._inRange(e.width,-this.padding()*2-i,i)){this.update();return}if(pn.Util._inRange(e.height,-this.padding()*2-i,i)){this.update();return}const s=new pn.Transform;if(s.rotate(oa.Konva.getAngle(this.rotation())),this._movingAnchorName&&e.width<0&&this._movingAnchorName.indexOf("left")>=0){const m=s.point({x:-this.padding()*2,y:0});e.x+=m.x,e.y+=m.y,e.width+=this.padding()*2,this._movingAnchorName=this._movingAnchorName.replace("left","right"),this._anchorDragOffset.x-=m.x,this._anchorDragOffset.y-=m.y}else if(this._movingAnchorName&&e.width<0&&this._movingAnchorName.indexOf("right")>=0){const m=s.point({x:this.padding()*2,y:0});this._movingAnchorName=this._movingAnchorName.replace("right","left"),this._anchorDragOffset.x-=m.x,this._anchorDragOffset.y-=m.y,e.width+=this.padding()*2}if(this._movingAnchorName&&e.height<0&&this._movingAnchorName.indexOf("top")>=0){const m=s.point({x:0,y:-this.padding()*2});e.x+=m.x,e.y+=m.y,this._movingAnchorName=this._movingAnchorName.replace("top","bottom"),this._anchorDragOffset.x-=m.x,this._anchorDragOffset.y-=m.y,e.height+=this.padding()*2}else if(this._movingAnchorName&&e.height<0&&this._movingAnchorName.indexOf("bottom")>=0){const m=s.point({x:0,y:this.padding()*2});this._movingAnchorName=this._movingAnchorName.replace("bottom","top"),this._anchorDragOffset.x-=m.x,this._anchorDragOffset.y-=m.y,e.height+=this.padding()*2}if(this.boundBoxFunc()){const m=this.boundBoxFunc()(n,e);m?e=m:pn.Util.warn("boundBoxFunc returned falsy. You should return new bound rect from it!")}const a=1e7,o=new pn.Transform;o.translate(n.x,n.y),o.rotate(n.rotation),o.scale(n.width/a,n.height/a);const u=new pn.Transform,c=e.width/a,d=e.height/a;this.flipEnabled()===!1?(u.translate(e.x,e.y),u.rotate(e.rotation),u.translate(e.width<0?e.width:0,e.height<0?e.height:0),u.scale(Math.abs(c),Math.abs(d))):(u.translate(e.x,e.y),u.rotate(e.rotation),u.scale(c,d));const p=u.multiply(o.invert());this._nodes.forEach(m=>{var _;const y=m.getParent().getAbsoluteTransform(),b=m.getTransform().copy();b.translate(m.offsetX(),m.offsetY());const S=new pn.Transform;S.multiply(y.copy().invert()).multiply(p).multiply(y).multiply(b);const w=S.decompose();m.setAttrs(w),(_=m.getLayer())===null||_===void 0||_.batchDraw()}),this.rotation(pn.Util._getRotation(e.rotation)),this._nodes.forEach(m=>{this._fire("transform",{evt:t,target:m}),m._fire("transform",{evt:t,target:m})}),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(pn.Util._getRotation(t.rotation));const n=t.width,i=t.height,s=this.enabledAnchors(),a=this.resizeEnabled(),o=this.padding(),u=this.anchorSize(),c=this.find("._anchor");c.forEach(p=>{p.setAttrs({width:u,height:u,offsetX:u/2,offsetY:u/2,stroke:this.anchorStroke(),strokeWidth:this.anchorStrokeWidth(),fill:this.anchorFill(),cornerRadius:this.anchorCornerRadius()})}),this._batchChangeChild(".top-left",{x:0,y:0,offsetX:u/2+o,offsetY:u/2+o,visible:a&&s.indexOf("top-left")>=0}),this._batchChangeChild(".top-center",{x:n/2,y:0,offsetY:u/2+o,visible:a&&s.indexOf("top-center")>=0}),this._batchChangeChild(".top-right",{x:n,y:0,offsetX:u/2-o,offsetY:u/2+o,visible:a&&s.indexOf("top-right")>=0}),this._batchChangeChild(".middle-left",{x:0,y:i/2,offsetX:u/2+o,visible:a&&s.indexOf("middle-left")>=0}),this._batchChangeChild(".middle-right",{x:n,y:i/2,offsetX:u/2-o,visible:a&&s.indexOf("middle-right")>=0}),this._batchChangeChild(".bottom-left",{x:0,y:i,offsetX:u/2+o,offsetY:u/2-o,visible:a&&s.indexOf("bottom-left")>=0}),this._batchChangeChild(".bottom-center",{x:n/2,y:i,offsetY:u/2-o,visible:a&&s.indexOf("bottom-center")>=0}),this._batchChangeChild(".bottom-right",{x:n,y:i,offsetX:u/2-o,offsetY:u/2-o,visible:a&&s.indexOf("bottom-right")>=0}),this._batchChangeChild(".rotater",{x:n/2,y:-this.rotateAnchorOffset()*pn.Util._sign(i)-o,visible:this.rotateEnabled()}),this._batchChangeChild(".back",{width:n,height:i,visible:this.borderEnabled(),stroke:this.borderStroke(),strokeWidth:this.borderStrokeWidth(),dash:this.borderDash(),x:0,y:0});const d=this.anchorStyleFunc();d&&c.forEach(p=>{d(p)}),(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=""),K$.Group.prototype.destroy.call(this),this.detach(),this._removeEvents(),this}toObject(){return q$.Node.prototype.toObject.call(this)}clone(e){return q$.Node.prototype.clone.call(this,e)}getClientRect(){return this.nodes().length>0?super.getClientRect():{x:0,y:0,width:0,height:0}}}fy.Transformer=qt,qt.isTransforming=()=>$w>0;function Jde(r){return r instanceof Array||pn.Util.warn("enabledAnchors value should be an array"),r instanceof Array&&r.forEach(function(e){py.indexOf(e)===-1&&pn.Util.warn("Unknown anchor name: "+e+". Available names are: "+py.join(", "))}),r||[]}qt.prototype.className="Transformer",(0,Vde._registerNode)(qt),rn.Factory.addGetterSetter(qt,"enabledAnchors",py,Jde),rn.Factory.addGetterSetter(qt,"flipEnabled",!0,(0,Ol.getBooleanValidator)()),rn.Factory.addGetterSetter(qt,"resizeEnabled",!0),rn.Factory.addGetterSetter(qt,"anchorSize",10,(0,Ol.getNumberValidator)()),rn.Factory.addGetterSetter(qt,"rotateEnabled",!0),rn.Factory.addGetterSetter(qt,"rotateLineVisible",!0),rn.Factory.addGetterSetter(qt,"rotationSnaps",[]),rn.Factory.addGetterSetter(qt,"rotateAnchorOffset",50,(0,Ol.getNumberValidator)()),rn.Factory.addGetterSetter(qt,"rotateAnchorCursor","crosshair"),rn.Factory.addGetterSetter(qt,"rotationSnapTolerance",5,(0,Ol.getNumberValidator)()),rn.Factory.addGetterSetter(qt,"borderEnabled",!0),rn.Factory.addGetterSetter(qt,"anchorStroke","rgb(0, 161, 255)"),rn.Factory.addGetterSetter(qt,"anchorStrokeWidth",1,(0,Ol.getNumberValidator)()),rn.Factory.addGetterSetter(qt,"anchorFill","white"),rn.Factory.addGetterSetter(qt,"anchorCornerRadius",0,(0,Ol.getNumberValidator)()),rn.Factory.addGetterSetter(qt,"borderStroke","rgb(0, 161, 255)"),rn.Factory.addGetterSetter(qt,"borderStrokeWidth",1,(0,Ol.getNumberValidator)()),rn.Factory.addGetterSetter(qt,"borderDash"),rn.Factory.addGetterSetter(qt,"keepRatio",!0),rn.Factory.addGetterSetter(qt,"shiftBehavior","default"),rn.Factory.addGetterSetter(qt,"centeredScaling",!1),rn.Factory.addGetterSetter(qt,"ignoreStroke",!1),rn.Factory.addGetterSetter(qt,"padding",0,(0,Ol.getNumberValidator)()),rn.Factory.addGetterSetter(qt,"node"),rn.Factory.addGetterSetter(qt,"nodes"),rn.Factory.addGetterSetter(qt,"boundBoxFunc"),rn.Factory.addGetterSetter(qt,"anchorDragBoundFunc"),rn.Factory.addGetterSetter(qt,"anchorStyleFunc"),rn.Factory.addGetterSetter(qt,"shouldOverdrawWholeArea",!1),rn.Factory.addGetterSetter(qt,"useSingleNodeRotation",!0),rn.Factory.backCompat(qt,{lineEnabled:"borderEnabled",rotateHandlerOffset:"rotateAnchorOffset",enabledHandlers:"enabledAnchors"});var my={};Object.defineProperty(my,"__esModule",{value:!0}),my.Wedge=void 0;const gy=Dt,Qde=vs,Zde=$t,Z$=Ct,ehe=$t;class Io extends Qde.Shape{_sceneFunc(e){e.beginPath(),e.arc(0,0,this.radius(),0,Zde.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)}}my.Wedge=Io,Io.prototype.className="Wedge",Io.prototype._centroid=!0,Io.prototype._attrsAffectingSize=["radius"],(0,ehe._registerNode)(Io),gy.Factory.addGetterSetter(Io,"radius",0,(0,Z$.getNumberValidator)()),gy.Factory.addGetterSetter(Io,"angle",0,(0,Z$.getNumberValidator)()),gy.Factory.addGetterSetter(Io,"clockwise",!1),gy.Factory.backCompat(Io,{angleDeg:"angle",getAngleDeg:"getAngle",setAngleDeg:"setAngle"});var _y={};Object.defineProperty(_y,"__esModule",{value:!0}),_y.Blur=void 0;const e4=Dt,the=Mn,nhe=Ct;function t4(){this.r=0,this.g=0,this.b=0,this.a=0,this.next=null}const she=[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],rhe=[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 ihe(r,e){const t=r.data,n=r.width,i=r.height;let s,a,o,u,c,d,p,m,_,y,b,S,w,x,E,I,R,P,B,O,F,D,L,G,j=e+e+1,te=n-1,W=i-1,Q=e+1,oe=Q*(Q+1)/2,Ce=new t4,fe=null,ne=Ce,ae=null,be=null,Se=she[e],Me=rhe[e];for(o=1;o<j;o++)ne=ne.next=new t4,o===Q&&(fe=ne);for(ne.next=Ce,p=d=0,a=0;a<i;a++){for(I=R=P=B=m=_=y=b=0,S=Q*(O=t[d]),w=Q*(F=t[d+1]),x=Q*(D=t[d+2]),E=Q*(L=t[d+3]),m+=oe*O,_+=oe*F,y+=oe*D,b+=oe*L,ne=Ce,o=0;o<Q;o++)ne.r=O,ne.g=F,ne.b=D,ne.a=L,ne=ne.next;for(o=1;o<Q;o++)u=d+((te<o?te:o)<<2),m+=(ne.r=O=t[u])*(G=Q-o),_+=(ne.g=F=t[u+1])*G,y+=(ne.b=D=t[u+2])*G,b+=(ne.a=L=t[u+3])*G,I+=O,R+=F,P+=D,B+=L,ne=ne.next;for(ae=Ce,be=fe,s=0;s<n;s++)t[d+3]=L=b*Se>>Me,L!==0?(L=255/L,t[d]=(m*Se>>Me)*L,t[d+1]=(_*Se>>Me)*L,t[d+2]=(y*Se>>Me)*L):t[d]=t[d+1]=t[d+2]=0,m-=S,_-=w,y-=x,b-=E,S-=ae.r,w-=ae.g,x-=ae.b,E-=ae.a,u=p+((u=s+e+1)<te?u:te)<<2,I+=ae.r=t[u],R+=ae.g=t[u+1],P+=ae.b=t[u+2],B+=ae.a=t[u+3],m+=I,_+=R,y+=P,b+=B,ae=ae.next,S+=O=be.r,w+=F=be.g,x+=D=be.b,E+=L=be.a,I-=O,R-=F,P-=D,B-=L,be=be.next,d+=4;p+=n}for(s=0;s<n;s++){for(R=P=B=I=_=y=b=m=0,d=s<<2,S=Q*(O=t[d]),w=Q*(F=t[d+1]),x=Q*(D=t[d+2]),E=Q*(L=t[d+3]),m+=oe*O,_+=oe*F,y+=oe*D,b+=oe*L,ne=Ce,o=0;o<Q;o++)ne.r=O,ne.g=F,ne.b=D,ne.a=L,ne=ne.next;for(c=n,o=1;o<=e;o++)d=c+s<<2,m+=(ne.r=O=t[d])*(G=Q-o),_+=(ne.g=F=t[d+1])*G,y+=(ne.b=D=t[d+2])*G,b+=(ne.a=L=t[d+3])*G,I+=O,R+=F,P+=D,B+=L,ne=ne.next,o<W&&(c+=n);for(d=s,ae=Ce,be=fe,a=0;a<i;a++)u=d<<2,t[u+3]=L=b*Se>>Me,L>0?(L=255/L,t[u]=(m*Se>>Me)*L,t[u+1]=(_*Se>>Me)*L,t[u+2]=(y*Se>>Me)*L):t[u]=t[u+1]=t[u+2]=0,m-=S,_-=w,y-=x,b-=E,S-=ae.r,w-=ae.g,x-=ae.b,E-=ae.a,u=s+((u=a+Q)<W?u:W)*n<<2,m+=I+=ae.r=t[u],_+=R+=ae.g=t[u+1],y+=P+=ae.b=t[u+2],b+=B+=ae.a=t[u+3],ae=ae.next,S+=O=be.r,w+=F=be.g,x+=D=be.b,E+=L=be.a,I-=O,R-=F,P-=D,B-=L,be=be.next,d+=n}}const ahe=function(e){const t=Math.round(this.blurRadius());t>0&&ihe(e,t)};_y.Blur=ahe,e4.Factory.addGetterSetter(the.Node,"blurRadius",0,(0,nhe.getNumberValidator)(),e4.Factory.afterSetFilter);var yy={};Object.defineProperty(yy,"__esModule",{value:!0}),yy.Brighten=void 0;const n4=Dt,ohe=Mn,lhe=Ct,uhe=function(r){let e=this.brightness()*255,t=r.data,n=t.length,i;for(i=0;i<n;i+=4)t[i]+=e,t[i+1]+=e,t[i+2]+=e};yy.Brighten=uhe,n4.Factory.addGetterSetter(ohe.Node,"brightness",0,(0,lhe.getNumberValidator)(),n4.Factory.afterSetFilter);var vy={};Object.defineProperty(vy,"__esModule",{value:!0}),vy.Contrast=void 0;const s4=Dt,che=Mn,dhe=Ct,hhe=function(r){const e=Math.pow((this.contrast()+100)/100,2);let t=r.data,n=t.length,i=150,s=150,a=150,o;for(o=0;o<n;o+=4)i=t[o],s=t[o+1],a=t[o+2],i/=255,i-=.5,i*=e,i+=.5,i*=255,s/=255,s-=.5,s*=e,s+=.5,s*=255,a/=255,a-=.5,a*=e,a+=.5,a*=255,i=i<0?0:i>255?255:i,s=s<0?0:s>255?255:s,a=a<0?0:a>255?255:a,t[o]=i,t[o+1]=s,t[o+2]=a};vy.Contrast=hhe,s4.Factory.addGetterSetter(che.Node,"contrast",0,(0,dhe.getNumberValidator)(),s4.Factory.afterSetFilter);var by={};Object.defineProperty(by,"__esModule",{value:!0}),by.Emboss=void 0;const $l=Dt,Sy=Mn,fhe=Un,r4=Ct,phe=function(r){let e=this.embossStrength()*10,t=this.embossWhiteLevel()*255,n=this.embossDirection(),i=this.embossBlend(),s=0,a=0,o=r.data,u=r.width,c=r.height,d=u*4,p=c;switch(n){case"top-left":s=-1,a=-1;break;case"top":s=-1,a=0;break;case"top-right":s=-1,a=1;break;case"right":s=0,a=1;break;case"bottom-right":s=1,a=1;break;case"bottom":s=1,a=0;break;case"bottom-left":s=1,a=-1;break;case"left":s=0,a=-1;break;default:fhe.Util.error("Unknown emboss direction: "+n)}do{const m=(p-1)*d;let _=s;p+_<1&&(_=0),p+_>c&&(_=0);const y=(p-1+_)*u*4;let b=u;do{const S=m+(b-1)*4;let w=a;b+w<1&&(w=0),b+w>u&&(w=0);const x=y+(b-1+w)*4,E=o[S]-o[x],I=o[S+1]-o[x+1],R=o[S+2]-o[x+2];let P=E;const B=P>0?P:-P,O=I>0?I:-I,F=R>0?R:-R;if(O>B&&(P=I),F>B&&(P=R),P*=e,i){const D=o[S]+P,L=o[S+1]+P,G=o[S+2]+P;o[S]=D>255?255:D<0?0:D,o[S+1]=L>255?255:L<0?0:L,o[S+2]=G>255?255:G<0?0:G}else{let D=t-P;D<0?D=0:D>255&&(D=255),o[S]=o[S+1]=o[S+2]=D}}while(--b)}while(--p)};by.Emboss=phe,$l.Factory.addGetterSetter(Sy.Node,"embossStrength",.5,(0,r4.getNumberValidator)(),$l.Factory.afterSetFilter),$l.Factory.addGetterSetter(Sy.Node,"embossWhiteLevel",.5,(0,r4.getNumberValidator)(),$l.Factory.afterSetFilter),$l.Factory.addGetterSetter(Sy.Node,"embossDirection","top-left",null,$l.Factory.afterSetFilter),$l.Factory.addGetterSetter(Sy.Node,"embossBlend",!1,null,$l.Factory.afterSetFilter);var Ty={};Object.defineProperty(Ty,"__esModule",{value:!0}),Ty.Enhance=void 0;const i4=Dt,mhe=Mn,ghe=Ct;function Dw(r,e,t,n,i){let s=t-e,a=i-n,o;return s===0?n+a/2:a===0?n:(o=(r-e)/s,o=a*o+n,o)}const _he=function(r){let e=r.data,t=e.length,n=e[0],i=n,s,a=e[1],o=a,u,c=e[2],d=c,p,m;const _=this.enhance();if(_===0)return;for(m=0;m<t;m+=4)s=e[m+0],s<n?n=s:s>i&&(i=s),u=e[m+1],u<a?a=u:u>o&&(o=u),p=e[m+2],p<c?c=p:p>d&&(d=p);i===n&&(i=255,n=0),o===a&&(o=255,a=0),d===c&&(d=255,c=0);let y,b,S,w,x,E,I,R,P;for(_>0?(b=i+_*(255-i),S=n-_*(n-0),x=o+_*(255-o),E=a-_*(a-0),R=d+_*(255-d),P=c-_*(c-0)):(y=(i+n)*.5,b=i+_*(i-y),S=n+_*(n-y),w=(o+a)*.5,x=o+_*(o-w),E=a+_*(a-w),I=(d+c)*.5,R=d+_*(d-I),P=c+_*(c-I)),m=0;m<t;m+=4)e[m+0]=Dw(e[m+0],n,i,S,b),e[m+1]=Dw(e[m+1],a,o,E,x),e[m+2]=Dw(e[m+2],c,d,P,R)};Ty.Enhance=_he,i4.Factory.addGetterSetter(mhe.Node,"enhance",0,(0,ghe.getNumberValidator)(),i4.Factory.afterSetFilter);var wy={};Object.defineProperty(wy,"__esModule",{value:!0}),wy.Grayscale=void 0;const yhe=function(r){let e=r.data,t=e.length,n,i;for(n=0;n<t;n+=4)i=.34*e[n]+.5*e[n+1]+.16*e[n+2],e[n]=i,e[n+1]=i,e[n+2]=i};wy.Grayscale=yhe;var Cy={};Object.defineProperty(Cy,"__esModule",{value:!0}),Cy.HSL=void 0;const ud=Dt,Pw=Mn,Fw=Ct;ud.Factory.addGetterSetter(Pw.Node,"hue",0,(0,Fw.getNumberValidator)(),ud.Factory.afterSetFilter),ud.Factory.addGetterSetter(Pw.Node,"saturation",0,(0,Fw.getNumberValidator)(),ud.Factory.afterSetFilter),ud.Factory.addGetterSetter(Pw.Node,"luminance",0,(0,Fw.getNumberValidator)(),ud.Factory.afterSetFilter);const vhe=function(r){let e=r.data,t=e.length,n=1,i=Math.pow(2,this.saturation()),s=Math.abs(this.hue()+360)%360,a=this.luminance()*127,o;const u=n*i*Math.cos(s*Math.PI/180),c=n*i*Math.sin(s*Math.PI/180),d=.299*n+.701*u+.167*c,p=.587*n-.587*u+.33*c,m=.114*n-.114*u-.497*c,_=.299*n-.299*u-.328*c,y=.587*n+.413*u+.035*c,b=.114*n-.114*u+.293*c,S=.299*n-.3*u+1.25*c,w=.587*n-.586*u-1.05*c,x=.114*n+.886*u-.2*c;let E,I,R,P;for(o=0;o<t;o+=4)E=e[o+0],I=e[o+1],R=e[o+2],P=e[o+3],e[o+0]=d*E+p*I+m*R+a,e[o+1]=_*E+y*I+b*R+a,e[o+2]=S*E+w*I+x*R+a,e[o+3]=P};Cy.HSL=vhe;var Ey={};Object.defineProperty(Ey,"__esModule",{value:!0}),Ey.HSV=void 0;const cd=Dt,Mw=Mn,Lw=Ct,bhe=function(r){const e=r.data,t=e.length,n=Math.pow(2,this.value()),i=Math.pow(2,this.saturation()),s=Math.abs(this.hue()+360)%360,a=n*i*Math.cos(s*Math.PI/180),o=n*i*Math.sin(s*Math.PI/180),u=.299*n+.701*a+.167*o,c=.587*n-.587*a+.33*o,d=.114*n-.114*a-.497*o,p=.299*n-.299*a-.328*o,m=.587*n+.413*a+.035*o,_=.114*n-.114*a+.293*o,y=.299*n-.3*a+1.25*o,b=.587*n-.586*a-1.05*o,S=.114*n+.886*a-.2*o;let w,x,E,I;for(let R=0;R<t;R+=4)w=e[R+0],x=e[R+1],E=e[R+2],I=e[R+3],e[R+0]=u*w+c*x+d*E,e[R+1]=p*w+m*x+_*E,e[R+2]=y*w+b*x+S*E,e[R+3]=I};Ey.HSV=bhe,cd.Factory.addGetterSetter(Mw.Node,"hue",0,(0,Lw.getNumberValidator)(),cd.Factory.afterSetFilter),cd.Factory.addGetterSetter(Mw.Node,"saturation",0,(0,Lw.getNumberValidator)(),cd.Factory.afterSetFilter),cd.Factory.addGetterSetter(Mw.Node,"value",0,(0,Lw.getNumberValidator)(),cd.Factory.afterSetFilter);var xy={};Object.defineProperty(xy,"__esModule",{value:!0}),xy.Invert=void 0;const She=function(r){let e=r.data,t=e.length,n;for(n=0;n<t;n+=4)e[n]=255-e[n],e[n+1]=255-e[n+1],e[n+2]=255-e[n+2]};xy.Invert=She;var Iy={};Object.defineProperty(Iy,"__esModule",{value:!0}),Iy.Kaleidoscope=void 0;const Ay=Dt,a4=Mn,o4=Un,l4=Ct,The=function(r,e,t){let n=r.data,i=e.data,s=r.width,a=r.height,o=t.polarCenterX||s/2,u=t.polarCenterY||a/2,c,d,p,m=0,_=0,y=0,b=0,S,w=Math.sqrt(o*o+u*u);d=s-o,p=a-u,S=Math.sqrt(d*d+p*p),w=S>w?S:w;let x=a,E=s,I,R,P=360/E*Math.PI/180,B,O;for(R=0;R<E;R+=1)for(B=Math.sin(R*P),O=Math.cos(R*P),I=0;I<x;I+=1)d=Math.floor(o+w*I/x*O),p=Math.floor(u+w*I/x*B),c=(p*s+d)*4,m=n[c+0],_=n[c+1],y=n[c+2],b=n[c+3],c=(R+I*s)*4,i[c+0]=m,i[c+1]=_,i[c+2]=y,i[c+3]=b},whe=function(r,e,t){let n=r.data,i=e.data,s=r.width,a=r.height,o=t.polarCenterX||s/2,u=t.polarCenterY||a/2,c,d,p,m,_,y=0,b=0,S=0,w=0,x,E=Math.sqrt(o*o+u*u);d=s-o,p=a-u,x=Math.sqrt(d*d+p*p),E=x>E?x:E;let I=a,R=s,P,B,O=t.polarRotation||0,F,D;for(d=0;d<s;d+=1)for(p=0;p<a;p+=1)m=d-o,_=p-u,P=Math.sqrt(m*m+_*_)*I/E,B=(Math.atan2(_,m)*180/Math.PI+360+O)%360,B=B*R/360,F=Math.floor(B),D=Math.floor(P),c=(D*s+F)*4,y=n[c+0],b=n[c+1],S=n[c+2],w=n[c+3],c=(p*s+d)*4,i[c+0]=y,i[c+1]=b,i[c+2]=S,i[c+3]=w},Che=function(r){const e=r.width,t=r.height;let n,i,s,a,o,u,c,d,p,m,_=Math.round(this.kaleidoscopePower());const y=Math.round(this.kaleidoscopeAngle()),b=Math.floor(e*(y%360)/360);if(_<1)return;const S=o4.Util.createCanvasElement();S.width=e,S.height=t;const w=S.getContext("2d").getImageData(0,0,e,t);o4.Util.releaseCanvas(S),The(r,w,{polarCenterX:e/2,polarCenterY:t/2});let x=e/Math.pow(2,_);for(;x<=8;)x=x*2,_-=1;x=Math.ceil(x);let E=x,I=0,R=E,P=1;for(b+x>e&&(I=E,R=0,P=-1),i=0;i<t;i+=1)for(n=I;n!==R;n+=P)s=Math.round(n+b)%e,p=(e*i+s)*4,o=w.data[p+0],u=w.data[p+1],c=w.data[p+2],d=w.data[p+3],m=(e*i+n)*4,w.data[m+0]=o,w.data[m+1]=u,w.data[m+2]=c,w.data[m+3]=d;for(i=0;i<t;i+=1)for(E=Math.floor(x),a=0;a<_;a+=1){for(n=0;n<E+1;n+=1)p=(e*i+n)*4,o=w.data[p+0],u=w.data[p+1],c=w.data[p+2],d=w.data[p+3],m=(e*i+E*2-n-1)*4,w.data[m+0]=o,w.data[m+1]=u,w.data[m+2]=c,w.data[m+3]=d;E*=2}whe(w,r,{polarRotation:0})};Iy.Kaleidoscope=Che,Ay.Factory.addGetterSetter(a4.Node,"kaleidoscopePower",2,(0,l4.getNumberValidator)(),Ay.Factory.afterSetFilter),Ay.Factory.addGetterSetter(a4.Node,"kaleidoscopeAngle",0,(0,l4.getNumberValidator)(),Ay.Factory.afterSetFilter);var Ry={};Object.defineProperty(Ry,"__esModule",{value:!0}),Ry.Mask=void 0;const u4=Dt,Ehe=Mn,xhe=Ct;function Ny(r,e,t){let n=(t*r.width+e)*4;const i=[];return i.push(r.data[n++],r.data[n++],r.data[n++],r.data[n++]),i}function hp(r,e){return Math.sqrt(Math.pow(r[0]-e[0],2)+Math.pow(r[1]-e[1],2)+Math.pow(r[2]-e[2],2))}function Ihe(r){const e=[0,0,0];for(let t=0;t<r.length;t++)e[0]+=r[t][0],e[1]+=r[t][1],e[2]+=r[t][2];return e[0]/=r.length,e[1]/=r.length,e[2]/=r.length,e}function Ahe(r,e){const t=Ny(r,0,0),n=Ny(r,r.width-1,0),i=Ny(r,0,r.height-1),s=Ny(r,r.width-1,r.height-1),a=e||10;if(hp(t,n)<a&&hp(n,s)<a&&hp(s,i)<a&&hp(i,t)<a){const o=Ihe([n,t,s,i]),u=[];for(let c=0;c<r.width*r.height;c++){const d=hp(o,[r.data[c*4],r.data[c*4+1],r.data[c*4+2]]);u[c]=d<a?0:255}return u}}function Rhe(r,e){for(let t=0;t<r.width*r.height;t++)r.data[4*t+3]=e[t]}function Nhe(r,e,t){const n=[1,1,1,1,0,1,1,1,1],i=Math.round(Math.sqrt(n.length)),s=Math.floor(i/2),a=[];for(let o=0;o<t;o++)for(let u=0;u<e;u++){const c=o*e+u;let d=0;for(let p=0;p<i;p++)for(let m=0;m<i;m++){const _=o+p-s,y=u+m-s;if(_>=0&&_<t&&y>=0&&y<e){const b=_*e+y,S=n[p*i+m];d+=r[b]*S}}a[c]=d===2040?255:0}return a}function khe(r,e,t){const n=[1,1,1,1,1,1,1,1,1],i=Math.round(Math.sqrt(n.length)),s=Math.floor(i/2),a=[];for(let o=0;o<t;o++)for(let u=0;u<e;u++){const c=o*e+u;let d=0;for(let p=0;p<i;p++)for(let m=0;m<i;m++){const _=o+p-s,y=u+m-s;if(_>=0&&_<t&&y>=0&&y<e){const b=_*e+y,S=n[p*i+m];d+=r[b]*S}}a[c]=d>=1020?255:0}return a}function Ohe(r,e,t){const n=[.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111],i=Math.round(Math.sqrt(n.length)),s=Math.floor(i/2),a=[];for(let o=0;o<t;o++)for(let u=0;u<e;u++){const c=o*e+u;let d=0;for(let p=0;p<i;p++)for(let m=0;m<i;m++){const _=o+p-s,y=u+m-s;if(_>=0&&_<t&&y>=0&&y<e){const b=_*e+y,S=n[p*i+m];d+=r[b]*S}}a[c]=d}return a}const $he=function(r){let e=this.threshold(),t=Ahe(r,e);return t&&(t=Nhe(t,r.width,r.height),t=khe(t,r.width,r.height),t=Ohe(t,r.width,r.height),Rhe(r,t)),r};Ry.Mask=$he,u4.Factory.addGetterSetter(Ehe.Node,"threshold",0,(0,xhe.getNumberValidator)(),u4.Factory.afterSetFilter);var ky={};Object.defineProperty(ky,"__esModule",{value:!0}),ky.Noise=void 0;const c4=Dt,Dhe=Mn,Phe=Ct,Fhe=function(r){const e=this.noise()*255,t=r.data,n=t.length,i=e/2;for(let s=0;s<n;s+=4)t[s+0]+=i-2*i*Math.random(),t[s+1]+=i-2*i*Math.random(),t[s+2]+=i-2*i*Math.random()};ky.Noise=Fhe,c4.Factory.addGetterSetter(Dhe.Node,"noise",.2,(0,Phe.getNumberValidator)(),c4.Factory.afterSetFilter);var Oy={};Object.defineProperty(Oy,"__esModule",{value:!0}),Oy.Pixelate=void 0;const d4=Dt,Mhe=Un,Lhe=Mn,Uhe=Ct,Bhe=function(r){let e=Math.ceil(this.pixelSize()),t=r.width,n=r.height,i,s,a,o,u,c,d,p=Math.ceil(t/e),m=Math.ceil(n/e),_,y,b,S,w,x,E,I=r.data;if(e<=0){Mhe.Util.error("pixelSize value can not be <= 0");return}for(w=0;w<p;w+=1)for(x=0;x<m;x+=1){for(o=0,u=0,c=0,d=0,_=w*e,y=_+e,b=x*e,S=b+e,E=0,i=_;i<y;i+=1)if(!(i>=t))for(s=b;s<S;s+=1)s>=n||(a=(t*s+i)*4,o+=I[a+0],u+=I[a+1],c+=I[a+2],d+=I[a+3],E+=1);for(o=o/E,u=u/E,c=c/E,d=d/E,i=_;i<y;i+=1)if(!(i>=t))for(s=b;s<S;s+=1)s>=n||(a=(t*s+i)*4,I[a+0]=o,I[a+1]=u,I[a+2]=c,I[a+3]=d)}};Oy.Pixelate=Bhe,d4.Factory.addGetterSetter(Lhe.Node,"pixelSize",8,(0,Uhe.getNumberValidator)(),d4.Factory.afterSetFilter);var $y={};Object.defineProperty($y,"__esModule",{value:!0}),$y.Posterize=void 0;const h4=Dt,Hhe=Mn,Vhe=Ct,Ghe=function(r){let e=Math.round(this.levels()*254)+1,t=r.data,n=t.length,i=255/e,s;for(s=0;s<n;s+=1)t[s]=Math.floor(t[s]/i)*i};$y.Posterize=Ghe,h4.Factory.addGetterSetter(Hhe.Node,"levels",.5,(0,Vhe.getNumberValidator)(),h4.Factory.afterSetFilter);var Dy={};Object.defineProperty(Dy,"__esModule",{value:!0}),Dy.RGB=void 0;const Py=Dt,Uw=Mn,Whe=Ct,zhe=function(r){let e=r.data,t=e.length,n=this.red(),i=this.green(),s=this.blue(),a,o;for(a=0;a<t;a+=4)o=(.34*e[a]+.5*e[a+1]+.16*e[a+2])/255,e[a]=o*n,e[a+1]=o*i,e[a+2]=o*s,e[a+3]=e[a+3]};Dy.RGB=zhe,Py.Factory.addGetterSetter(Uw.Node,"red",0,function(r){return this._filterUpToDate=!1,r>255?255:r<0?0:Math.round(r)}),Py.Factory.addGetterSetter(Uw.Node,"green",0,function(r){return this._filterUpToDate=!1,r>255?255:r<0?0:Math.round(r)}),Py.Factory.addGetterSetter(Uw.Node,"blue",0,Whe.RGBComponent,Py.Factory.afterSetFilter);var Fy={};Object.defineProperty(Fy,"__esModule",{value:!0}),Fy.RGBA=void 0;const fp=Dt,My=Mn,jhe=Ct,qhe=function(r){const e=r.data,t=e.length,n=this.red(),i=this.green(),s=this.blue(),a=this.alpha();for(let o=0;o<t;o+=4){const u=1-a;e[o]=n*a+e[o]*u,e[o+1]=i*a+e[o+1]*u,e[o+2]=s*a+e[o+2]*u}};Fy.RGBA=qhe,fp.Factory.addGetterSetter(My.Node,"red",0,function(r){return this._filterUpToDate=!1,r>255?255:r<0?0:Math.round(r)}),fp.Factory.addGetterSetter(My.Node,"green",0,function(r){return this._filterUpToDate=!1,r>255?255:r<0?0:Math.round(r)}),fp.Factory.addGetterSetter(My.Node,"blue",0,jhe.RGBComponent,fp.Factory.afterSetFilter),fp.Factory.addGetterSetter(My.Node,"alpha",1,function(r){return this._filterUpToDate=!1,r>1?1:r<0?0:r});var Ly={};Object.defineProperty(Ly,"__esModule",{value:!0}),Ly.Sepia=void 0;const Khe=function(r){let e=r.data,t=e.length,n,i,s,a;for(n=0;n<t;n+=4)i=e[n+0],s=e[n+1],a=e[n+2],e[n+0]=Math.min(255,i*.393+s*.769+a*.189),e[n+1]=Math.min(255,i*.349+s*.686+a*.168),e[n+2]=Math.min(255,i*.272+s*.534+a*.131)};Ly.Sepia=Khe;var Uy={};Object.defineProperty(Uy,"__esModule",{value:!0}),Uy.Solarize=void 0;const Xhe=function(r){const e=r.data,t=r.width,n=r.height,i=t*4;let s=n;do{const a=(s-1)*i;let o=t;do{const u=a+(o-1)*4;let c=e[u],d=e[u+1],p=e[u+2];c>127&&(c=255-c),d>127&&(d=255-d),p>127&&(p=255-p),e[u]=c,e[u+1]=d,e[u+2]=p}while(--o)}while(--s)};Uy.Solarize=Xhe;var By={};Object.defineProperty(By,"__esModule",{value:!0}),By.Threshold=void 0;const f4=Dt,Yhe=Mn,Jhe=Ct,Qhe=function(r){const e=this.threshold()*255,t=r.data,n=t.length;for(let i=0;i<n;i+=1)t[i]=t[i]<e?0:255};By.Threshold=Qhe,f4.Factory.addGetterSetter(Yhe.Node,"threshold",.5,(0,Jhe.getNumberValidator)(),f4.Factory.afterSetFilter),Object.defineProperty(L0,"__esModule",{value:!0}),L0.Konva=void 0;const p4=e$,Zhe=X0,efe=Q0,tfe=ty,nfe=ny,sfe=sy,m4=ad,rfe=op,ife=sd,afe=up,ofe=ay,lfe=oy,ufe=ly,cfe=uy,dfe=od,hfe=hy,ffe=fy,pfe=my,mfe=_y,gfe=yy,_fe=vy,yfe=by,vfe=Ty,bfe=wy,Sfe=Cy,Tfe=Ey,wfe=xy,Cfe=Iy,Efe=Ry,xfe=ky,Ife=Oy,Afe=$y,Rfe=Dy,Nfe=Fy,kfe=Ly,Ofe=Uy,$fe=By;L0.Konva=p4.Konva.Util._assign(p4.Konva,{Arc:Zhe.Arc,Arrow:efe.Arrow,Circle:tfe.Circle,Ellipse:nfe.Ellipse,Image:sfe.Image,Label:m4.Label,Tag:m4.Tag,Line:rfe.Line,Path:ife.Path,Rect:afe.Rect,RegularPolygon:ofe.RegularPolygon,Ring:lfe.Ring,Sprite:ufe.Sprite,Star:cfe.Star,Text:dfe.Text,TextPath:hfe.TextPath,Transformer:ffe.Transformer,Wedge:pfe.Wedge,Filters:{Blur:mfe.Blur,Brighten:gfe.Brighten,Contrast:_fe.Contrast,Emboss:yfe.Emboss,Enhance:vfe.Enhance,Grayscale:bfe.Grayscale,HSL:Sfe.HSL,HSV:Tfe.HSV,Invert:wfe.Invert,Kaleidoscope:Cfe.Kaleidoscope,Mask:Efe.Mask,Noise:xfe.Noise,Pixelate:Ife.Pixelate,Posterize:Afe.Posterize,RGB:Rfe.RGB,RGBA:Nfe.RGBA,Sepia:kfe.Sepia,Solarize:Ofe.Solarize,Threshold:$fe.Threshold}});var Dfe=iw.exports;Object.defineProperty(Dfe,"__esModule",{value:!0});const Pfe=L0;iw.exports=Pfe.Konva;var Ffe=iw.exports;const dd=mn(Ffe),Bw={STROKE_WIDTH:5,STROKE_COLOR:"#f32",EMPTY_DRAWER_RECT_COLOR:"#fff"};class Hw{constructor(e){this.stage=null,this.strokeWidth=Bw.STROKE_WIDTH,this.strokeColor=Bw.STROKE_COLOR,this.emptyDrawerRectColor=Bw.EMPTY_DRAWER_RECT_COLOR,this.emptyDrawerRect=null;const{container:t,width:n,height:i}=e,s=new dd.Stage({container:t,width:n,height:i});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 dd.Layer;return this.stage.add(e),e}initFreeDrawing(e){let t=!1,n;this.stage.on("mousedown touchstart",i=>{t=!0;const s=this.stage.getPointerPosition();n=new dd.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(n)}),this.stage.on("mouseup touchend",()=>{t=!1}),this.stage.on("mousemove touchmove",i=>{if(!t)return;i.evt.preventDefault();const s=this.stage.getPointerPosition(),a=n.points().concat([s.x,s.y]);n.points(a)})}addRect(e,t,n){const i=new dd.Rect({width:t,height:n,fill:this.emptyDrawerRectColor});return e.add(i),this.emptyDrawerRect=i,i}addImage(e,t){const n=new dd.Image({image:t,x:(this.stage.width()-t.width)/2,y:(this.stage.height()-t.height)/2});return e.add(n),n}addWakeupLine(e){const t=new dd.Line({stroke:"#ffffff",strokeWidth:1,globalCompositeOperation:"source-over",lineCap:"round",lineJoin:"round",points:[0,0,0,0]});e.add(t)}}const Mfe={container:"screen-share-video-container",compositeCanvasContainer:"composite-canvas-container",compositeCanvas:"composite-canvas",drawerContainer:"container",videoElement:"whiteboard-source-video",videoElementContainer:"whiteboard-wrapper"};class pp extends O0{constructor(e,t={}){super("ScreenShareWhiteboard","screen"),this.imageSrc=null,this.konvaDrawer=null,this.mode=void 0,this.screenSharePlugin=null,this.selectors={},this.screenSharePlugin=e,this.selectors={...Mfe,...t.selectors||{}}}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,document.body.appendChild(t)}getAspectRatioDimensions(e,t){const n=e.getTracks()[0].getSettings(),i=t.clientWidth,s=t.clientHeight,a=n.width,o=n.height,u=a/o,c=i/s;let d=0,p=0;return u>c?(d=i,p=i/u):(p=s,d=s*u),{width:d,height:p}}async start(e){this.createVideoElement(),this.initialStream=e,this.video.srcObject=e;const t=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 n=document.getElementById(this.selectors.compositeCanvasContainer);n.style.setProperty("position","relative"),n.style.setProperty("margin","auto 0");const{width:i,height:s}=this.getAspectRatioDimensions(e,t);let a=i,o=s;this.screenShareKonvaDrawer=new Hw({container:this.selectors.drawerContainer,width:a,height:o});const u=this.screenShareKonvaDrawer.addLayer();this.screenShareKonvaDrawer.initFreeDrawing(u);const c=document.getElementById(this.selectors.drawerContainer),d=c.querySelector("canvas"),p=c.querySelector(".konvajs-content"),m=document.getElementById(this.selectors.compositeCanvas);m.style.setProperty("position","absolute"),m.style.setProperty("top","0"),m.style.setProperty("left","0");const _=m.getContext("2d"),y=()=>{const{width:w,height:x}=this.getAspectRatioDimensions(e,t);a=w,o=x,d.width=w,d.height=x,d.style.width=`${w}px`,d.style.height=`${x}px`,p.style.width=`${w}px`,p.style.height=`${x}px`,n.style.height=`${x}px`,m.width=w,m.height=x};y(),window.addEventListener("resize",()=>{y(),this.screenShareKonvaDrawer.addWakeupLine(u)});const b=this.video,S=()=>{_.drawImage(b,0,0,a,o),_.drawImage(d,0,0,a,o),requestAnimationFrame(S)};return S(),m.captureStream(30)}stop(){const e=this.initialStream;return this.initialStream=null,this.video=null,this.wrapperEl=null,this.screenShareKonvaDrawer=null,e}setupScreenShareDrawerOptions(e){this.screenShareKonvaDrawer&&this.screenShareKonvaDrawer.setupDrawerOptions(e)}}pp.video=null,pp.wrapperEl=null,pp.screenShareKonvaDrawer=null,pp.initialStream=null;const g4={WHITEBOARD:"whiteboard",IMAGE_WHITEBOARD:"imageWhiteboard"},Lfe={container:"presentation-video-container",drawerContainer:"presentationCanvasWrapper"};class Ufe extends M0{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={...Lfe,...e.selectors||{}},this.selectors.document||(this.selectors.document=document)}setupDrawerOptions(e){this.konvaDrawer&&this.konvaDrawer.setupDrawerOptions(e)}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,n=e.clientHeight;this.konvaDrawer=new Hw({container:this.selectors.drawerContainer,width:t,height:n});const i=this.konvaDrawer.addLayer();this.konvaDrawer.addRect(i,t,n),this.konvaDrawer.initFreeDrawing(i)}async drawImageWhiteboard(){const e=this.selectors.document.getElementById(this.selectors.container),t=e.clientWidth,n=e.clientHeight,i=await yue(this.imageSrc);this.konvaDrawer=new Hw({container:this.selectors.drawerContainer,width:t,height:n});const s=this.konvaDrawer.addLayer();this.konvaDrawer.addImage(s,i),s.batchDraw(),this.konvaDrawer.initFreeDrawing(s)}async generateStream(){if(this.mode===g4.WHITEBOARD)this.drawEmptyWhiteboard();else if(this.mode===g4.IMAGE_WHITEBOARD)await this.drawImageWhiteboard();else return;const t=this.selectors.document.getElementById(this.selectors.drawerContainer).querySelector("canvas"),n=t.getContext("2d");function i(){n.fillRect(0,0,1,1),requestAnimationFrame(i)}i();const s=t.captureStream(30);this.stream=s}async kill(){this.konvaDrawer=null,await this.stop(),this.session._ua.emit("stopWhiteboard")}}const Bfe=gs,Hfe=qi(),$r=new Bfe("WebSocketInterface");var Vfe=class{constructor(e){$r.debug('new() [url:"%s"]',e),this._url=e,this._sip_uri=null,this._via_transport=null,this._ws=null;const t=Hfe.parse(e,"absoluteURI");if(t===-1)throw $r.warn(`invalid WebSocket URI: ${e}`),new TypeError(`Invalid argument: ${e}`);if(t.scheme!=="wss"&&t.scheme!=="ws")throw $r.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($r.debug("connect()"),this.isConnected()){$r.debug(`WebSocket ${this._url} is already connected`);return}else if(this.isConnecting()){$r.debug(`WebSocket ${this._url} is connecting`);return}this._ws&&this.disconnect(),$r.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(){$r.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 $r.debug("send()"),this.isConnected()?(this._ws.send(e),!0):($r.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(){$r.debug(`WebSocket ${this._url} connected`),this.onconnect()}_onClose({wasClean:e,code:t,reason:n}){$r.debug(`WebSocket ${this._url} closed`),e===!1&&$r.debug("WebSocket abrupt disconnection"),this.ondisconnect(!e,t,n)}_onMessage({data:e}){$r.debug("received WebSocket message"),this.ondata(e)}_onError(e){$r.warn(`WebSocket ${this._url} error: `,e)}};const Vw=Ap,Gfe=kt,Wfe=no,zfe=zs(),jfe=yE,qfe=Za(),Kfe=V1(),Xfe=qi(),Yfe=Vfe;oc("JsSIP")("version %s",Vw.version);var Jfe={C:Gfe,Exceptions:Wfe,Utils:zfe,UA:jfe,URI:qfe,NameAddrHeader:Kfe,WebSocketInterface:Yfe,Grammar:Xfe,debug:oc,get name(){return Vw.title},get version(){return Vw.version}};const Qfe=mn(Jfe);function Gw(r){return r<10?`0${r}`:`${r}`}function Zfe(r){let e=r.hours||0,t=r.minutes||0,n=r.seconds||0;n++,n===60&&(n=0,t++,t===60&&(t=0,e++));const i=`${Gw(e)}:${Gw(t)}:${Gw(n)}`;return{seconds:n,minutes:t,hours:e,formatted:i}}var Zs={};Zs.forEach=async(r,e,t)=>{const n=[];for(let i=0;i<r.length;i++)if(i in r){const s=Promise.resolve(r[i]).then(a=>e.call(t||globalThis,a,i,r));n.push(s)}await Promise.all(n)},Zs.forEachSeries=async(r,e,t)=>{for(let n=0;n<r.length;n++)n in r&&await e.call(t||globalThis,await r[n],n,r)},Zs.map=async(r,e,t)=>{const n=[];for(let i=0;i<r.length;i++)i in r&&(n[i]=Promise.resolve(r[i]).then(s=>e.call(t||globalThis,s,i,r)));return Promise.all(n)},Zs.mapSeries=async(r,e,t)=>{const n=[];for(let i=0;i<r.length;i++)i in r&&(n[i]=await e.call(t||globalThis,await r[i],i,r));return n},Zs.find=(r,e,t)=>new Promise((n,i)=>{if(r.length===0)return n();let s=1;for(let a=0;a<r.length;a++){const o=u=>{u?n(r[a]):s===r.length&&n(),s++};Promise.resolve(r[a]).then(u=>e.call(t||globalThis,u,a,r)).then(o).catch(i)}}),Zs.findSeries=async(r,e,t)=>{for(let n=0;n<r.length;n++)if(await e.call(t||globalThis,await r[n],n,r))return r[n]},Zs.findIndex=(r,e,t)=>new Promise((n,i)=>{if(r.length===0)return n(-1);let s=1;for(let a=0;a<r.length;a++){const o=u=>{u?n(a):s===r.length&&n(-1),s++};Promise.resolve(r[a]).then(u=>e.call(t||globalThis,u,a,r)).then(o).catch(i)}}),Zs.findIndexSeries=async(r,e,t)=>{for(let n=0;n<r.length;n++)if(await e.call(t||globalThis,await r[n],n,r))return n},Zs.some=(r,e,t)=>new Promise((n,i)=>{if(r.length===0)return n(!1);let s=1;for(let a=0;a<r.length;a++){if(!(a in r)){s++;continue}const o=u=>{u?n(!0):s===r.length&&n(!1),s++};Promise.resolve(r[a]).then(u=>e.call(t||globalThis,u,a,r)).then(o).catch(i)}}),Zs.someSeries=async(r,e,t)=>{for(let n=0;n<r.length;n++)if(n in r&&await e.call(t||globalThis,await r[n],n,r))return!0;return!1},Zs.every=(r,e,t)=>new Promise((n,i)=>{if(r.length===0)return n(!0);let s=1;for(let a=0;a<r.length;a++){if(!(a in r)){s++;continue}const o=u=>{u?s===r.length&&n(!0):n(!1),s++};Promise.resolve(r[a]).then(u=>e.call(t||globalThis,u,a,r)).then(o).catch(i)}}),Zs.everySeries=async(r,e,t)=>{for(let n=0;n<r.length;n++)if(n in r&&!await e.call(t||globalThis,await r[n],n,r))return!1;return!0},Zs.filter=(r,e,t)=>new Promise(async(n,i)=>{const s=[];for(let o=0;o<r.length;o++)o in r&&(s[o]=Promise.resolve(r[o]).then(u=>e.call(t||globalThis,u,o,r)).catch(i));const a=[];for(let o=0;o<s.length;o++)await s[o]&&a.push(await r[o]);n(a)}),Zs.filterSeries=async(r,e,t)=>{const n=[];for(let i=0;i<r.length;i++)i in r&&await e.call(t||globalThis,await r[i],i,r)&&n.push(await r[i]);return n},Zs.reduce=async(r,e,t)=>{if(r.length===0&&t===void 0)throw TypeError("Reduce of empty array with no initial value");let n,i;for(t!==void 0?(i=t,n=0):(i=r[0],n=1),n;n<r.length;n++)n in r&&(i=await e(await i,await r[n],n,r));return i};var _4={};(function(r){const e=Zs;Object.keys(e).forEach(t=>{const n=t.charAt(0).toUpperCase()+t.slice(1);r[`async${n}`]=async function(...i){return e[t](this,...i)}})})(_4);var epe=Object.assign(Zs,{instanceMethods:_4});const Yu=new AudioContext,la={NEW_CALL:"new_call",CALL_CONFIRMED:"confirmed",CALL_FAILED:"failed",CALL_PROGRESS:"progress",CALL_ENDED:"ended"};var tpe={exports:{}};(function(r){var e=function(t){var n=Object.prototype,i=n.hasOwnProperty,s=Object.defineProperty||function(fe,ne,ae){fe[ne]=ae.value},a,o=typeof Symbol=="function"?Symbol:{},u=o.iterator||"@@iterator",c=o.asyncIterator||"@@asyncIterator",d=o.toStringTag||"@@toStringTag";function p(fe,ne,ae){return Object.defineProperty(fe,ne,{value:ae,enumerable:!0,configurable:!0,writable:!0}),fe[ne]}try{p({},"")}catch{p=function(ne,ae,be){return ne[ae]=be}}function m(fe,ne,ae,be){var Se=ne&&ne.prototype instanceof E?ne:E,Me=Object.create(Se.prototype),ot=new Q(be||[]);return s(Me,"_invoke",{value:G(fe,ae,ot)}),Me}t.wrap=m;function _(fe,ne,ae){try{return{type:"normal",arg:fe.call(ne,ae)}}catch(be){return{type:"throw",arg:be}}}var y="suspendedStart",b="suspendedYield",S="executing",w="completed",x={};function E(){}function I(){}function R(){}var P={};p(P,u,function(){return this});var B=Object.getPrototypeOf,O=B&&B(B(oe([])));O&&O!==n&&i.call(O,u)&&(P=O);var F=R.prototype=E.prototype=Object.create(P);I.prototype=R,s(F,"constructor",{value:R,configurable:!0}),s(R,"constructor",{value:I,configurable:!0}),I.displayName=p(R,d,"GeneratorFunction");function D(fe){["next","throw","return"].forEach(function(ne){p(fe,ne,function(ae){return this._invoke(ne,ae)})})}t.isGeneratorFunction=function(fe){var ne=typeof fe=="function"&&fe.constructor;return ne?ne===I||(ne.displayName||ne.name)==="GeneratorFunction":!1},t.mark=function(fe){return Object.setPrototypeOf?Object.setPrototypeOf(fe,R):(fe.__proto__=R,p(fe,d,"GeneratorFunction")),fe.prototype=Object.create(F),fe},t.awrap=function(fe){return{__await:fe}};function L(fe,ne){function ae(Me,ot,Ve,q){var ue=_(fe[Me],fe,ot);if(ue.type==="throw")q(ue.arg);else{var Ue=ue.arg,mt=Ue.value;return mt&&typeof mt=="object"&&i.call(mt,"__await")?ne.resolve(mt.__await).then(function($e){ae("next",$e,Ve,q)},function($e){ae("throw",$e,Ve,q)}):ne.resolve(mt).then(function($e){Ue.value=$e,Ve(Ue)},function($e){return ae("throw",$e,Ve,q)})}}var be;function Se(Me,ot){function Ve(){return new ne(function(q,ue){ae(Me,ot,q,ue)})}return be=be?be.then(Ve,Ve):Ve()}s(this,"_invoke",{value:Se})}D(L.prototype),p(L.prototype,c,function(){return this}),t.AsyncIterator=L,t.async=function(fe,ne,ae,be,Se){Se===void 0&&(Se=Promise);var Me=new L(m(fe,ne,ae,be),Se);return t.isGeneratorFunction(ne)?Me:Me.next().then(function(ot){return ot.done?ot.value:Me.next()})};function G(fe,ne,ae){var be=y;return function(Me,ot){if(be===S)throw new Error("Generator is already running");if(be===w){if(Me==="throw")throw ot;return Ce()}for(ae.method=Me,ae.arg=ot;;){var Ve=ae.delegate;if(Ve){var q=j(Ve,ae);if(q){if(q===x)continue;return q}}if(ae.method==="next")ae.sent=ae._sent=ae.arg;else if(ae.method==="throw"){if(be===y)throw be=w,ae.arg;ae.dispatchException(ae.arg)}else ae.method==="return"&&ae.abrupt("return",ae.arg);be=S;var ue=_(fe,ne,ae);if(ue.type==="normal"){if(be=ae.done?w:b,ue.arg===x)continue;return{value:ue.arg,done:ae.done}}else ue.type==="throw"&&(be=w,ae.method="throw",ae.arg=ue.arg)}}}function j(fe,ne){var ae=ne.method,be=fe.iterator[ae];if(be===a)return ne.delegate=null,ae==="throw"&&fe.iterator.return&&(ne.method="return",ne.arg=a,j(fe,ne),ne.method==="throw")||ae!=="return"&&(ne.method="throw",ne.arg=new TypeError("The iterator does not provide a '"+ae+"' method")),x;var Se=_(be,fe.iterator,ne.arg);if(Se.type==="throw")return ne.method="throw",ne.arg=Se.arg,ne.delegate=null,x;var Me=Se.arg;if(!Me)return ne.method="throw",ne.arg=new TypeError("iterator result is not an object"),ne.delegate=null,x;if(Me.done)ne[fe.resultName]=Me.value,ne.next=fe.nextLoc,ne.method!=="return"&&(ne.method="next",ne.arg=a);else return Me;return ne.delegate=null,x}D(F),p(F,d,"Generator"),p(F,u,function(){return this}),p(F,"toString",function(){return"[object Generator]"});function te(fe){var ne={tryLoc:fe[0]};1 in fe&&(ne.catchLoc=fe[1]),2 in fe&&(ne.finallyLoc=fe[2],ne.afterLoc=fe[3]),this.tryEntries.push(ne)}function W(fe){var ne=fe.completion||{};ne.type="normal",delete ne.arg,fe.completion=ne}function Q(fe){this.tryEntries=[{tryLoc:"root"}],fe.forEach(te,this),this.reset(!0)}t.keys=function(fe){var ne=Object(fe),ae=[];for(var be in ne)ae.push(be);return ae.reverse(),function Se(){for(;ae.length;){var Me=ae.pop();if(Me in ne)return Se.value=Me,Se.done=!1,Se}return Se.done=!0,Se}};function oe(fe){if(fe){var ne=fe[u];if(ne)return ne.call(fe);if(typeof fe.next=="function")return fe;if(!isNaN(fe.length)){var ae=-1,be=function Se(){for(;++ae<fe.length;)if(i.call(fe,ae))return Se.value=fe[ae],Se.done=!1,Se;return Se.value=a,Se.done=!0,Se};return be.next=be}}return{next:Ce}}t.values=oe;function Ce(){return{value:a,done:!0}}return Q.prototype={constructor:Q,reset:function(fe){if(this.prev=0,this.next=0,this.sent=this._sent=a,this.done=!1,this.delegate=null,this.method="next",this.arg=a,this.tryEntries.forEach(W),!fe)for(var ne in this)ne.charAt(0)==="t"&&i.call(this,ne)&&!isNaN(+ne.slice(1))&&(this[ne]=a)},stop:function(){this.done=!0;var fe=this.tryEntries[0],ne=fe.completion;if(ne.type==="throw")throw ne.arg;return this.rval},dispatchException:function(fe){if(this.done)throw fe;var ne=this;function ae(q,ue){return Me.type="throw",Me.arg=fe,ne.next=q,ue&&(ne.method="next",ne.arg=a),!!ue}for(var be=this.tryEntries.length-1;be>=0;--be){var Se=this.tryEntries[be],Me=Se.completion;if(Se.tryLoc==="root")return ae("end");if(Se.tryLoc<=this.prev){var ot=i.call(Se,"catchLoc"),Ve=i.call(Se,"finallyLoc");if(ot&&Ve){if(this.prev<Se.catchLoc)return ae(Se.catchLoc,!0);if(this.prev<Se.finallyLoc)return ae(Se.finallyLoc)}else if(ot){if(this.prev<Se.catchLoc)return ae(Se.catchLoc,!0)}else if(Ve){if(this.prev<Se.finallyLoc)return ae(Se.finallyLoc)}else throw new Error("try statement without catch or finally")}}},abrupt:function(fe,ne){for(var ae=this.tryEntries.length-1;ae>=0;--ae){var be=this.tryEntries[ae];if(be.tryLoc<=this.prev&&i.call(be,"finallyLoc")&&this.prev<be.finallyLoc){var Se=be;break}}Se&&(fe==="break"||fe==="continue")&&Se.tryLoc<=ne&&ne<=Se.finallyLoc&&(Se=null);var Me=Se?Se.completion:{};return Me.type=fe,Me.arg=ne,Se?(this.method="next",this.next=Se.finallyLoc,x):this.complete(Me)},complete:function(fe,ne){if(fe.type==="throw")throw fe.arg;return fe.type==="break"||fe.type==="continue"?this.next=fe.arg:fe.type==="return"?(this.rval=this.arg=fe.arg,this.method="return",this.next="end"):fe.type==="normal"&&ne&&(this.next=ne),x},finish:function(fe){for(var ne=this.tryEntries.length-1;ne>=0;--ne){var ae=this.tryEntries[ne];if(ae.finallyLoc===fe)return this.complete(ae.completion,ae.afterLoc),W(ae),x}},catch:function(fe){for(var ne=this.tryEntries.length-1;ne>=0;--ne){var ae=this.tryEntries[ne];if(ae.tryLoc===fe){var be=ae.completion;if(be.type==="throw"){var Se=be.arg;W(ae)}return Se}}throw new Error("illegal catch attempt")},delegateYield:function(fe,ne,ae){return this.delegate={iterator:oe(fe),resultName:ne,nextLoc:ae},this.method==="next"&&(this.arg=a),x}},t}(r.exports);try{regeneratorRuntime=e}catch{typeof globalThis=="object"?globalThis.regeneratorRuntime=e:Function("r","regeneratorRuntime = r")(e)}})(tpe);var y4={exports:{}};(function(r){(function(e,t){r.exports?r.exports=t():e.log=t()})(Qn,function(){var e=function(){},t="undefined",n=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),i=["trace","debug","info","warn","error"];function s(b,S){var w=b[S];if(typeof w.bind=="function")return w.bind(b);try{return Function.prototype.bind.call(w,b)}catch{return function(){return Function.prototype.apply.apply(w,[b,arguments])}}}function a(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function o(b){return b==="debug"&&(b="log"),typeof console===t?!1:b==="trace"&&n?a:console[b]!==void 0?s(console,b):console.log!==void 0?s(console,"log"):e}function u(b,S){for(var w=0;w<i.length;w++){var x=i[w];this[x]=w<b?e:this.methodFactory(x,b,S)}this.log=this.debug}function c(b,S,w){return function(){typeof console!==t&&(u.call(this,S,w),this[b].apply(this,arguments))}}function d(b,S,w){return o(b)||c.apply(this,arguments)}function p(b,S,w){var x=this,E;S=S??"WARN";var I="loglevel";typeof b=="string"?I+=":"+b:typeof b=="symbol"&&(I=void 0);function R(F){var D=(i[F]||"silent").toUpperCase();if(!(typeof window===t||!I)){try{window.localStorage[I]=D;return}catch{}try{window.document.cookie=encodeURIComponent(I)+"="+D+";"}catch{}}}function P(){var F;if(!(typeof window===t||!I)){try{F=window.localStorage[I]}catch{}if(typeof F===t)try{var D=window.document.cookie,L=D.indexOf(encodeURIComponent(I)+"=");L!==-1&&(F=/^([^;]+)/.exec(D.slice(L))[1])}catch{}return x.levels[F]===void 0&&(F=void 0),F}}function B(){if(!(typeof window===t||!I)){try{window.localStorage.removeItem(I);return}catch{}try{window.document.cookie=encodeURIComponent(I)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}x.name=b,x.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},x.methodFactory=w||d,x.getLevel=function(){return E},x.setLevel=function(F,D){if(typeof F=="string"&&x.levels[F.toUpperCase()]!==void 0&&(F=x.levels[F.toUpperCase()]),typeof F=="number"&&F>=0&&F<=x.levels.SILENT){if(E=F,D!==!1&&R(F),u.call(x,F,b),typeof console===t&&F<x.levels.SILENT)return"No console available for logging"}else throw"log.setLevel() called with invalid level: "+F},x.setDefaultLevel=function(F){S=F,P()||x.setLevel(F,!1)},x.resetLevel=function(){x.setLevel(S,!1),B()},x.enableAll=function(F){x.setLevel(x.levels.TRACE,F)},x.disableAll=function(F){x.setLevel(x.levels.SILENT,F)};var O=P();O==null&&(O=S),x.setLevel(O,!1)}var m=new p,_={};m.getLogger=function(S){if(typeof S!="symbol"&&typeof S!="string"||S==="")throw new TypeError("You must supply a name when creating a logger.");var w=_[S];return w||(w=_[S]=new p(S,m.getLevel(),m.methodFactory)),w};var y=typeof window!==t?window.log:void 0;return m.noConflict=function(){return typeof window!==t&&window.log===m&&(window.log=y),m},m.getLoggers=function(){return _},m.default=m,m})})(y4);var _r=y4.exports;const Ao=()=>`${new Date().toISOString()} | metrics`,Ro=(r,e,t)=>`${r} | ${e} | ${t}`;_r.setDefaultLevel(_r.levels.TRACE);const npe=r=>{_r.info(Ro(Ao(),"log ",`set log level to ${r?"verbose":"info"}`)),_r.setLevel(r?_r.levels.TRACE:_r.levels.INFO)},spe=r=>{const e=[...Object.keys(_r.levels)];e.includes(r)?(_r.info(Ro(Ao(),"log ",`update log level to ${r.toLowerCase()}`)),_r.setLevel(r)):_r.warn(Ro(Ao(),"log ","Incorrect log level please choose one of "),e)},Qt=(r,e,t)=>{t?_r.debug(Ro(Ao(),r,e),t):_r.debug(Ro(Ao(),r,e))},Ww=(r,e)=>{_r.info(Ro(Ao(),r,e))},Ju=(r,e)=>{_r.info(Ro(Ao(),r,e))},Hy=(r,e)=>{_r.warn(Ro(Ao(),r,e))},hd=(r,e)=>{_r.error(Ro(Ao(),r,e))};function rpe(r){return Math.floor(Math.random()*r).toString()}function v4(r,e){let t=e;return r.forEach(n=>{t=t.replace(n,"")}),t}function ipe(r,e){let t="";for(let n=0;n<e;n+=1)t+=r[rpe(r.length)];return t}function ape({length:r=20,useLetters:e=!0,useNumbers:t=!0,includeSymbols:n=[],excludeSymbols:i=[]}={}){let s="abcdefghijklmnopqrstuvwxyz",a="0123456789",o=[],u=[],c=[];return e&&(i.length&&(s=v4(i,s)),u=s.split("")),t&&(i.length&&(a=v4(i,a)),c=a.split("")),o=[...u,...c,...n],ipe(o,r)}var ope=ape;const mp=mn(ope),lpe=()=>"WebRTCMetrics",upe=()=>"5.0.3",vn={INBOUND:"inbound",OUTBOUND:"outbound"},No={IDLE:"idle",RUNNING:"running",MUTED:"muted"},gp={NEW:"new",CHECKING:"checking",CONNECTED:"connected",COMPLETED:"completed",DISCONNECTED:"disconnected",FAILED:"failed",CLOSED:"closed"},cpe=()=>({...{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:[]}}),b4={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:vn.INBOUND},S4={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:vn.OUTBOUND},T4={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:vn.INBOUND},w4={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:vn.OUTBOUND},dpe=r=>{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(r){const t={...r,audio:{},video:{},data:{...r.data},network:{...r.network},experimental:{...r.experimental}};return Object.keys(r.audio).forEach(n=>{t.audio[n]={...r.audio[n]}}),Object.keys(r.video).forEach(n=>{t.video[n]={...r.video[n]}}),t}return{...e,audio:{},video:{},data:{...e.data},network:{...e.network},experimental:{...e.experimental}}},hpe={refreshEvery:2e3,startAfter:0,stopAfter:-1,verbose:!1,pname:`p-${mp()}`,cid:`c-${mp()}`,uid:`u-${mp()}`,record:!1,ticket:!0},ua={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"},we={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"},_e={SUCCEEDED:"succeeded",AUDIO:"audio",VIDEO:"video"},_p={ETHERNET:0,CELLULAR_5G:2,WIFI:3,CELLULAR_4G:5,CELLULAR:10},zw={ETHERNET:"ethernet",CELLULAR_4G:"cellular",WIFI:"wifi"},Le={AUDIO:"audio",VIDEO:"video",NETWORK:"network",DATA:"data"},jw="config ",fpe=(r,e={},t)=>{const n={...t,...e};return e.pname||Hy(jw,`Argument [String] 'cfg.pname' for the peerConnection name or id is missing - use generated '${t.pname}'`),e.cid||Hy(jw,`Argument [String] 'cfg.cid' for the call name or id is missing - use generated '${t.cid}'`),e.uid||Hy(jw,`Argument [String] 'cfg.uid' for the user name or id is missing - use generated '${t.uid}'`),n.pc=r,n},ppe=(r={})=>{const e={...hpe,...r};return e.name=lpe(),e.version=upe(),e},yp=(r,e,t,n=!1,i)=>{let s=r.map(a=>{if(!t)return a[e];if(!i)return a[e][t];const o=a[e][i];return o?o[t]:null});return s=s.filter(a=>n?Number.isFinite(a)&&a>0:Number.isFinite(a)),s.length===0?[]:s},Dl=r=>r.reduce((e,t)=>e+t,0)/r.length,mpe=()=>`probe-${mp()}`,gpe=()=>`coltr-${mp()}`,C4=r=>new Promise(e=>setTimeout(e,r)),qw=(r,e,t)=>{e?r.call(e,t):r(t)},Bn=(r,e,t,n)=>{const i=yp(r,e,t,!0,n);if(i.length===0)return null;const s=i.reduce((c,d)=>c+d,0)/i.length;return s===0?null:i.map(c=>Math.abs(s-c)).reduce((c,d)=>c+d,0)/i.length*100/s},jn=(r,e,t,n=!1,i)=>{const s=yp(r,e,t,n,i);return s.length===0?null:s.reduce((a,o)=>a+o,0)/s.length},Qu=(r,e,t)=>yp(r,e,t).reduce((i,s)=>i+s,0),Hn=(r,e,t,n)=>{const i=yp(r,e,t,!0,n);return i.length===0?null:Math.min(...i)},Vn=(r,e,t,n)=>{const i=yp(r,e,t,!1,n);return i.length===0?null:Math.max(...i)},er=(r,e,t,n)=>{const i=r.slice().pop();if(!i)return null;if(!t)return i[e];if(!n)return i[e][t];const s=i[e][n];return s?s[t]:null},_pe=r=>r.slice().pop(),Fs=(r,e,t)=>{if(!e)return null;const n={};let i=e[_e.AUDIO][r];i||(i=t===vn.INBOUND?{...b4}:{...S4}),n[_e.AUDIO]=i;let s=e[_e.VIDEO][r];return s||(s=t===vn.INBOUND?{...T4}:{...w4}),n[_e.VIDEO]=s,n},vp="exporter ",ype="2.0",E4=(r,e,t)=>{if(!r||r.length===0)return 0;const n=r[r.length-1];if(!n)return 0;const i=n[e][t];if(i){const s=i.total_rtt_ms_out,a=i.total_rtt_measure_out;return!a||!s?jn(r,e,"delta_rtt_ms_out",!1,t):Number(s/a)}return null},vpe=(r,e)=>{if(!r||r.length===0)return 0;const t=r[r.length-1];if(!t)return 0;const n=t[e].total_rtt_connectivity_ms,i=t[e].total_rtt_connectivity_measure;return!i||!n?jn(r,e,"delta_rtt_connectivity_ms"):Number(n/i)},bpe=r=>er(r,"network","local_candidate_type")!=="relay"?`direct/${er(r,"network","local_candidate_protocol")}`:`turn/${er(r,"network","local_candidate_relay_protocol")}`,Spe=r=>{const e=er(r,"network","remote_candidate_type"),t=er(r,"network","remote_candidate_protocol");return e!=="relay"?`direct/${t}`:`turn/${t}`};class Tpe{constructor(e){this._start=null,this._end=null,this._cfg=e,this._referenceReport=null,this._reports=[],this._events=[]}start(){Ww(vp,"start() - start exporter...");const e=new Date;return this._start=e.toJSON(),e}stop(){Ww(vp,"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&&(Qt(vp,`addReport() - add report to exporter at ${e.timestamp}`),this._reports.push(e))}addCustomEvent(e){this._events.push(e)}reset(){Ww(vp,"resetReports() - reset reports"),this._reports=[],this._referenceReport=null,this._start=null,this._end=null}get ticket(){Qt(vp,"ticket() - generate ticket");const e=er(this._reports,"audio","total_packets_lost_in"),t=er(this._reports,"audio","total_packets_in"),n=er(this._reports,"video","total_packets_lost_in"),i=er(this._reports,"video","total_packets_in"),s={},a=_pe(this._reports);return a&&(Object.keys(a[_e.AUDIO]).forEach(o=>{const u=a[_e.AUDIO][o];if(s[u.ssrc]={type:_e.AUDIO,direction:u.direction},u.direction===vn.INBOUND){const c={avg:jn(this._reports,_e.AUDIO,"delta_jitter_ms_in",!1,o),min:Hn(this._reports,_e.AUDIO,"delta_jitter_ms_in",o),max:Vn(this._reports,_e.AUDIO,"delta_jitter_ms_in",o),volatility:Bn(this._reports,_e.AUDIO,"delta_jitter_ms_in",o),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},d={avg:jn(this._reports,_e.AUDIO,"delta_kbs_in",!1,o),min:Hn(this._reports,_e.AUDIO,"delta_kbs_in",o),max:Vn(this._reports,_e.AUDIO,"delta_kbs_in",o),volatility:Bn(this._reports,_e.AUDIO,"delta_kbs_in",o),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},p={avg:jn(this._reports,_e.AUDIO,"delta_KBytes_in",!1,o),min:Hn(this._reports,_e.AUDIO,"delta_KBytes_in",o),max:Vn(this._reports,_e.AUDIO,"delta_KBytes_in",o),volatility:Bn(this._reports,_e.AUDIO,"delta_KBytes_in",o),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},m={emodel:{avg:jn(this._reports,_e.AUDIO,"mos_emodel_in",!1,o),min:Hn(this._reports,_e.AUDIO,"mos_emodel_in",o),max:Vn(this._reports,_e.AUDIO,"mos_emodel_in",o),volatility:Bn(this._reports,_e.AUDIO,"mos_emodel_in",o)},effective:{avg:jn(this._reports,_e.AUDIO,"mos_in",!1,o),min:Hn(this._reports,_e.AUDIO,"mos_in",o),max:Vn(this._reports,_e.AUDIO,"mos_in",o),volatility:Bn(this._reports,_e.AUDIO,"mos_in",o)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}},_=er(this._reports,_e.AUDIO,"total_packets_lost_in",o),y=er(this._reports,_e.AUDIO,"total_packets_in",o),b={lost:_,avg:Math.round((_/(_+y)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};s[o].jitter=c,s[o].mos=m,s[o].traffic=p,s[o].bitrate=d,s[o].loss=b}else{const c={avg:jn(this._reports,_e.AUDIO,"delta_jitter_ms_out",!1,o),min:Hn(this._reports,_e.AUDIO,"delta_jitter_ms_out",o),max:Vn(this._reports,_e.AUDIO,"delta_jitter_ms_out",o),volatility:Bn(this._reports,_e.AUDIO,"delta_jitter_ms_out",o),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},d={avg:jn(this._reports,_e.AUDIO,"delta_kbs_out",!1,o),min:Hn(this._reports,_e.AUDIO,"delta_kbs_out",o),max:Vn(this._reports,_e.AUDIO,"delta_kbs_out",o),volatility:Bn(this._reports,_e.AUDIO,"delta_kbs_out",o),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},p={avg:jn(this._reports,_e.AUDIO,"delta_KBytes_out",!1,o),min:Hn(this._reports,_e.AUDIO,"delta_KBytes_out",o),max:Vn(this._reports,_e.AUDIO,"delta_KBytes_out",o),volatility:Bn(this._reports,_e.AUDIO,"delta_KBytes_out",o),_unit:{avg:"KB",min:"KB",max:"KB",bitrate:"kbs",volatility:"percent"}},m={avg:E4(this._reports,_e.AUDIO,o),min:Hn(this._reports,_e.AUDIO,"delta_rtt_ms_out",o),max:Vn(this._reports,_e.AUDIO,"delta_rtt_ms_out",o),volatility:Bn(this._reports,_e.AUDIO,"delta_rtt_ms_out",o),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},_=er(this._reports,_e.AUDIO,"total_packets_lost_out",o),y=er(this._reports,_e.AUDIO,"total_packets_out",o),b={lost:_,avg:Math.round((_/(_+y)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}},S={emodel:{avg:jn(this._reports,_e.AUDIO,"mos_emodel_out",!1,o),min:Hn(this._reports,_e.AUDIO,"mos_emodel_out",o),max:Vn(this._reports,_e.AUDIO,"mos_emodel_out",o),volatility:Bn(this._reports,_e.AUDIO,"mos_emodel_out",o)},effective:{avg:jn(this._reports,_e.AUDIO,"mos_out",!1,o),min:Hn(this._reports,_e.AUDIO,"mos_out",o),max:Vn(this._reports,_e.AUDIO,"mos_out",o),volatility:Bn(this._reports,_e.AUDIO,"mos_out",o)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}};s[o].jitter=c,s[o].rtt=m,s[o].traffic=p,s[o].bitrate=d,s[o].loss=b,s[o].mos=S}}),Object.keys(a[_e.VIDEO]).forEach(o=>{const u=a[_e.VIDEO][o];if(s[o]={type:_e.VIDEO,direction:u.direction},u.direction===vn.INBOUND){const c={avg:jn(this._reports,_e.VIDEO,"delta_jitter_ms_in",!1,o),min:Hn(this._reports,_e.VIDEO,"delta_jitter_ms_in",o),max:Vn(this._reports,_e.VIDEO,"delta_jitter_ms_in",o),volatility:Bn(this._reports,_e.VIDEO,"delta_jitter_ms_in",o),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},d={avg:jn(this._reports,_e.VIDEO,"delta_kbs_in",!1,o),min:Hn(this._reports,_e.VIDEO,"delta_kbs_in",o),max:Vn(this._reports,_e.VIDEO,"delta_kbs_in",o),volatility:Bn(this._reports,_e.VIDEO,"delta_kbs_in",o),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},p={avg:jn(this._reports,_e.VIDEO,"delta_KBytes_in",!1,o),min:Hn(this._reports,_e.VIDEO,"delta_KBytes_in",o),max:Vn(this._reports,_e.VIDEO,"delta_KBytes_in",o),volatility:Bn(this._reports,_e.VIDEO,"delta_KBytes_in",o),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},m=er(this._reports,_e.VIDEO,"total_packets_lost_in",o),_=er(this._reports,_e.VIDEO,"total_packets_in",o),y={lost:m,avg:Math.round((m/(m+_)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};s[o].jitter=c,s[o].traffic=p,s[o].bitrate=d,s[o].loss=y}else{const c={avg:jn(this._reports,_e.VIDEO,"delta_jitter_ms_out",!1,o),min:Hn(this._reports,_e.VIDEO,"delta_jitter_ms_out",o),max:Vn(this._reports,_e.VIDEO,"delta_jitter_ms_out",o),volatility:Bn(this._reports,_e.VIDEO,"delta_jitter_ms_out",o),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},d={avg:jn(this._reports,_e.VIDEO,"delta_kbs_out",!1,o),min:Hn(this._reports,_e.VIDEO,"delta_kbs_out",o),max:Vn(this._reports,_e.VIDEO,"delta_kbs_out",o),volatility:Bn(this._reports,_e.VIDEO,"delta_kbs_out",o),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},p={avg:jn(this._reports,_e.VIDEO,"delta_KBytes_out",!1,o),min:Hn(this._reports,_e.VIDEO,"delta_KBytes_out",o),max:Vn(this._reports,_e.VIDEO,"delta_KBytes_out",o),volatility:Bn(this._reports,_e.VIDEO,"delta_KBytes_out",o),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},m={avg:E4(this._reports,_e.VIDEO,o),min:Hn(this._reports,_e.VIDEO,"delta_rtt_ms_out",o),max:Vn(this._reports,_e.VIDEO,"delta_rtt_ms_out",o),volatility:Bn(this._reports,_e.VIDEO,"delta_rtt_ms_out",o),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},_=er(this._reports,_e.VIDEO,"total_packets_lost_out",o),y=er(this._reports,_e.VIDEO,"total_packets_out",o),b={lost:_,avg:Math.round((_/(_+y)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};s[o].jitter=c,s[o].rtt=m,s[o].traffic=p,s[o].bitrate=d,s[o].loss=b}})),{version:ype,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:vpe(this._reports,"data"),min:Hn(this._reports,"data","delta_rtt_connectivity_ms"),max:Vn(this._reports,"data","delta_rtt_connectivity_ms"),volatility:Bn(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((n/(n+i)*100||0)*100)/100}},unit:{avg:"percent"}},bitrate:{in:{avg:jn(this._reports,"data","delta_kbs_in"),min:Hn(this._reports,"data","delta_kbs_in"),max:Vn(this._reports,"data","delta_kbs_in"),volatility:Bn(this._reports,"data","delta_kbs_in")},out:{avg:jn(this._reports,"data","delta_kbs_out"),min:Hn(this._reports,"data","delta_kbs_out"),max:Vn(this._reports,"data","delta_kbs_out"),volatility:Bn(this._reports,"data","delta_kbs_out")},unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},traffic:{in:{avg:jn(this._reports,"data","delta_KBytes_in"),min:Hn(this._reports,"data","delta_KBytes_in"),max:Vn(this._reports,"data","delta_KBytes_in"),volatility:Bn(this._reports,"data","delta_KBytes_in")},out:{avg:jn(this._reports,"data","delta_KBytes_out"),min:Hn(this._reports,"data","delta_KBytes_out"),max:Vn(this._reports,"data","delta_KBytes_out"),volatility:Bn(this._reports,"data","delta_KBytes_out")},unit:{avg:"KBytes",min:"KBytes",max:"KBytes",volatility:"percent"}},network:{localConnection:bpe(this._reports),remoteConnection:Spe(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 Pl="extractor ",x4=(r,e,t,n)=>{let i=!1;const s=n[e].total_rtt_ms_out,a=n[e].total_rtt_measure_out,o=t?t[e].total_rtt_ms_out:0,u=t?t[e].total_rtt_measure_out:0,c={rtt:null,totalRTT:s,totalRTTMeasurements:a};if(r[we.TIMESTAMP]===n[e].timestamp_out||!Object.prototype.hasOwnProperty.call(r,we.ROUND_TRIP_TIME)||Object.prototype.hasOwnProperty.call(r,we.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS)&&(i=!0,Number(r[we.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])===0||Number(r[we.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])-u===a))return c;const d=1e3*Number(r[we.ROUND_TRIP_TIME]);let p=s+d,m=a+1;return i&&(p=1e3*Number(r[we.TOTAL_ROUND_TRIP_TIME])-o,m=Number(r[we.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])-u),{rtt:d,totalRTT:p,totalRTTMeasurements:m}},wpe=(r,e,t,n)=>{if(!Object.prototype.hasOwnProperty.call(r,we.CURRENT_ROUND_TRIP_TIME))return{rtt:null,totalRTT:n[e].total_rtt_connectivity_ms,totalRTTMeasurements:n[e].total_rtt_connectivity_measure};const i=1e3*Number(r[we.CURRENT_ROUND_TRIP_TIME]);let s=n[e].total_rtt_connectivity_ms+i,a=n[e].total_rtt_connectivity_measure+1;return Object.prototype.hasOwnProperty.call(r,we.TOTAL_ROUND_TRIP_TIME)&&(s=1e3*Number(r[we.TOTAL_ROUND_TRIP_TIME])-(t?t[e].total_rtt_connectivity_ms:0)),Object.prototype.hasOwnProperty.call(r,we.RESPONSES_RECEIVED)&&(a=Number(r[we.RESPONSES_RECEIVED])-(t?t[e].total_rtt_connectivity_measure:0)),{rtt:i,totalRTT:s,totalRTTMeasurements:a}},Vy=(r,e,t)=>r[we.TIMESTAMP]===t[e].timestamp_out||!Object.prototype.hasOwnProperty.call(r,we.JITTER)?null:1e3*(Number(r[we.JITTER])||0),Cpe=(r,e)=>{if(!Object.prototype.hasOwnProperty.call(r,we.FRAMES_DECODED)||!Object.prototype.hasOwnProperty.call(r,we.TOTAL_DECODE_TIME))return{delta_ms_decode_frame:e[_e.VIDEO].delta_ms_decode_frame_in,frames_decoded:e[_e.VIDEO].total_frames_decoded_in,total_decode_time:e[_e.VIDEO].total_time_decoded_in};const t=r[we.FRAMES_DECODED],n=r[we.TOTAL_DECODE_TIME],i=n-e[_e.VIDEO].total_time_decoded_in,s=t-e[_e.VIDEO].total_frames_decoded_in;return{delta_ms_decode_frame:s>0?i*1e3/s:0,frames_decoded:t,total_decode_time:n}},Epe=(r,e)=>{if(!Object.prototype.hasOwnProperty.call(r,we.FRAMES_ENCODED)||!Object.prototype.hasOwnProperty.call(r,we.TOTAL_ENCODE_TIME))return{delta_ms_encode_frame:e[_e.VIDEO].delta_ms_encode_frame_out,frames_encoded:e[_e.VIDEO].total_frames_encoded_out,total_encode_time:e[_e.VIDEO].total_time_encoded_out};const t=r[we.FRAMES_ENCODED],n=r[we.TOTAL_ENCODE_TIME],i=n-e[_e.VIDEO].total_time_encoded_out,s=t-e[_e.VIDEO].total_frames_encoded_out;return{delta_ms_encode_frame:s>0&&i?i*1e3/s:0,frames_encoded:t,total_encode_time:n}},I4=(r,e,t,n)=>{if(!Object.prototype.hasOwnProperty.call(r,we.PACKETS_SENT)||!Object.prototype.hasOwnProperty.call(r,we.BYTES_SENT))return{packetsSent:t[e].total_packets_out,packetsLost:t[e].total_packets_lost_out,bytesSent:t[e].total_KBytes_out};const i=Number(r[we.PACKETS_SENT])||0-(n?n[e].total_packets_out:0),s=i-t[e].total_packets_out,a=Number(r[we.BYTES_SENT])/1024-(n?n[e].total_KBytes_out:0),o=a-t[e].total_KBytes_out,u=r[we.TIMESTAMP]||Date.now(),c=n?n.timestamp:null;let d=t.timestamp;!d&&c&&(d=c);const p=d?u-d:0,m=p>0?o*.008*1024/p*1e3:0;return{packetsSent:i,deltaPacketsSent:s,KBytesSent:a,deltaKBytesSent:o,kbsSent:m}},A4=(r,e,t,n)=>{let i=t[e].total_packets_lost_out,s=0,a=0;return Object.prototype.hasOwnProperty.call(r,we.PACKETS_LOST)&&(i=Number(r[we.PACKETS_LOST])||0-(n?n[e].total_packets_lost_out:0),s=i-t[e].total_packets_lost_out),Object.prototype.hasOwnProperty.call(r,we.FRACTION_LOST)&&(a=Number(100*r[we.FRACTION_LOST])),{packetsLost:i,deltaPacketsLost:s,fractionLost:a}},R4=(r,e,t,n)=>{if(!Object.prototype.hasOwnProperty.call(r,we.PACKETS_RECEIVED)||!Object.prototype.hasOwnProperty.call(r,we.PACKETS_LOST)||!Object.prototype.hasOwnProperty.call(r,we.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 i=Number(r[we.PACKETS_RECEIVED])||0-(n?n[e].total_packets_in:0),s=Number(r[we.PACKETS_LOST])||0-(n?n[e].total_packets_lost_in:0),a=s-t[e].total_packets_lost_in,o=i-t[e].total_packets_in,u=i!==t[e].total_packets_in?a*100/(a+o):0,c=Number(r[we.BYTES_RECEIVED])/1024-(n?n[e].total_KBytes_in:0),d=c-t[e].total_KBytes_in,p=r[we.TIMESTAMP]||Date.now(),m=n?n.timestamp:null;let _=t.timestamp;!_&&m&&(_=m);const y=_?p-_:0,b=y>0?d*.008*1024/y*1e3:0;return{percentPacketsLost:u,packetsReceived:i,deltaPacketsReceived:o,packetsLost:s,deltaPacketsLost:a,KBytesReceived:c,deltaKBytesReceived:d,kbsReceived:b}},xpe=r=>r[we.CANDIDATE_TYPE]!=="relay"?"":r[we.RELAY_PROTOCOL]||"",Ipe=r=>{if(!Object.prototype.hasOwnProperty.call(r,we.NETWORK_TYPE))return _p.WIFI;switch(r[we.NETWORK_TYPE]){case zw.ETHERNET:return _p.ETHERNET;case zw.CELLULAR_4G:return _p.CELLULAR_4G;case zw.WIFI:return _p.WIFI;default:return _p.CELLULAR}},N4=r=>!Object.prototype.hasOwnProperty.call(r,we.FRAME_HEIGHT)||!Object.prototype.hasOwnProperty.call(r,we.FRAME_WIDTH)?{width:null,height:null,framerate:null}:{width:r[we.FRAME_WIDTH]||null,height:r[we.FRAME_HEIGHT]||null,framerate:r[we.FRAMES_PER_SECOND]},Ape=r=>{const e=Object.prototype.hasOwnProperty.call(r,we.QUALITY_LIMITATION_REASON)?r[we.QUALITY_LIMITATION_REASON]:null,t=Object.prototype.hasOwnProperty.call(r,we.QUALITY_LIMITATION_RESOLUTION_CHANGES)?r[we.QUALITY_LIMITATION_RESOLUTION_CHANGES]:null,n=Object.prototype.hasOwnProperty.call(r,we.QUALITY_LIMITATION_DURATIONS)?r[we.QUALITY_LIMITATION_DURATIONS]:null;return n&&Object.keys(n).forEach(i=>{n[i]>1e3&&(n[i]=Number(n[i]/1e3))}),{reason:e,durations:n,resolutionChanges:t}},Rpe=(r,e,t)=>{if(!Object.prototype.hasOwnProperty.call(r,we.PLI)||!Object.prototype.hasOwnProperty.call(r,we.NACK))return{pliCount:e.total_pli_sent_in,nackCount:e.total_nack_sent_in,deltaPliCount:0,deltaNackCount:0};const n=(r[we.PLI]||0)-(t?t[_e.VIDEO].total_pli_sent_in:0),i=(r[we.NACK]||0)-(t?t[_e.VIDEO].total_nack_sent_in:0);return{pliCount:n,nackCount:i,deltaPliCount:n-e[_e.VIDEO].total_pli_sent_in,deltaNackCount:i-e[_e.VIDEO].total_nack_sent_in}},Npe=(r,e,t)=>{if(!Object.prototype.hasOwnProperty.call(r,we.PLI)||!Object.prototype.hasOwnProperty.call(r,we.NACK))return{pliCount:e.total_pli_received_out,nackCount:e.total_nack_received_out,deltaPliCount:0,deltaNackCount:0};const n=(r[we.PLI]||0)-(t?t[_e.VIDEO].total_pli_received_out:0),i=(r[we.NACK]||0)-(t?t[_e.VIDEO].total_nack_received_out:0);return{pliCount:n,nackCount:i,deltaPliCount:n-e[_e.VIDEO].total_pli_received_out,deltaNackCount:i-e[_e.VIDEO].total_nack_received_out}},kpe=r=>({channels:r[we.CHANNELS]||null,clock_rate:r[we.CLOCK_RATE]||null,mime_type:r[we.MIME_TYPE]||null,sdp_fmtp_line:r[we.SDP_FMTP_LINE]||null}),Ope=r=>({clock_rate:r[we.CLOCK_RATE]||null,mime_type:r[we.MIME_TYPE]||null}),$pe=(r,e,t)=>{const n=(r[we.BYTES_RECEIVED]||0)/1024-(t?t.data.total_KBytes_in:0),i=(r[we.BYTES_SENT]||0)/1024-(t?t.data.total_KBytes_out:0),s=r[we.TIMESTAMP]||Date.now(),a=n-e.data.total_KBytes_in,o=i-e.data.total_KBytes_out,u=t?t.timestamp:null;let c=e.timestamp;!c&&u&&(c=u);const d=c?s-c:0,p=d>0?a*.008*1024/d*1e3:0,m=d>0?o*.008*1024/d*1e3:0;return{total_KBytes_received:n,total_KBytes_sent:i,delta_KBytes_received:a,delta_KBytes_sent:o,kbs_speed_received:p,kbs_speed_sent:m}},Dpe=r=>{const e=r[we.AVAILABLE_INCOMING_BITRATE]/1024||0,t=r[we.AVAILABLE_OUTGOING_BITRATE]/1024||0;return{kbs_incoming_bandwidth:e,kbs_outgoing_bandwidth:t}},Ppe=(r,e,t,n)=>{if(!r)return[];switch(r[we.TYPE]){case ua.CANDIDATE_PAIR:let i=!1;if(r[we.NOMINATED]&&r[we.STATE]===_e.SUCCEEDED&&(i=!0,Qt(Pl,`analyze() - got stats ${r[we.TYPE]} for ${t}`,r),we.SELECTED in r&&!r[we.SELECTED]&&(i=!1)),i){const a=r[we.LOCAL_CANDIDATE_ID],o=r[we.REMOTE_CANDIDATE_ID],u=$pe(r,e,n),c=Dpe(r),d=wpe(r,"data",n,e);return[{type:Le.NETWORK,value:{local_candidate_id:a}},{type:Le.NETWORK,value:{remote_candidate_id:o}},{type:Le.DATA,value:{total_KBytes_in:u.total_KBytes_received}},{type:Le.DATA,value:{total_KBytes_out:u.total_KBytes_sent}},{type:Le.DATA,value:{delta_KBytes_in:u.delta_KBytes_received}},{type:Le.DATA,value:{delta_KBytes_out:u.delta_KBytes_sent}},{type:Le.DATA,value:{delta_kbs_in:u.kbs_speed_received}},{type:Le.DATA,value:{delta_kbs_out:u.kbs_speed_sent}},{type:Le.DATA,value:{delta_kbs_bandwidth_in:c.kbs_incoming_bandwidth}},{type:Le.DATA,value:{delta_kbs_bandwidth_out:c.kbs_outgoing_bandwidth}},{type:Le.DATA,value:{delta_rtt_connectivity_ms:d.rtt}},{type:Le.DATA,value:{total_rtt_connectivity_ms:d.totalRTT}},{type:Le.DATA,value:{total_rtt_connectivity_measure:d.totalRTTMeasurements}}]}break;case ua.LOCAL_CANDIDATE:if(r[we.ID]===e.network.local_candidate_id)return[{type:Le.NETWORK,value:{infrastructure:Ipe(r)}},{type:Le.NETWORK,value:{local_candidate_type:r[we.CANDIDATE_TYPE]||""}},{type:Le.NETWORK,value:{local_candidate_protocol:r[we.PROTOCOL]||""}},{type:Le.NETWORK,value:{local_candidate_relay_protocol:xpe(r)}}];break;case ua.REMOTE_CANDIDATE:if(r[we.ID]===e.network.remote_candidate_id)return[{type:Le.NETWORK,value:{remote_candidate_type:r[we.CANDIDATE_TYPE]||""}},{type:Le.NETWORK,value:{remote_candidate_protocol:r[we.PROTOCOL]||""}}];break;case ua.INBOUND_RTP:{Qt(Pl,`analyze() - got stats ${r[we.TYPE]} for ${t}`,r);const a=r[we.SSRC],o=Fs(a,e,vn.INBOUND);o&&(o.timestamp=e.timestamp);const u=Fs(a,n,vn.INBOUND);if(u&&(u.timestamp=n.timestamp),r[we.MEDIA_TYPE]===_e.AUDIO){const c=R4(r,_e.AUDIO,o,u),d=Vy(r,_e.AUDIO,o),p=r[we.CODEC_ID]||"";return[{ssrc:a,type:Le.AUDIO,value:{codec_id_in:p}},{ssrc:a,type:Le.AUDIO,value:{total_packets_in:c.packetsReceived}},{ssrc:a,type:Le.AUDIO,value:{delta_packets_in:c.deltaPacketsReceived}},{ssrc:a,type:Le.AUDIO,value:{total_packets_lost_in:c.packetsLost}},{ssrc:a,type:Le.AUDIO,value:{delta_packets_lost_in:c.deltaPacketsLost}},{ssrc:a,type:Le.AUDIO,value:{percent_packets_lost_in:c.percentPacketsLost}},{ssrc:a,type:Le.AUDIO,value:{total_KBytes_in:c.KBytesReceived}},{ssrc:a,type:Le.AUDIO,value:{delta_KBytes_in:c.deltaKBytesReceived}},{ssrc:a,type:Le.AUDIO,value:{delta_kbs_in:c.kbsReceived}},{ssrc:a,type:Le.AUDIO,value:{delta_jitter_ms_in:d}}]}if(r[we.MEDIA_TYPE]===_e.VIDEO){const c=Cpe(r,o),d=R4(r,_e.VIDEO,o,u),p=Vy(r,_e.VIDEO,o),m=r[we.DECODER_IMPLEMENTATION]||null,_=r[we.CODEC_ID]||null,y=N4(r),b=Rpe(r,o,u);return[{ssrc:a,type:Le.VIDEO,value:{codec_id_in:_}},{ssrc:a,type:Le.VIDEO,value:{total_packets_in:d.packetsReceived}},{ssrc:a,type:Le.VIDEO,value:{delta_packets_in:d.deltaPacketsReceived}},{ssrc:a,type:Le.VIDEO,value:{total_packets_lost_in:d.packetsLost}},{ssrc:a,type:Le.VIDEO,value:{delta_packets_lost_in:d.deltaPacketsLost}},{ssrc:a,type:Le.VIDEO,value:{percent_packets_lost_in:d.percentPacketsLost}},{ssrc:a,type:Le.VIDEO,value:{total_KBytes_in:d.KBytesReceived}},{ssrc:a,type:Le.VIDEO,value:{delta_KBytes_in:d.deltaKBytesReceived}},{ssrc:a,type:Le.VIDEO,value:{delta_kbs_in:d.kbsReceived}},{ssrc:a,type:Le.VIDEO,value:{delta_jitter_ms_in:p}},{ssrc:a,type:Le.VIDEO,value:{decoder_in:m}},{ssrc:a,type:Le.VIDEO,value:{delta_ms_decode_frame_in:c.delta_ms_decode_frame}},{ssrc:a,type:Le.VIDEO,value:{total_frames_decoded_in:c.frames_decoded}},{ssrc:a,type:Le.VIDEO,value:{total_time_decoded_in:c.total_decode_time}},{ssrc:a,type:Le.VIDEO,value:{total_nack_sent_in:b.nackCount}},{ssrc:a,type:Le.VIDEO,value:{delta_nack_sent_in:b.deltaNackCount}},{ssrc:a,type:Le.VIDEO,value:{total_pli_sent_in:b.pliCount}},{ssrc:a,type:Le.VIDEO,value:{delta_pli_sent_in:b.deltaPliCount}},{ssrc:a,type:Le.VIDEO,value:{size_in:y}}]}break}case ua.OUTBOUND_RTP:{Qt(Pl,`analyze() - got stats ${r[we.TYPE]} for ${t}`,r);const a=r[we.SSRC],o=Fs(a,e,vn.OUTBOUND);o&&(o.timestamp=e.timestamp);const u=Fs(a,n,vn.OUTBOUND);if(u&&(u.timestamp=n.timestamp),r[we.MEDIA_TYPE]===_e.AUDIO){const c=r[we.CODEC_ID]||null,d=I4(r,_e.AUDIO,o,u);return[{ssrc:a,type:Le.AUDIO,value:{codec_id_out:c}},{ssrc:a,type:Le.AUDIO,value:{total_packets_out:d.packetsSent}},{ssrc:a,type:Le.AUDIO,value:{delta_packets_out:d.deltaPacketsSent}},{ssrc:a,type:Le.AUDIO,value:{total_KBytes_out:d.KBytesSent}},{ssrc:a,type:Le.AUDIO,value:{delta_KBytes_out:d.deltaKBytesSent}},{ssrc:a,type:Le.AUDIO,value:{delta_kbs_out:d.kbsSent}}]}if(r[we.MEDIA_TYPE]===_e.VIDEO){const c=r[we.ENCODER_IMPLEMENTATION]||null,d=r[we.CODEC_ID]||null,p=Epe(r,o),m=N4(r),_=Ape(r),y=Npe(r,o,u),b=I4(r,_e.VIDEO,o,u);return[{ssrc:a,type:Le.VIDEO,value:{codec_id_out:d}},{ssrc:a,type:Le.VIDEO,value:{total_packets_out:b.packetsSent}},{ssrc:a,type:Le.VIDEO,value:{delta_packets_out:b.deltaPacketsSent}},{ssrc:a,type:Le.VIDEO,value:{total_KBytes_out:b.KBytesSent}},{ssrc:a,type:Le.VIDEO,value:{delta_KBytes_out:b.deltaKBytesSent}},{ssrc:a,type:Le.VIDEO,value:{delta_kbs_out:b.kbsSent}},{ssrc:a,type:Le.VIDEO,value:{encoder_out:c}},{ssrc:a,type:Le.VIDEO,value:{delta_ms_encode_frame_out:p.delta_ms_encode_frame}},{ssrc:a,type:Le.VIDEO,value:{total_frames_encoded_out:p.frames_encoded}},{ssrc:a,type:Le.VIDEO,value:{total_time_encoded_out:p.total_encode_time}},{ssrc:a,type:Le.VIDEO,value:{total_nack_received_out:y.nackCount}},{ssrc:a,type:Le.VIDEO,value:{delta_nack_received_out:y.deltaNackCount}},{ssrc:a,type:Le.VIDEO,value:{total_pli_received_out:y.pliCount}},{ssrc:a,type:Le.VIDEO,value:{delta_pli_received_out:y.deltaPliCount}},{ssrc:a,type:Le.VIDEO,value:{size_out:m}},{ssrc:a,type:Le.VIDEO,value:{limitation_out:_}}]}break}case ua.MEDIA_SOURCE:{Qt(Pl,`analyze() - got stats ${r[we.TYPE]} for ${t}`,r);break}case ua.TRACK:{Qt(Pl,`analyze() - got stats ${r[we.TYPE]} for ${t}`,r);break}case ua.CODEC:const s=[];return Object.keys(e[_e.AUDIO]).forEach(a=>{const o=e[_e.AUDIO][a];if(o.codec_id_in===r[we.ID]||o.codec_id_out===r[we.ID]){Qt(Pl,`analyze() - got stats ${r[we.TYPE]} for ${t}`,r);const u=kpe(r);r[we.ID]===o.codec_id_in?s.push({ssrc:o.ssrc,type:Le.AUDIO,value:{codec_in:u}}):s.push({ssrc:o.ssrc,type:Le.AUDIO,value:{codec_out:u}})}}),Object.keys(e[_e.VIDEO]).forEach(a=>{const o=e[_e.VIDEO][a];if(o.codec_id_in===r[we.ID]||o.codec_id_out===r[we.ID]){Qt(Pl,`analyze() - got stats ${r[we.TYPE]} for ${t}`,r);const u=Ope(r);r[we.ID]===o.codec_id_in?s.push({ssrc:o.ssrc,type:Le.VIDEO,value:{codec_in:u}}):s.push({ssrc:o.ssrc,type:Le.VIDEO,value:{codec_out:u}})}}),s;case ua.REMOTE_INBOUND_RTP:{Qt(Pl,`analyze() - got stats ${r[we.TYPE]} for ${t}`,r);const a=r[we.SSRC],o=Fs(a,e,vn.OUTBOUND),u=Fs(a,n,vn.OUTBOUND);if(r[we.KIND]===_e.AUDIO){const c=x4(r,_e.AUDIO,u,o),d=Vy(r,_e.AUDIO,o),p=A4(r,_e.AUDIO,o,u);return[{ssrc:a,type:Le.AUDIO,value:{delta_rtt_ms_out:c.rtt}},{ssrc:a,type:Le.AUDIO,value:{total_rtt_ms_out:c.totalRTT}},{ssrc:a,type:Le.AUDIO,value:{total_rtt_measure_out:c.totalRTTMeasurements}},{ssrc:a,type:Le.AUDIO,value:{delta_jitter_ms_out:d}},{ssrc:a,type:Le.AUDIO,value:{timestamp_out:r[we.TIMESTAMP]}},{ssrc:a,type:Le.AUDIO,value:{total_packets_lost_out:p.packetsLost}},{ssrc:a,type:Le.AUDIO,value:{delta_packets_lost_out:p.deltaPacketsLost}},{ssrc:a,type:Le.AUDIO,value:{percent_packets_lost_out:p.fractionLost}}]}if(r[we.KIND]===_e.VIDEO){const c=x4(r,_e.VIDEO,u,o),d=Vy(r,_e.VIDEO,o),p=A4(r,_e.VIDEO,o,u);return[{ssrc:a,type:Le.VIDEO,value:{delta_rtt_ms_out:c.rtt}},{ssrc:a,type:Le.VIDEO,value:{total_rtt_ms_out:c.totalRTT}},{ssrc:a,type:Le.VIDEO,value:{total_rtt_measure_out:c.totalRTTMeasurements}},{ssrc:a,type:Le.VIDEO,value:{delta_jitter_ms_out:d}},{ssrc:a,type:Le.VIDEO,value:{timestamp_out:r[we.TIMESTAMP]}},{ssrc:a,type:Le.VIDEO,value:{total_packets_lost_out:p.packetsLost}},{ssrc:a,type:Le.VIDEO,value:{delta_packets_lost_out:p.deltaPacketsLost}},{ssrc:a,type:Le.VIDEO,value:{percent_packets_lost_out:p.fractionLost}}]}break}}return[]},Gy=r=>r<0?1:r>100?4.5:1+.035*r+7/1e6*r*(r-60)*(100-r),Fpe=(r,e=_e.AUDIO,t,n,i)=>{const s=Fs(i,r,vn.INBOUND),a=Fs(i,t,vn.INBOUND),o=Fs(i,n,vn.INBOUND),u=[],c=[],d=s[e].percent_packets_lost_in,p=s[e].delta_jitter_ms_in,m=a&&a[e].delta_jitter_ms_in||null,_=o&&o[e].delta_jitter_ms_in||null,y=r.data.delta_rtt_connectivity_ms,b=t&&t.data.delta_rtt_connectivity_ms||null,S=n&&n.data.delta_rtt_connectivity_ms||null;y&&u.push(y),b&&u.push(b),S&&u.push(S),p&&c.push(p),t&&m&&c.push(m),n&&_&&c.push(_);const w=u.length>0?Dl(u):100,x=c.length>0?Dl(c):10,E=93.2-d,I=.18*E*E-27.9*E+1126.62,R=(w+x)/2,P=R-177.3<0?0:1,B=.024*R+.11*(R-177.3)*P,O=I-B;return Gy(O)},Mpe=(r,e=_e.AUDIO,t,n,i)=>{const s=Fs(i,r,vn.OUTBOUND),a=Fs(i,t,vn.OUTBOUND),o=Fs(i,n,vn.OUTBOUND),u=[],c=[],d=s[e].percent_packets_lost_out,p=s[e].delta_rtt_ms_out,m=a&&a[e].delta_rtt_ms_out||null,_=o&&o[e].delta_rtt_ms_out||null,y=s[e].delta_jitter_ms_out,b=a&&a[e].delta_jitter_ms_out||null,S=o&&o[e].delta_jitter_ms_out||null,w=r.data.delta_rtt_connectivity_ms,x=t&&t.data.delta_rtt_connectivity_ms||null,E=n&&n.data.delta_rtt_connectivity_ms||null;p?u.push(p):w&&u.push(w),m?u.push(m):x&&u.push(x),_?u.push(_):E&&u.push(E),y&&c.push(y),t&&b&&c.push(b),n&&S&&c.push(S);const I=u.length>0?Dl(u):100,R=c.length>0?Dl(c):10,P=93.2-d,B=.18*P*P-27.9*P+1126.62,O=(I+R)/2,F=O-177.3<0?0:1,D=.024*O+.11*(O-177.3)*F,L=B-D;return Gy(L)},Lpe=(r,e=_e.AUDIO,t,n,i)=>{const s=Fs(i,r,vn.INBOUND),a=Fs(i,t,vn.INBOUND),o=Fs(i,n,vn.INBOUND),u=[],c=[],d=s[e].percent_packets_lost_in/100,p=s[e].delta_jitter_ms_in,m=a&&a[e].delta_jitter_ms_in||null,_=o&&o[e].delta_jitter_ms_in||null,y=r.data.delta_rtt_connectivity_ms,b=t&&t.data.delta_rtt_connectivity_ms||null,S=n&&n.data.delta_rtt_connectivity_ms||null;y&&u.push(y),b&&u.push(b),S&&u.push(S),p&&c.push(p),a&&m&&c.push(m),o&&_&&c.push(_);const w=u.length>0?Dl(u):100,x=c.length>0?Dl(c):10,E=0,I=19.8,R=29.7,P=30,B=(w+x)/2+P,O=B-177.3<0?0:1,F=.024*B+.11*(B-177.3)*O,L=93.2-(E+I*Math.log(1+R*d)+F);return Gy(L)},Upe=(r,e=_e.AUDIO,t,n,i)=>{const s=Fs(i,r,vn.OUTBOUND),a=Fs(i,t,vn.OUTBOUND),o=Fs(i,n,vn.OUTBOUND),u=[],c=[],d=s[e].percent_packets_lost_out/100,p=s[e].delta_rtt_ms_out,m=a&&a[e].delta_rtt_ms_out||null,_=o&&o[e].delta_rtt_ms_out||null,y=s[e].delta_jitter_ms_out,b=a&&a[e].delta_jitter_ms_out||null,S=o&&o[e].delta_jitter_ms_out||null,w=r.data.delta_rtt_connectivity_ms,x=t&&t.data.delta_rtt_connectivity_ms||null,E=n&&n.data.delta_rtt_connectivity_ms||null;p?u.push(p):w&&u.push(w),m?u.push(m):x&&u.push(x),_?u.push(_):E&&u.push(E),y&&c.push(y),a&&b&&c.push(b),o&&S&&c.push(S);const I=u.length>0?Dl(u):100,R=c.length>0?Dl(c):10,P=0,B=19.8,O=29.7,F=30,D=(I+R)/2+F,L=D-177.3<0?0:1,G=.024*D+.11*(D-177.3)*L,te=93.2-(P+B*Math.log(1+O*d)+G);return Gy(te)};class Bpe{constructor(e,t){this._callbacks={onreport:null,onticket:null},this._id=gpe(),this._moduleName=this._id,this._probeId=t,this._config=e,this._exporter=new Tpe(e),this._state=No.IDLE,this.registerToPCEvents(),Ju(this._moduleName,`new collector created for probe ${this._probeId}`)}analyze(e,t,n,i){const s=(u,c)=>u===_e.AUDIO?c===ua.INBOUND_RTP?{...b4}:{...S4}:c===ua.INBOUND_RTP?{...T4}:{...w4},a=dpe(t);a.pname=this._config.pname,a.call_id=this._config.cid,a.user_id=this._config.uid,a.count=t?t.count+1:1;let o=null;return e.forEach(u=>{!o&&u.timestamp&&(o=u.timestamp),Ppe(u,a,a.pname,i).forEach(d=>{if(d.value&&d.type)if(d.ssrc){let p=a[d.type][d.ssrc];p||(p=s(d.type,u.type),p.ssrc=d.ssrc,a[d.type][d.ssrc]=p),Object.keys(d.value).forEach(m=>{p[m]=d.value[m]})}else Object.keys(d.value).forEach(p=>{a[d.type][p]=d.value[p]})})}),a.timestamp=o,Object.keys(a[_e.AUDIO]).forEach(u=>{const c=a[_e.AUDIO][u];c.direction===vn.INBOUND?(c.mos_emodel_in=Fpe(a,_e.AUDIO,t,n,c.ssrc),c.mos_in=Lpe(a,_e.AUDIO,t,n,c.ssrc)):(c.mos_emodel_out=Mpe(a,_e.AUDIO,t,n,c.ssrc),c.mos_out=Upe(a,_e.AUDIO,t,n,c.ssrc))}),a}async takeReferenceStats(){return new Promise((e,t)=>{const n=Date.now();setTimeout(async()=>{try{const i=Date.now()-n,s=Date.now(),a=await this._config.pc.getStats(),o=this.analyze(a,null,null,null),u=Date.now();o.experimental.time_to_measure_ms=u-s,o.experimental.time_to_wait_ms=i,this._exporter.saveReferenceReport(o),Qt(this._moduleName,`got reference report for probe ${this._probeId}`),e()}catch(i){t(i)}},this._config.startAfter)})}async collectStats(){try{if(this._state!==No.RUNNING||!this._config.pc)return Qt(this._moduleName,`report discarded (too late) for probe ${this._probeId}`),null;const e=Date.now(),t=await this._config.pc.getStats(),n=this.analyze(t,this._exporter.getLastReport(),this._exporter.getBeforeLastReport(),this._exporter.getReferenceReport()),i=Date.now();return n.experimental.time_to_measure_ms=i-e,this._exporter.addReport(n),Qt(this._moduleName,`got report for probe ${this._probeId}#${this._exporter.getReportsNumber()+1}`),this.fireOnReport(n),n}catch(e){return hd(this._moduleName,`got error ${e}`),null}}async start(){Qt(this._moduleName,"starting"),this.state=No.RUNNING,this._startedTime=this._exporter.start(),Qt(this._moduleName,"started")}async mute(){this.state=No.MUTED,Qt(this._moduleName,"muted")}async unmute(){this.state=No.RUNNING,Qt(this._moduleName,"unmuted")}async stop(e){if(Qt(this._moduleName,`stopping${e?" by watchdog":""}...`),this._stoppedTime=this._exporter.stop(),this.state=No.IDLE,this._config.ticket){const{ticket:t}=this._exporter;this.fireOnTicket(t)}this._exporter.reset(),Qt(this._moduleName,"stopped")}registerCallback(e,t,n){e in this._callbacks?(this._callbacks[e]={callback:t,context:n},Qt(this._moduleName,`registered callback '${e}'`)):hd(this._moduleName,`can't register callback for '${e}' - not found`)}unregisterCallback(e){e in this._callbacks?(this._callbacks[e]=null,delete this._callbacks[e],Qt(this._moduleName,`unregistered callback '${e}'`)):hd(this._moduleName,`can't unregister callback for '${e}' - not found`)}fireOnReport(e){this._callbacks.onreport&&qw(this._callbacks.onreport.callback,this._callbacks.onreport.context,e)}fireOnTicket(e){this._callbacks.onticket&&qw(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,Qt(this._moduleName,`state changed to ${e}`)}addCustomEvent(e,t,n,i){this._exporter.addCustomEvent({at:typeof e=="object"?e.toJSON():e,category:t,name:n,description:i})}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{hd(this._moduleName,"can't get devices")}},e){e.oniceconnectionstatechange=()=>{const n=e.iceConnectionState;n===gp.CONNECTED||n===gp.COMPLETED?this.addCustomEvent(new Date().toJSON(),"call",n,"ICE connection state"):n===gp.DISCONNECTED||n===gp.FAILED?this.addCustomEvent(new Date().toJSON(),"call",n,"ICE connection state"):n===gp.CLOSED&&this.addCustomEvent(new Date().toJSON(),"call","ended","ICE connection state")},e.onicegatheringstatechange=()=>{const n=e.iceGatheringState;this.addCustomEvent(new Date().toJSON(),"call",n,"ICE gathering state")},e.ontrack=n=>{this.addCustomEvent(new Date().toJSON(),"call",`${n.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 n=t[0],{transport:i}=n;if(i){const{iceTransport:s}=i;s&&(s.onselectedcandidatepairchange=()=>{this.addCustomEvent(new Date().toJSON(),"call","transport","Candidates Pair changed")})}}}}}class Hpe{constructor(e){this._id=e.pname&&e.pname.substr(0,12).padEnd(12," ")||mpe(),this._moduleName=this._id,Ju(this._moduleName,"probe created"),this._config=e,this._collector=new Bpe(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,n,i=new Date().toJSON()){this._collector.addCustomEvent(i,t,e,n)}get isRunning(){return this._collector.state===No.RUNNING}get isIdle(){return this._collector.state===No.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){Hy(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 yr="engine ";class Vpe{constructor(e){this._config=e,this._probes=[],this._startedTime=null,this._callbacks={onresult:null},Ju(yr,`configured for probing every ${this._config.refreshEvery}ms`),Ju(yr,`configured for starting after ${this._config.startAfter}ms`),Ju(yr,`${!this._config.stopAfter||this._config.stopAfter!==-1?`configured for stopped after ${this._config.stopAfter}ms`:"configured for never stopped"}`),Qt(yr,"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 n=fpe(e,t,this._config),i=new Hpe(n);return this._probes.push(i),Qt(yr,`${this._probes.length} probes registered`),i}removeExistingProbe(e){if(!e)throw new Error("undefined probe");e.state===No.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())),n=()=>this.isIdle?!1:!this._config.stopAfter||this._config.stopAfter<0?!0:Date.now()<this._startedTime+this._config.stopAfter,i=async()=>{const s=cpe(),a=this._probes.filter(o=>o.isRunning);for(const o of a){const u=await o.collectStats();u&&s.probes.push(u),Qt(yr,`got probe ${o.id}`),await C4(0)}return s.delta_time_to_measure_probes_ms=Qu(s.probes,"experimental","time_to_measure_ms"),s.delta_KBytes_in=Qu(s.probes,"data","delta_KBytes_in"),s.delta_KBytes_out=Qu(s.probes,"data","delta_KBytes_out"),s.delta_kbs_in=Qu(s.probes,"data","delta_kbs_in"),s.delta_kbs_out=Qu(s.probes,"data","delta_kbs_out"),s.total_time_decoded_in=Qu(s.probes,"video","total_time_decoded_in"),s.total_time_encoded_out=Qu(s.probes,"video","total_time_encoded_out"),s};for(Qt(yr,"starting to collect"),e(),Qt(yr,"generating reference reports..."),await t(),Qt(yr,"reference reports generated"),this._startedTime=Date.now();n();)if(Qt(yr,`wait ${this._config.refreshEvery}ms before collecting`),await C4(this._config.refreshEvery),n()){Qt(yr,"collecting...");const s=Date.now(),a=await i(),o=Date.now();a.delta_time_consumed_to_measure_ms=o-s,this.fireOnReports(a),Qt(yr,"collected")}Qt(yr,"reaching end of the collecting period..."),this.isRunning&&setTimeout(()=>{this.stop()},0)}stop(e){const t=n=>{this._probes.forEach(i=>{i.stop(n)})};Ju(yr,"stop collecting"),t(e)}registerCallback(e,t,n){e in this._callbacks?(this._callbacks[e]={callback:t,context:n},Qt(yr,`registered callback '${e}'`)):hd(yr,`can't register callback for '${e}' - not found`)}unregisterCallback(e){e in this._callbacks?(this._callbacks[e]=null,delete this._callbacks[e],Qt(this._moduleName,`unregistered callback '${e}'`)):hd(this._moduleName,`can't unregister callback for '${e}' - not found`)}fireOnReports(e){this._callbacks.onresult&&e.probes.length>0&&qw(this._callbacks.onresult.callback,this._callbacks.onresult.context,e)}}const Gpe="interface ";class Wpe{constructor(e){this._config=ppe(e),Ju(Gpe,`welcome to ${this._config.name} version ${this._config.version}`),npe(this._config.verbose||!1),this._engine=new Vpe(this._config)}setupLogLevel(e){spe(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 zpe(r,e){return Object.keys(r).filter(t=>e.includes(t)).reduce((t,n)=>{const i=n;return{...t,[i]:r[i]}},{})}const jpe=["mos_in","codec_in","delta_KBytes_in","delta_kbs_in","delta_jitter_ms_in","delta_packets_lost_in"];class qpe{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){console.log("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 n=Yu.createAnalyser(),i=Yu.createMediaStreamSource(e),s=Yu.createScriptProcessor(2048,1,1);n.smoothingTimeConstant=.8,n.fftSize=1024,i.connect(n),n.connect(s),s.connect(Yu.destination),this.intervals[t]=setInterval(()=>{const a=new Uint8Array(n.frequencyBinCount);n.getByteFrequencyData(a);let o=0;const u=a.length;for(let d=0;d<u;d++)o+=a[d];const c=o/u;this.onChangeFunction(t,c)},this.emitInterval)}}const Wy={SELECTED_INPUT_DEVICE:"OpensipsJSInputDevice",SELECTED_OUTPUT_DEVICE:"OpensipsJSOutputDevice"},Kpe=0;class Xpe{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 qpe({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 ZO()?{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(Wy.SELECTED_INPUT_DEVICE)||"default",t=localStorage.getItem(Wy.SELECTED_OUTPUT_DEVICE)||"default";try{const n=await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints),i=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(i),await this.setMicrophone(e),await this.setSpeaker(t),navigator.mediaDevices.addEventListener("devicechange",async()=>{const s=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(s)}),n.getTracks().forEach(s=>s.stop())}catch(n){console.error(n)}}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");console.log("callId",e),console.log("value",t);const i=this.extendedCalls[e];console.log("call",i),i.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(n=>n.enabled=!e),this.roomReconfigure(t)}mute(){this.processMute(!0)}unmute(){this.processMute(!1)}async processHold({callId:e,toHold:t,automatic:n}){const i=this.extendedCalls[e];i._automaticHold=n??!1,await new Promise(o=>{const u=()=>{o()};t?i.hold({},u):i.unhold({},u)}),this.updateCall(i);const a=Object.values(this.extendedCalls).filter(o=>o.roomId===this.currentActiveRoomId&&(t?e!==o._id:!0));a.length>1&&await this.doConference(a)}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===Kpe).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",n=>{this.triggerAddStream(n,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]=YO(e),this.context.emit("changeActiveCalls",this.activeCalls)}updateRoom(e){const n={...this.activeRooms[e.roomId],...e};this.activeRooms={...this.activeRooms,[e.roomId]:{...n}},this.context.emit("updateRoom",{room:n,roomList:this.activeRooms})}hasAutoAnswerHeaders(e){const t=/answer-after=0/,i=e.request.getHeader("Call-Info");return i&&t.test(i)}addCall(e,t=!0){this.activeCalls={...this.activeCalls,[e._id]:YO(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 n={...{...this.callStatus[e.callId]}};e.isMoving!==void 0&&(n.isMoving=e.isMoving),e.isTransferring!==void 0&&(n.isTransferring=e.isTransferring),e.isMerging!==void 0&&(n.isMerging=e.isMerging),this.callStatus={...this.callStatus,[e.callId]:{...n}},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=QO(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:n})=>n===e)||(this.setSelectedInputDevice(e),Object.keys(this.getActiveCalls).length===0))return;await this.setupStream();const t=Object.values(this.extendedCalls).filter(n=>n.roomId===this.currentActiveRoomId);t.length===1?Object.values(t).forEach(async n=>{const i=this.getActiveStream();n.connection.getSenders()[0].replaceTrack(i.getTracks()[0]),this.updateCall(n)}):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:i})=>i===e))return;this.setSelectedOutputDevice(e);const t=Object.values(this.extendedCalls);if(t.length===0)return;const n=t.filter(i=>i.roomId===this.currentActiveRoomId);n.length===1?t.forEach(i=>{var s;(s=i.audioTag)==null||s.setSinkId(e),this.updateCall(i)}):await this.doConference(n)}removeRoom(e){const t={...this.activeRooms},n={...t[e]};delete t[e],this.activeRooms={...t},this.context.emit("removeRoom",{room:n,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 n;if(e===void 0)return;const t=Object.values(this.extendedCalls).filter(i=>i.roomId===e);if(this.currentActiveRoomId===e?t.forEach(i=>{i.audioTag&&(this.muteReconfigure(i),i.audioTag.muted=!1,this.updateCall(i))}):t.forEach(i=>{i.audioTag&&(i.audioTag.muted=!0,this.updateCall(i))}),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&&((n=t[0].connection)!=null&&n.getSenders()[0])){const i=this.getActiveStream();await t[0].connection.getSenders()[0].replaceTrack(i.getTracks()[0]),this.muteReconfigure(t[0])}}else t.length>1&&await this.doConference(t)}async doConference(e){const t=[];e.forEach(n=>{n!=null&&n.connection.getReceivers().forEach(i=>{t.push(i.track)})}),await epe.forEach(e,async n=>{var a;if(n==null)return;const i=new MediaStream,s=Yu.createMediaStreamDestination();if(n.connection.getReceivers().forEach(o=>{t.forEach(u=>{i.addTrack(o.track),o.track.id!==u.id&&Yu.createMediaStreamSource(new MediaStream([u])).connect(s)})}),e[0].roomId===this.currentActiveRoomId){const o=this.getActiveStream();Yu.createMediaStreamSource(o).connect(s)}(a=n.connection)!=null&&a.getSenders()[0]&&(await n.connection.getSenders()[0].replaceTrack(s.stream.getTracks()[0]),this.muteReconfigure(n))})}processCallerMute(e,t){const n=this.extendedCalls[e];n&&n.connection.getReceivers().length&&(n.localMuted=t,n.connection.getReceivers().forEach(i=>{i.track.enabled=!t}),this.updateCall(n))}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 n=this.extendedCalls[e];if(!n._is_confirmed&&!n._is_canceled){const i=`sip:${t}@${this.context.sipDomain}`;n.terminate({status_code:302,reason_phrase:"Moved Temporarily",extraHeaders:[`Contact: ${i}`]});return}this.updateCallStatus({callId:e,isTransferring:!0}),n.refer(`sip:${t}@${this.context.sipDomain}`),this.updateCall(n)}mergeCall(e){const t=Object.values(this.extendedCalls).filter(s=>s.roomId===e);if(t.length!==2)return;const n=t[0],i=t[1];!n||!i||(this.updateCallStatus({callId:n._id,isMerging:!0}),this.updateCallStatus({callId:i._id,isMerging:!0}),n.refer(i.remote_identity.uri.toString(),{replaces:i}),this.updateCall(n))}mergeCallByIds(e,t){const n=Object.values(this.extendedCalls).find(s=>s._id===e),i=Object.values(this.extendedCalls).find(s=>s._id===t);if(!n||!i)throw new Error("Call ID is not provided");this.updateCallStatus({callId:e,isMerging:!0}),this.updateCallStatus({callId:t,isMerging:!0}),n.refer(i.remote_identity.uri.toString(),{replaces:i}),this.updateCall(n)}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 n=setInterval(()=>{const i={...this.callTime[e]},s=Zfe(i);this.setCallTime({callId:e,...s})},1e3);this.setTimeInterval(e,n)}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 c,d;const t=e.session;if(this.getActiveCalls[t.id]!==void 0)return;const i=this.getNewRoomId(),s={started:new Date,incomingInProgress:!1,roomId:i};t.direction==="incoming"?(this.context.logger.log("New incoming call from",(d=(c=t._remote_identity)==null?void 0:c._uri)==null?void 0:d._user),s.incomingInProgress=!0,this.context.subscribe(la.CALL_CONFIRMED,p=>{t.id===p.id&&(this.updateRoom({incomingInProgress:!1,roomId:i}),this.startCallTimer(t.id))}),this.context.subscribe(la.CALL_FAILED,p=>{t.id===p.id&&(this.updateRoom({incomingInProgress:!1,roomId:i}),this.deleteRoomIfEmpty(i))})):t.direction==="outgoing"&&(t.once("confirmed",()=>{this.startCallTimer(t.id)}),this.startCallTimer(t.id));const a=t,o=this.hasAutoAnswerHeaders(e),u=a.direction==="incoming"&&!this.hasActiveCalls&&(o||this.autoAnswer);a.roomId=i,a.localMuted=!1,a.autoAnswer=u,u?this.addCall(a,!1):this.addCall(a),this.addCallStatus(t.id),this.addRoom(s),u&&this.answerCall(a._id)}removeCall(e){const t={...this.activeCalls};delete t[e],this.activeCalls={...t};const n={...this.extendedCalls};delete n[e],this.extendedCalls={...n},this.context.emit("changeActiveCalls",this.activeCalls)}activeCallListRemove(e){var i;const t=this.extendedCalls[e._id];this.stopVUMeter("origin"),(i=t.connection)==null||i.getSenders().forEach(s=>{s.track.stop()});const n=t.roomId;this.removeCall(e._id),this.roomReconfigure(n)}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:la.NEW_CALL,session:t,event:e}),t.on("ended",n=>{var s,a,o;this.stopVUMeter(t.id),this.context.logger.log("Session ended for",(a=(s=t._remote_identity)==null?void 0:s._uri)==null?void 0:a._user),this.context.triggerListener({listenerType:la.CALL_ENDED,session:t,event:n});const i=this.getActiveCalls[t.id];i&&this.activeCallListRemove(i),this.stopCallTimer(t.id),this.removeCallStatus(t.id),this.removeCallMetrics(t.id),Object.keys(this.extendedCalls).length||(this.setIsMuted(!1),(o=this.initialStreamValue)==null||o.getTracks().forEach(u=>u.stop()),this.initialStreamValue=null)}),t.on("progress",n=>{var i,s;this.context.logger.log("Session in progress for",(s=(i=t._remote_identity)==null?void 0:i._uri)==null?void 0:s._user),this.context.triggerListener({listenerType:la.CALL_PROGRESS,session:t,event:n})}),t.on("failed",n=>{var s,a,o;this.stopVUMeter(t.id),this.context.logger.log("Session failed for",(a=(s=t._remote_identity)==null?void 0:s._uri)==null?void 0:a._user),this.context.triggerListener({listenerType:la.CALL_FAILED,session:t,event:n}),t.id===this.callAddingInProgress&&(this.callAddingInProgress=void 0);const i=this.getActiveCalls[t.id];i&&this.activeCallListRemove(i),this.stopCallTimer(t.id),this.removeCallStatus(t.id),this.removeCallMetrics(t.id),Object.keys(this.extendedCalls).length||(this.setIsMuted(!1),(o=this.initialStreamValue)==null||o.getTracks().forEach(u=>u.stop()),this.initialStreamValue=null)}),t.on("confirmed",n=>{var i,s;this.context.logger.log("Session confirmed for",(s=(i=t._remote_identity)==null?void 0:i._uri)==null?void 0:s._user),this.context.triggerListener({listenerType:la.CALL_CONFIRMED,session:t,event:n}),this.updateCall(t),t.id===this.callAddingInProgress&&(this.callAddingInProgress=void 0)}),await this.setupCall(e),t.direction==="outgoing"){const n=this.getActiveCalls[t.id].roomId;this.setActiveRoom(n)}}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(Wy.SELECTED_INPUT_DEVICE,e),this.selectedMediaDevices.input=e,this.context.emit("changeActiveInputMediaDevice",e)}setSelectedOutputDevice(e){localStorage.setItem(Wy.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 Wpe(this.metricConfig),n=t.createProbe(e.connection,{cid:e._id}),i=[];let s;n.onreport=a=>{Object.entries(a.audio).forEach(([c,d])=>{d.direction==="inbound"&&!i.includes(c)&&(i.push(c),s=c)});const o=a.audio[s];if(!o)return;const u=zpe(o,jpe);u.callId=e._id,this.setCallMetrics(u)},this.context.subscribe(la.CALL_ENDED,a=>{a._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 n=QO(this.initialStreamValue,this.microphoneInputLevel*2),i=this.isMuted||this.muteWhenJoin;n.getTracks().forEach(a=>a.enabled=!i),this.setActiveStream(n),await t.connection.getSenders()[0].replaceTrack(n.getTracks()[0]);const s=new MediaStream([e.track]);Fue(s,t,this.selectedOutputDevice,this.speakerVolume),this.setupVUMeter(s,t._id),this.getCallQuality(t),this.updateCall(t)}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}...`);const n=this.context.call(`sip:${e}@${this.context.sipDomain}`,this.sipOptions);this.callAddingInProgress=n.id,t&&this.currentActiveRoomId!==void 0&&this.processRoomChange({callId:n.id,roomId:this.currentActiveRoomId}),n.connection.addEventListener("track",i=>{this.triggerAddStream(i,n)})}async processRoomChange({callId:e,roomId:t}){const n=this.extendedCalls[e].roomId;this.extendedCalls[e].roomId=t;const i=this.extendedCalls[e];return this.updateCall(i),await this.setActiveRoom(t),Promise.all([this.roomReconfigure(n),this.roomReconfigure(t)]).then(()=>{this.deleteRoomIfEmpty(n),this.deleteRoomIfEmpty(t)})}}class Ype{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)}startScreenShare(){this.context.startScreenShare()}startBlur(){this.context.startBlur()}stopBlur(){this.context.stopBlur()}}class Jpe{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]=JO(e),this.context.emit("changeActiveMessages",this.activeMessages)}addMMSRPSession(e){this.activeMessages={...this.activeMessages,[e._id]:JO(e)},this.extendedMessages[e._id]=e,this.context.emit("changeActiveMessages",this.activeMessages)}addMSRPMessage(e,t){const n=this.msrpHistory[t.id]||[];n.push(e),this.msrpHistory={...this.msrpHistory,[t.id]:[...n]},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 n=e;this.addMMSRPSession(n)}triggerMSRPListener({listenerType:e,session:t,event:n}){const i=this.context.listenersList[e];!i||!i.length||i.forEach(s=>{s(t,n)})}removeMMSRPSession(e){const t={...this.activeMessages};delete t[e],this.activeMessages={...t};const n={...this.extendedMessages};delete n[e],this.extendedMessages={...n},this.context.emit("changeActiveMessages",this.activeMessages)}activeMessageListRemove(e){this.removeMMSRPSession(e._id)}newMSRPSessionCallback(e){const t=e.session;t.on("ended",n=>{this.triggerMSRPListener({listenerType:la.CALL_ENDED,session:t,event:n});const i=this.getActiveMessages[t.id];this.activeMessageListRemove(i)}),t.on("failed",n=>{this.triggerMSRPListener({listenerType:la.CALL_FAILED,session:t,event:n});const i=this.getActiveMessages[t.id];this.activeMessageListRemove(i)}),t.on("confirmed",n=>{this.triggerMSRPListener({listenerType:la.CALL_CONFIRMED,session:t,event:n}),this.updateMSRPSession(t)}),t.on("newMessage",n=>{this.addMSRPMessage(n,t)}),this.addMessageSession(t)}setIsMSRPInitializing(e){this.isMSRPInitializingValue=e,this.context.emit("isMSRPInitializingChanged",e)}initMSRP(e,t,n){if(e.length===0)return console.error("Target must be a valid string");const i=this.context.startMSRP(e,n);i.on("active",()=>{this.addMessageSession(i),i.sendMSRP(t),this.setIsMSRPInitializing(!1)}),this.setIsMSRPInitializing(!0)}sendMSRP(e,t){const n=this.extendedMessages[e];if(!n)throw new Error(`MSRP session with id ${e} doesn't exist!`);n.sendMSRP(t)}}const Kw={AUDIO:"audio",VIDEO:"video",MSRP:"msrp"};class Qpe extends Rue{constructor(e,t){if(!e.modules.length)throw new Error("options.modules should include at least 1 module");const n={...e.configuration,sockets:e.socketInterfaces.map(i=>new Qfe.WebSocketInterface(i))};super(n),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&&Mue(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(console.log("RRR use",e),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 M0)e.setOpensips(this),console.log("RRR push to newStreamPlugins"),this.newStreamPlugins.push(e);else if(e instanceof O0)e.setOpensips(this),console.log("RRR push to processStreamPlugins"),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(Kw.AUDIO)&&(this.audio=new Xpe(this)),this.modules.includes(Kw.MSRP)&&(this.msrp=new Jpe(this)),this.modules.includes(Kw.VIDEO)&&(this.video=new Ype(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 i=!this.listenersList[e]||!this.listenersList[e].length?[t]:[...this.listenersList[e],t];this.listenersList={...this.listenersList,[e]:i}}removeIListener(e){const t={...this.listenersList};delete t[e],this.listenersList={...t}}triggerListener({listenerType:e,session:t,event:n}){const i=this.listenersList[e];!i||!i.length||i.forEach(s=>{s(t,n)})}setInitialized(e){this.initialized=e,this.emit("ready",e)}setConnected(e){this.connected=e,this.emit("connection",e)}}return Er.BaseNewStreamPlugin=M0,Er.BaseProcessStreamPlugin=O0,Er.ScreenSharePlugin=Lue,Er.ScreenShareWhiteBoardPlugin=pp,Er.StreamMaskPlugin=bue,Er.WhiteBoardPlugin=Ufe,Er.default=Qpe,Object.defineProperties(Er,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}}),Er}({});