From e59fb839080dda76a6b358ab16f7484ae5addf41 Mon Sep 17 00:00:00 2001 From: Jacky Zhao Date: Thu, 9 Feb 2023 10:13:35 -0800 Subject: [PATCH] 0.5.0: customizable user metadata and renderfunction --- dist/cursor-chat.es.js | 14 +++++++------- dist/cursor-chat.umd.js | 10 +++++----- dist/main.d.ts | 15 ++++++++++++++- package.json | 2 +- src/main.ts | 30 ++++++++++++++++++++---------- 5 files changed, 47 insertions(+), 24 deletions(-) diff --git a/dist/cursor-chat.es.js b/dist/cursor-chat.es.js index 376a140..db5c966 100644 --- a/dist/cursor-chat.es.js +++ b/dist/cursor-chat.es.js @@ -9846,7 +9846,7 @@ var randomColor = { exports: {} }; }); })(randomColor, randomColor.exports); var randomcolor = randomColor.exports; -function cursorFactory(cursor) { +function defaultCursorRenderer(cursor) { const htmlFragment = `
{ +const initCursorChat = (room_id = `cursor-chat-room-${window.location.host + window.location.pathname}`, triggerKey = "/", cursorDivId = "cursor-chat-layer", chatDivId = "cursor-chat-box", userMetaData = {}, renderCursor = defaultCursorRenderer) => { const cursorDiv = document.getElementById(cursorDivId); const chatDiv = document.getElementById(chatDivId); if (!cursorDiv || !chatDiv) { @@ -9882,12 +9882,12 @@ const initCursorChat = (room_id, triggerKey = "/", cursorDivId = "cursor-chat-la } const me = { id: nanoid(), - color: randomcolor(), x: 0, y: 0, - chat: "" + chat: "", + color: randomcolor(), + userMetaData }; - room_id = room_id || `cursor-chat-room-${window.location.host + window.location.pathname}`; const doc2 = new Doc(); const provider = new WebrtcProvider(room_id, doc2); const others = doc2.getMap("state"); @@ -9941,7 +9941,7 @@ const initCursorChat = (room_id, triggerKey = "/", cursorDivId = "cursor-chat-la switch (change.action) { case "add": const new_cursor = others.get(cursor_id); - const new_cursor_div = cursorFactory(new_cursor); + const new_cursor_div = renderCursor(new_cursor); new_cursor_div.classList.add("new"); cursorDiv.appendChild(new_cursor_div); const add_point_closure = ([x, y]) => new_cursor_div.style.setProperty("transform", `translate(${x}px, ${y}px)`); @@ -9976,4 +9976,4 @@ const initCursorChat = (room_id, triggerKey = "/", cursorDivId = "cursor-chat-la }); return cleanup; }; -export { initCursorChat }; +export { defaultCursorRenderer, initCursorChat }; diff --git a/dist/cursor-chat.umd.js b/dist/cursor-chat.umd.js index faa28de..5ab10f2 100644 --- a/dist/cursor-chat.umd.js +++ b/dist/cursor-chat.umd.js @@ -1,7 +1,7 @@ -(function(wt,ft){typeof exports=="object"&&typeof module!="undefined"?ft(exports):typeof define=="function"&&define.amd?define(["exports"],ft):(wt=typeof globalThis!="undefined"?globalThis:wt||self,ft(wt["cursor-chat"]={}))})(this,function(wt){"use strict";var il=Object.defineProperty,sl=Object.defineProperties;var ol=Object.getOwnPropertyDescriptors;var hs=Object.getOwnPropertySymbols;var al=Object.prototype.hasOwnProperty,ll=Object.prototype.propertyIsEnumerable;var us=(wt,ft,lt)=>ft in wt?il(wt,ft,{enumerable:!0,configurable:!0,writable:!0,value:lt}):wt[ft]=lt,Ge=(wt,ft)=>{for(var lt in ft||(ft={}))al.call(ft,lt)&&us(wt,lt,ft[lt]);if(hs)for(var lt of hs(ft))ll.call(ft,lt)&&us(wt,lt,ft[lt]);return wt},In=(wt,ft)=>sl(wt,ol(ft));var ft="";const lt=()=>new Map,Je=e=>{const t=lt();return e.forEach((n,i)=>{t.set(i,n)}),t},St=(e,t,n)=>{let i=e.get(t);return i===void 0&&e.set(t,i=n()),i},ds=(e,t)=>{const n=[];for(const[i,s]of e)n.push(t(s,i));return n},fs=(e,t)=>{for(const[n,i]of e)if(t(i,n))return!0;return!1},Ie=()=>new Set,Ln=e=>e[e.length-1],ps=(e,t)=>{for(let n=0;n{this.off(t,i),n(...s)};this.on(t,i)}off(t,n){const i=this._observers.get(t);i!==void 0&&(i.delete(n),i.size===0&&this._observers.delete(t))}emit(t,n){return Ar((this._observers.get(t)||lt()).values()).forEach(i=>i(...n))}destroy(){this._observers=lt()}}const de=Math.floor,Mn=Math.abs,ys=Math.log10,xn=(e,t)=>ee>t?e:t,Dr=e=>e!==0?e<0:1/e<0,ms=String.fromCharCode,ws=e=>e.toLowerCase(),bs=/^\s*/g,_s=e=>e.replace(bs,""),vs=/([A-Z])/g,Ir=(e,t)=>_s(e.replace(vs,n=>`${t}${ws(n)}`)),Ss=e=>{const t=unescape(encodeURIComponent(e)),n=t.length,i=new Uint8Array(n);for(let s=0;sLr.encode(e):Ss;let On=typeof TextDecoder=="undefined"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});On&&On.decode(new Uint8Array).length===1&&(On=null);const xr=e=>e===void 0?null:e;class Es{constructor(){this.map=new Map}setItem(t,n){this.map.set(t,n)}getItem(t){return this.map.get(t)}}let Or=new Es,Nr=!0;try{typeof localStorage!="undefined"&&(Or=localStorage,Nr=!1)}catch{}const Ur=Or,Cs=e=>Nr||addEventListener("storage",e),Ke=typeof process!="undefined"&&process.release&&/node|io\.js/.test(process.release.name),Fr=typeof window!="undefined"&&!Ke;typeof navigator!="undefined"&&/Mac/.test(navigator.platform);let Lt;const ks=()=>{if(Lt===void 0)if(Ke){Lt=lt();const e=process.argv;let t=null;for(let n=0;n{if(e.length!==0){const[t,n]=e.split("=");Lt.set(`--${Ir(t,"-")}`,n),Lt.set(`-${Ir(t,"-")}`,n)}})):Lt=lt();return Lt},Rs=e=>ks().has(e),Pr=e=>xr(Ke?process.env[e.toUpperCase()]:Ur.getItem(e));(e=>Rs("--"+e)||Pr(e)!==null)("production");const Br=1,jr=2,Nn=4,Un=8,Le=32,Bt=64,_t=128,Xe=31,Fn=63,Qt=127,Ts=2147483647;class Ze{constructor(t){this.arr=t,this.pos=0}}const Mt=e=>new Ze(e),As=e=>e.pos!==e.arr.length,Ds=(e,t)=>{const n=Vn(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n},pt=e=>Ds(e,G(e)),te=e=>e.arr[e.pos++],G=e=>{let t=0,n=0;for(;;){const i=e.arr[e.pos++];if(t=t|(i&Qt)<>>0;if(n>35)throw new Error("Integer out of range!")}},Pn=e=>{let t=e.arr[e.pos++],n=t&Fn,i=6;const s=(t&Bt)>0?-1:1;if((t&_t)===0)return s*n;for(;;){if(t=e.arr[e.pos++],n=n|(t&Qt)<>>0);if(i>41)throw new Error("Integer out of range!")}},jt=e=>{let t=G(e);if(t===0)return"";{let n=String.fromCodePoint(te(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(te(e));else for(;t>0;){const i=t<1e4?t:1e4,s=e.arr.subarray(e.pos,e.pos+i);e.pos+=i,n+=String.fromCodePoint.apply(null,s),t-=i}return decodeURIComponent(escape(n))}},Bn=(e,t)=>{const n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},Is=[e=>{},e=>null,Pn,e=>Bn(e,4).getFloat32(0,!1),e=>Bn(e,8).getFloat64(0,!1),e=>Bn(e,8).getBigInt64(0,!1),e=>!1,e=>!0,jt,e=>{const t=G(e),n={};for(let i=0;i{const t=G(e),n=[];for(let i=0;iIs[127-te(e)](e);class Vr extends Ze{constructor(t,n){super(t);this.reader=n,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),As(this)?this.count=G(this)+1:this.count=-1),this.count--,this.s}}class Qe extends Ze{constructor(t){super(t);this.s=0,this.count=0}read(){if(this.count===0){this.s=Pn(this);const t=Dr(this.s);this.count=1,t&&(this.s=-this.s,this.count=G(this)+2)}return this.count--,this.s}}class jn extends Ze{constructor(t){super(t);this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){const t=Pn(this),n=t&1;this.diff=t>>1,this.count=1,n&&(this.count=G(this)+2)}return this.s+=this.diff,this.count--,this.s}}class Ls{constructor(t){this.decoder=new Qe(t),this.str=jt(this.decoder),this.spos=0}read(){const t=this.spos+this.decoder.read(),n=this.str.slice(this.spos,t);return this.spos=t,n}}const qr=e=>new Uint8Array(e),Vn=(e,t,n)=>new Uint8Array(e,t,n),Ms=e=>new Uint8Array(e),xs=e=>{let t="";for(let n=0;nBuffer.from(e.buffer,e.byteOffset,e.byteLength).toString("base64"),Ns=e=>{const t=atob(e),n=qr(t.length);for(let i=0;i{const t=Buffer.from(e,"base64");return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)},Wr=Fr?xs:Os,Hr=Fr?Ns:Us,Fs=e=>{const t=qr(e.byteLength);return t.set(e),t},Ps=Number.isInteger||(e=>typeof e=="number"&&isFinite(e)&&de(e)===e);class Me{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const dt=()=>new Me,Bs=e=>{let t=e.cpos;for(let n=0;n{const t=new Uint8Array(Bs(e));let n=0;for(let i=0;i{const n=e.cbuf.length;n-e.cpos{const n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(n*2),e.cpos=0),e.cbuf[e.cpos++]=t},xe=gt,q=(e,t)=>{for(;t>Qt;)gt(e,_t|Qt&t),t>>>=7;gt(e,Qt&t)},qn=(e,t)=>{const n=Dr(t);for(n&&(t=-t),gt(e,(t>Fn?_t:0)|(n?Bt:0)|Fn&t),t>>>=6;t>0;)gt(e,(t>Qt?_t:0)|Qt&t),t>>>=7},xt=(e,t)=>{const n=unescape(encodeURIComponent(t)),i=n.length;q(e,i);for(let s=0;s{const n=e.cbuf.length,i=e.cpos,s=xn(n-i,t.length),o=t.length-s;e.cbuf.set(t.subarray(0,s),i),e.cpos+=s,o>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(Zt(n*2,o)),e.cbuf.set(t.subarray(s)),e.cpos=o)},ct=(e,t)=>{q(e,t.byteLength),tn(e,t)},Wn=(e,t)=>{js(e,t);const n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},Vs=(e,t)=>Wn(e,4).setFloat32(0,t,!1),qs=(e,t)=>Wn(e,8).setFloat64(0,t,!1),Ws=(e,t)=>Wn(e,8).setBigInt64(0,t,!1),$r=new DataView(new ArrayBuffer(4)),Hs=e=>($r.setFloat32(0,e),$r.getFloat32(0)===e),pe=(e,t)=>{switch(typeof t){case"string":gt(e,119),xt(e,t);break;case"number":Ps(t)&&t<=Ts?(gt(e,125),qn(e,t)):Hs(t)?(gt(e,124),Vs(e,t)):(gt(e,123),qs(e,t));break;case"bigint":gt(e,122),Ws(e,t);break;case"object":if(t===null)gt(e,126);else if(t instanceof Array){gt(e,117),q(e,t.length);for(let n=0;n0&&q(this,this.count-1),this.count=1,this.w(this,t),this.s=t)}}const zr=e=>{e.count>0&&(qn(e.encoder,e.count===1?e.s:-e.s),e.count>1&&q(e.encoder,e.count-2))};class en{constructor(){this.encoder=new Me,this.s=0,this.count=0}write(t){this.s===t?this.count++:(zr(this),this.count=1,this.s=t)}toUint8Array(){return zr(this),st(this.encoder)}}const Gr=e=>{if(e.count>0){const t=e.diff<<1|(e.count===1?0:1);qn(e.encoder,t),e.count>1&&q(e.encoder,e.count-2)}};class Hn{constructor(){this.encoder=new Me,this.s=0,this.count=0,this.diff=0}write(t){this.diff===t-this.s?(this.s=t,this.count++):(Gr(this),this.count=1,this.diff=t-this.s,this.s=t)}toUint8Array(){return Gr(this),st(this.encoder)}}class $s{constructor(){this.sarr=[],this.s="",this.lensE=new en}write(t){this.s+=t,this.s.length>19&&(this.sarr.push(this.s),this.s=""),this.lensE.write(t.length)}toUint8Array(){const t=new Me;return this.sarr.push(this.s),this.s="",xt(t,this.sarr.join("")),tn(t,this.lensE.toUint8Array()),st(t)}}const Jr=typeof crypto=="undefined"?null:crypto,Ys=Jr!==null?e=>{const t=new ArrayBuffer(e),n=new Uint8Array(t);return Jr.getRandomValues(n),t}:e=>{const t=new ArrayBuffer(e),n=new Uint8Array(t);for(let i=0;i>>0);return t},zs=Math.random,Kr=()=>new Uint32Array(Ys(4))[0],Gs=[1e7]+-1e3+-4e3+-8e3+-1e11,Xr=()=>Gs.replace(/[018]/g,e=>(e^Kr()&15>>e/4).toString(16)),Ot=Date.now,Js=e=>new Promise(e),Ks=e=>Promise.reject(e),$n=e=>Promise.resolve(e),ge=e=>new Error(e),Nt=()=>{throw ge("Method unimplemented")},Ut=()=>{throw ge("Unexpected case")},Xs=Object.keys,nn=e=>Xs(e).length,Zs=(e,t)=>{for(const n in e)if(!t(e[n],n))return!1;return!0},Zr=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Qs=(e,t)=>e===t||nn(e)===nn(t)&&Zs(e,(n,i)=>(n!==void 0||Zr(t,i))&&t[i]===n),Yn=(e,t,n=0)=>{try{for(;n{},eo=(e,t)=>e===t,Oe=(e,t)=>{if(e==null||t==null)return eo(e,t);if(e.constructor!==t.constructor)return!1;if(e===t)return!0;switch(e.constructor){case ArrayBuffer:e=new Uint8Array(e),t=new Uint8Array(t);case Uint8Array:{if(e.byteLength!==t.byteLength)return!1;for(let n=0;nnew no(e,t),ee=typeof document!="undefined"?document:{};typeof DOMParser!="undefined"&&new DOMParser;const ro=e=>ds(e,(t,n)=>`${n}:${t};`).join("");ee.ELEMENT_NODE,ee.TEXT_NODE,ee.CDATA_SECTION_NODE,ee.COMMENT_NODE,ee.DOCUMENT_NODE,ee.DOCUMENT_TYPE_NODE,ee.DOCUMENT_FRAGMENT_NODE;const vt=Vt(),Ht=Vt(),zn=Vt(),rn=Vt(),Gn=Vt(),Jn=Vt(),Kn=Vt(),sn=Vt(),Ne=Vt(),io={[vt]:qt("font-weight","bold"),[Ht]:qt("font-weight","normal"),[zn]:qt("color","blue"),[Gn]:qt("color","green"),[rn]:qt("color","grey"),[Jn]:qt("color","red"),[Kn]:qt("color","purple"),[sn]:qt("color","orange"),[Ne]:qt("color","black")},so={[vt]:"\x1B[1m",[Ht]:"\x1B[2m",[zn]:"\x1B[34m",[Gn]:"\x1B[32m",[rn]:"\x1B[37m",[Jn]:"\x1B[31m",[Kn]:"\x1B[35m",[sn]:"\x1B[38;5;208m",[Ne]:"\x1B[0m"},oo=Ke?e=>{const t=[],n=[];let i=0;for(;i0&&(t.push("\x1B[0m"),n.push(t.join("")));i{const t=[],n=[],i=lt();let s=[],o=0;for(;o0||l.length>0?(t.push("%c"+c),n.push(l)):t.push(c)}else break}for(o>0&&(s=n,s.unshift(t.join("")));o{console.log(...oo(e)),ao.forEach(t=>t.print(e))},ao=new Set,ti=[Gn,Kn,sn,zn];let Xn=0,ei=Ot();const lo=e=>{const t=ti[Xn],n=Pr("log"),i=n!==null&&(n==="*"||n==="true"||new RegExp(n,"gi").test(e));return Xn=(Xn+1)%ti.length,e+=": ",i?(...s)=>{const o=Ot(),c=o-ei;ei=o,Qr(t,e,Ne,...s.map(h=>typeof h=="string"||typeof h=="symbol"?h:JSON.stringify(h)),t," +"+c+"ms")}:to},ni=e=>({[Symbol.iterator](){return this},next:e}),co=(e,t)=>ni(()=>{let n;do n=e.next();while(!n.done&&!t(n.value));return n}),Zn=(e,t)=>ni(()=>{const{done:n,value:i}=e.next();return{done:n,value:n?void 0:t(i)}});class yl extends ue{constructor(t,n){super();this.doc=t,this.awareness=n}}class Qn{constructor(t,n){this.clock=t,this.len=n}}class ye{constructor(){this.clients=new Map}}const ne=(e,t,n)=>t.clients.forEach((i,s)=>{const o=e.doc.store.clients.get(s);for(let c=0;c{let n=0,i=e.length-1;for(;n<=i;){const s=de((n+i)/2),o=e[s],c=o.clock;if(c<=t){if(t{const n=e.clients.get(t.client);return n!==void 0&&ho(n,t.clock)!==null},tr=e=>{e.clients.forEach(t=>{t.sort((s,o)=>s.clock-o.clock);let n,i;for(n=1,i=1;n=o.clock?s.len=Zt(s.len,o.clock+o.len-s.clock):(i{const t=new ye;for(let n=0;n{if(!t.clients.has(s)){const o=i.slice();for(let c=n+1;c{St(e.clients,t,()=>[]).push(new Qn(n,i))},ri=()=>new ye,uo=e=>{const t=ri();return e.clients.forEach((n,i)=>{const s=[];for(let o=0;o0&&t.clients.set(i,s)}),t},me=(e,t)=>{q(e.restEncoder,t.clients.size),t.clients.forEach((n,i)=>{e.resetDsCurVal(),q(e.restEncoder,i);const s=n.length;q(e.restEncoder,s);for(let o=0;o{const t=new ye,n=G(e.restDecoder);for(let i=0;i0){const c=St(t.clients,s,()=>[]);for(let h=0;h{const i=new ye,s=G(e.restDecoder);for(let o=0;o0){const o=new re;return q(o.restEncoder,0),me(o,i),o.toUint8Array()}return null},si=Kr;class we extends ue{constructor({guid:t=Xr(),collectionid:n=null,gc:i=!0,gcFilter:s=()=>!0,meta:o=null,autoLoad:c=!1,shouldLoad:h=!0}={}){super();this.gc=i,this.gcFilter=s,this.clientID=si(),this.guid=t,this.collectionid=n,this.share=new Map,this.store=new mi,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=h,this.autoLoad=c,this.meta=o,this.isLoaded=!1,this.whenLoaded=Js(l=>{this.on("load",()=>{this.isLoaded=!0,l(this)})})}load(){const t=this._item;t!==null&&!this.shouldLoad&&tt(t.parent.doc,n=>{n.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(Array.from(this.subdocs).map(t=>t.guid))}transact(t,n=null){tt(this,t,n)}get(t,n=yt){const i=St(this.share,t,()=>{const o=new n;return o._integrate(this,null),o}),s=i.constructor;if(n!==yt&&s!==n)if(s===yt){const o=new n;o._map=i._map,i._map.forEach(c=>{for(;c!==null;c=c.left)c.parent=o}),o._start=i._start;for(let c=o._start;c!==null;c=c.right)c.parent=o;return o._length=i._length,this.share.set(t,o),o._integrate(this,null),o}else throw new Error(`Type with the name ${t} has already been defined with a different constructor`);return i}getArray(t=""){return this.get(t,ve)}getText(t=""){return this.get(t,Ce)}getMap(t=""){return this.get(t,Se)}getXmlFragment(t=""){return this.get(t,ie)}toJSON(){const t={};return this.share.forEach((n,i)=>{t[i]=n.toJSON()}),t}destroy(){Ar(this.subdocs).forEach(n=>n.destroy());const t=this._item;if(t!==null){this._item=null;const n=t.content;n.doc=new we(In(Ge({guid:this.guid},n.opts),{shouldLoad:!1})),n.doc._item=t,tt(t.parent.doc,i=>{const s=n.doc;t.deleted||i.subdocsAdded.add(s),i.subdocsRemoved.add(this)},null,!0)}this.emit("destroyed",[!0]),this.emit("destroy",[this]),super.destroy()}on(t,n){super.on(t,n)}off(t,n){super.off(t,n)}}class oi{constructor(t){this.restDecoder=t}resetDsCurVal(){}readDsClock(){return G(this.restDecoder)}readDsLen(){return G(this.restDecoder)}}class ai extends oi{readLeftID(){return K(G(this.restDecoder),G(this.restDecoder))}readRightID(){return K(G(this.restDecoder),G(this.restDecoder))}readClient(){return G(this.restDecoder)}readInfo(){return te(this.restDecoder)}readString(){return jt(this.restDecoder)}readParentInfo(){return G(this.restDecoder)===1}readTypeRef(){return G(this.restDecoder)}readLen(){return G(this.restDecoder)}readAny(){return fe(this.restDecoder)}readBuf(){return Fs(pt(this.restDecoder))}readJSON(){return JSON.parse(jt(this.restDecoder))}readKey(){return jt(this.restDecoder)}}class fo{constructor(t){this.dsCurrVal=0,this.restDecoder=t}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=G(this.restDecoder),this.dsCurrVal}readDsLen(){const t=G(this.restDecoder)+1;return this.dsCurrVal+=t,t}}class be extends fo{constructor(t){super(t);this.keys=[],G(t),this.keyClockDecoder=new jn(pt(t)),this.clientDecoder=new Qe(pt(t)),this.leftClockDecoder=new jn(pt(t)),this.rightClockDecoder=new jn(pt(t)),this.infoDecoder=new Vr(pt(t),te),this.stringDecoder=new Ls(pt(t)),this.parentInfoDecoder=new Vr(pt(t),te),this.typeRefDecoder=new Qe(pt(t)),this.lenDecoder=new Qe(pt(t))}readLeftID(){return new _e(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new _e(this.clientDecoder.read(),this.rightClockDecoder.read())}readClient(){return this.clientDecoder.read()}readInfo(){return this.infoDecoder.read()}readString(){return this.stringDecoder.read()}readParentInfo(){return this.parentInfoDecoder.read()===1}readTypeRef(){return this.typeRefDecoder.read()}readLen(){return this.lenDecoder.read()}readAny(){return fe(this.restDecoder)}readBuf(){return pt(this.restDecoder)}readJSON(){return fe(this.restDecoder)}readKey(){const t=this.keyClockDecoder.read();if(t{i=Zt(i,t[0].id.clock);const s=Ft(t,i);q(e.restEncoder,t.length-s),e.writeClient(n),q(e.restEncoder,i);const o=t[s];o.write(e,i-o.id.clock);for(let c=s+1;c{const i=new Map;n.forEach((s,o)=>{ht(t,o)>s&&i.set(o,s)}),hn(t).forEach((s,o)=>{n.has(o)||i.set(o,0)}),q(e.restEncoder,i.size),Array.from(i.entries()).sort((s,o)=>o[0]-s[0]).forEach(([s,o])=>{po(e,t.clients.get(s),s,o)})},go=(e,t)=>{const n=lt(),i=G(e.restDecoder);for(let s=0;s{const i=[];let s=Array.from(n.keys()).sort((f,p)=>f-p);if(s.length===0)return null;const o=()=>{if(s.length===0)return null;let f=n.get(s[s.length-1]);for(;f.refs.length===f.i;)if(s.pop(),s.length>0)f=n.get(s[s.length-1]);else return null;return f};let c=o();if(c===null&&i.length===0)return null;const h=new mi,l=new Map,y=(f,p)=>{const S=l.get(f);(S==null||S>p)&&l.set(f,p)};let w=c.refs[c.i++];const u=new Map,g=()=>{for(const f of i){const p=f.id.client,S=n.get(p);S?(S.i--,h.clients.set(p,S.refs.slice(S.i)),n.delete(p),S.i=0,S.refs=[]):h.clients.set(p,[f]),s=s.filter(M=>M!==p)}i.length=0};for(;;){if(w.constructor!==Ct){const p=St(u,w.id.client,()=>ht(t,w.id.client))-w.id.clock;if(p<0)i.push(w),y(w.id.client,w.id.clock-1),g();else{const S=w.getMissing(e,t);if(S!==null){i.push(w);const M=n.get(S)||{refs:[],i:0};if(M.refs.length===M.i)y(S,ht(t,S)),g();else{w=M.refs[M.i++];continue}}else(p===0||p0)w=i.pop();else if(c!==null&&c.i0){const f=new re;return rr(f,h,new Map),q(f.restEncoder,0),{missing:l,update:f.toUint8Array()}}return null},mo=(e,t)=>rr(e,t.doc.store,t.beforeState),wo=(e,t,n,i=new be(e))=>tt(t,s=>{s.local=!1;let o=!1;const c=s.doc,h=c.store,l=go(i,c),y=yo(s,h,l),w=h.pendingStructs;if(w){for(const[g,f]of w.missing)if(ff)&&w.missing.set(g,f)}w.update=fn([w.update,y.update])}}else h.pendingStructs=y;const u=ii(i,s,h);if(h.pendingDs){const g=new be(Mt(h.pendingDs));G(g.restDecoder);const f=ii(g,s,h);u&&f?h.pendingDs=fn([u,f]):h.pendingDs=u||f}else h.pendingDs=u;if(o){const g=h.pendingStructs.update;h.pendingStructs=null,hi(s.doc,g)}},n,!1),hi=(e,t,n,i=be)=>{const s=Mt(t);wo(s,e,n,new i(s))},bo=(e,t,n)=>hi(e,t,n,ai),_o=(e,t,n=new Map)=>{rr(e,t.store,n),me(e,uo(t.store))},vo=(e,t=new Uint8Array([0]),n=new re)=>{const i=ui(t);_o(n,e,i);const s=[n.toUint8Array()];if(e.store.pendingDs&&s.push(e.store.pendingDs),e.store.pendingStructs&&s.push(Po(e.store.pendingStructs.update,t)),s.length>1){if(n.constructor===Fe)return Uo(s.map((o,c)=>c===0?o:jo(o)));if(n.constructor===re)return fn(s)}return s[0]},So=(e,t)=>vo(e,t,new Fe),Eo=e=>{const t=new Map,n=G(e.restDecoder);for(let i=0;iEo(new oi(Mt(e))),di=(e,t)=>(q(e.restEncoder,t.size),Array.from(t.entries()).sort((n,i)=>i[0]-n[0]).forEach(([n,i])=>{q(e.restEncoder,n),q(e.restEncoder,i)}),e),Co=(e,t)=>di(e,hn(t.store)),ko=(e,t=new ci)=>(e instanceof Map?di(t,e):Co(t,e),t.toUint8Array()),Ro=e=>ko(e,new li);class To{constructor(){this.l=[]}}const fi=()=>new To,pi=(e,t)=>e.l.push(t),gi=(e,t)=>{const n=e.l,i=n.length;e.l=n.filter(s=>t!==s),i===e.l.length&&console.error("[yjs] Tried to remove event handler that doesn't exist.")},yi=(e,t,n)=>Yn(e.l,[t,n]);class _e{constructor(t,n){this.client=t,this.clock=n}}const an=(e,t)=>e===t||e!==null&&t!==null&&e.client===t.client&&e.clock===t.clock,K=(e,t)=>new _e(e,t),Ao=e=>{for(const[t,n]of e.doc.share.entries())if(n===e)return t;throw Ut()},ln=(e,t)=>{for(;t!==null;){if(t.parent===e)return!0;t=t.parent._item}return!1};class Do{constructor(t,n){this.ds=t,this.sv=n}}((e,t)=>new Do(e,t))(ri(),new Map);const Pe=(e,t)=>t===void 0?!e.deleted:t.sv.has(e.id.client)&&(t.sv.get(e.id.client)||0)>e.id.clock&&!on(t.ds,e.id),cn=(e,t)=>{const n=St(e.meta,cn,Ie),i=e.doc.store;n.has(t)||(t.sv.forEach((s,o)=>{s{}),n.add(t))};class mi{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}}const hn=e=>{const t=new Map;return e.clients.forEach((n,i)=>{const s=n[n.length-1];t.set(i,s.id.clock+s.length)}),t},ht=(e,t)=>{const n=e.clients.get(t);if(n===void 0)return 0;const i=n[n.length-1];return i.id.clock+i.length},wi=(e,t)=>{let n=e.clients.get(t.id.client);if(n===void 0)n=[],e.clients.set(t.id.client,n);else{const i=n[n.length-1];if(i.id.clock+i.length!==t.id.clock)throw Ut()}n.push(t)},Ft=(e,t)=>{let n=0,i=e.length-1,s=e[i],o=s.id.clock;if(o===t)return i;let c=de(t/(o+s.length-1)*i);for(;n<=i;){if(s=e[c],o=s.id.clock,o<=t){if(t{const n=e.clients.get(t.client);return n[Ft(n,t.clock)]},ir=(e,t,n)=>{const i=Ft(t,n),s=t[i];return s.id.clock{const n=e.doc.store.clients.get(t.client);return n[ir(e,n,t.clock)]},bi=(e,t,n)=>{const i=t.clients.get(n.client),s=Ft(i,n.clock),o=i[s];return n.clock!==o.id.clock+o.length-1&&o.constructor!==Et&&i.splice(s+1,0,kn(e,o,n.clock-o.id.clock+1)),o},Io=(e,t,n)=>{const i=e.clients.get(t.id.client);i[Ft(i,t.id.clock)]=n},_i=(e,t,n,i,s)=>{if(i===0)return;const o=n+i;let c=ir(e,t,n),h;do h=t[c++],ot.deleteSet.clients.size===0&&!fs(t.afterState,(n,i)=>t.beforeState.get(i)!==n)?!1:(tr(t.deleteSet),mo(e,t),me(e,t.deleteSet),!0),Si=(e,t,n)=>{const i=t._item;(i===null||i.id.clock<(e.beforeState.get(i.id.client)||0)&&!i.deleted)&&St(e.changed,t,Ie).add(n)},dn=(e,t)=>{const n=e[t-1],i=e[t];n.deleted===i.deleted&&n.constructor===i.constructor&&n.mergeWith(i)&&(e.splice(t,1),i instanceof rt&&i.parentSub!==null&&i.parent._map.get(i.parentSub)===i&&i.parent._map.set(i.parentSub,n))},Mo=(e,t,n)=>{for(const[i,s]of e.clients.entries()){const o=t.clients.get(i);for(let c=s.length-1;c>=0;c--){const h=s[c],l=h.clock+h.len;for(let y=Ft(o,h.clock),w=o[y];y{e.clients.forEach((n,i)=>{const s=t.clients.get(i);for(let o=n.length-1;o>=0;o--){const c=n[o],h=xn(s.length-1,1+Ft(s,c.clock+c.len-1));for(let l=h,y=s[l];l>0&&y.id.clock>=c.clock;y=s[--l])dn(s,l)}})},Ei=(e,t)=>{if(th.push(()=>{(y._item===null||!y._item.deleted)&&y._callObserver(n,l)})),h.push(()=>{n.changedParentTypes.forEach((l,y)=>h.push(()=>{(y._item===null||!y._item.deleted)&&(l=l.filter(w=>w.target._item===null||!w.target._item.deleted),l.forEach(w=>{w.currentTarget=y}),l.sort((w,u)=>w.path.length-u.path.length),yi(y._dEH,l,n))})),h.push(()=>i.emit("afterTransaction",[n,i]))}),Yn(h,[])}finally{i.gc&&Mo(o,s,i.gcFilter),xo(o,s),n.afterState.forEach((w,u)=>{const g=n.beforeState.get(u)||0;if(g!==w){const f=s.clients.get(u),p=Zt(Ft(f,g),1);for(let S=f.length-1;S>=p;S--)dn(f,S)}});for(let w=0;w0&&dn(f,p)}if(!n.local&&n.afterState.get(i.clientID)!==n.beforeState.get(i.clientID)&&(Qr(sn,vt,"[yjs] ",Ht,Jn,"Changed the client-id because another client seems to be using it."),i.clientID=si()),i.emit("afterTransactionCleanup",[n,i]),i._observers.has("update")){const w=new Fe;vi(w,n)&&i.emit("update",[w.toUint8Array(),n.origin,i,n])}if(i._observers.has("updateV2")){const w=new re;vi(w,n)&&i.emit("updateV2",[w.toUint8Array(),n.origin,i,n])}const{subdocsAdded:h,subdocsLoaded:l,subdocsRemoved:y}=n;(h.size>0||y.size>0||l.size>0)&&(h.forEach(w=>{w.clientID=i.clientID,w.collectionid==null&&(w.collectionid=i.collectionid),i.subdocs.add(w)}),y.forEach(w=>i.subdocs.delete(w)),i.emit("subdocs",[{loaded:l,added:h,removed:y},i,n]),y.forEach(w=>w.destroy())),e.length<=t+1?(i._transactionCleanups=[],i.emit("afterAllTransactions",[i,e])):Ei(e,t+1)}}},tt=(e,t,n=null,i=!0)=>{const s=e._transactionCleanups;let o=!1;e._transaction===null&&(o=!0,e._transaction=new Lo(e,n,i),s.push(e._transaction),s.length===1&&e.emit("beforeAllTransactions",[e]),e.emit("beforeTransaction",[e._transaction,e]));try{t(e._transaction)}finally{o&&s[0]===e._transaction&&Ei(s,0)}};class Oo{constructor(t,n){this.insertions=n,this.deletions=t,this.meta=new Map}}const Ci=(e,t,n)=>{ne(e,n.deletions,i=>{i instanceof rt&&t.scope.some(s=>ln(s,i))&&gr(i,!1)})},ki=(e,t,n)=>{let i=null,s=null;const o=e.doc,c=e.scope;if(tt(o,h=>{for(;t.length>0&&i===null;){const l=o.store,y=t.pop(),w=new Set,u=[];let g=!1;ne(h,y.insertions,f=>{if(f instanceof rt){if(f.redone!==null){let{item:p,diff:S}=Ca(l,f.id);S>0&&(p=bt(h,K(p.id.client,p.id.clock+S))),f=p}!f.deleted&&c.some(p=>ln(p,f))&&u.push(f)}}),ne(h,y.deletions,f=>{f instanceof rt&&c.some(p=>ln(p,f))&&!on(y.insertions,f.id)&&w.add(f)}),w.forEach(f=>{g=Yi(h,f,w,y.insertions)!==null||g});for(let f=u.length-1;f>=0;f--){const p=u[f];e.deleteFilter(p)&&(p.delete(h),g=!0)}i=g?y:null}h.changed.forEach((l,y)=>{l.has(null)&&y._searchMarker&&(y._searchMarker.length=0)}),s=h},e),i!=null){const h=s.changedParentTypes;e.emit("stack-item-popped",[{stackItem:i,type:n,changedParentTypes:h},e])}return i};class bl extends ue{constructor(t,{captureTimeout:n=500,deleteFilter:i=()=>!0,trackedOrigins:s=new Set([null])}={}){super();this.scope=[],this.addToScope(t),this.deleteFilter=i,s.add(this),this.trackedOrigins=s,this.undoStack=[],this.redoStack=[],this.undoing=!1,this.redoing=!1,this.doc=this.scope[0].doc,this.lastChange=0,this.doc.on("afterTransaction",o=>{if(!this.scope.some(f=>o.changedParentTypes.has(f))||!this.trackedOrigins.has(o.origin)&&(!o.origin||!this.trackedOrigins.has(o.origin.constructor)))return;const c=this.undoing,h=this.redoing,l=c?this.redoStack:this.undoStack;c?this.stopCapturing():h||this.clear(!1,!0);const y=new ye;o.afterState.forEach((f,p)=>{const S=o.beforeState.get(p)||0,M=f-S;M>0&&Ue(y,p,S,M)});const w=Ot();let u=!1;if(w-this.lastChange0&&!c&&!h){const f=l[l.length-1];f.deletions=er([f.deletions,o.deleteSet]),f.insertions=er([f.insertions,y])}else l.push(new Oo(o.deleteSet,y)),u=!0;!c&&!h&&(this.lastChange=w),ne(o,o.deleteSet,f=>{f instanceof rt&&this.scope.some(p=>ln(p,f))&&gr(f,!0)});const g=[{stackItem:l[l.length-1],origin:o.origin,type:c?"redo":"undo",changedParentTypes:o.changedParentTypes},this];u?this.emit("stack-item-added",g):this.emit("stack-item-updated",g)}),this.doc.on("destroy",()=>{this.destroy()})}addToScope(t){t=gs(t)?t:[t],t.forEach(n=>{this.scope.every(i=>i!==n)&&this.scope.push(n)})}clear(t=!0,n=!0){(t&&this.canUndo()||n&&this.canRedo())&&this.doc.transact(i=>{t&&(this.undoStack.forEach(s=>Ci(i,this,s)),this.undoStack=[]),n&&(this.redoStack.forEach(s=>Ci(i,this,s)),this.redoStack=[]),this.emit("stack-cleared",[{undoStackCleared:t,redoStackCleared:n}])})}stopCapturing(){this.lastChange=0}undo(){this.undoing=!0;let t;try{t=ki(this,this.undoStack,"undo")}finally{this.undoing=!1}return t}redo(){this.redoing=!0;let t;try{t=ki(this,this.redoStack,"redo")}finally{this.redoing=!1}return t}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}}function*No(e){const t=G(e.restDecoder);for(let n=0;nfn(e,ai,Fe),Fo=(e,t)=>{if(e.constructor===Et){const{client:n,clock:i}=e.id;return new Et(K(n,i+t),e.length-t)}else if(e.constructor===Ct){const{client:n,clock:i}=e.id;return new Ct(K(n,i+t),e.length-t)}else{const n=e,{client:i,clock:s}=n.id;return new rt(K(i,s+t),null,K(i,s+t-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(t))}},fn=(e,t=be,n=re)=>{if(e.length===1)return e[0];const i=e.map(w=>new t(Mt(w)));let s=i.map(w=>new sr(w,!0)),o=null;const c=new n,h=new or(c);for(;s=s.filter(g=>g.curr!==null),s.sort((g,f)=>{if(g.curr.id.client===f.curr.id.client){const p=g.curr.id.clock-f.curr.id.clock;return p===0?g.curr.constructor===f.curr.constructor?0:g.curr.constructor===Ct?1:-1:p}else return f.curr.id.client-g.curr.id.client}),s.length!==0;){const w=s[0],u=w.curr.id.client;if(o!==null){let g=w.curr,f=!1;for(;g!==null&&g.id.clock+g.length<=o.struct.id.clock+o.struct.length&&g.id.client>=o.struct.id.client;)g=w.next(),f=!0;if(g===null||g.id.client!==u||f&&g.id.clock>o.struct.id.clock+o.struct.length)continue;if(u!==o.struct.id.client)$t(h,o.struct,o.offset),o={struct:g,offset:0},w.next();else if(o.struct.id.clock+o.struct.length0&&(o.struct.constructor===Ct?o.struct.length-=p:g=Fo(g,p)),o.struct.mergeWith(g)||($t(h,o.struct,o.offset),o={struct:g,offset:0},w.next())}}else o={struct:w.curr,offset:0},w.next();for(let g=w.curr;g!==null&&g.id.client===u&&g.id.clock===o.struct.id.clock+o.struct.length&&g.constructor!==Ct;g=w.next())$t(h,o.struct,o.offset),o={struct:g,offset:0}}o!==null&&($t(h,o.struct,o.offset),o=null),ar(h);const l=i.map(w=>nr(w)),y=er(l);return me(c,y),c.toUint8Array()},Po=(e,t,n=be,i=re)=>{const s=ui(t),o=new i,c=new or(o),h=new n(Mt(e)),l=new sr(h,!1);for(;l.curr;){const w=l.curr,u=w.id.client,g=s.get(u)||0;if(l.curr.constructor===Ct){l.next();continue}if(w.id.clock+w.length>g)for($t(c,w,Zt(g-w.id.clock,0)),l.next();l.curr&&l.curr.id.client===u;)$t(c,l.curr,0),l.next();else for(;l.curr&&l.curr.id.client===u&&l.curr.id.clock+l.curr.length<=g;)l.next()}ar(c);const y=nr(h);return me(o,y),o.toUint8Array()},Ri=e=>{e.written>0&&(e.clientStructs.push({written:e.written,restEncoder:st(e.encoder.restEncoder)}),e.encoder.restEncoder=dt(),e.written=0)},$t=(e,t,n)=>{e.written>0&&e.currClient!==t.id.client&&Ri(e),e.written===0&&(e.currClient=t.id.client,e.encoder.writeClient(t.id.client),q(e.encoder.restEncoder,t.id.clock+n)),t.write(e.encoder,n),e.written++},ar=e=>{Ri(e);const t=e.encoder.restEncoder;q(t,e.clientStructs.length);for(let n=0;n{const i=new t(Mt(e)),s=new sr(i,!1),o=new n,c=new or(o);for(let l=s.curr;l!==null;l=s.next())$t(c,l,0);ar(c);const h=nr(i);return me(o,h),o.toUint8Array()},jo=e=>Bo(e,be,Fe);class pn{constructor(t,n){this.target=t,this.currentTarget=t,this.transaction=n,this._changes=null,this._keys=null,this._delta=null}get path(){return Vo(this.currentTarget,this.target)}deletes(t){return on(this.transaction.deleteSet,t.id)}get keys(){if(this._keys===null){const t=new Map,n=this.target;this.transaction.changed.get(n).forEach(s=>{if(s!==null){const o=n._map.get(s);let c,h;if(this.adds(o)){let l=o.left;for(;l!==null&&this.adds(l);)l=l.left;if(this.deletes(o))if(l!==null&&this.deletes(l))c="delete",h=Ln(l.content.getContent());else return;else l!==null&&this.deletes(l)?(c="update",h=Ln(l.content.getContent())):(c="add",h=void 0)}else if(this.deletes(o))c="delete",h=Ln(o.content.getContent());else return;t.set(s,{action:c,oldValue:h})}}),this._keys=t}return this._keys}get delta(){return this.changes.delta}adds(t){return t.id.clock>=(this.transaction.beforeState.get(t.id.client)||0)}get changes(){let t=this._changes;if(t===null){const n=this.target,i=Ie(),s=Ie(),o=[];if(t={added:i,deleted:s,delta:o,keys:this.keys},this.transaction.changed.get(n).has(null)){let h=null;const l=()=>{h&&o.push(h)};for(let y=n._start;y!==null;y=y.right)y.deleted?this.deletes(y)&&!this.adds(y)&&((h===null||h.delete===void 0)&&(l(),h={delete:0}),h.delete+=y.length,s.add(y)):this.adds(y)?((h===null||h.insert===void 0)&&(l(),h={insert:[]}),h.insert=h.insert.concat(y.content.getContent()),i.add(y)):((h===null||h.retain===void 0)&&(l(),h={retain:0}),h.retain+=y.length);h!==null&&h.retain===void 0&&l()}this._changes=t}return t}}const Vo=(e,t)=>{const n=[];for(;t._item!==null&&t!==e;){if(t._item.parentSub!==null)n.unshift(t._item.parentSub);else{let i=0,s=t._item.parent._start;for(;s!==t._item&&s!==null;)s.deleted||i++,s=s.right;n.unshift(i)}t=t._item.parent}return n},Ti=80;let lr=0;class qo{constructor(t,n){t.marker=!0,this.p=t,this.index=n,this.timestamp=lr++}}const Wo=e=>{e.timestamp=lr++},Ai=(e,t,n)=>{e.p.marker=!1,e.p=t,t.marker=!0,e.index=n,e.timestamp=lr++},Ho=(e,t,n)=>{if(e.length>=Ti){const i=e.reduce((s,o)=>s.timestamp{if(e._start===null||t===0||e._searchMarker===null)return null;const n=e._searchMarker.length===0?null:e._searchMarker.reduce((o,c)=>Mn(t-o.index)t;)i=i.left,!i.deleted&&i.countable&&(s-=i.length);for(;i.left!==null&&i.left.id.client===i.id.client&&i.left.id.clock+i.left.length===i.id.clock;)i=i.left,!i.deleted&&i.countable&&(s-=i.length);return n!==null&&Mn(n.index-s){for(let i=e.length-1;i>=0;i--){const s=e[i];if(n>0){let o=s.p;for(o.marker=!1;o&&(o.deleted||!o.countable);)o=o.left,o&&!o.deleted&&o.countable&&(s.index-=o.length);if(o===null||o.marker===!0){e.splice(i,1);continue}s.p=o,o.marker=!0}(t0&&t===s.index)&&(s.index=Zt(t,s.index+n))}},yn=(e,t,n)=>{const i=e,s=t.changedParentTypes;for(;St(s,e,()=>[]).push(n),e._item!==null;)e=e._item.parent;yi(i._eH,n,t)};class yt{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=fi(),this._dEH=fi(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(t,n){this.doc=t,this._item=n}_copy(){throw Nt()}clone(){throw Nt()}_write(t){}get _first(){let t=this._start;for(;t!==null&&t.deleted;)t=t.right;return t}_callObserver(t,n){!t.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(t){pi(this._eH,t)}observeDeep(t){pi(this._dEH,t)}unobserve(t){gi(this._eH,t)}unobserveDeep(t){gi(this._dEH,t)}toJSON(){}}const Di=(e,t,n)=>{t<0&&(t=e._length+t),n<0&&(n=e._length+n);let i=n-t;const s=[];let o=e._start;for(;o!==null&&i>0;){if(o.countable&&!o.deleted){const c=o.content.getContent();if(c.length<=t)t-=c.length;else{for(let h=t;h0;h++)s.push(c[h]),i--;t=0}}o=o.right}return s},Ii=e=>{const t=[];let n=e._start;for(;n!==null;){if(n.countable&&!n.deleted){const i=n.content.getContent();for(let s=0;s{let n=0,i=e._start;for(;i!==null;){if(i.countable&&!i.deleted){const s=i.content.getContent();for(let o=0;o{const n=[];return mn(e,(i,s)=>{n.push(t(i,s,e))}),n},$o=e=>{let t=e._start,n=null,i=0;return{[Symbol.iterator](){return this},next:()=>{if(n===null){for(;t!==null&&t.deleted;)t=t.right;if(t===null)return{done:!0,value:void 0};n=t.content.getContent(),i=0,t=t.right}const s=n[i++];return n.length<=i&&(n=null),{done:!1,value:s}}}},Mi=(e,t)=>{const n=gn(e,t);let i=e._start;for(n!==null&&(i=n.p,t-=n.index);i!==null;i=i.right)if(!i.deleted&&i.countable){if(t{let s=n;const o=e.doc,c=o.clientID,h=o.store,l=n===null?t._start:n.right;let y=[];const w=()=>{y.length>0&&(s=new rt(K(c,ht(h,c)),s,s&&s.lastId,l,l&&l.id,t,null,new oe(y)),s.integrate(e,0),y=[])};i.forEach(u=>{if(u===null)y.push(u);else switch(u.constructor){case Number:case Object:case Boolean:case Array:case String:y.push(u);break;default:switch(w(),u.constructor){case Uint8Array:case ArrayBuffer:s=new rt(K(c,ht(h,c)),s,s&&s.lastId,l,l&&l.id,t,null,new Ve(new Uint8Array(u))),s.integrate(e,0);break;case we:s=new rt(K(c,ht(h,c)),s,s&&s.lastId,l,l&&l.id,t,null,new We(u)),s.integrate(e,0);break;default:if(u instanceof yt)s=new rt(K(c,ht(h,c)),s,s&&s.lastId,l,l&&l.id,t,null,new Wt(u)),s.integrate(e,0);else throw new Error("Unexpected content type in insert operation")}}}),w()},xi=ge("Length exceeded!"),Oi=(e,t,n,i)=>{if(n>t._length)throw xi;if(n===0)return t._searchMarker&&Be(t._searchMarker,n,i.length),wn(e,t,null,i);const s=n,o=gn(t,n);let c=t._start;for(o!==null&&(c=o.p,n-=o.index,n===0&&(c=c.prev,n+=c&&c.countable&&!c.deleted?c.length:0));c!==null;c=c.right)if(!c.deleted&&c.countable){if(n<=c.length){n{let s=(t._searchMarker||[]).reduce((o,c)=>c.index>o.index?c:o,{index:0,p:t._start}).p;if(s)for(;s.right;)s=s.right;return wn(e,t,s,n)},Ni=(e,t,n,i)=>{if(i===0)return;const s=n,o=i,c=gn(t,n);let h=t._start;for(c!==null&&(h=c.p,n-=c.index);h!==null&&n>0;h=h.right)!h.deleted&&h.countable&&(n0&&h!==null;)h.deleted||(i0)throw xi;t._searchMarker&&Be(t._searchMarker,s,-o+i)},bn=(e,t,n)=>{const i=t._map.get(n);i!==void 0&&i.delete(e)},cr=(e,t,n,i)=>{const s=t._map.get(n)||null,o=e.doc,c=o.clientID;let h;if(i==null)h=new oe([i]);else switch(i.constructor){case Number:case Object:case Boolean:case Array:case String:h=new oe([i]);break;case Uint8Array:h=new Ve(i);break;case we:h=new We(i);break;default:if(i instanceof yt)h=new Wt(i);else throw new Error("Unexpected content type")}new rt(K(c,ht(o.store,c)),s,s&&s.lastId,null,null,t,n,h).integrate(e,0)},hr=(e,t)=>{const n=e._map.get(t);return n!==void 0&&!n.deleted?n.content.getContent()[n.length-1]:void 0},Ui=e=>{const t={};return e._map.forEach((n,i)=>{n.deleted||(t[i]=n.content.getContent()[n.length-1])}),t},Fi=(e,t)=>{const n=e._map.get(t);return n!==void 0&&!n.deleted},_n=e=>co(e.entries(),t=>!t[1].deleted);class zo extends pn{constructor(t,n){super(t,n);this._transaction=n}}class ve extends yt{constructor(){super();this._prelimContent=[],this._searchMarker=[]}static from(t){const n=new ve;return n.push(t),n}_integrate(t,n){super._integrate(t,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new ve}clone(){const t=new ve;return t.insert(0,this.toArray().map(n=>n instanceof yt?n.clone():n)),t}get length(){return this._prelimContent===null?this._length:this._prelimContent.length}_callObserver(t,n){super._callObserver(t,n),yn(this,t,new zo(this,t))}insert(t,n){this.doc!==null?tt(this.doc,i=>{Oi(i,this,t,n)}):this._prelimContent.splice(t,0,...n)}push(t){this.doc!==null?tt(this.doc,n=>{Yo(n,this,t)}):this._prelimContent.push(...t)}unshift(t){this.insert(0,t)}delete(t,n=1){this.doc!==null?tt(this.doc,i=>{Ni(i,this,t,n)}):this._prelimContent.splice(t,n)}get(t){return Mi(this,t)}toArray(){return Ii(this)}slice(t=0,n=this.length){return Di(this,t,n)}toJSON(){return this.map(t=>t instanceof yt?t.toJSON():t)}map(t){return Li(this,t)}forEach(t){mn(this,t)}[Symbol.iterator](){return $o(this)}_write(t){t.writeTypeRef(ya)}}const Go=e=>new ve;class Jo extends pn{constructor(t,n,i){super(t,n);this.keysChanged=i}}class Se extends yt{constructor(t){super();this._prelimContent=null,t===void 0?this._prelimContent=new Map:this._prelimContent=new Map(t)}_integrate(t,n){super._integrate(t,n),this._prelimContent.forEach((i,s)=>{this.set(s,i)}),this._prelimContent=null}_copy(){return new Se}clone(){const t=new Se;return this.forEach((n,i)=>{t.set(i,n instanceof yt?n.clone():n)}),t}_callObserver(t,n){yn(this,t,new Jo(this,t,n))}toJSON(){const t={};return this._map.forEach((n,i)=>{if(!n.deleted){const s=n.content.getContent()[n.length-1];t[i]=s instanceof yt?s.toJSON():s}}),t}get size(){return[..._n(this._map)].length}keys(){return Zn(_n(this._map),t=>t[0])}values(){return Zn(_n(this._map),t=>t[1].content.getContent()[t[1].length-1])}entries(){return Zn(_n(this._map),t=>[t[0],t[1].content.getContent()[t[1].length-1]])}forEach(t){const n={};return this._map.forEach((i,s)=>{i.deleted||t(i.content.getContent()[i.length-1],s,this)}),n}[Symbol.iterator](){return this.entries()}delete(t){this.doc!==null?tt(this.doc,n=>{bn(n,this,t)}):this._prelimContent.delete(t)}set(t,n){return this.doc!==null?tt(this.doc,i=>{cr(i,this,t,n)}):this._prelimContent.set(t,n),n}get(t){return hr(this,t)}has(t){return Fi(this,t)}clear(){this.doc!==null?tt(this.doc,t=>{this.forEach(function(n,i,s){bn(t,s,i)})}):this._prelimContent.clear()}_write(t){t.writeTypeRef(ma)}}const Ko=e=>new Se,Yt=(e,t)=>e===t||typeof e=="object"&&typeof t=="object"&&e&&t&&Qs(e,t);class ur{constructor(t,n,i,s){this.left=t,this.right=n,this.index=i,this.currentAttributes=s}forward(){switch(this.right===null&&Ut(),this.right.content.constructor){case ut:this.right.deleted||Ee(this.currentAttributes,this.right.content);break;default:this.right.deleted||(this.index+=this.right.length);break}this.left=this.right,this.right=this.right.right}}const Pi=(e,t,n)=>{for(;t.right!==null&&n>0;){switch(t.right.content.constructor){case ut:t.right.deleted||Ee(t.currentAttributes,t.right.content);break;default:t.right.deleted||(n{const i=new Map,s=gn(t,n);if(s){const o=new ur(s.p.left,s.p,s.index,i);return Pi(e,o,n-s.index)}else{const o=new ur(null,t._start,0,i);return Pi(e,o,n)}},Bi=(e,t,n,i)=>{for(;n.right!==null&&(n.right.deleted===!0||n.right.content.constructor===ut&&Yt(i.get(n.right.content.key),n.right.content.value));)n.right.deleted||i.delete(n.right.content.key),n.forward();const s=e.doc,o=s.clientID;i.forEach((c,h)=>{const l=n.left,y=n.right,w=new rt(K(o,ht(s.store,o)),l,l&&l.lastId,y,y&&y.id,t,null,new ut(h,c));w.integrate(e,0),n.right=w,n.forward()})},Ee=(e,t)=>{const{key:n,value:i}=t;i===null?e.delete(n):e.set(n,i)},ji=(e,t)=>{for(;e.right!==null;){if(!(e.right.deleted||e.right.content.constructor===ut&&Yt(t[e.right.content.key]||null,e.right.content.value)))break;e.forward()}},Vi=(e,t,n,i)=>{const s=e.doc,o=s.clientID,c=new Map;for(const h in i){const l=i[h],y=n.currentAttributes.get(h)||null;if(!Yt(y,l)){c.set(h,y);const{left:w,right:u}=n;n.right=new rt(K(o,ht(s.store,o)),w,w&&w.lastId,u,u&&u.id,t,null,new ut(h,l)),n.right.integrate(e,0),n.forward()}}return c},dr=(e,t,n,i,s)=>{n.currentAttributes.forEach((g,f)=>{s[f]===void 0&&(s[f]=null)});const o=e.doc,c=o.clientID;ji(n,s);const h=Vi(e,t,n,s),l=i.constructor===String?new Pt(i):i instanceof yt?new Wt(i):new se(i);let{left:y,right:w,index:u}=n;t._searchMarker&&Be(t._searchMarker,n.index,l.getLength()),w=new rt(K(c,ht(o.store,c)),y,y&&y.lastId,w,w&&w.id,t,null,l),w.integrate(e,0),n.right=w,n.index=u,n.forward(),Bi(e,t,n,h)},qi=(e,t,n,i,s)=>{const o=e.doc,c=o.clientID;ji(n,s);const h=Vi(e,t,n,s);for(;n.right!==null&&(i>0||n.right.content.constructor===ut);){if(!n.right.deleted)switch(n.right.content.constructor){case ut:{const{key:l,value:y}=n.right.content,w=s[l];w!==void 0&&(Yt(w,y)?h.delete(l):h.set(l,y),n.right.delete(e));break}default:i0){let l="";for(;i>0;i--)l+=` -`;n.right=new rt(K(c,ht(o.store,c)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,t,null,new Pt(l)),n.right.integrate(e,0),n.forward()}Bi(e,t,n,h)},Wi=(e,t,n,i,s)=>{let o=n;const c=Je(s);for(;o&&(!o.countable||o.deleted);)!o.deleted&&o.content.constructor===ut&&Ee(c,o.content),o=o.right;let h=0,l=!1;for(;t!==o;){if(n===t&&(l=!0),!t.deleted){const y=t.content;switch(y.constructor){case ut:{const{key:w,value:u}=y;((c.get(w)||null)!==u||(i.get(w)||null)===u)&&(t.delete(e),h++,!l&&(s.get(w)||null)===u&&(i.get(w)||null)!==u&&s.delete(w));break}}}t=t.right}return h},Xo=(e,t)=>{for(;t&&t.right&&(t.right.deleted||!t.right.countable);)t=t.right;const n=new Set;for(;t&&(t.deleted||!t.countable);){if(!t.deleted&&t.content.constructor===ut){const i=t.content.key;n.has(i)?t.delete(e):n.add(i)}t=t.left}},Zo=e=>{let t=0;return tt(e.doc,n=>{let i=e._start,s=e._start,o=lt();const c=Je(o);for(;s;){if(s.deleted===!1)switch(s.content.constructor){case ut:Ee(c,s.content);break;default:t+=Wi(n,i,s,o,c),o=Je(c),i=s;break}s=s.right}}),t},Hi=(e,t,n)=>{const i=n,s=Je(t.currentAttributes),o=t.right;for(;n>0&&t.right!==null;){if(t.right.deleted===!1)switch(t.right.content.constructor){case Wt:case se:case Pt:n{s===null?this.childListChanged=!0:this.keysChanged.add(s)})}get changes(){if(this._changes===null){const t={keys:this.keys,delta:this.delta,added:new Set,deleted:new Set};this._changes=t}return this._changes}get delta(){if(this._delta===null){const t=this.target.doc,n=[];tt(t,i=>{const s=new Map,o=new Map;let c=this.target._start,h=null;const l={};let y="",w=0,u=0;const g=()=>{if(h!==null){let f;switch(h){case"delete":f={delete:u},u=0;break;case"insert":f={insert:y},s.size>0&&(f.attributes={},s.forEach((p,S)=>{p!==null&&(f.attributes[S]=p)})),y="";break;case"retain":if(f={retain:w},Object.keys(l).length>0){f.attributes={};for(const p in l)f.attributes[p]=l[p]}w=0;break}n.push(f),h=null}};for(;c!==null;){switch(c.content.constructor){case Wt:case se:this.adds(c)?this.deletes(c)||(g(),h="insert",y=c.content.getContent()[0],g()):this.deletes(c)?(h!=="delete"&&(g(),h="delete"),u+=1):c.deleted||(h!=="retain"&&(g(),h="retain"),w+=1);break;case Pt:this.adds(c)?this.deletes(c)||(h!=="insert"&&(g(),h="insert"),y+=c.content.str):this.deletes(c)?(h!=="delete"&&(g(),h="delete"),u+=c.length):c.deleted||(h!=="retain"&&(g(),h="retain"),w+=c.length);break;case ut:{const{key:f,value:p}=c.content;if(this.adds(c)){if(!this.deletes(c)){const S=s.get(f)||null;Yt(S,p)?p!==null&&c.delete(i):(h==="retain"&&g(),Yt(p,o.get(f)||null)?delete l[f]:l[f]=p)}}else if(this.deletes(c)){o.set(f,p);const S=s.get(f)||null;Yt(S,p)||(h==="retain"&&g(),l[f]=S)}else if(!c.deleted){o.set(f,p);const S=l[f];S!==void 0&&(Yt(S,p)?S!==null&&c.delete(i):(h==="retain"&&g(),p===null?delete l[f]:l[f]=p))}c.deleted||(h==="insert"&&g(),Ee(s,c.content));break}}c=c.right}for(g();n.length>0;){const f=n[n.length-1];if(f.retain!==void 0&&f.attributes===void 0)n.pop();else break}}),this._delta=n}return this._delta}}class Ce extends yt{constructor(t){super();this._pending=t!==void 0?[()=>this.insert(0,t)]:[],this._searchMarker=[]}get length(){return this._length}_integrate(t,n){super._integrate(t,n);try{this._pending.forEach(i=>i())}catch(i){console.error(i)}this._pending=null}_copy(){return new Ce}clone(){const t=new Ce;return t.applyDelta(this.toDelta()),t}_callObserver(t,n){super._callObserver(t,n);const i=new Qo(this,t,n),s=t.doc;if(yn(this,t,i),!t.local){let o=!1;for(const[c,h]of t.afterState.entries()){const l=t.beforeState.get(c)||0;if(h!==l&&(_i(t,s.store.clients.get(c),l,h,y=>{!y.deleted&&y.content.constructor===ut&&(o=!0)}),o))break}o||ne(t,t.deleteSet,c=>{c instanceof Et||o||c.parent===this&&c.content.constructor===ut&&(o=!0)}),tt(s,c=>{o?Zo(this):ne(c,c.deleteSet,h=>{h instanceof Et||h.parent===this&&Xo(c,h)})})}}toString(){let t="",n=this._start;for(;n!==null;)!n.deleted&&n.countable&&n.content.constructor===Pt&&(t+=n.content.str),n=n.right;return t}toJSON(){return this.toString()}applyDelta(t,{sanitize:n=!0}={}){this.doc!==null?tt(this.doc,i=>{const s=new ur(null,this._start,0,new Map);for(let o=0;o0)&&dr(i,this,s,h,c.attributes||{})}else c.retain!==void 0?qi(i,this,s,c.retain,c.attributes||{}):c.delete!==void 0&&Hi(i,s,c.delete)}}):this._pending.push(()=>this.applyDelta(t))}toDelta(t,n,i){const s=[],o=new Map,c=this.doc;let h="",l=this._start;function y(){if(h.length>0){const w={};let u=!1;o.forEach((f,p)=>{u=!0,w[p]=f});const g={insert:h};u&&(g.attributes=w),s.push(g),h=""}}return tt(c,w=>{for(t&&cn(w,t),n&&cn(w,n);l!==null;){if(Pe(l,t)||n!==void 0&&Pe(l,n))switch(l.content.constructor){case Pt:{const u=o.get("ychange");t!==void 0&&!Pe(l,t)?(u===void 0||u.user!==l.id.client||u.state!=="removed")&&(y(),o.set("ychange",i?i("removed",l.id):{type:"removed"})):n!==void 0&&!Pe(l,n)?(u===void 0||u.user!==l.id.client||u.state!=="added")&&(y(),o.set("ychange",i?i("added",l.id):{type:"added"})):u!==void 0&&(y(),o.delete("ychange")),h+=l.content.str;break}case Wt:case se:{y();const u={insert:l.content.getContent()[0]};if(o.size>0){const g={};u.attributes=g,o.forEach((f,p)=>{g[p]=f})}s.push(u);break}case ut:Pe(l,t)&&(y(),Ee(o,l.content));break}l=l.right}y()},cn),s}insert(t,n,i){if(n.length<=0)return;const s=this.doc;s!==null?tt(s,o=>{const c=vn(o,this,t);i||(i={},c.currentAttributes.forEach((h,l)=>{i[l]=h})),dr(o,this,c,n,i)}):this._pending.push(()=>this.insert(t,n,i))}insertEmbed(t,n,i={}){const s=this.doc;s!==null?tt(s,o=>{const c=vn(o,this,t);dr(o,this,c,n,i)}):this._pending.push(()=>this.insertEmbed(t,n,i))}delete(t,n){if(n===0)return;const i=this.doc;i!==null?tt(i,s=>{Hi(s,vn(s,this,t),n)}):this._pending.push(()=>this.delete(t,n))}format(t,n,i){if(n===0)return;const s=this.doc;s!==null?tt(s,o=>{const c=vn(o,this,t);c.right!==null&&qi(o,this,c,n,i)}):this._pending.push(()=>this.format(t,n,i))}removeAttribute(t){this.doc!==null?tt(this.doc,n=>{bn(n,this,t)}):this._pending.push(()=>this.removeAttribute(t))}setAttribute(t,n){this.doc!==null?tt(this.doc,i=>{cr(i,this,t,n)}):this._pending.push(()=>this.setAttribute(t,n))}getAttribute(t){return hr(this,t)}getAttributes(t){return Ui(this)}_write(t){t.writeTypeRef(wa)}}const ta=e=>new Ce;class fr{constructor(t,n=()=>!0){this._filter=n,this._root=t,this._currentNode=t._start,this._firstCall=!0}[Symbol.iterator](){return this}next(){let t=this._currentNode,n=t&&t.content&&t.content.type;if(t!==null&&(!this._firstCall||t.deleted||!this._filter(n)))do if(n=t.content.type,!t.deleted&&(n.constructor===je||n.constructor===ie)&&n._start!==null)t=n._start;else for(;t!==null;)if(t.right!==null){t=t.right;break}else t.parent===this._root?t=null:t=t.parent._item;while(t!==null&&(t.deleted||!this._filter(t.content.type)));return this._firstCall=!1,t===null?{value:void 0,done:!0}:(this._currentNode=t,{value:t.content.type,done:!1})}}class ie extends yt{constructor(){super();this._prelimContent=[]}get firstChild(){const t=this._first;return t?t.content.getContent()[0]:null}_integrate(t,n){super._integrate(t,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new ie}clone(){const t=new ie;return t.insert(0,this.toArray().map(n=>n instanceof yt?n.clone():n)),t}get length(){return this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(t){return new fr(this,t)}querySelector(t){t=t.toUpperCase();const i=new fr(this,s=>s.nodeName&&s.nodeName.toUpperCase()===t).next();return i.done?null:i.value}querySelectorAll(t){return t=t.toUpperCase(),Array.from(new fr(this,n=>n.nodeName&&n.nodeName.toUpperCase()===t))}_callObserver(t,n){yn(this,t,new ra(this,n,t))}toString(){return Li(this,t=>t.toString()).join("")}toJSON(){return this.toString()}toDOM(t=document,n={},i){const s=t.createDocumentFragment();return i!==void 0&&i._createAssociation(s,this),mn(this,o=>{s.insertBefore(o.toDOM(t,n,i),null)}),s}insert(t,n){this.doc!==null?tt(this.doc,i=>{Oi(i,this,t,n)}):this._prelimContent.splice(t,0,...n)}insertAfter(t,n){if(this.doc!==null)tt(this.doc,i=>{const s=t&&t instanceof yt?t._item:t;wn(i,this,s,n)});else{const i=this._prelimContent,s=t===null?0:i.findIndex(o=>o===t)+1;if(s===0&&t!==null)throw ge("Reference item not found");i.splice(s,0,...n)}}delete(t,n=1){this.doc!==null?tt(this.doc,i=>{Ni(i,this,t,n)}):this._prelimContent.splice(t,n)}toArray(){return Ii(this)}push(t){this.insert(this.length,t)}unshift(t){this.insert(0,t)}get(t){return Mi(this,t)}slice(t=0,n=this.length){return Di(this,t,n)}_write(t){t.writeTypeRef(_a)}}const ea=e=>new ie;class je extends ie{constructor(t="UNDEFINED"){super();this.nodeName=t,this._prelimAttrs=new Map}get nextSibling(){const t=this._item?this._item.next:null;return t?t.content.type:null}get prevSibling(){const t=this._item?this._item.prev:null;return t?t.content.type:null}_integrate(t,n){super._integrate(t,n),this._prelimAttrs.forEach((i,s)=>{this.setAttribute(s,i)}),this._prelimAttrs=null}_copy(){return new je(this.nodeName)}clone(){const t=new je(this.nodeName),n=this.getAttributes();for(const i in n)t.setAttribute(i,n[i]);return t.insert(0,this.toArray().map(i=>i instanceof yt?i.clone():i)),t}toString(){const t=this.getAttributes(),n=[],i=[];for(const h in t)i.push(h);i.sort();const s=i.length;for(let h=0;h0?" "+n.join(" "):"";return`<${o}${c}>${super.toString()}`}removeAttribute(t){this.doc!==null?tt(this.doc,n=>{bn(n,this,t)}):this._prelimAttrs.delete(t)}setAttribute(t,n){this.doc!==null?tt(this.doc,i=>{cr(i,this,t,n)}):this._prelimAttrs.set(t,n)}getAttribute(t){return hr(this,t)}hasAttribute(t){return Fi(this,t)}getAttributes(t){return Ui(this)}toDOM(t=document,n={},i){const s=t.createElement(this.nodeName),o=this.getAttributes();for(const c in o)s.setAttribute(c,o[c]);return mn(this,c=>{s.appendChild(c.toDOM(t,n,i))}),i!==void 0&&i._createAssociation(s,this),s}_write(t){t.writeTypeRef(ba),t.writeKey(this.nodeName)}}const na=e=>new je(e.readKey());class ra extends pn{constructor(t,n,i){super(t,i);this.childListChanged=!1,this.attributesChanged=new Set,n.forEach(s=>{s===null?this.childListChanged=!0:this.attributesChanged.add(s)})}}class Sn extends Se{constructor(t){super();this.hookName=t}_copy(){return new Sn(this.hookName)}clone(){const t=new Sn(this.hookName);return this.forEach((n,i)=>{t.set(i,n)}),t}toDOM(t=document,n={},i){const s=n[this.hookName];let o;return s!==void 0?o=s.createDom(this):o=document.createElement(this.hookName),o.setAttribute("data-yjs-hook",this.hookName),i!==void 0&&i._createAssociation(o,this),o}_write(t){t.writeTypeRef(va),t.writeKey(this.hookName)}}const ia=e=>new Sn(e.readKey());class En extends Ce{get nextSibling(){const t=this._item?this._item.next:null;return t?t.content.type:null}get prevSibling(){const t=this._item?this._item.prev:null;return t?t.content.type:null}_copy(){return new En}clone(){const t=new En;return t.applyDelta(this.toDelta()),t}toDOM(t=document,n,i){const s=t.createTextNode(this.toString());return i!==void 0&&i._createAssociation(s,this),s}toString(){return this.toDelta().map(t=>{const n=[];for(const s in t.attributes){const o=[];for(const c in t.attributes[s])o.push({key:c,value:t.attributes[s][c]});o.sort((c,h)=>c.keys.nodeName=0;s--)i+=``;return i}).join("")}toJSON(){return this.toString()}_write(t){t.writeTypeRef(Sa)}}const sa=e=>new En;class pr{constructor(t,n){this.id=t,this.length=n}get deleted(){throw Nt()}mergeWith(t){return!1}write(t,n,i){throw Nt()}integrate(t,n){throw Nt()}}const oa=0;class Et extends pr{get deleted(){return!0}delete(){}mergeWith(t){return this.constructor!==t.constructor?!1:(this.length+=t.length,!0)}integrate(t,n){n>0&&(this.id.clock+=n,this.length-=n),wi(t.doc.store,this)}write(t,n){t.writeInfo(oa),t.writeLen(this.length-n)}getMissing(t,n){return null}}class Ve{constructor(t){this.content=t}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new Ve(this.content)}splice(t){throw Nt()}mergeWith(t){return!1}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeBuf(this.content)}getRef(){return 3}}const aa=e=>new Ve(e.readBuf());class qe{constructor(t){this.len=t}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new qe(this.len)}splice(t){const n=new qe(this.len-t);return this.len=t,n}mergeWith(t){return this.len+=t.len,!0}integrate(t,n){Ue(t.deleteSet,n.id.client,n.id.clock,this.len),n.markDeleted()}delete(t){}gc(t){}write(t,n){t.writeLen(this.len-n)}getRef(){return 1}}const la=e=>new qe(e.readLen()),$i=(e,t)=>new we(In(Ge({guid:e},t),{shouldLoad:t.shouldLoad||t.autoLoad||!1}));class We{constructor(t){t._item&&console.error("This document was already integrated as a sub-document. You should create a second instance instead with the same guid."),this.doc=t;const n={};this.opts=n,t.gc||(n.gc=!1),t.autoLoad&&(n.autoLoad=!0),t.meta!==null&&(n.meta=t.meta)}getLength(){return 1}getContent(){return[this.doc]}isCountable(){return!0}copy(){return new We($i(this.doc.guid,this.opts))}splice(t){throw Nt()}mergeWith(t){return!1}integrate(t,n){this.doc._item=n,t.subdocsAdded.add(this.doc),this.doc.shouldLoad&&t.subdocsLoaded.add(this.doc)}delete(t){t.subdocsAdded.has(this.doc)?t.subdocsAdded.delete(this.doc):t.subdocsRemoved.add(this.doc)}gc(t){}write(t,n){t.writeString(this.doc.guid),t.writeAny(this.opts)}getRef(){return 9}}const ca=e=>new We($i(e.readString(),e.readAny()));class se{constructor(t){this.embed=t}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new se(this.embed)}splice(t){throw Nt()}mergeWith(t){return!1}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeJSON(this.embed)}getRef(){return 5}}const ha=e=>new se(e.readJSON());class ut{constructor(t,n){this.key=t,this.value=n}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new ut(this.key,this.value)}splice(t){throw Nt()}mergeWith(t){return!1}integrate(t,n){n.parent._searchMarker=null}delete(t){}gc(t){}write(t,n){t.writeKey(this.key),t.writeJSON(this.value)}getRef(){return 6}}const ua=e=>new ut(e.readKey(),e.readJSON());class Cn{constructor(t){this.arr=t}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new Cn(this.arr)}splice(t){const n=new Cn(this.arr.slice(t));return this.arr=this.arr.slice(0,t),n}mergeWith(t){return this.arr=this.arr.concat(t.arr),!0}integrate(t,n){}delete(t){}gc(t){}write(t,n){const i=this.arr.length;t.writeLen(i-n);for(let s=n;s{const t=e.readLen(),n=[];for(let i=0;i{const t=e.readLen(),n=[];for(let i=0;i=55296&&i<=56319&&(this.str=this.str.slice(0,t-1)+"\uFFFD",n.str="\uFFFD"+n.str.slice(1)),n}mergeWith(t){return this.str+=t.str,!0}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeString(n===0?this.str:this.str.slice(n))}getRef(){return 4}}const pa=e=>new Pt(e.readString()),ga=[Go,Ko,ta,na,ea,ia,sa],ya=0,ma=1,wa=2,ba=3,_a=4,va=5,Sa=6;class Wt{constructor(t){this.type=t}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new Wt(this.type._copy())}splice(t){throw Nt()}mergeWith(t){return!1}integrate(t,n){this.type._integrate(t.doc,n)}delete(t){let n=this.type._start;for(;n!==null;)n.deleted?t._mergeStructs.push(n):n.delete(t),n=n.right;this.type._map.forEach(i=>{i.deleted?t._mergeStructs.push(i):i.delete(t)}),t.changed.delete(this.type)}gc(t){let n=this.type._start;for(;n!==null;)n.gc(t,!0),n=n.right;this.type._start=null,this.type._map.forEach(i=>{for(;i!==null;)i.gc(t,!0),i=i.left}),this.type._map=new Map}write(t,n){this.type._write(t)}getRef(){return 7}}const Ea=e=>new Wt(ga[e.readTypeRef()](e)),Ca=(e,t)=>{let n=t,i=0,s;do i>0&&(n=K(n.client,n.clock+i)),s=un(e,n),i=n.clock-s.id.clock,n=s.redone;while(n!==null&&s instanceof rt);return{item:s,diff:i}},gr=(e,t)=>{for(;e!==null&&e.keep!==t;)e.keep=t,e=e.parent._item},kn=(e,t,n)=>{const{client:i,clock:s}=t.id,o=new rt(K(i,s+n),t,K(i,s+n-1),t.right,t.rightOrigin,t.parent,t.parentSub,t.content.splice(n));return t.deleted&&o.markDeleted(),t.keep&&(o.keep=!0),t.redone!==null&&(o.redone=K(t.redone.client,t.redone.clock+n)),t.right=o,o.right!==null&&(o.right.left=o),e._mergeStructs.push(o),o.parentSub!==null&&o.right===null&&o.parent._map.set(o.parentSub,o),t.length=n,o},Yi=(e,t,n,i)=>{const s=e.doc,o=s.store,c=s.clientID,h=t.redone;if(h!==null)return bt(e,h);let l=t.parent._item,y=null,w;if(l!==null&&l.deleted===!0){if(l.redone===null&&(!n.has(l)||Yi(e,l,n,i)===null))return null;for(;l.redone!==null;)l=bt(e,l.redone)}const u=l===null?t.parent:l.content.type;if(t.parentSub===null){for(y=t.left,w=t;y!==null;){let S=y;for(;S!==null&&S.parent._item!==l;)S=S.redone===null?null:bt(e,S.redone);if(S!==null&&S.parent._item===l){y=S;break}y=y.left}for(;w!==null;){let S=w;for(;S!==null&&S.parent._item!==l;)S=S.redone===null?null:bt(e,S.redone);if(S!==null&&S.parent._item===l){w=S;break}w=w.right}}else if(w=null,t.right){for(y=t;y!==null&&y.right!==null&&on(i,y.right.id);)y=y.right;for(;y!==null&&y.redone!==null;)y=bt(e,y.redone);if(y===null||y.parent._item!==l||y&&y.right!==null)return null}else y=u._map.get(t.parentSub)||null;const g=ht(o,c),f=K(c,g),p=new rt(f,y,y&&y.lastId,w,w&&w.id,u,t.parentSub,t.content.copy());return t.redone=f,gr(p,!0),p.integrate(e,0),p};class rt extends pr{constructor(t,n,i,s,o,c,h,l){super(t,l.getLength());this.origin=i,this.left=n,this.right=s,this.rightOrigin=o,this.parent=c,this.parentSub=h,this.redone=null,this.content=l,this.info=this.content.isCountable()?jr:0}set marker(t){(this.info&Un)>0!==t&&(this.info^=Un)}get marker(){return(this.info&Un)>0}get keep(){return(this.info&Br)>0}set keep(t){this.keep!==t&&(this.info^=Br)}get countable(){return(this.info&jr)>0}get deleted(){return(this.info&Nn)>0}set deleted(t){this.deleted!==t&&(this.info^=Nn)}markDeleted(){this.info|=Nn}getMissing(t,n){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=ht(n,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=ht(n,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===_e&&this.id.client!==this.parent.client&&this.parent.clock>=ht(n,this.parent.client))return this.parent.client;if(this.origin&&(this.left=bi(t,n,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=bt(t,this.rightOrigin),this.rightOrigin=this.right.id),(this.left&&this.left.constructor===Et||this.right&&this.right.constructor===Et)&&(this.parent=null),!this.parent)this.left&&this.left.constructor===rt&&(this.parent=this.left.parent,this.parentSub=this.left.parentSub),this.right&&this.right.constructor===rt&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);else if(this.parent.constructor===_e){const i=un(n,this.parent);i.constructor===Et?this.parent=null:this.parent=i.content.type}return null}integrate(t,n){if(n>0&&(this.id.clock+=n,this.left=bi(t,t.doc.store,K(this.id.client,this.id.clock-1)),this.origin=this.left.lastId,this.content=this.content.splice(n),this.length-=n),this.parent){if(!this.left&&(!this.right||this.right.left!==null)||this.left&&this.left.right!==this.right){let i=this.left,s;if(i!==null)s=i.right;else if(this.parentSub!==null)for(s=this.parent._map.get(this.parentSub)||null;s!==null&&s.left!==null;)s=s.left;else s=this.parent._start;const o=new Set,c=new Set;for(;s!==null&&s!==this.right;){if(c.add(s),o.add(s),an(this.origin,s.origin)){if(s.id.client{i.p===t&&(i.p=this,!this.deleted&&this.countable&&(i.index-=this.length))}),t.keep&&(this.keep=!0),this.right=t.right,this.right!==null&&(this.right.left=this),this.length+=t.length,!0}return!1}delete(t){if(!this.deleted){const n=this.parent;this.countable&&this.parentSub===null&&(n._length-=this.length),this.markDeleted(),Ue(t.deleteSet,this.id.client,this.id.clock,this.length),Si(t,n,this.parentSub),this.content.delete(t)}}gc(t,n){if(!this.deleted)throw Ut();this.content.gc(t),n?Io(t,this,new Et(this.id,this.length)):this.content=new qe(this.length)}write(t,n){const i=n>0?K(this.id.client,this.id.clock+n-1):this.origin,s=this.rightOrigin,o=this.parentSub,c=this.content.getRef()&Xe|(i===null?0:_t)|(s===null?0:Bt)|(o===null?0:Le);if(t.writeInfo(c),i!==null&&t.writeLeftID(i),s!==null&&t.writeRightID(s),i===null&&s===null){const h=this.parent;if(h._item!==void 0){const l=h._item;if(l===null){const y=Ao(h);t.writeParentInfo(!0),t.writeString(y)}else t.writeParentInfo(!1),t.writeLeftID(l.id)}else h.constructor===String?(t.writeParentInfo(!0),t.writeString(h)):h.constructor===_e?(t.writeParentInfo(!1),t.writeLeftID(h)):Ut();o!==null&&t.writeString(o)}this.content.write(t,n)}}const zi=(e,t)=>ka[t&Xe](e),ka=[()=>{Ut()},la,da,aa,pa,ha,ua,Ea,fa,ca,()=>{Ut()}],Ra=10;class Ct extends pr{get deleted(){return!0}delete(){}mergeWith(t){return this.constructor!==t.constructor?!1:(this.length+=t.length,!0)}integrate(t,n){Ut()}write(t,n){t.writeInfo(Ra),q(t.restEncoder,this.length-n)}getMissing(t,n){return null}}const Gi=typeof window!="undefined"?window:typeof global!="undefined"?global:{},Ji="__ $YJS$ __";Gi[Ji]===!0&&console.warn("Yjs was already imported. Importing different versions of Yjs often leads to issues."),Gi[Ji]=!0;const Ta=1200,Aa=2500,Rn=3e4,yr=e=>{if(e.shouldConnect&&e.ws===null){const t=new WebSocket(e.url),n=e.binaryType;let i=null;n&&(t.binaryType=n),e.ws=t,e.connecting=!0,e.connected=!1,t.onmessage=c=>{e.lastMessageReceived=Ot();const h=c.data,l=typeof h=="string"?JSON.parse(h):h;l&&l.type==="pong"&&(clearTimeout(i),i=setTimeout(o,Rn/2)),e.emit("message",[l,e])};const s=c=>{e.ws!==null&&(e.ws=null,e.connecting=!1,e.connected?(e.connected=!1,e.emit("disconnect",[{type:"disconnect",error:c},e])):e.unsuccessfulReconnects++,setTimeout(yr,xn(ys(e.unsuccessfulReconnects+1)*Ta,Aa),e)),clearTimeout(i)},o=()=>{e.ws===t&&e.send({type:"ping"})};t.onclose=()=>s(null),t.onerror=c=>s(c),t.onopen=()=>{e.lastMessageReceived=Ot(),e.connecting=!1,e.connected=!0,e.unsuccessfulReconnects=0,e.emit("connect",[{type:"connect"},e]),i=setTimeout(o,Rn/2)}}};class Da extends ue{constructor(t,{binaryType:n}={}){super();this.url=t,this.ws=null,this.binaryType=n||null,this.connected=!1,this.connecting=!1,this.unsuccessfulReconnects=0,this.lastMessageReceived=0,this.shouldConnect=!0,this._checkInterval=setInterval(()=>{this.connected&&Rnn.key===t&&this.onmessage!==null&&this.onmessage({data:Hr(n.newValue||"")}))}postMessage(t){Ur.setItem(this.room,Wr(Ms(t)))}}const Ma=typeof BroadcastChannel=="undefined"?La:BroadcastChannel,mr=e=>St(Ia,e,()=>{const t=new Set,n=new Ma(e);return n.onmessage=i=>t.forEach(s=>s(i.data)),{bc:n,subs:t}}),xa=(e,t)=>mr(e).subs.add(t),Oa=(e,t)=>mr(e).subs.delete(t),Na=(e,t)=>{const n=mr(e);n.bc.postMessage(t),n.subs.forEach(i=>i(t))},Ua=()=>{let e=!0;return(t,n)=>{if(e){e=!1;try{t()}finally{e=!0}}else n!==void 0&&n()}};var kt=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function Tn(e){throw new Error('Could not dynamically require "'+e+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var Ki={exports:{}};(function(e,t){(function(n){e.exports=n()})(function(){var n=Math.floor,i=Math.abs,s=Math.pow;return function(){function o(c,h,l){function y(g,f){if(!h[g]){if(!c[g]){var p=typeof Tn=="function"&&Tn;if(!f&&p)return p(g,!0);if(w)return w(g,!0);var S=new Error("Cannot find module '"+g+"'");throw S.code="MODULE_NOT_FOUND",S}var M=h[g]={exports:{}};c[g][0].call(M.exports,function(x){var F=c[g][1][x];return y(F||x)},M,M.exports,o,c,h,l)}return h[g].exports}for(var w=typeof Tn=="function"&&Tn,u=0;u>16,v[R++]=255&C>>8,v[R++]=255&C;return A===2&&(C=S[E.charCodeAt(D)]<<2|S[E.charCodeAt(D+1)]>>4,v[R++]=255&C),A===1&&(C=S[E.charCodeAt(D)]<<10|S[E.charCodeAt(D+1)]<<4|S[E.charCodeAt(D+2)]>>2,v[R++]=255&C>>8,v[R++]=255&C),v}function u(E){return p[63&E>>18]+p[63&E>>12]+p[63&E>>6]+p[63&E]}function g(E,C,D){for(var m,k=[],A=C;AR?R:v+A));return m===1?(C=E[D-1],k.push(p[C>>2]+p[63&C<<4]+"==")):m===2&&(C=(E[D-2]<<8)+E[D-1],k.push(p[C>>10]+p[63&C>>4]+p[63&C<<2]+"=")),k.join("")}h.byteLength=function(E){var C=l(E),D=C[0],m=C[1];return 3*(D+m)/4-m},h.toByteArray=w,h.fromByteArray=f;for(var p=[],S=[],M=typeof Uint8Array=="undefined"?Array:Uint8Array,x="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",F=0,b=x.length;Fr)throw new RangeError('The value "'+r+'" is invalid for option "size"')}function p(r,a,d){return f(r),0>=r||a===void 0?w(r):typeof d=="string"?w(r).fill(a,d):w(r).fill(a)}function S(r){return f(r),w(0>r?0:0|E(r))}function M(r,a){if((typeof a!="string"||a==="")&&(a="utf8"),!u.isEncoding(a))throw new TypeError("Unknown encoding: "+a);var d=0|C(r,a),T=w(d),I=T.write(r,a);return I!==d&&(T=T.slice(0,I)),T}function x(r){for(var a=0>r.length?0:0|E(r.length),d=w(a),T=0;Ta||r.byteLength=2147483647)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+2147483647 .toString(16)+" bytes");return 0|r}function C(r,a){if(u.isBuffer(r))return r.length;if(ArrayBuffer.isView(r)||L(r,ArrayBuffer))return r.byteLength;if(typeof r!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof r);var d=r.length,T=2>>1;case"base64":return Dt(r).length;default:if(I)return T?-1:ce(r).length;a=(""+a).toLowerCase(),I=!0}}function D(r,a,d){var T=!1;if((a===void 0||0>a)&&(a=0),a>this.length||((d===void 0||d>this.length)&&(d=this.length),0>=d)||(d>>>=0,a>>>=0,d<=a))return"";for(r||(r="utf8");;)switch(r){case"hex":return Tt(this,a,d);case"utf8":case"utf-8":return et(this,a,d);case"ascii":return Y(this,a,d);case"latin1":case"binary":return Re(this,a,d);case"base64":return J(this,a,d);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Gt(this,a,d);default:if(T)throw new TypeError("Unknown encoding: "+r);r=(r+"").toLowerCase(),T=!0}}function m(r,a,d){var T=r[a];r[a]=r[d],r[d]=T}function k(r,a,d,T,I){if(r.length===0)return-1;if(typeof d=="string"?(T=d,d=0):2147483647d&&(d=-2147483648),d=+d,N(d)&&(d=I?0:r.length-1),0>d&&(d=r.length+d),d>=r.length){if(I)return-1;d=r.length-1}else if(0>d)if(I)d=0;else return-1;if(typeof a=="string"&&(a=u.from(a,T)),u.isBuffer(a))return a.length===0?-1:A(r,a,d,T,I);if(typeof a=="number")return a&=255,typeof Uint8Array.prototype.indexOf=="function"?I?Uint8Array.prototype.indexOf.call(r,a,d):Uint8Array.prototype.lastIndexOf.call(r,a,d):A(r,[a],d,T,I);throw new TypeError("val must be string, number or Buffer")}function A(r,a,d,T,I){function U(Te,ze){return j===1?Te[ze]:Te.readUInt16BE(ze*j)}var j=1,Z=r.length,it=a.length;if(T!==void 0&&(T=(T+"").toLowerCase(),T==="ucs2"||T==="ucs-2"||T==="utf16le"||T==="utf-16le")){if(2>r.length||2>a.length)return-1;j=2,Z/=2,it/=2,d/=2}var Q;if(I){var X=-1;for(Q=d;QZ&&(d=Z-it),Q=d;0<=Q;Q--){for(var mt=!0,he=0;heI&&(T=I)):T=I;var U=a.length;T>U/2&&(T=U/2);for(var j,Z=0;ZU&&(j=U):Z===2?(it=r[I+1],(192&it)==128&&(mt=(31&U)<<6|63&it,127mt||57343mt&&(j=mt)))}j===null?(j=65533,Z=1):65535>>10),j=56320|1023&j),T.push(j),I+=Z}return ot(T)}function ot(r){var a=r.length;if(a<=4096)return l.apply(String,r);for(var d="",T=0;Ta)&&(a=0),(!d||0>d||d>T)&&(d=T);for(var I="",U=a;Ur)throw new RangeError("offset is not uint");if(r+a>d)throw new RangeError("Trying to access beyond buffer length")}function nt(r,a,d,T,I,U){if(!u.isBuffer(r))throw new TypeError('"buffer" argument must be a Buffer instance');if(a>I||ar.length)throw new RangeError("Index out of range")}function At(r,a,d,T){if(d+T>r.length)throw new RangeError("Index out of range");if(0>d)throw new RangeError("Index out of range")}function Jt(r,a,d,T,I){return a=+a,d>>>=0,I||At(r,a,d,4),V.write(r,a,d,T,23,4),d+4}function Kt(r,a,d,T,I){return a=+a,d>>>=0,I||At(r,a,d,8),V.write(r,a,d,T,52,8),d+8}function $e(r){if(r=r.split("=")[0],r=r.trim().replace(_,""),2>r.length)return"";for(;r.length%4!=0;)r+="=";return r}function le(r){return 16>r?"0"+r.toString(16):r.toString(16)}function ce(r,a){a=a||1/0;for(var d,T=r.length,I=null,U=[],j=0;jd){if(!I){if(56319d){-1<(a-=3)&&U.push(239,191,189),I=d;continue}d=(I-55296<<10|d-56320)+65536}else I&&-1<(a-=3)&&U.push(239,191,189);if(I=null,128>d){if(0>(a-=1))break;U.push(d)}else if(2048>d){if(0>(a-=2))break;U.push(192|d>>6,128|63&d)}else if(65536>d){if(0>(a-=3))break;U.push(224|d>>12,128|63&d>>6,128|63&d)}else if(1114112>d){if(0>(a-=4))break;U.push(240|d>>18,128|63&d>>12,128|63&d>>6,128|63&d)}else throw new Error("Invalid code point")}return U}function Ye(r){for(var a=[],d=0;d(a-=2));++j)d=r.charCodeAt(j),T=d>>8,I=d%256,U.push(I),U.push(T);return U}function Dt(r){return B.toByteArray($e(r))}function It(r,a,d,T){for(var I=0;I=a.length||I>=r.length);++I)a[I+d]=r[I];return I}function L(r,a){return r instanceof a||r!=null&&r.constructor!=null&&r.constructor.name!=null&&r.constructor.name===a.name}function N(r){return r!==r}var B=o("base64-js"),V=o("ieee754");h.Buffer=u,h.SlowBuffer=function(r){return+r!=r&&(r=0),u.alloc(+r)},h.INSPECT_MAX_BYTES=50,h.kMaxLength=2147483647,u.TYPED_ARRAY_SUPPORT=function(){try{var r=new Uint8Array(1);return r.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},r.foo()===42}catch{return!1}}(),u.TYPED_ARRAY_SUPPORT||typeof console=="undefined"||typeof console.error!="function"||console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."),Object.defineProperty(u.prototype,"parent",{enumerable:!0,get:function(){return u.isBuffer(this)?this.buffer:void 0}}),Object.defineProperty(u.prototype,"offset",{enumerable:!0,get:function(){return u.isBuffer(this)?this.byteOffset:void 0}}),typeof Symbol!="undefined"&&Symbol.species!=null&&u[Symbol.species]===u&&Object.defineProperty(u,Symbol.species,{value:null,configurable:!0,enumerable:!1,writable:!1}),u.poolSize=8192,u.from=function(r,a,d){return g(r,a,d)},u.prototype.__proto__=Uint8Array.prototype,u.__proto__=Uint8Array,u.alloc=function(r,a,d){return p(r,a,d)},u.allocUnsafe=function(r){return S(r)},u.allocUnsafeSlow=function(r){return S(r)},u.isBuffer=function(r){return r!=null&&r._isBuffer===!0&&r!==u.prototype},u.compare=function(r,a){if(L(r,Uint8Array)&&(r=u.from(r,r.offset,r.byteLength)),L(a,Uint8Array)&&(a=u.from(a,a.offset,a.byteLength)),!u.isBuffer(r)||!u.isBuffer(a))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(r===a)return 0;for(var d=r.length,T=a.length,I=0,U=y(d,T);Ia&&(r+=" ... "),""},u.prototype.compare=function(r,a,d,T,I){if(L(r,Uint8Array)&&(r=u.from(r,r.offset,r.byteLength)),!u.isBuffer(r))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof r);if(a===void 0&&(a=0),d===void 0&&(d=r?r.length:0),T===void 0&&(T=0),I===void 0&&(I=this.length),0>a||d>r.length||0>T||I>this.length)throw new RangeError("out of range index");if(T>=I&&a>=d)return 0;if(T>=I)return-1;if(a>=d)return 1;if(a>>>=0,d>>>=0,T>>>=0,I>>>=0,this===r)return 0;for(var U=I-T,j=d-a,Z=y(U,j),it=this.slice(T,I),Q=r.slice(a,d),X=0;X>>=0,isFinite(d)?(d>>>=0,T===void 0&&(T="utf8")):(T=d,d=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");var I=this.length-a;if((d===void 0||d>I)&&(d=I),0d||0>a)||a>this.length)throw new RangeError("Attempt to write outside buffer bounds");T||(T="utf8");for(var U=!1;;)switch(T){case"hex":return v(this,r,a,d);case"utf8":case"utf-8":return R(this,r,a,d);case"ascii":return O(this,r,a,d);case"latin1":case"binary":return P(this,r,a,d);case"base64":return W(this,r,a,d);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return z(this,r,a,d);default:if(U)throw new TypeError("Unknown encoding: "+T);T=(""+T).toLowerCase(),U=!0}},u.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}},u.prototype.slice=function(r,a){var d=this.length;r=~~r,a=a===void 0?d:~~a,0>r?(r+=d,0>r&&(r=0)):r>d&&(r=d),0>a?(a+=d,0>a&&(a=0)):a>d&&(a=d),a>>=0,a>>>=0,d||at(r,a,this.length);for(var T=this[r],I=1,U=0;++U>>=0,a>>>=0,d||at(r,a,this.length);for(var T=this[r+--a],I=1;0>>=0,a||at(r,1,this.length),this[r]},u.prototype.readUInt16LE=function(r,a){return r>>>=0,a||at(r,2,this.length),this[r]|this[r+1]<<8},u.prototype.readUInt16BE=function(r,a){return r>>>=0,a||at(r,2,this.length),this[r]<<8|this[r+1]},u.prototype.readUInt32LE=function(r,a){return r>>>=0,a||at(r,4,this.length),(this[r]|this[r+1]<<8|this[r+2]<<16)+16777216*this[r+3]},u.prototype.readUInt32BE=function(r,a){return r>>>=0,a||at(r,4,this.length),16777216*this[r]+(this[r+1]<<16|this[r+2]<<8|this[r+3])},u.prototype.readIntLE=function(r,a,d){r>>>=0,a>>>=0,d||at(r,a,this.length);for(var T=this[r],I=1,U=0;++U=I&&(T-=s(2,8*a)),T},u.prototype.readIntBE=function(r,a,d){r>>>=0,a>>>=0,d||at(r,a,this.length);for(var T=a,I=1,U=this[r+--T];0=I&&(U-=s(2,8*a)),U},u.prototype.readInt8=function(r,a){return r>>>=0,a||at(r,1,this.length),128&this[r]?-1*(255-this[r]+1):this[r]},u.prototype.readInt16LE=function(r,a){r>>>=0,a||at(r,2,this.length);var d=this[r]|this[r+1]<<8;return 32768&d?4294901760|d:d},u.prototype.readInt16BE=function(r,a){r>>>=0,a||at(r,2,this.length);var d=this[r+1]|this[r]<<8;return 32768&d?4294901760|d:d},u.prototype.readInt32LE=function(r,a){return r>>>=0,a||at(r,4,this.length),this[r]|this[r+1]<<8|this[r+2]<<16|this[r+3]<<24},u.prototype.readInt32BE=function(r,a){return r>>>=0,a||at(r,4,this.length),this[r]<<24|this[r+1]<<16|this[r+2]<<8|this[r+3]},u.prototype.readFloatLE=function(r,a){return r>>>=0,a||at(r,4,this.length),V.read(this,r,!0,23,4)},u.prototype.readFloatBE=function(r,a){return r>>>=0,a||at(r,4,this.length),V.read(this,r,!1,23,4)},u.prototype.readDoubleLE=function(r,a){return r>>>=0,a||at(r,8,this.length),V.read(this,r,!0,52,8)},u.prototype.readDoubleBE=function(r,a){return r>>>=0,a||at(r,8,this.length),V.read(this,r,!1,52,8)},u.prototype.writeUIntLE=function(r,a,d,T){if(r=+r,a>>>=0,d>>>=0,!T){var I=s(2,8*d)-1;nt(this,r,a,d,I,0)}var U=1,j=0;for(this[a]=255&r;++j>>=0,d>>>=0,!T){var I=s(2,8*d)-1;nt(this,r,a,d,I,0)}var U=d-1,j=1;for(this[a+U]=255&r;0<=--U&&(j*=256);)this[a+U]=255&r/j;return a+d},u.prototype.writeUInt8=function(r,a,d){return r=+r,a>>>=0,d||nt(this,r,a,1,255,0),this[a]=255&r,a+1},u.prototype.writeUInt16LE=function(r,a,d){return r=+r,a>>>=0,d||nt(this,r,a,2,65535,0),this[a]=255&r,this[a+1]=r>>>8,a+2},u.prototype.writeUInt16BE=function(r,a,d){return r=+r,a>>>=0,d||nt(this,r,a,2,65535,0),this[a]=r>>>8,this[a+1]=255&r,a+2},u.prototype.writeUInt32LE=function(r,a,d){return r=+r,a>>>=0,d||nt(this,r,a,4,4294967295,0),this[a+3]=r>>>24,this[a+2]=r>>>16,this[a+1]=r>>>8,this[a]=255&r,a+4},u.prototype.writeUInt32BE=function(r,a,d){return r=+r,a>>>=0,d||nt(this,r,a,4,4294967295,0),this[a]=r>>>24,this[a+1]=r>>>16,this[a+2]=r>>>8,this[a+3]=255&r,a+4},u.prototype.writeIntLE=function(r,a,d,T){if(r=+r,a>>>=0,!T){var I=s(2,8*d-1);nt(this,r,a,d,I-1,-I)}var U=0,j=1,Z=0;for(this[a]=255&r;++Ur&&Z===0&&this[a+U-1]!==0&&(Z=1),this[a+U]=255&(r/j>>0)-Z;return a+d},u.prototype.writeIntBE=function(r,a,d,T){if(r=+r,a>>>=0,!T){var I=s(2,8*d-1);nt(this,r,a,d,I-1,-I)}var U=d-1,j=1,Z=0;for(this[a+U]=255&r;0<=--U&&(j*=256);)0>r&&Z===0&&this[a+U+1]!==0&&(Z=1),this[a+U]=255&(r/j>>0)-Z;return a+d},u.prototype.writeInt8=function(r,a,d){return r=+r,a>>>=0,d||nt(this,r,a,1,127,-128),0>r&&(r=255+r+1),this[a]=255&r,a+1},u.prototype.writeInt16LE=function(r,a,d){return r=+r,a>>>=0,d||nt(this,r,a,2,32767,-32768),this[a]=255&r,this[a+1]=r>>>8,a+2},u.prototype.writeInt16BE=function(r,a,d){return r=+r,a>>>=0,d||nt(this,r,a,2,32767,-32768),this[a]=r>>>8,this[a+1]=255&r,a+2},u.prototype.writeInt32LE=function(r,a,d){return r=+r,a>>>=0,d||nt(this,r,a,4,2147483647,-2147483648),this[a]=255&r,this[a+1]=r>>>8,this[a+2]=r>>>16,this[a+3]=r>>>24,a+4},u.prototype.writeInt32BE=function(r,a,d){return r=+r,a>>>=0,d||nt(this,r,a,4,2147483647,-2147483648),0>r&&(r=4294967295+r+1),this[a]=r>>>24,this[a+1]=r>>>16,this[a+2]=r>>>8,this[a+3]=255&r,a+4},u.prototype.writeFloatLE=function(r,a,d){return Jt(this,r,a,!0,d)},u.prototype.writeFloatBE=function(r,a,d){return Jt(this,r,a,!1,d)},u.prototype.writeDoubleLE=function(r,a,d){return Kt(this,r,a,!0,d)},u.prototype.writeDoubleBE=function(r,a,d){return Kt(this,r,a,!1,d)},u.prototype.copy=function(r,a,d,T){if(!u.isBuffer(r))throw new TypeError("argument should be a Buffer");if(d||(d=0),T||T===0||(T=this.length),a>=r.length&&(a=r.length),a||(a=0),0a)throw new RangeError("targetStart out of bounds");if(0>d||d>=this.length)throw new RangeError("Index out of range");if(0>T)throw new RangeError("sourceEnd out of bounds");T>this.length&&(T=this.length),r.length-aI||T==="latin1")&&(r=I)}}else typeof r=="number"&&(r&=255);if(0>a||this.length>>=0,d=d===void 0?this.length:d>>>0,r||(r=0);var U;if(typeof r=="number")for(U=a;U{S==="%%"||(f++,S==="%c"&&(p=f))}),u.splice(p,0,g)},h.save=function(u){try{u?h.storage.setItem("debug",u):h.storage.removeItem("debug")}catch{}},h.load=y,h.useColors=function(){return!!(typeof window!="undefined"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))||!(typeof navigator!="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))&&(typeof document!="undefined"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window!="undefined"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator!="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&31<=parseInt(RegExp.$1,10)||typeof navigator!="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))},h.storage=function(){try{return localStorage}catch{}}(),h.destroy=(()=>{let u=!1;return()=>{u||(u=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),h.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],h.log=console.debug||console.log||(()=>{}),c.exports=o("./common")(h);const{formatters:w}=c.exports;w.j=function(u){try{return JSON.stringify(u)}catch(g){return"[UnexpectedJSONParseError]: "+g.message}}}).call(this)}).call(this,o("_process"))},{"./common":5,_process:12}],5:[function(o,c){c.exports=function(h){function l(u){function g(...S){if(!g.enabled)return;const M=g,x=+new Date,F=x-(f||x);M.diff=F,M.prev=f,M.curr=x,f=x,S[0]=l.coerce(S[0]),typeof S[0]!="string"&&S.unshift("%O");let b=0;S[0]=S[0].replace(/%([a-zA-Z%])/g,(C,D)=>{if(C==="%%")return"%";b++;const m=l.formatters[D];if(typeof m=="function"){const k=S[b];C=m.call(M,k),S.splice(b,1),b--}return C}),l.formatArgs.call(M,S),(M.log||l.log).apply(M,S)}let f,p=null;return g.namespace=u,g.useColors=l.useColors(),g.color=l.selectColor(u),g.extend=y,g.destroy=l.destroy,Object.defineProperty(g,"enabled",{enumerable:!0,configurable:!1,get:()=>p===null?l.enabled(u):p,set:S=>{p=S}}),typeof l.init=="function"&&l.init(g),g}function y(u,g){const f=l(this.namespace+(typeof g=="undefined"?":":g)+u);return f.log=this.log,f}function w(u){return u.toString().substring(2,u.toString().length-2).replace(/\.\*\?$/,"*")}return l.debug=l,l.default=l,l.coerce=function(u){return u instanceof Error?u.stack||u.message:u},l.disable=function(){const u=[...l.names.map(w),...l.skips.map(w).map(g=>"-"+g)].join(",");return l.enable(""),u},l.enable=function(u){l.save(u),l.names=[],l.skips=[];let g;const f=(typeof u=="string"?u:"").split(/[\s,]+/),p=f.length;for(g=0;g{l[u]=h[u]}),l.names=[],l.skips=[],l.formatters={},l.selectColor=function(u){let g=0;for(let f=0;fW&&!J.warned){J.warned=!0;var et=new Error("Possible EventEmitter memory leak detected. "+J.length+" "+(R+" listeners added. Use emitter.setMaxListeners() to increase limit"));et.name="MaxListenersExceededWarning",et.emitter=v,et.type=R,et.count=J.length,h(et)}return v}function g(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function f(v,R,O){var P={fired:!1,wrapFn:void 0,target:v,type:R,listener:O},W=g.bind(P);return W.listener=O,P.wrapFn=W,W}function p(v,R,O){var P=v._events;if(P===void 0)return[];var W=P[R];return W===void 0?[]:typeof W=="function"?O?[W.listener||W]:[W]:O?F(W):M(W,W.length)}function S(v){var R=this._events;if(R!==void 0){var O=R[v];if(typeof O=="function")return 1;if(O!==void 0)return O.length}return 0}function M(v,R){for(var O=Array(R),P=0;Pv||k(v))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+v+".");A=v}}),l.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},l.prototype.setMaxListeners=function(v){if(typeof v!="number"||0>v||k(v))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+v+".");return this._maxListeners=v,this},l.prototype.getMaxListeners=function(){return w(this)},l.prototype.emit=function(v){for(var R=[],O=1;OW)return this;W===0?O.shift():x(O,W),O.length===1&&(P[v]=O[0]),P.removeListener!==void 0&&this.emit("removeListener",v,J||R)}return this},l.prototype.off=l.prototype.removeListener,l.prototype.removeAllListeners=function(v){var R,O,P;if(O=this._events,O===void 0)return this;if(O.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):O[v]!==void 0&&(--this._eventsCount==0?this._events=Object.create(null):delete O[v]),this;if(arguments.length===0){var W,z=Object.keys(O);for(P=0;P */h.read=function(l,y,w,u,g){var f,p,S=8*g-u-1,M=(1<>1,F=-7,b=w?g-1:0,E=w?-1:1,C=l[y+b];for(b+=E,f=C&(1<<-F)-1,C>>=-F,F+=S;0>=-F,F+=u;0>1,D=g===23?s(2,-24)-s(2,-77):0,m=u?0:f-1,k=u?1:-1,A=0>y||y===0&&0>1/y?1:0;for(y=i(y),isNaN(y)||y===1/0?(S=isNaN(y)?1:0,p=E):(p=n(F(y)/x),1>y*(M=s(2,-p))&&(p--,M*=2),y+=1<=p+C?D/M:D*s(2,1-C),2<=y*M&&(p++,M/=2),p+C>=E?(S=0,p=E):1<=p+C?(S=(y*M-1)*s(2,g),p+=C):(S=y*s(2,C-1)*s(2,g),p=0));8<=g;l[w+m]=255&S,m+=k,S/=256,g-=8);for(p=p<=1.5*p?"s":"")}c.exports=function(g,f){f=f||{};var p=typeof g;if(p=="string"&&0 */let l;c.exports=typeof queueMicrotask=="function"?queueMicrotask.bind(typeof window=="undefined"?h:window):y=>(l||(l=Promise.resolve())).then(y).catch(w=>setTimeout(()=>{throw w},0))}).call(this)}).call(this,typeof kt=="undefined"?typeof self=="undefined"?typeof window=="undefined"?{}:window:self:kt)},{}],14:[function(o,c){(function(h,l){(function(){var y=o("safe-buffer").Buffer,w=l.crypto||l.msCrypto;c.exports=w&&w.getRandomValues?function(u,g){if(u>4294967295)throw new RangeError("requested too many random bytes");var f=y.allocUnsafe(u);if(0M?0:+M,S.length)===S}function u(p,S,M){return(M===void 0||M>p.length)&&(M=p.length),p.substring(M-S.length,M)===S}function g(p,S,M){return typeof M!="number"&&(M=0),!(M+S.length>p.length)&&p.indexOf(S,M)!==-1}var f={};l("ERR_INVALID_OPT_VALUE",function(p,S){return'The value "'+S+'" is invalid for option "'+p+'"'},TypeError),l("ERR_INVALID_ARG_TYPE",function(p,S,M){var x;typeof S=="string"&&w(S,"not ")?(x="must not be",S=S.replace(/^not /,"")):x="must be";var F;if(u(p," argument"))F="The ".concat(p," ").concat(x," ").concat(y(S,"type"));else{var b=g(p,".")?"property":"argument";F='The "'.concat(p,'" ').concat(b," ").concat(x," ").concat(y(S,"type"))}return F+=". Received type ".concat(typeof M),F},TypeError),l("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),l("ERR_METHOD_NOT_IMPLEMENTED",function(p){return"The "+p+" method is not implemented"}),l("ERR_STREAM_PREMATURE_CLOSE","Premature close"),l("ERR_STREAM_DESTROYED",function(p){return"Cannot call "+p+" after a stream was destroyed"}),l("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),l("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),l("ERR_STREAM_WRITE_AFTER_END","write after end"),l("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),l("ERR_UNKNOWN_ENCODING",function(p){return"Unknown encoding: "+p},TypeError),l("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),c.exports.codes=f},{}],16:[function(o,c){(function(h){(function(){function l(x){return this instanceof l?(g.call(this,x),f.call(this,x),this.allowHalfOpen=!0,void(x&&(x.readable===!1&&(this.readable=!1),x.writable===!1&&(this.writable=!1),x.allowHalfOpen===!1&&(this.allowHalfOpen=!1,this.once("end",y))))):new l(x)}function y(){this._writableState.ended||h.nextTick(w,this)}function w(x){x.end()}var u=Object.keys||function(x){var F=[];for(var b in x)F.push(b);return F};c.exports=l;var g=o("./_stream_readable"),f=o("./_stream_writable");o("inherits")(l,g);for(var p,S=u(f.prototype),M=0;M>>1,_|=_>>>2,_|=_>>>4,_|=_>>>8,_|=_>>>16,_++),_}function F(_,r){return 0>=_||r.length===0&&r.ended?0:r.objectMode?1:_===_?(_>r.highWaterMark&&(r.highWaterMark=x(_)),_<=r.length?_:r.ended?r.length:(r.needReadable=!0,0)):r.flowing&&r.length?r.buffer.head.data.length:r.length}function b(_,r){if(Y("onEofChunk"),!r.ended){if(r.decoder){var a=r.decoder.end();a&&a.length&&(r.buffer.push(a),r.length+=r.objectMode?1:a.length)}r.ended=!0,r.sync?E(_):(r.needReadable=!1,!r.emittedReadable&&(r.emittedReadable=!0,C(_)))}}function E(_){var r=_._readableState;Y("emitReadable",r.needReadable,r.emittedReadable),r.needReadable=!1,r.emittedReadable||(Y("emitReadable",r.flowing),r.emittedReadable=!0,h.nextTick(C,_))}function C(_){var r=_._readableState;Y("emitReadable_",r.destroyed,r.length,r.ended),!r.destroyed&&(r.length||r.ended)&&(_.emit("readable"),r.emittedReadable=!1),r.needReadable=!r.flowing&&!r.ended&&r.length<=r.highWaterMark,P(_)}function D(_,r){r.readingMore||(r.readingMore=!0,h.nextTick(m,_,r))}function m(_,r){for(;!r.reading&&!r.ended&&(r.length=r.length?(a=r.decoder?r.buffer.join(""):r.buffer.length===1?r.buffer.first():r.buffer.concat(r.length),r.buffer.clear()):a=r.buffer.consume(_,r.decoder),a}function z(_){var r=_._readableState;Y("endReadable",r.endEmitted),r.endEmitted||(r.ended=!0,h.nextTick(J,r,_))}function J(_,r){if(Y("endReadableNT",_.endEmitted,_.length),!_.endEmitted&&_.length===0&&(_.endEmitted=!0,r.readable=!1,r.emit("end"),_.autoDestroy)){var a=r._writableState;(!a||a.autoDestroy&&a.finished)&&r.destroy()}}function et(_,r){for(var a=0,d=_.length;a=r.highWaterMark)||r.ended))return Y("read: emitReadable",r.length,r.ended),r.length===0&&r.ended?z(this):E(this),null;if(_=F(_,r),_===0&&r.ended)return r.length===0&&z(this),null;var d=r.needReadable;Y("need readable",d),(r.length===0||r.length-_>>0),D=this.head,m=0;D;)f(D.data,C,m),m+=D.data.length,D=D.next;return C}},{key:"consume",value:function(E,C){var D;return Ek.length?k.length:E;if(m+=A===k.length?k:k.slice(0,E),E-=A,E===0){A===k.length?(++D,this.head=C.next?C.next:this.tail=null):(this.head=C,C.data=k.slice(A));break}++D}return this.length-=D,m}},{key:"_getBuffer",value:function(E){var C=S.allocUnsafe(E),D=this.head,m=1;for(D.data.copy(C),E-=D.data.length;D=D.next;){var k=D.data,A=E>k.length?k.length:E;if(k.copy(C,C.length-E,0,A),E-=A,E===0){A===k.length?(++m,this.head=D.next?D.next:this.tail=null):(this.head=D,D.data=k.slice(A));break}++m}return this.length-=m,C}},{key:F,value:function(E,C){return x(this,l({},C,{depth:0,customInspect:!1}))}}]),b}()},{buffer:3,util:2}],23:[function(o,c){(function(h){(function(){function l(u,g){w(u,g),y(u)}function y(u){u._writableState&&!u._writableState.emitClose||u._readableState&&!u._readableState.emitClose||u.emit("close")}function w(u,g){u.emit("error",g)}c.exports={destroy:function(u,g){var f=this,p=this._readableState&&this._readableState.destroyed,S=this._writableState&&this._writableState.destroyed;return p||S?(g?g(u):u&&(this._writableState?!this._writableState.errorEmitted&&(this._writableState.errorEmitted=!0,h.nextTick(w,this,u)):h.nextTick(w,this,u)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(u||null,function(M){!g&&M?f._writableState?f._writableState.errorEmitted?h.nextTick(y,f):(f._writableState.errorEmitted=!0,h.nextTick(l,f,M)):h.nextTick(l,f,M):g?(h.nextTick(y,f),g(M)):h.nextTick(y,f)}),this)},undestroy:function(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)},errorOrDestroy:function(u,g){var f=u._readableState,p=u._writableState;f&&f.autoDestroy||p&&p.autoDestroy?u.destroy(g):u.emit("error",g)}}}).call(this)}).call(this,o("_process"))},{_process:12}],24:[function(o,c){function h(g){var f=!1;return function(){if(!f){f=!0;for(var p=arguments.length,S=Array(p),M=0;Mb.length)throw new M("streams");var D,m=b.map(function(k,A){var v=Af){var p=g?u:"highWaterMark";throw new l(p,f)}return n(f)}return y.objectMode?16:16384}}},{"../../../errors":15}],28:[function(o,c){c.exports=o("events").EventEmitter},{events:7}],29:[function(o,c,h){h=c.exports=o("./lib/_stream_readable.js"),h.Stream=h,h.Readable=h,h.Writable=o("./lib/_stream_writable.js"),h.Duplex=o("./lib/_stream_duplex.js"),h.Transform=o("./lib/_stream_transform.js"),h.PassThrough=o("./lib/_stream_passthrough.js"),h.finished=o("./lib/internal/streams/end-of-stream.js"),h.pipeline=o("./lib/internal/streams/pipeline.js")},{"./lib/_stream_duplex.js":16,"./lib/_stream_passthrough.js":17,"./lib/_stream_readable.js":18,"./lib/_stream_transform.js":19,"./lib/_stream_writable.js":20,"./lib/internal/streams/end-of-stream.js":24,"./lib/internal/streams/pipeline.js":26}],30:[function(o,c,h){function l(g,f){for(var p in g)f[p]=g[p]}function y(g,f,p){return u(g,f,p)}/*! safe-buffer. MIT License. Feross Aboukhadijeh */var w=o("buffer"),u=w.Buffer;u.from&&u.alloc&&u.allocUnsafe&&u.allocUnsafeSlow?c.exports=w:(l(w,h),h.Buffer=y),y.prototype=Object.create(u.prototype),l(u,y),y.from=function(g,f,p){if(typeof g=="number")throw new TypeError("Argument must not be a number");return u(g,f,p)},y.alloc=function(g,f,p){if(typeof g!="number")throw new TypeError("Argument must be a number");var S=u(g);return f===void 0?S.fill(0):typeof p=="string"?S.fill(f,p):S.fill(f),S},y.allocUnsafe=function(g){if(typeof g!="number")throw new TypeError("Argument must be a number");return u(g)},y.allocUnsafeSlow=function(g){if(typeof g!="number")throw new TypeError("Argument must be a number");return w.SlowBuffer(g)}},{buffer:3}],31:[function(o,c,h){function l(m){if(!m)return"utf8";for(var k;;)switch(m){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return m;default:if(k)return;m=(""+m).toLowerCase(),k=!0}}function y(m){var k=l(m);if(typeof k!="string"&&(C.isEncoding===D||!D(m)))throw new Error("Unknown encoding: "+m);return k||m}function w(m){this.encoding=y(m);var k;switch(this.encoding){case"utf16le":this.text=S,this.end=M,k=4;break;case"utf8":this.fillLast=p,k=4;break;case"base64":this.text=x,this.end=F,k=3;break;default:return this.write=b,void(this.end=E)}this.lastNeed=0,this.lastTotal=0,this.lastChar=C.allocUnsafe(k)}function u(m){return 127>=m?0:m>>5==6?2:m>>4==14?3:m>>3==30?4:m>>6==2?-1:-2}function g(m,k,A){var v=k.length-1;if(v=v)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=m[m.length-2],this.lastChar[1]=m[m.length-1],A.slice(0,-1)}return A}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=m[m.length-1],m.toString("utf16le",k,m.length-1)}function M(m){var k=m&&m.length?this.write(m):"";if(this.lastNeed){var A=this.lastTotal-this.lastNeed;return k+this.lastChar.toString("utf16le",0,A)}return k}function x(m,k){var A=(m.length-k)%3;return A==0?m.toString("base64",k):(this.lastNeed=3-A,this.lastTotal=3,A==1?this.lastChar[0]=m[m.length-1]:(this.lastChar[0]=m[m.length-2],this.lastChar[1]=m[m.length-1]),m.toString("base64",k,m.length-A))}function F(m){var k=m&&m.length?this.write(m):"";return this.lastNeed?k+this.lastChar.toString("base64",0,3-this.lastNeed):k}function b(m){return m.toString(this.encoding)}function E(m){return m&&m.length?this.write(m):""}var C=o("safe-buffer").Buffer,D=C.isEncoding||function(m){switch(m=""+m,m&&m.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};h.StringDecoder=w,w.prototype.write=function(m){if(m.length===0)return"";var k,A;if(this.lastNeed){if(k=this.fillLast(m),k===void 0)return"";A=this.lastNeed,this.lastNeed=0}else A=0;return A */const y=o("debug")("simple-peer"),w=o("get-browser-rtc"),u=o("randombytes"),g=o("readable-stream"),f=o("queue-microtask"),p=o("err-code"),{Buffer:S}=o("buffer"),M=65536;class x extends g.Duplex{constructor(b){if(b=Object.assign({allowHalfOpen:!1},b),super(b),this._id=u(4).toString("hex").slice(0,7),this._debug("new peer %o",b),this.channelName=b.initiator?b.channelName||u(20).toString("hex"):null,this.initiator=b.initiator||!1,this.channelConfig=b.channelConfig||x.channelConfig,this.channelNegotiated=this.channelConfig.negotiated,this.config=Object.assign({},x.config,b.config),this.offerOptions=b.offerOptions||{},this.answerOptions=b.answerOptions||{},this.sdpTransform=b.sdpTransform||(E=>E),this.streams=b.streams||(b.stream?[b.stream]:[]),this.trickle=b.trickle===void 0||b.trickle,this.allowHalfTrickle=b.allowHalfTrickle!==void 0&&b.allowHalfTrickle,this.iceCompleteTimeout=b.iceCompleteTimeout||5e3,this.destroyed=!1,this.destroying=!1,this._connected=!1,this.remoteAddress=void 0,this.remoteFamily=void 0,this.remotePort=void 0,this.localAddress=void 0,this.localFamily=void 0,this.localPort=void 0,this._wrtc=b.wrtc&&typeof b.wrtc=="object"?b.wrtc:w(),!this._wrtc)throw p(typeof window=="undefined"?new Error("No WebRTC support: Specify `opts.wrtc` option in this environment"):new Error("No WebRTC support: Not a supported browser"),"ERR_WEBRTC_SUPPORT");this._pcReady=!1,this._channelReady=!1,this._iceComplete=!1,this._iceCompleteTimer=null,this._channel=null,this._pendingCandidates=[],this._isNegotiating=!1,this._firstNegotiation=!0,this._batchedNegotiation=!1,this._queuedNegotiation=!1,this._sendersAwaitingStable=[],this._senderMap=new Map,this._closingInterval=null,this._remoteTracks=[],this._remoteStreams=[],this._chunk=null,this._cb=null,this._interval=null;try{this._pc=new this._wrtc.RTCPeerConnection(this.config)}catch(E){return void this.destroy(p(E,"ERR_PC_CONSTRUCTOR"))}this._isReactNativeWebrtc=typeof this._pc._peerConnectionId=="number",this._pc.oniceconnectionstatechange=()=>{this._onIceStateChange()},this._pc.onicegatheringstatechange=()=>{this._onIceStateChange()},this._pc.onconnectionstatechange=()=>{this._onConnectionStateChange()},this._pc.onsignalingstatechange=()=>{this._onSignalingStateChange()},this._pc.onicecandidate=E=>{this._onIceCandidate(E)},typeof this._pc.peerIdentity=="object"&&this._pc.peerIdentity.catch(E=>{this.destroy(p(E,"ERR_PC_PEER_IDENTITY"))}),this.initiator||this.channelNegotiated?this._setupData({channel:this._pc.createDataChannel(this.channelName,this.channelConfig)}):this._pc.ondatachannel=E=>{this._setupData(E)},this.streams&&this.streams.forEach(E=>{this.addStream(E)}),this._pc.ontrack=E=>{this._onTrack(E)},this._debug("initial negotiation"),this._needsNegotiation(),this._onFinishBound=()=>{this._onFinish()},this.once("finish",this._onFinishBound)}get bufferSize(){return this._channel&&this._channel.bufferedAmount||0}get connected(){return this._connected&&this._channel.readyState==="open"}address(){return{port:this.localPort,family:this.localFamily,address:this.localAddress}}signal(b){if(!this.destroying){if(this.destroyed)throw p(new Error("cannot signal after peer is destroyed"),"ERR_DESTROYED");if(typeof b=="string")try{b=JSON.parse(b)}catch{b={}}this._debug("signal()"),b.renegotiate&&this.initiator&&(this._debug("got request to renegotiate"),this._needsNegotiation()),b.transceiverRequest&&this.initiator&&(this._debug("got request for transceiver"),this.addTransceiver(b.transceiverRequest.kind,b.transceiverRequest.init)),b.candidate&&(this._pc.remoteDescription&&this._pc.remoteDescription.type?this._addIceCandidate(b.candidate):this._pendingCandidates.push(b.candidate)),b.sdp&&this._pc.setRemoteDescription(new this._wrtc.RTCSessionDescription(b)).then(()=>{this.destroyed||(this._pendingCandidates.forEach(E=>{this._addIceCandidate(E)}),this._pendingCandidates=[],this._pc.remoteDescription.type==="offer"&&this._createAnswer())}).catch(E=>{this.destroy(p(E,"ERR_SET_REMOTE_DESCRIPTION"))}),b.sdp||b.candidate||b.renegotiate||b.transceiverRequest||this.destroy(p(new Error("signal() called with invalid signal data"),"ERR_SIGNALING"))}}_addIceCandidate(b){const E=new this._wrtc.RTCIceCandidate(b);this._pc.addIceCandidate(E).catch(C=>{!E.address||E.address.endsWith(".local")?l("Ignoring unsupported ICE candidate."):this.destroy(p(C,"ERR_ADD_ICE_CANDIDATE"))})}send(b){if(!this.destroying){if(this.destroyed)throw p(new Error("cannot send after peer is destroyed"),"ERR_DESTROYED");this._channel.send(b)}}addTransceiver(b,E){if(!this.destroying){if(this.destroyed)throw p(new Error("cannot addTransceiver after peer is destroyed"),"ERR_DESTROYED");if(this._debug("addTransceiver()"),this.initiator)try{this._pc.addTransceiver(b,E),this._needsNegotiation()}catch(C){this.destroy(p(C,"ERR_ADD_TRANSCEIVER"))}else this.emit("signal",{type:"transceiverRequest",transceiverRequest:{kind:b,init:E}})}}addStream(b){if(!this.destroying){if(this.destroyed)throw p(new Error("cannot addStream after peer is destroyed"),"ERR_DESTROYED");this._debug("addStream()"),b.getTracks().forEach(E=>{this.addTrack(E,b)})}}addTrack(b,E){if(this.destroying)return;if(this.destroyed)throw p(new Error("cannot addTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("addTrack()");const C=this._senderMap.get(b)||new Map;let D=C.get(E);if(!D)D=this._pc.addTrack(b,E),C.set(E,D),this._senderMap.set(b,C),this._needsNegotiation();else throw D.removed?p(new Error("Track has been removed. You should enable/disable tracks that you want to re-add."),"ERR_SENDER_REMOVED"):p(new Error("Track has already been added to that stream."),"ERR_SENDER_ALREADY_ADDED")}replaceTrack(b,E,C){if(this.destroying)return;if(this.destroyed)throw p(new Error("cannot replaceTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("replaceTrack()");const D=this._senderMap.get(b),m=D?D.get(C):null;if(!m)throw p(new Error("Cannot replace track that was never added."),"ERR_TRACK_NOT_ADDED");E&&this._senderMap.set(E,D),m.replaceTrack==null?this.destroy(p(new Error("replaceTrack is not supported in this browser"),"ERR_UNSUPPORTED_REPLACETRACK")):m.replaceTrack(E)}removeTrack(b,E){if(this.destroying)return;if(this.destroyed)throw p(new Error("cannot removeTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("removeSender()");const C=this._senderMap.get(b),D=C?C.get(E):null;if(!D)throw p(new Error("Cannot remove track that was never added."),"ERR_TRACK_NOT_ADDED");try{D.removed=!0,this._pc.removeTrack(D)}catch(m){m.name==="NS_ERROR_UNEXPECTED"?this._sendersAwaitingStable.push(D):this.destroy(p(m,"ERR_REMOVE_TRACK"))}this._needsNegotiation()}removeStream(b){if(!this.destroying){if(this.destroyed)throw p(new Error("cannot removeStream after peer is destroyed"),"ERR_DESTROYED");this._debug("removeSenders()"),b.getTracks().forEach(E=>{this.removeTrack(E,b)})}}_needsNegotiation(){this._debug("_needsNegotiation"),this._batchedNegotiation||(this._batchedNegotiation=!0,f(()=>{this._batchedNegotiation=!1,this.initiator||!this._firstNegotiation?(this._debug("starting batched negotiation"),this.negotiate()):this._debug("non-initiator initial negotiation request discarded"),this._firstNegotiation=!1}))}negotiate(){if(!this.destroying){if(this.destroyed)throw p(new Error("cannot negotiate after peer is destroyed"),"ERR_DESTROYED");this.initiator?this._isNegotiating?(this._queuedNegotiation=!0,this._debug("already negotiating, queueing")):(this._debug("start negotiation"),setTimeout(()=>{this._createOffer()},0)):this._isNegotiating?(this._queuedNegotiation=!0,this._debug("already negotiating, queueing")):(this._debug("requesting negotiation from initiator"),this.emit("signal",{type:"renegotiate",renegotiate:!0})),this._isNegotiating=!0}}destroy(b){this._destroy(b,()=>{})}_destroy(b,E){this.destroyed||this.destroying||(this.destroying=!0,this._debug("destroying (error: %s)",b&&(b.message||b)),f(()=>{if(this.destroyed=!0,this.destroying=!1,this._debug("destroy (error: %s)",b&&(b.message||b)),this.readable=this.writable=!1,this._readableState.ended||this.push(null),this._writableState.finished||this.end(),this._connected=!1,this._pcReady=!1,this._channelReady=!1,this._remoteTracks=null,this._remoteStreams=null,this._senderMap=null,clearInterval(this._closingInterval),this._closingInterval=null,clearInterval(this._interval),this._interval=null,this._chunk=null,this._cb=null,this._onFinishBound&&this.removeListener("finish",this._onFinishBound),this._onFinishBound=null,this._channel){try{this._channel.close()}catch{}this._channel.onmessage=null,this._channel.onopen=null,this._channel.onclose=null,this._channel.onerror=null}if(this._pc){try{this._pc.close()}catch{}this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ontrack=null,this._pc.ondatachannel=null}this._pc=null,this._channel=null,b&&this.emit("error",b),this.emit("close"),E()}))}_setupData(b){if(!b.channel)return this.destroy(p(new Error("Data channel event is missing `channel` property"),"ERR_DATA_CHANNEL"));this._channel=b.channel,this._channel.binaryType="arraybuffer",typeof this._channel.bufferedAmountLowThreshold=="number"&&(this._channel.bufferedAmountLowThreshold=M),this.channelName=this._channel.label,this._channel.onmessage=C=>{this._onChannelMessage(C)},this._channel.onbufferedamountlow=()=>{this._onChannelBufferedAmountLow()},this._channel.onopen=()=>{this._onChannelOpen()},this._channel.onclose=()=>{this._onChannelClose()},this._channel.onerror=C=>{const D=C.error instanceof Error?C.error:new Error(`Datachannel error: ${C.message} ${C.filename}:${C.lineno}:${C.colno}`);this.destroy(p(D,"ERR_DATA_CHANNEL"))};let E=!1;this._closingInterval=setInterval(()=>{this._channel&&this._channel.readyState==="closing"?(E&&this._onChannelClose(),E=!0):E=!1},5e3)}_read(){}_write(b,E,C){if(this.destroyed)return C(p(new Error("cannot write after peer is destroyed"),"ERR_DATA_CHANNEL"));if(this._connected){try{this.send(b)}catch(D){return this.destroy(p(D,"ERR_DATA_CHANNEL"))}this._channel.bufferedAmount>M?(this._debug("start backpressure: bufferedAmount %d",this._channel.bufferedAmount),this._cb=C):C(null)}else this._debug("write before connect"),this._chunk=b,this._cb=C}_onFinish(){if(!this.destroyed){const b=()=>{setTimeout(()=>this.destroy(),1e3)};this._connected?b():this.once("connect",b)}}_startIceCompleteTimeout(){this.destroyed||this._iceCompleteTimer||(this._debug("started iceComplete timeout"),this._iceCompleteTimer=setTimeout(()=>{this._iceComplete||(this._iceComplete=!0,this._debug("iceComplete timeout completed"),this.emit("iceTimeout"),this.emit("_iceComplete"))},this.iceCompleteTimeout))}_createOffer(){this.destroyed||this._pc.createOffer(this.offerOptions).then(b=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(b.sdp=h(b.sdp)),b.sdp=this.sdpTransform(b.sdp);const E=()=>{if(!this.destroyed){const C=this._pc.localDescription||b;this._debug("signal"),this.emit("signal",{type:C.type,sdp:C.sdp})}};this._pc.setLocalDescription(b).then(()=>{this._debug("createOffer success"),this.destroyed||(this.trickle||this._iceComplete?E():this.once("_iceComplete",E))}).catch(C=>{this.destroy(p(C,"ERR_SET_LOCAL_DESCRIPTION"))})}).catch(b=>{this.destroy(p(b,"ERR_CREATE_OFFER"))})}_requestMissingTransceivers(){this._pc.getTransceivers&&this._pc.getTransceivers().forEach(b=>{b.mid||!b.sender.track||b.requested||(b.requested=!0,this.addTransceiver(b.sender.track.kind))})}_createAnswer(){this.destroyed||this._pc.createAnswer(this.answerOptions).then(b=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(b.sdp=h(b.sdp)),b.sdp=this.sdpTransform(b.sdp);const E=()=>{if(!this.destroyed){const C=this._pc.localDescription||b;this._debug("signal"),this.emit("signal",{type:C.type,sdp:C.sdp}),this.initiator||this._requestMissingTransceivers()}};this._pc.setLocalDescription(b).then(()=>{this.destroyed||(this.trickle||this._iceComplete?E():this.once("_iceComplete",E))}).catch(C=>{this.destroy(p(C,"ERR_SET_LOCAL_DESCRIPTION"))})}).catch(b=>{this.destroy(p(b,"ERR_CREATE_ANSWER"))})}_onConnectionStateChange(){this.destroyed||this._pc.connectionState==="failed"&&this.destroy(p(new Error("Connection failed."),"ERR_CONNECTION_FAILURE"))}_onIceStateChange(){if(this.destroyed)return;const b=this._pc.iceConnectionState,E=this._pc.iceGatheringState;this._debug("iceStateChange (connection: %s) (gathering: %s)",b,E),this.emit("iceStateChange",b,E),(b==="connected"||b==="completed")&&(this._pcReady=!0,this._maybeReady()),b==="failed"&&this.destroy(p(new Error("Ice connection failed."),"ERR_ICE_CONNECTION_FAILURE")),b==="closed"&&this.destroy(p(new Error("Ice connection closed."),"ERR_ICE_CONNECTION_CLOSED"))}getStats(b){const E=C=>(Object.prototype.toString.call(C.values)==="[object Array]"&&C.values.forEach(D=>{Object.assign(C,D)}),C);this._pc.getStats.length===0||this._isReactNativeWebrtc?this._pc.getStats().then(C=>{const D=[];C.forEach(m=>{D.push(E(m))}),b(null,D)},C=>b(C)):0{if(this.destroyed)return;const D=[];C.result().forEach(m=>{const k={};m.names().forEach(A=>{k[A]=m.stat(A)}),k.id=m.id,k.type=m.type,k.timestamp=m.timestamp,D.push(E(k))}),b(null,D)},C=>b(C)):b(null,[])}_maybeReady(){if(this._debug("maybeReady pc %s channel %s",this._pcReady,this._channelReady),this._connected||this._connecting||!this._pcReady||!this._channelReady)return;this._connecting=!0;const b=()=>{this.destroyed||this.getStats((E,C)=>{if(this.destroyed)return;E&&(C=[]);const D={},m={},k={};let A=!1;C.forEach(R=>{(R.type==="remotecandidate"||R.type==="remote-candidate")&&(D[R.id]=R),(R.type==="localcandidate"||R.type==="local-candidate")&&(m[R.id]=R),(R.type==="candidatepair"||R.type==="candidate-pair")&&(k[R.id]=R)});const v=R=>{A=!0;let O=m[R.localCandidateId];O&&(O.ip||O.address)?(this.localAddress=O.ip||O.address,this.localPort=+O.port):O&&O.ipAddress?(this.localAddress=O.ipAddress,this.localPort=+O.portNumber):typeof R.googLocalAddress=="string"&&(O=R.googLocalAddress.split(":"),this.localAddress=O[0],this.localPort=+O[1]),this.localAddress&&(this.localFamily=this.localAddress.includes(":")?"IPv6":"IPv4");let P=D[R.remoteCandidateId];P&&(P.ip||P.address)?(this.remoteAddress=P.ip||P.address,this.remotePort=+P.port):P&&P.ipAddress?(this.remoteAddress=P.ipAddress,this.remotePort=+P.portNumber):typeof R.googRemoteAddress=="string"&&(P=R.googRemoteAddress.split(":"),this.remoteAddress=P[0],this.remotePort=+P[1]),this.remoteAddress&&(this.remoteFamily=this.remoteAddress.includes(":")?"IPv6":"IPv4"),this._debug("connect local: %s:%s remote: %s:%s",this.localAddress,this.localPort,this.remoteAddress,this.remotePort)};if(C.forEach(R=>{R.type==="transport"&&R.selectedCandidatePairId&&v(k[R.selectedCandidatePairId]),(R.type==="googCandidatePair"&&R.googActiveConnection==="true"||(R.type==="candidatepair"||R.type==="candidate-pair")&&R.selected)&&v(R)}),!A&&(!Object.keys(k).length||Object.keys(m).length))return void setTimeout(b,100);if(this._connecting=!1,this._connected=!0,this._chunk){try{this.send(this._chunk)}catch(O){return this.destroy(p(O,"ERR_DATA_CHANNEL"))}this._chunk=null,this._debug('sent chunk from "write before connect"');const R=this._cb;this._cb=null,R(null)}typeof this._channel.bufferedAmountLowThreshold!="number"&&(this._interval=setInterval(()=>this._onInterval(),150),this._interval.unref&&this._interval.unref()),this._debug("connect"),this.emit("connect")})};b()}_onInterval(){this._cb&&this._channel&&!(this._channel.bufferedAmount>M)&&this._onChannelBufferedAmountLow()}_onSignalingStateChange(){this.destroyed||(this._pc.signalingState==="stable"&&(this._isNegotiating=!1,this._debug("flushing sender queue",this._sendersAwaitingStable),this._sendersAwaitingStable.forEach(b=>{this._pc.removeTrack(b),this._queuedNegotiation=!0}),this._sendersAwaitingStable=[],this._queuedNegotiation?(this._debug("flushing negotiation queue"),this._queuedNegotiation=!1,this._needsNegotiation()):(this._debug("negotiated"),this.emit("negotiated"))),this._debug("signalingStateChange %s",this._pc.signalingState),this.emit("signalingStateChange",this._pc.signalingState))}_onIceCandidate(b){this.destroyed||(b.candidate&&this.trickle?this.emit("signal",{type:"candidate",candidate:{candidate:b.candidate.candidate,sdpMLineIndex:b.candidate.sdpMLineIndex,sdpMid:b.candidate.sdpMid}}):!b.candidate&&!this._iceComplete&&(this._iceComplete=!0,this.emit("_iceComplete")),b.candidate&&this._startIceCompleteTimeout())}_onChannelMessage(b){if(this.destroyed)return;let E=b.data;E instanceof ArrayBuffer&&(E=S.from(E)),this.push(E)}_onChannelBufferedAmountLow(){if(!this.destroyed&&this._cb){this._debug("ending backpressure: bufferedAmount %d",this._channel.bufferedAmount);const b=this._cb;this._cb=null,b(null)}}_onChannelOpen(){this._connected||this.destroyed||(this._debug("on channel open"),this._channelReady=!0,this._maybeReady())}_onChannelClose(){this.destroyed||(this._debug("on channel close"),this.destroy())}_onTrack(b){this.destroyed||b.streams.forEach(E=>{this._debug("on track"),this.emit("track",b.track,E),this._remoteTracks.push({track:b.track,stream:E}),this._remoteStreams.some(C=>C.id===E.id)||(this._remoteStreams.push(E),f(()=>{this._debug("on stream"),this.emit("stream",E)}))})}_debug(){const b=[].slice.call(arguments);b[0]="["+this._id+"] "+b[0],y.apply(null,b)}}x.WEBRTC_SUPPORT=!!w(),x.config={iceServers:[{urls:["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478"]}],sdpSemantics:"unified-plan"},x.channelConfig={},c.exports=x},{buffer:3,debug:4,"err-code":6,"get-browser-rtc":8,"queue-microtask":13,randombytes:14,"readable-stream":29}]},{},[])("/")})})(Ki);var Fa=Ki.exports;const wr=0,br=1,Xi=2,Zi=(e,t)=>{q(e,wr);const n=Ro(t);ct(e,n)},Qi=(e,t,n)=>{q(e,br),ct(e,So(t,n))},Pa=(e,t,n)=>Qi(t,n,pt(e)),ts=(e,t,n)=>{try{bo(t,pt(e),n)}catch(i){console.error("Caught error while handling a Yjs update",i)}},Ba=(e,t)=>{q(e,Xi),ct(e,t)},ja=ts,Va=(e,t,n,i)=>{const s=G(e);switch(s){case wr:Pa(e,t,n);break;case br:ts(e,n,i);break;case Xi:ja(e,n,i);break;default:throw new Error("Unknown message type")}return s},_r=3e4;class qa extends ue{constructor(t){super();this.doc=t,this.clientID=t.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{const n=Ot();this.getLocalState()!==null&&_r/2<=n-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());const i=[];this.meta.forEach((s,o)=>{o!==this.clientID&&_r<=n-s.lastUpdated&&this.states.has(o)&&i.push(o)}),i.length>0&&vr(this,i,"timeout")},de(_r/10)),t.on("destroy",()=>{this.destroy()}),this.setLocalState({})}destroy(){this.emit("destroy",[this]),this.setLocalState(null),super.destroy(),clearInterval(this._checkInterval)}getLocalState(){return this.states.get(this.clientID)||null}setLocalState(t){const n=this.clientID,i=this.meta.get(n),s=i===void 0?0:i.clock+1,o=this.states.get(n);t===null?this.states.delete(n):this.states.set(n,t),this.meta.set(n,{clock:s,lastUpdated:Ot()});const c=[],h=[],l=[],y=[];t===null?y.push(n):o==null?t!=null&&c.push(n):(h.push(n),Oe(o,t)||l.push(n)),(c.length>0||l.length>0||y.length>0)&&this.emit("change",[{added:c,updated:l,removed:y},"local"]),this.emit("update",[{added:c,updated:h,removed:y},"local"])}setLocalStateField(t,n){const i=this.getLocalState();i!==null&&this.setLocalState(In(Ge({},i),{[t]:n}))}getStates(){return this.states}}const vr=(e,t,n)=>{const i=[];for(let s=0;s0&&(e.emit("change",[{added:[],updated:[],removed:i},n]),e.emit("update",[{added:[],updated:[],removed:i},n]))},An=(e,t,n=e.states)=>{const i=t.length,s=dt();q(s,i);for(let o=0;o{const i=Mt(t),s=Ot(),o=[],c=[],h=[],l=[],y=G(i);for(let w=0;w0||h.length>0||l.length>0)&&e.emit("change",[{added:o,updated:h,removed:l},n]),(o.length>0||c.length>0||l.length>0)&&e.emit("update",[{added:o,updated:c,removed:l},n])},Ha=(e,t)=>{const n=Mr(e).buffer,i=Mr(t).buffer;return crypto.subtle.importKey("raw",n,"PBKDF2",!1,["deriveKey"]).then(s=>crypto.subtle.deriveKey({name:"PBKDF2",salt:i,iterations:1e5,hash:"SHA-256"},s,{name:"AES-GCM",length:256},!0,["encrypt","decrypt"]))},es=(e,t)=>{if(!t)return $n(e);const n=crypto.getRandomValues(new Uint8Array(12));return crypto.subtle.encrypt({name:"AES-GCM",iv:n},t,e).then(i=>{const s=dt();return xt(s,"AES-GCM"),ct(s,n),ct(s,new Uint8Array(i)),st(s)})},$a=(e,t)=>{const n=dt();return pe(n,e),es(st(n),t)},ns=(e,t)=>{if(!t)return $n(e);const n=Mt(e);jt(n)!=="AES-GCM"&&Ks(ge("Unknown encryption algorithm"));const s=pt(n),o=pt(n);return crypto.subtle.decrypt({name:"AES-GCM",iv:s},t,o).then(c=>new Uint8Array(c))},Ya=(e,t)=>ns(e,t).then(n=>fe(Mt(new Uint8Array(n)))),Rt=lo("y-webrtc"),ke=0,rs=3,He=1,Sr=4,Dn=new Map,ae=new Map,is=e=>{let t=!0;e.webrtcConns.forEach(n=>{n.synced||(t=!1)}),(!t&&e.synced||t&&!e.synced)&&(e.synced=t,e.provider.emit("synced",[{synced:t}]),Rt("synced ",vt,e.name,Ht," with all peers"))},ss=(e,t,n)=>{const i=Mt(t),s=dt(),o=G(i);if(e===void 0)return null;const c=e.awareness,h=e.doc;let l=!1;switch(o){case ke:{q(s,ke);const y=Va(i,s,h,e);y===br&&!e.synced&&n(),y===wr&&(l=!0);break}case rs:q(s,He),ct(s,An(c,Array.from(c.getStates().keys()))),l=!0;break;case He:Wa(c,pt(i),e);break;case Sr:{const y=te(i)===1,w=jt(i);if(w!==e.peerId&&(e.bcConns.has(w)&&!y||!e.bcConns.has(w)&&y)){const u=[],g=[];y?(e.bcConns.add(w),g.push(w)):(e.bcConns.delete(w),u.push(w)),e.provider.emit("peers",[{added:g,removed:u,webrtcPeers:Array.from(e.webrtcConns.keys()),bcPeers:Array.from(e.bcConns)}]),ls(e)}break}default:return console.error("Unable to compute message"),s}return l?s:null},za=(e,t)=>{const n=e.room;return Rt("received message from ",vt,e.remotePeerId,rn," (",n.name,")",Ht,Ne),ss(n,t,()=>{e.synced=!0,Rt("synced ",vt,n.name,Ht," with ",vt,e.remotePeerId),is(n)})},Er=(e,t)=>{Rt("send message to ",vt,e.remotePeerId,Ht,rn," (",e.room.name,")",Ne);try{e.peer.send(st(t))}catch{}},Ga=(e,t)=>{Rt("broadcast message in ",vt,e.name,Ht),e.webrtcConns.forEach(n=>{try{n.peer.send(t)}catch{}})};class os{constructor(t,n,i,s){Rt("establishing connection to ",vt,i),this.room=s,this.remotePeerId=i,this.closed=!1,this.connected=!1,this.synced=!1,this.peer=new Fa(Ge({initiator:n},s.provider.peerOpts)),this.peer.on("signal",o=>{kr(t,s,{to:i,from:s.peerId,type:"signal",signal:o})}),this.peer.on("connect",()=>{Rt("connected to ",vt,i),this.connected=!0;const c=s.provider.doc,h=s.awareness,l=dt();q(l,ke),Zi(l,c),Er(this,l);const y=h.getStates();if(y.size>0){const w=dt();q(w,He),ct(w,An(h,Array.from(y.keys()))),Er(this,w)}}),this.peer.on("close",()=>{this.connected=!1,this.closed=!0,s.webrtcConns.has(this.remotePeerId)&&(s.webrtcConns.delete(this.remotePeerId),s.provider.emit("peers",[{removed:[this.remotePeerId],added:[],webrtcPeers:Array.from(s.webrtcConns.keys()),bcPeers:Array.from(s.bcConns)}])),is(s),this.peer.destroy(),Rt("closed connection to ",vt,i),Cr(s)}),this.peer.on("error",o=>{Rt("Error in connection to ",vt,i,": ",o),Cr(s)}),this.peer.on("data",o=>{const c=za(this,o);c!==null&&Er(this,c)})}destroy(){this.peer.destroy()}}const zt=(e,t)=>es(t,e.key).then(n=>e.mux(()=>Na(e.name,n))),as=(e,t)=>{e.bcconnected&&zt(e,t),Ga(e,t)},Cr=e=>{Dn.forEach(t=>{t.connected&&(t.send({type:"subscribe",topics:[e.name]}),e.webrtcConns.size{if(e.provider.filterBcConns){const t=dt();q(t,Sr),xe(t,1),xt(t,e.peerId),zt(e,st(t))}};class Ja{constructor(t,n,i,s){this.peerId=Xr(),this.doc=t,this.awareness=n.awareness,this.provider=n,this.synced=!1,this.name=i,this.key=s,this.webrtcConns=new Map,this.bcConns=new Set,this.mux=Ua(),this.bcconnected=!1,this._bcSubscriber=o=>ns(new Uint8Array(o),s).then(c=>this.mux(()=>{const h=ss(this,c,()=>{});h&&zt(this,st(h))})),this._docUpdateHandler=(o,c)=>{const h=dt();q(h,ke),Ba(h,o),as(this,st(h))},this._awarenessUpdateHandler=({added:o,updated:c,removed:h},l)=>{const y=o.concat(c).concat(h),w=dt();q(w,He),ct(w,An(this.awareness,y)),as(this,st(w))},this._beforeUnloadHandler=()=>{vr(this.awareness,[t.clientID],"window unload"),ae.forEach(o=>{o.disconnect()})},typeof window!="undefined"?window.addEventListener("beforeunload",this._beforeUnloadHandler):typeof process!="undefined"&&process.on("exit",this._beforeUnloadHandler)}connect(){this.doc.on("update",this._docUpdateHandler),this.awareness.on("update",this._awarenessUpdateHandler),Cr(this);const t=this.name;xa(t,this._bcSubscriber),this.bcconnected=!0,ls(this);const n=dt();q(n,ke),Zi(n,this.doc),zt(this,st(n));const i=dt();q(i,ke),Qi(i,this.doc),zt(this,st(i));const s=dt();q(s,rs),zt(this,st(s));const o=dt();q(o,He),ct(o,An(this.awareness,[this.doc.clientID])),zt(this,st(o))}disconnect(){Dn.forEach(n=>{n.connected&&n.send({type:"unsubscribe",topics:[this.name]})}),vr(this.awareness,[this.doc.clientID],"disconnect");const t=dt();q(t,Sr),xe(t,0),xt(t,this.peerId),zt(this,st(t)),Oa(this.name,this._bcSubscriber),this.bcconnected=!1,this.doc.off("update",this._docUpdateHandler),this.awareness.off("update",this._awarenessUpdateHandler),this.webrtcConns.forEach(n=>n.destroy())}destroy(){this.disconnect(),typeof window!="undefined"?window.removeEventListener("beforeunload",this._beforeUnloadHandler):typeof process!="undefined"&&process.off("exit",this._beforeUnloadHandler)}}const Ka=(e,t,n,i)=>{if(ae.has(n))throw ge(`A Yjs Doc connected to room "${n}" already exists!`);const s=new Ja(e,t,n,i);return ae.set(n,s),s},kr=(e,t,n)=>{t.key?$a(n,t.key).then(i=>{e.send({type:"publish",topic:t.name,data:Wr(i)})}):e.send({type:"publish",topic:t.name,data:n})};class Xa extends Da{constructor(t){super(t);this.providers=new Set,this.on("connect",()=>{Rt(`connected (${t})`);const n=Array.from(ae.keys());this.send({type:"subscribe",topics:n}),ae.forEach(i=>kr(this,i,{type:"announce",from:i.peerId}))}),this.on("message",n=>{switch(n.type){case"publish":{const i=n.topic,s=ae.get(i);if(s==null||typeof i!="string")return;const o=c=>{const h=s.webrtcConns,l=s.peerId;if(c==null||c.from===l||c.to!==void 0&&c.to!==l||s.bcConns.has(c.from))return;const y=h.has(c.from)?()=>{}:()=>s.provider.emit("peers",[{removed:[],added:[c.from],webrtcPeers:Array.from(s.webrtcConns.keys()),bcPeers:Array.from(s.bcConns)}]);switch(c.type){case"announce":h.sizenew os(this,!0,c.from,s)),y());break;case"signal":c.to===l&&(St(h,c.from,()=>new os(this,!1,c.from,s)).peer.signal(c.signal),y());break}};s.key?typeof n.data=="string"&&Ya(Hr(n.data),s.key).then(o):o(n.data)}}}),this.on("disconnect",()=>Rt(`disconnect (${t})`))}}class Za extends ue{constructor(t,n,{signaling:i=["wss://signaling.yjs.dev","wss://y-webrtc-signaling-eu.herokuapp.com","wss://y-webrtc-signaling-us.herokuapp.com"],password:s=null,awareness:o=new qa(n),maxConns:c=20+de(zs()*15),filterBcConns:h=!0,peerOpts:l={}}={}){super();this.roomName=t,this.doc=n,this.filterBcConns=h,this.awareness=o,this.shouldConnect=!1,this.signalingUrls=i,this.signalingConns=[],this.maxConns=c,this.peerOpts=l,this.key=s?Ha(s,t):$n(null),this.room=null,this.key.then(y=>{this.room=Ka(n,this,t,y),this.shouldConnect?this.room.connect():this.room.disconnect()}),this.connect(),this.destroy=this.destroy.bind(this),n.on("destroy",this.destroy)}get connected(){return this.room!==null&&this.shouldConnect}connect(){this.shouldConnect=!0,this.signalingUrls.forEach(t=>{const n=St(Dn,t,()=>new Xa(t));this.signalingConns.push(n),n.providers.add(this)}),this.room&&this.room.connect()}disconnect(){this.shouldConnect=!1,this.signalingConns.forEach(t=>{t.providers.delete(this),t.providers.size===0&&(t.destroy(),Dn.delete(t.url))}),this.room&&this.room.disconnect()}destroy(){this.doc.off("destroy",this.destroy),this.key.then(()=>{this.room.destroy(),ae.delete(this.roomName)}),super.destroy()}}var $=class{static clamp(e,t,n){return Math.max(t,typeof n!="undefined"?Math.min(e,n):e)}static clampV(e,t,n){return e.map(i=>n?$.clamp(i,t,n):$.clamp(i,t))}static cross(e,t,n){return(t[0]-e[0])*(n[1]-e[1])-(n[0]-e[0])*(t[1]-e[1])}static snap(e,t=1){return[Math.round(e[0]/t)*t,Math.round(e[1]/t)*t]}},H=$;H.neg=e=>[-e[0],-e[1]],H.add=(e,t)=>[e[0]+t[0],e[1]+t[1]],H.addScalar=(e,t)=>[e[0]+t,e[1]+t],H.sub=(e,t)=>[e[0]-t[0],e[1]-t[1]],H.subScalar=(e,t)=>[e[0]-t,e[1]-t],H.vec=(e,t)=>[t[0]-e[0],t[1]-e[1]],H.mul=(e,t)=>[e[0]*t,e[1]*t],H.mulV=(e,t)=>[e[0]*t[0],e[1]*t[1]],H.div=(e,t)=>[e[0]/t,e[1]/t],H.divV=(e,t)=>[e[0]/t[0],e[1]/t[1]],H.per=e=>[e[1],-e[0]],H.dpr=(e,t)=>e[0]*t[0]+e[1]*t[1],H.cpr=(e,t)=>e[0]*t[1]-t[0]*e[1],H.len2=e=>e[0]*e[0]+e[1]*e[1],H.len=e=>Math.hypot(e[0],e[1]),H.pry=(e,t)=>$.dpr(e,t)/$.len(t),H.uni=e=>$.div(e,$.len(e)),H.normalize=e=>$.uni(e),H.tangent=(e,t)=>$.uni($.sub(e,t)),H.dist2=(e,t)=>$.len2($.sub(e,t)),H.dist=(e,t)=>Math.hypot(e[1]-t[1],e[0]-t[0]),H.fastDist=(e,t)=>{const n=[t[0]-e[0],t[1]-e[1]],i=[Math.abs(n[0]),Math.abs(n[1])];let s=1/Math.max(i[0],i[1]);return s=s*(1.29289-(i[0]+i[1])*s*.29289),[n[0]*s,n[1]*s]},H.ang=(e,t)=>Math.atan2($.cpr(e,t),$.dpr(e,t)),H.angle=(e,t)=>Math.atan2(t[1]-e[1],t[0]-e[0]),H.med=(e,t)=>$.mul($.add(e,t),.5),H.rot=(e,t=0)=>[e[0]*Math.cos(t)-e[1]*Math.sin(t),e[0]*Math.sin(t)+e[1]*Math.cos(t)],H.rotWith=(e,t,n=0)=>{if(n===0)return e;const i=Math.sin(n),s=Math.cos(n),o=e[0]-t[0],c=e[1]-t[1],h=o*s-c*i,l=o*i+c*s;return[h+t[0],l+t[1]]},H.isEqual=(e,t)=>e[0]===t[0]&&e[1]===t[1],H.lrp=(e,t,n)=>$.add(e,$.mul($.sub(t,e),n)),H.int=(e,t,n,i,s=1)=>{const o=($.clamp(n,i)-n)/(i-n);return $.add($.mul(e,1-o),$.mul(t,s))},H.ang3=(e,t,n)=>{const i=$.vec(t,e),s=$.vec(t,n);return $.ang(i,s)},H.abs=e=>[Math.abs(e[0]),Math.abs(e[1])],H.rescale=(e,t)=>{const n=$.len(e);return[t*e[0]/n,t*e[1]/n]},H.isLeft=(e,t,n)=>(t[0]-e[0])*(n[1]-e[1])-(n[0]-e[0])*(t[1]-e[1]),H.clockwise=(e,t,n)=>$.isLeft(e,t,n)>0,H.toFixed=(e,t=2)=>e.map(n=>+n.toFixed(t)),H.nearestPointOnLineThroughPoint=(e,t,n)=>$.add(e,$.mul(t,$.pry($.sub(n,e),t))),H.distanceToLineThroughPoint=(e,t,n)=>$.dist(n,$.nearestPointOnLineThroughPoint(e,t,n)),H.nearestPointOnLineSegment=(e,t,n,i=!0)=>{const s=$.uni($.sub(t,e)),o=$.add(e,$.mul(s,$.pry($.sub(n,e),s)));if(i){if(o[0]Math.max(e[0],t[0]))return e[0]>t[0]?e:t;if(o[1]Math.max(e[1],t[1]))return e[1]>t[1]?e:t}return o},H.distanceToLineSegment=(e,t,n,i=!0)=>$.dist(n,$.nearestPointOnLineSegment(e,t,n,i)),H.nudge=(e,t,n)=>$.isEqual(e,t)?e:$.add(e,$.mul($.uni($.sub(t,e)),n)),H.nudgeAtAngle=(e,t,n)=>[Math.cos(t)*n+e[0],Math.sin(t)*n+e[1]],H.toPrecision=(e,t=4)=>[+e[0].toPrecision(t),+e[1].toPrecision(t)],H.pointsBetween=(e,t,n=6)=>Array.from(Array(n)).map((i,s)=>{const o=s/(n-1),c=Math.min(1,.5+Math.abs(.5-o));return[...$.lrp(e,t,o),c]}),H.slope=(e,t)=>e[0]===t[0]?NaN:(e[1]-t[1])/(e[0]-t[0]),H.max=(...e)=>[Math.max(...e.map(t=>t[0])),Math.max(...e.map(t=>t[1]))],H.min=(...e)=>[Math.max(...e.map(t=>t[0])),Math.max(...e.map(t=>t[1]))];var Qa=class{constructor(e=[]){this.points=[],this.lengths=[],this.totalLength=0,this.addPoint=t=>{if(this.prev){const n=H.dist(this.prev,t);this.lengths.push(n),this.totalLength+=n,this.points.push(t)}this.prev=t},this.clear=()=>{this.points=this.prev?[this.prev]:[],this.totalLength=0},this.getSplinePoint=t=>{const{points:n}=this,i=n.length-1,s=Math.trunc(t),o=Math.min(s+1,i),c=Math.min(o+1,i),h=Math.min(c+1,i),l=o-1,y=t-s,w=y*y,u=w*y,g=-u+2*w-y,f=3*u-5*w+2,p=-3*u+4*w+y,S=u-w;return[(n[l][0]*g+n[o][0]*f+n[c][0]*p+n[h][0]*S)/2,(n[l][1]*g+n[o][1]*f+n[c][1]*p+n[h][1]*S)/2]},this.points=e,this.lengths=e.map((t,n,i)=>n===0?0:H.dist(t,i[n-1])),this.totalLength=this.lengths.reduce((t,n)=>t+n,0)}},Rr=class{constructor(e){this.state="idle",this.queue=[],this.timestamp=performance.now(),this.lastRequestId=0,this.timeoutId=0,this.spline=new Qa,this.addPoint=t=>{clearTimeout(this.timeoutId);const n=performance.now(),i=Math.min(n-this.timestamp,Rr.MAX_INTERVAL);if(!this.prevPoint){this.spline.clear(),this.prevPoint=t,this.spline.addPoint(t),this.cb(t),this.state="stopped";return}if(this.state==="stopped"){if(H.dist(this.prevPoint,t)<4){this.cb(t);return}this.spline.clear(),this.spline.addPoint(this.prevPoint),this.spline.addPoint(this.prevPoint),this.spline.addPoint(t),this.state="idle"}else this.spline.addPoint(t);if(i<16){this.prevPoint=t,this.timestamp=n,this.cb(t);return}const s={start:this.spline.points.length-3,from:this.prevPoint,to:t,duration:i};switch(this.prevPoint=t,this.timestamp=n,this.state){case"idle":{this.state="animating",this.animateNext(s);break}case"animating":{this.queue.push(s);break}}},this.animateNext=t=>{const n=performance.now(),i=()=>{const s=(performance.now()-n)/t.duration;if(s<=1&&this.spline.points.length>0){try{this.cb(this.spline.getSplinePoint(s+t.start))}catch(c){console.warn(c)}this.lastRequestId=requestAnimationFrame(i);return}const o=this.queue.shift();o?(this.state="animating",this.animateNext(o)):(this.state="idle",this.timeoutId=setTimeout(()=>{this.state="stopped"},Rr.MAX_INTERVAL))};i()},this.dispose=()=>{clearTimeout(this.timeoutId)},this.cb=e}},cs=Rr;cs.MAX_INTERVAL=300;let tl=(e=21)=>crypto.getRandomValues(new Uint8Array(e)).reduce((t,n)=>(n&=63,n<36?t+=n.toString(36):n<62?t+=(n-26).toString(36).toUpperCase():n>62?t+="-":t+="_",t),"");var Tr={exports:{}};(function(e,t){(function(n,i){{var s=i();e&&e.exports&&(t=e.exports=s),t.randomColor=s}})(kt,function(){var n=null,i={};x();var s=[],o=function(m){if(m=m||{},m.seed!==void 0&&m.seed!==null&&m.seed===parseInt(m.seed,10))n=m.seed;else if(typeof m.seed=="string")n=C(m.seed);else{if(m.seed!==void 0&&m.seed!==null)throw new TypeError("The seed value must be an integer or string");n=null}var k,A,v;if(m.count!==null&&m.count!==void 0){for(var R=m.count,O=[],P=0;PO.length;){var W=o(m);n!==null&&(m.seed=n),O.push(W)}return m.count=R,O}return k=c(m),A=h(k,m),v=l(k,A,m),y([k,A,v],m)};function c(m){if(s.length>0){var k=D(m.hue),A=p(k),v=(k[1]-k[0])/s.length,R=parseInt((A-k[0])/v);s[R]===!0?R=(R+2)%s.length:s[R]=!0;var O=(k[0]+R*v)%359,P=(k[0]+(R+1)*v)%359;return k=[O,P],A=p(k),A<0&&(A=360+A),A}else{var k=u(m.hue);return A=p(k),A<0&&(A=360+A),A}}function h(m,k){if(k.hue==="monochrome")return 0;if(k.luminosity==="random")return p([0,100]);var A=g(m),v=A[0],R=A[1];switch(k.luminosity){case"bright":v=55;break;case"dark":v=R-10;break;case"light":R=55;break}return p([v,R])}function l(m,k,A){var v=w(m,k),R=100;switch(A.luminosity){case"dark":R=v+20;break;case"light":v=(R+v)/2;break;case"random":v=0,R=100;break}return p([v,R])}function y(m,k){switch(k.format){case"hsvArray":return m;case"hslArray":return E(m);case"hsl":var A=E(m);return"hsl("+A[0]+", "+A[1]+"%, "+A[2]+"%)";case"hsla":var v=E(m),P=k.alpha||Math.random();return"hsla("+v[0]+", "+v[1]+"%, "+v[2]+"%, "+P+")";case"rgbArray":return F(m);case"rgb":var R=F(m);return"rgb("+R.join(", ")+")";case"rgba":var O=F(m),P=k.alpha||Math.random();return"rgba("+O.join(", ")+", "+P+")";default:return S(m)}}function w(m,k){for(var A=f(m).lowerBounds,v=0;v=R&&k<=P){var z=(W-O)/(P-R),J=O-z*R;return z*k+J}}return 0}function u(m){if(typeof parseInt(m)=="number"){var k=parseInt(m);if(k<360&&k>0)return[k,k]}if(typeof m=="string"){if(i[m]){var A=i[m];if(A.hueRange)return A.hueRange}else if(m.match(/^#?([0-9A-F]{3}|[0-9A-F]{6})$/i)){var v=b(m)[0];return[v,v]}}return[0,360]}function g(m){return f(m).saturationRange}function f(m){m>=334&&m<=360&&(m-=360);for(var k in i){var A=i[k];if(A.hueRange&&m>=A.hueRange[0]&&m<=A.hueRange[1])return i[k]}return"Color not found"}function p(m){if(n===null){var k=.618033988749895,A=Math.random();return A+=k,A%=1,Math.floor(m[0]+A*(m[1]+1-m[0]))}else{var v=m[1]||1,R=m[0]||0;n=(n*9301+49297)%233280;var O=n/233280;return Math.floor(R+O*(v-R))}}function S(m){var k=F(m);function A(R){var O=R.toString(16);return O.length==1?"0"+O:O}var v="#"+A(k[0])+A(k[1])+A(k[2]);return v}function M(m,k,A){var v=A[0][0],R=A[A.length-1][0],O=A[A.length-1][1],P=A[0][1];i[m]={hueRange:k,lowerBounds:A,saturationRange:[v,R],brightnessRange:[O,P]}}function x(){M("monochrome",null,[[0,0],[100,0]]),M("red",[-26,18],[[20,100],[30,92],[40,89],[50,85],[60,78],[70,70],[80,60],[90,55],[100,50]]),M("orange",[18,46],[[20,100],[30,93],[40,88],[50,86],[60,85],[70,70],[100,70]]),M("yellow",[46,62],[[25,100],[40,94],[50,89],[60,86],[70,84],[80,82],[90,80],[100,75]]),M("green",[62,178],[[30,100],[40,90],[50,85],[60,81],[70,74],[80,64],[90,50],[100,40]]),M("blue",[178,257],[[20,100],[30,86],[40,80],[50,74],[60,60],[70,52],[80,44],[90,39],[100,35]]),M("purple",[257,282],[[20,100],[30,87],[40,79],[50,70],[60,65],[70,59],[80,52],[90,45],[100,42]]),M("pink",[282,334],[[20,100],[30,90],[40,86],[60,84],[80,80],[90,75],[100,73]])}function F(m){var k=m[0];k===0&&(k=1),k===360&&(k=359),k=k/360;var A=m[1]/100,v=m[2]/100,R=Math.floor(k*6),O=k*6-R,P=v*(1-A),W=v*(1-O*A),z=v*(1-(1-O)*A),J=256,et=256,ot=256;switch(R){case 0:J=v,et=z,ot=P;break;case 1:J=W,et=v,ot=P;break;case 2:J=P,et=v,ot=z;break;case 3:J=P,et=W,ot=v;break;case 4:J=z,et=P,ot=v;break;case 5:J=v,et=P,ot=W;break}var Y=[Math.floor(J*255),Math.floor(et*255),Math.floor(ot*255)];return Y}function b(m){m=m.replace(/^#/,""),m=m.length===3?m.replace(/(.)/g,"$1$1"):m;var k=parseInt(m.substr(0,2),16)/255,A=parseInt(m.substr(2,2),16)/255,v=parseInt(m.substr(4,2),16)/255,R=Math.max(k,A,v),O=R-Math.min(k,A,v),P=R?O/R:0;switch(R){case k:return[60*((A-v)/O%6)||0,P,R];case A:return[60*((v-k)/O+2)||0,P,R];case v:return[60*((k-A)/O+4)||0,P,R]}}function E(m){var k=m[0],A=m[1]/100,v=m[2]/100,R=(2-A)*v;return[k,Math.round(A*v/(R<1?R:2-R)*1e4)/100,R/2*100]}function C(m){for(var k=0,A=0;A!==m.length&&!(k>=Number.MAX_SAFE_INTEGER);A++)k+=m.charCodeAt(A);return k}function D(m){if(isNaN(m)){if(typeof m=="string"){if(i[m]){var A=i[m];if(A.hueRange)return A.hueRange}else if(m.match(/^#?([0-9A-F]{3}|[0-9A-F]{6})$/i)){var v=b(m)[0];return f(v).hueRange}}}else{var k=parseInt(m);if(k<360&&k>0)return f(m).hueRange}return[0,360]}return o})})(Tr,Tr.exports);var el=Tr.exports;function nl(e){const t=`
+(function(ft,pt){typeof exports=="object"&&typeof module!="undefined"?pt(exports):typeof define=="function"&&define.amd?define(["exports"],pt):(ft=typeof globalThis!="undefined"?globalThis:ft||self,pt(ft["cursor-chat"]={}))})(this,function(ft){"use strict";var il=Object.defineProperty,sl=Object.defineProperties;var ol=Object.getOwnPropertyDescriptors;var us=Object.getOwnPropertySymbols;var al=Object.prototype.hasOwnProperty,ll=Object.prototype.propertyIsEnumerable;var ds=(ft,pt,lt)=>pt in ft?il(ft,pt,{enumerable:!0,configurable:!0,writable:!0,value:lt}):ft[pt]=lt,Ge=(ft,pt)=>{for(var lt in pt||(pt={}))al.call(pt,lt)&&ds(ft,lt,pt[lt]);if(us)for(var lt of us(pt))ll.call(pt,lt)&&ds(ft,lt,pt[lt]);return ft},In=(ft,pt)=>sl(ft,ol(pt));var pt="";const lt=()=>new Map,Je=e=>{const t=lt();return e.forEach((n,i)=>{t.set(i,n)}),t},St=(e,t,n)=>{let i=e.get(t);return i===void 0&&e.set(t,i=n()),i},fs=(e,t)=>{const n=[];for(const[i,s]of e)n.push(t(s,i));return n},ps=(e,t)=>{for(const[n,i]of e)if(t(i,n))return!0;return!1},Ie=()=>new Set,Ln=e=>e[e.length-1],gs=(e,t)=>{for(let n=0;n{this.off(t,i),n(...s)};this.on(t,i)}off(t,n){const i=this._observers.get(t);i!==void 0&&(i.delete(n),i.size===0&&this._observers.delete(t))}emit(t,n){return Ar((this._observers.get(t)||lt()).values()).forEach(i=>i(...n))}destroy(){this._observers=lt()}}const de=Math.floor,Mn=Math.abs,ms=Math.log10,xn=(e,t)=>ee>t?e:t,Dr=e=>e!==0?e<0:1/e<0,ws=String.fromCharCode,bs=e=>e.toLowerCase(),_s=/^\s*/g,vs=e=>e.replace(_s,""),Ss=/([A-Z])/g,Ir=(e,t)=>vs(e.replace(Ss,n=>`${t}${bs(n)}`)),Es=e=>{const t=unescape(encodeURIComponent(e)),n=t.length,i=new Uint8Array(n);for(let s=0;sLr.encode(e):Es;let On=typeof TextDecoder=="undefined"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});On&&On.decode(new Uint8Array).length===1&&(On=null);const xr=e=>e===void 0?null:e;class Cs{constructor(){this.map=new Map}setItem(t,n){this.map.set(t,n)}getItem(t){return this.map.get(t)}}let Or=new Cs,Nr=!0;try{typeof localStorage!="undefined"&&(Or=localStorage,Nr=!1)}catch{}const Ur=Or,ks=e=>Nr||addEventListener("storage",e),Ke=typeof process!="undefined"&&process.release&&/node|io\.js/.test(process.release.name),Fr=typeof window!="undefined"&&!Ke;typeof navigator!="undefined"&&/Mac/.test(navigator.platform);let Lt;const Rs=()=>{if(Lt===void 0)if(Ke){Lt=lt();const e=process.argv;let t=null;for(let n=0;n{if(e.length!==0){const[t,n]=e.split("=");Lt.set(`--${Ir(t,"-")}`,n),Lt.set(`-${Ir(t,"-")}`,n)}})):Lt=lt();return Lt},Ts=e=>Rs().has(e),Pr=e=>xr(Ke?process.env[e.toUpperCase()]:Ur.getItem(e));(e=>Ts("--"+e)||Pr(e)!==null)("production");const Br=1,jr=2,Nn=4,Un=8,Le=32,Bt=64,_t=128,Xe=31,Fn=63,Qt=127,As=2147483647;class Ze{constructor(t){this.arr=t,this.pos=0}}const Mt=e=>new Ze(e),Ds=e=>e.pos!==e.arr.length,Is=(e,t)=>{const n=Vn(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n},gt=e=>Is(e,G(e)),te=e=>e.arr[e.pos++],G=e=>{let t=0,n=0;for(;;){const i=e.arr[e.pos++];if(t=t|(i&Qt)<>>0;if(n>35)throw new Error("Integer out of range!")}},Pn=e=>{let t=e.arr[e.pos++],n=t&Fn,i=6;const s=(t&Bt)>0?-1:1;if((t&_t)===0)return s*n;for(;;){if(t=e.arr[e.pos++],n=n|(t&Qt)<>>0);if(i>41)throw new Error("Integer out of range!")}},jt=e=>{let t=G(e);if(t===0)return"";{let n=String.fromCodePoint(te(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(te(e));else for(;t>0;){const i=t<1e4?t:1e4,s=e.arr.subarray(e.pos,e.pos+i);e.pos+=i,n+=String.fromCodePoint.apply(null,s),t-=i}return decodeURIComponent(escape(n))}},Bn=(e,t)=>{const n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},Ls=[e=>{},e=>null,Pn,e=>Bn(e,4).getFloat32(0,!1),e=>Bn(e,8).getFloat64(0,!1),e=>Bn(e,8).getBigInt64(0,!1),e=>!1,e=>!0,jt,e=>{const t=G(e),n={};for(let i=0;i{const t=G(e),n=[];for(let i=0;iLs[127-te(e)](e);class Vr extends Ze{constructor(t,n){super(t);this.reader=n,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),Ds(this)?this.count=G(this)+1:this.count=-1),this.count--,this.s}}class Qe extends Ze{constructor(t){super(t);this.s=0,this.count=0}read(){if(this.count===0){this.s=Pn(this);const t=Dr(this.s);this.count=1,t&&(this.s=-this.s,this.count=G(this)+2)}return this.count--,this.s}}class jn extends Ze{constructor(t){super(t);this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){const t=Pn(this),n=t&1;this.diff=t>>1,this.count=1,n&&(this.count=G(this)+2)}return this.s+=this.diff,this.count--,this.s}}class Ms{constructor(t){this.decoder=new Qe(t),this.str=jt(this.decoder),this.spos=0}read(){const t=this.spos+this.decoder.read(),n=this.str.slice(this.spos,t);return this.spos=t,n}}const qr=e=>new Uint8Array(e),Vn=(e,t,n)=>new Uint8Array(e,t,n),xs=e=>new Uint8Array(e),Os=e=>{let t="";for(let n=0;nBuffer.from(e.buffer,e.byteOffset,e.byteLength).toString("base64"),Us=e=>{const t=atob(e),n=qr(t.length);for(let i=0;i{const t=Buffer.from(e,"base64");return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)},Wr=Fr?Os:Ns,Hr=Fr?Us:Fs,Ps=e=>{const t=qr(e.byteLength);return t.set(e),t},Bs=Number.isInteger||(e=>typeof e=="number"&&isFinite(e)&&de(e)===e);class Me{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const dt=()=>new Me,js=e=>{let t=e.cpos;for(let n=0;n{const t=new Uint8Array(js(e));let n=0;for(let i=0;i{const n=e.cbuf.length;n-e.cpos{const n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(n*2),e.cpos=0),e.cbuf[e.cpos++]=t},xe=yt,q=(e,t)=>{for(;t>Qt;)yt(e,_t|Qt&t),t>>>=7;yt(e,Qt&t)},qn=(e,t)=>{const n=Dr(t);for(n&&(t=-t),yt(e,(t>Fn?_t:0)|(n?Bt:0)|Fn&t),t>>>=6;t>0;)yt(e,(t>Qt?_t:0)|Qt&t),t>>>=7},xt=(e,t)=>{const n=unescape(encodeURIComponent(t)),i=n.length;q(e,i);for(let s=0;s{const n=e.cbuf.length,i=e.cpos,s=xn(n-i,t.length),o=t.length-s;e.cbuf.set(t.subarray(0,s),i),e.cpos+=s,o>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(Zt(n*2,o)),e.cbuf.set(t.subarray(s)),e.cpos=o)},ct=(e,t)=>{q(e,t.byteLength),tn(e,t)},Wn=(e,t)=>{Vs(e,t);const n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},qs=(e,t)=>Wn(e,4).setFloat32(0,t,!1),Ws=(e,t)=>Wn(e,8).setFloat64(0,t,!1),Hs=(e,t)=>Wn(e,8).setBigInt64(0,t,!1),$r=new DataView(new ArrayBuffer(4)),$s=e=>($r.setFloat32(0,e),$r.getFloat32(0)===e),pe=(e,t)=>{switch(typeof t){case"string":yt(e,119),xt(e,t);break;case"number":Bs(t)&&t<=As?(yt(e,125),qn(e,t)):$s(t)?(yt(e,124),qs(e,t)):(yt(e,123),Ws(e,t));break;case"bigint":yt(e,122),Hs(e,t);break;case"object":if(t===null)yt(e,126);else if(t instanceof Array){yt(e,117),q(e,t.length);for(let n=0;n0&&q(this,this.count-1),this.count=1,this.w(this,t),this.s=t)}}const zr=e=>{e.count>0&&(qn(e.encoder,e.count===1?e.s:-e.s),e.count>1&&q(e.encoder,e.count-2))};class en{constructor(){this.encoder=new Me,this.s=0,this.count=0}write(t){this.s===t?this.count++:(zr(this),this.count=1,this.s=t)}toUint8Array(){return zr(this),st(this.encoder)}}const Gr=e=>{if(e.count>0){const t=e.diff<<1|(e.count===1?0:1);qn(e.encoder,t),e.count>1&&q(e.encoder,e.count-2)}};class Hn{constructor(){this.encoder=new Me,this.s=0,this.count=0,this.diff=0}write(t){this.diff===t-this.s?(this.s=t,this.count++):(Gr(this),this.count=1,this.diff=t-this.s,this.s=t)}toUint8Array(){return Gr(this),st(this.encoder)}}class Ys{constructor(){this.sarr=[],this.s="",this.lensE=new en}write(t){this.s+=t,this.s.length>19&&(this.sarr.push(this.s),this.s=""),this.lensE.write(t.length)}toUint8Array(){const t=new Me;return this.sarr.push(this.s),this.s="",xt(t,this.sarr.join("")),tn(t,this.lensE.toUint8Array()),st(t)}}const Jr=typeof crypto=="undefined"?null:crypto,zs=Jr!==null?e=>{const t=new ArrayBuffer(e),n=new Uint8Array(t);return Jr.getRandomValues(n),t}:e=>{const t=new ArrayBuffer(e),n=new Uint8Array(t);for(let i=0;i>>0);return t},Gs=Math.random,Kr=()=>new Uint32Array(zs(4))[0],Js=[1e7]+-1e3+-4e3+-8e3+-1e11,Xr=()=>Js.replace(/[018]/g,e=>(e^Kr()&15>>e/4).toString(16)),Ot=Date.now,Ks=e=>new Promise(e),Xs=e=>Promise.reject(e),$n=e=>Promise.resolve(e),ge=e=>new Error(e),Nt=()=>{throw ge("Method unimplemented")},Ut=()=>{throw ge("Unexpected case")},Zs=Object.keys,nn=e=>Zs(e).length,Qs=(e,t)=>{for(const n in e)if(!t(e[n],n))return!1;return!0},Zr=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),to=(e,t)=>e===t||nn(e)===nn(t)&&Qs(e,(n,i)=>(n!==void 0||Zr(t,i))&&t[i]===n),Yn=(e,t,n=0)=>{try{for(;n{},no=(e,t)=>e===t,Oe=(e,t)=>{if(e==null||t==null)return no(e,t);if(e.constructor!==t.constructor)return!1;if(e===t)return!0;switch(e.constructor){case ArrayBuffer:e=new Uint8Array(e),t=new Uint8Array(t);case Uint8Array:{if(e.byteLength!==t.byteLength)return!1;for(let n=0;nnew ro(e,t),ee=typeof document!="undefined"?document:{};typeof DOMParser!="undefined"&&new DOMParser;const io=e=>fs(e,(t,n)=>`${n}:${t};`).join("");ee.ELEMENT_NODE,ee.TEXT_NODE,ee.CDATA_SECTION_NODE,ee.COMMENT_NODE,ee.DOCUMENT_NODE,ee.DOCUMENT_TYPE_NODE,ee.DOCUMENT_FRAGMENT_NODE;const vt=Vt(),Ht=Vt(),zn=Vt(),rn=Vt(),Gn=Vt(),Jn=Vt(),Kn=Vt(),sn=Vt(),Ne=Vt(),so={[vt]:qt("font-weight","bold"),[Ht]:qt("font-weight","normal"),[zn]:qt("color","blue"),[Gn]:qt("color","green"),[rn]:qt("color","grey"),[Jn]:qt("color","red"),[Kn]:qt("color","purple"),[sn]:qt("color","orange"),[Ne]:qt("color","black")},oo={[vt]:"\x1B[1m",[Ht]:"\x1B[2m",[zn]:"\x1B[34m",[Gn]:"\x1B[32m",[rn]:"\x1B[37m",[Jn]:"\x1B[31m",[Kn]:"\x1B[35m",[sn]:"\x1B[38;5;208m",[Ne]:"\x1B[0m"},ao=Ke?e=>{const t=[],n=[];let i=0;for(;i0&&(t.push("\x1B[0m"),n.push(t.join("")));i{const t=[],n=[],i=lt();let s=[],o=0;for(;o0||l.length>0?(t.push("%c"+h),n.push(l)):t.push(h)}else break}for(o>0&&(s=n,s.unshift(t.join("")));o{console.log(...ao(e)),lo.forEach(t=>t.print(e))},lo=new Set,ti=[Gn,Kn,sn,zn];let Xn=0,ei=Ot();const co=e=>{const t=ti[Xn],n=Pr("log"),i=n!==null&&(n==="*"||n==="true"||new RegExp(n,"gi").test(e));return Xn=(Xn+1)%ti.length,e+=": ",i?(...s)=>{const o=Ot(),h=o-ei;ei=o,Qr(t,e,Ne,...s.map(c=>typeof c=="string"||typeof c=="symbol"?c:JSON.stringify(c)),t," +"+h+"ms")}:eo},ni=e=>({[Symbol.iterator](){return this},next:e}),ho=(e,t)=>ni(()=>{let n;do n=e.next();while(!n.done&&!t(n.value));return n}),Zn=(e,t)=>ni(()=>{const{done:n,value:i}=e.next();return{done:n,value:n?void 0:t(i)}});class yl extends ue{constructor(t,n){super();this.doc=t,this.awareness=n}}class Qn{constructor(t,n){this.clock=t,this.len=n}}class ye{constructor(){this.clients=new Map}}const ne=(e,t,n)=>t.clients.forEach((i,s)=>{const o=e.doc.store.clients.get(s);for(let h=0;h{let n=0,i=e.length-1;for(;n<=i;){const s=de((n+i)/2),o=e[s],h=o.clock;if(h<=t){if(t{const n=e.clients.get(t.client);return n!==void 0&&uo(n,t.clock)!==null},tr=e=>{e.clients.forEach(t=>{t.sort((s,o)=>s.clock-o.clock);let n,i;for(n=1,i=1;n=o.clock?s.len=Zt(s.len,o.clock+o.len-s.clock):(i{const t=new ye;for(let n=0;n{if(!t.clients.has(s)){const o=i.slice();for(let h=n+1;h{St(e.clients,t,()=>[]).push(new Qn(n,i))},ri=()=>new ye,fo=e=>{const t=ri();return e.clients.forEach((n,i)=>{const s=[];for(let o=0;o0&&t.clients.set(i,s)}),t},me=(e,t)=>{q(e.restEncoder,t.clients.size),t.clients.forEach((n,i)=>{e.resetDsCurVal(),q(e.restEncoder,i);const s=n.length;q(e.restEncoder,s);for(let o=0;o{const t=new ye,n=G(e.restDecoder);for(let i=0;i0){const h=St(t.clients,s,()=>[]);for(let c=0;c{const i=new ye,s=G(e.restDecoder);for(let o=0;o0){const o=new re;return q(o.restEncoder,0),me(o,i),o.toUint8Array()}return null},si=Kr;class we extends ue{constructor({guid:t=Xr(),collectionid:n=null,gc:i=!0,gcFilter:s=()=>!0,meta:o=null,autoLoad:h=!1,shouldLoad:c=!0}={}){super();this.gc=i,this.gcFilter=s,this.clientID=si(),this.guid=t,this.collectionid=n,this.share=new Map,this.store=new mi,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=c,this.autoLoad=h,this.meta=o,this.isLoaded=!1,this.whenLoaded=Ks(l=>{this.on("load",()=>{this.isLoaded=!0,l(this)})})}load(){const t=this._item;t!==null&&!this.shouldLoad&&tt(t.parent.doc,n=>{n.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(Array.from(this.subdocs).map(t=>t.guid))}transact(t,n=null){tt(this,t,n)}get(t,n=mt){const i=St(this.share,t,()=>{const o=new n;return o._integrate(this,null),o}),s=i.constructor;if(n!==mt&&s!==n)if(s===mt){const o=new n;o._map=i._map,i._map.forEach(h=>{for(;h!==null;h=h.left)h.parent=o}),o._start=i._start;for(let h=o._start;h!==null;h=h.right)h.parent=o;return o._length=i._length,this.share.set(t,o),o._integrate(this,null),o}else throw new Error(`Type with the name ${t} has already been defined with a different constructor`);return i}getArray(t=""){return this.get(t,ve)}getText(t=""){return this.get(t,Ce)}getMap(t=""){return this.get(t,Se)}getXmlFragment(t=""){return this.get(t,ie)}toJSON(){const t={};return this.share.forEach((n,i)=>{t[i]=n.toJSON()}),t}destroy(){Ar(this.subdocs).forEach(n=>n.destroy());const t=this._item;if(t!==null){this._item=null;const n=t.content;n.doc=new we(In(Ge({guid:this.guid},n.opts),{shouldLoad:!1})),n.doc._item=t,tt(t.parent.doc,i=>{const s=n.doc;t.deleted||i.subdocsAdded.add(s),i.subdocsRemoved.add(this)},null,!0)}this.emit("destroyed",[!0]),this.emit("destroy",[this]),super.destroy()}on(t,n){super.on(t,n)}off(t,n){super.off(t,n)}}class oi{constructor(t){this.restDecoder=t}resetDsCurVal(){}readDsClock(){return G(this.restDecoder)}readDsLen(){return G(this.restDecoder)}}class ai extends oi{readLeftID(){return K(G(this.restDecoder),G(this.restDecoder))}readRightID(){return K(G(this.restDecoder),G(this.restDecoder))}readClient(){return G(this.restDecoder)}readInfo(){return te(this.restDecoder)}readString(){return jt(this.restDecoder)}readParentInfo(){return G(this.restDecoder)===1}readTypeRef(){return G(this.restDecoder)}readLen(){return G(this.restDecoder)}readAny(){return fe(this.restDecoder)}readBuf(){return Ps(gt(this.restDecoder))}readJSON(){return JSON.parse(jt(this.restDecoder))}readKey(){return jt(this.restDecoder)}}class po{constructor(t){this.dsCurrVal=0,this.restDecoder=t}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=G(this.restDecoder),this.dsCurrVal}readDsLen(){const t=G(this.restDecoder)+1;return this.dsCurrVal+=t,t}}class be extends po{constructor(t){super(t);this.keys=[],G(t),this.keyClockDecoder=new jn(gt(t)),this.clientDecoder=new Qe(gt(t)),this.leftClockDecoder=new jn(gt(t)),this.rightClockDecoder=new jn(gt(t)),this.infoDecoder=new Vr(gt(t),te),this.stringDecoder=new Ms(gt(t)),this.parentInfoDecoder=new Vr(gt(t),te),this.typeRefDecoder=new Qe(gt(t)),this.lenDecoder=new Qe(gt(t))}readLeftID(){return new _e(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new _e(this.clientDecoder.read(),this.rightClockDecoder.read())}readClient(){return this.clientDecoder.read()}readInfo(){return this.infoDecoder.read()}readString(){return this.stringDecoder.read()}readParentInfo(){return this.parentInfoDecoder.read()===1}readTypeRef(){return this.typeRefDecoder.read()}readLen(){return this.lenDecoder.read()}readAny(){return fe(this.restDecoder)}readBuf(){return gt(this.restDecoder)}readJSON(){return fe(this.restDecoder)}readKey(){const t=this.keyClockDecoder.read();if(t{i=Zt(i,t[0].id.clock);const s=Ft(t,i);q(e.restEncoder,t.length-s),e.writeClient(n),q(e.restEncoder,i);const o=t[s];o.write(e,i-o.id.clock);for(let h=s+1;h{const i=new Map;n.forEach((s,o)=>{ht(t,o)>s&&i.set(o,s)}),hn(t).forEach((s,o)=>{n.has(o)||i.set(o,0)}),q(e.restEncoder,i.size),Array.from(i.entries()).sort((s,o)=>o[0]-s[0]).forEach(([s,o])=>{go(e,t.clients.get(s),s,o)})},yo=(e,t)=>{const n=lt(),i=G(e.restDecoder);for(let s=0;s{const i=[];let s=Array.from(n.keys()).sort((g,f)=>g-f);if(s.length===0)return null;const o=()=>{if(s.length===0)return null;let g=n.get(s[s.length-1]);for(;g.refs.length===g.i;)if(s.pop(),s.length>0)g=n.get(s[s.length-1]);else return null;return g};let h=o();if(h===null&&i.length===0)return null;const c=new mi,l=new Map,m=(g,f)=>{const v=l.get(g);(v==null||v>f)&&l.set(g,f)};let b=h.refs[h.i++];const u=new Map,p=()=>{for(const g of i){const f=g.id.client,v=n.get(f);v?(v.i--,c.clients.set(f,v.refs.slice(v.i)),n.delete(f),v.i=0,v.refs=[]):c.clients.set(f,[g]),s=s.filter(x=>x!==f)}i.length=0};for(;;){if(b.constructor!==Ct){const f=St(u,b.id.client,()=>ht(t,b.id.client))-b.id.clock;if(f<0)i.push(b),m(b.id.client,b.id.clock-1),p();else{const v=b.getMissing(e,t);if(v!==null){i.push(b);const x=n.get(v)||{refs:[],i:0};if(x.refs.length===x.i)m(v,ht(t,v)),p();else{b=x.refs[x.i++];continue}}else(f===0||f0)b=i.pop();else if(h!==null&&h.i0){const g=new re;return rr(g,c,new Map),q(g.restEncoder,0),{missing:l,update:g.toUint8Array()}}return null},wo=(e,t)=>rr(e,t.doc.store,t.beforeState),bo=(e,t,n,i=new be(e))=>tt(t,s=>{s.local=!1;let o=!1;const h=s.doc,c=h.store,l=yo(i,h),m=mo(s,c,l),b=c.pendingStructs;if(b){for(const[p,g]of b.missing)if(gg)&&b.missing.set(p,g)}b.update=fn([b.update,m.update])}}else c.pendingStructs=m;const u=ii(i,s,c);if(c.pendingDs){const p=new be(Mt(c.pendingDs));G(p.restDecoder);const g=ii(p,s,c);u&&g?c.pendingDs=fn([u,g]):c.pendingDs=u||g}else c.pendingDs=u;if(o){const p=c.pendingStructs.update;c.pendingStructs=null,hi(s.doc,p)}},n,!1),hi=(e,t,n,i=be)=>{const s=Mt(t);bo(s,e,n,new i(s))},_o=(e,t,n)=>hi(e,t,n,ai),vo=(e,t,n=new Map)=>{rr(e,t.store,n),me(e,fo(t.store))},So=(e,t=new Uint8Array([0]),n=new re)=>{const i=ui(t);vo(n,e,i);const s=[n.toUint8Array()];if(e.store.pendingDs&&s.push(e.store.pendingDs),e.store.pendingStructs&&s.push(Bo(e.store.pendingStructs.update,t)),s.length>1){if(n.constructor===Fe)return Fo(s.map((o,h)=>h===0?o:Vo(o)));if(n.constructor===re)return fn(s)}return s[0]},Eo=(e,t)=>So(e,t,new Fe),Co=e=>{const t=new Map,n=G(e.restDecoder);for(let i=0;iCo(new oi(Mt(e))),di=(e,t)=>(q(e.restEncoder,t.size),Array.from(t.entries()).sort((n,i)=>i[0]-n[0]).forEach(([n,i])=>{q(e.restEncoder,n),q(e.restEncoder,i)}),e),ko=(e,t)=>di(e,hn(t.store)),Ro=(e,t=new ci)=>(e instanceof Map?di(t,e):ko(t,e),t.toUint8Array()),To=e=>Ro(e,new li);class Ao{constructor(){this.l=[]}}const fi=()=>new Ao,pi=(e,t)=>e.l.push(t),gi=(e,t)=>{const n=e.l,i=n.length;e.l=n.filter(s=>t!==s),i===e.l.length&&console.error("[yjs] Tried to remove event handler that doesn't exist.")},yi=(e,t,n)=>Yn(e.l,[t,n]);class _e{constructor(t,n){this.client=t,this.clock=n}}const an=(e,t)=>e===t||e!==null&&t!==null&&e.client===t.client&&e.clock===t.clock,K=(e,t)=>new _e(e,t),Do=e=>{for(const[t,n]of e.doc.share.entries())if(n===e)return t;throw Ut()},ln=(e,t)=>{for(;t!==null;){if(t.parent===e)return!0;t=t.parent._item}return!1};class Io{constructor(t,n){this.ds=t,this.sv=n}}((e,t)=>new Io(e,t))(ri(),new Map);const Pe=(e,t)=>t===void 0?!e.deleted:t.sv.has(e.id.client)&&(t.sv.get(e.id.client)||0)>e.id.clock&&!on(t.ds,e.id),cn=(e,t)=>{const n=St(e.meta,cn,Ie),i=e.doc.store;n.has(t)||(t.sv.forEach((s,o)=>{s{}),n.add(t))};class mi{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}}const hn=e=>{const t=new Map;return e.clients.forEach((n,i)=>{const s=n[n.length-1];t.set(i,s.id.clock+s.length)}),t},ht=(e,t)=>{const n=e.clients.get(t);if(n===void 0)return 0;const i=n[n.length-1];return i.id.clock+i.length},wi=(e,t)=>{let n=e.clients.get(t.id.client);if(n===void 0)n=[],e.clients.set(t.id.client,n);else{const i=n[n.length-1];if(i.id.clock+i.length!==t.id.clock)throw Ut()}n.push(t)},Ft=(e,t)=>{let n=0,i=e.length-1,s=e[i],o=s.id.clock;if(o===t)return i;let h=de(t/(o+s.length-1)*i);for(;n<=i;){if(s=e[h],o=s.id.clock,o<=t){if(t{const n=e.clients.get(t.client);return n[Ft(n,t.clock)]},ir=(e,t,n)=>{const i=Ft(t,n),s=t[i];return s.id.clock{const n=e.doc.store.clients.get(t.client);return n[ir(e,n,t.clock)]},bi=(e,t,n)=>{const i=t.clients.get(n.client),s=Ft(i,n.clock),o=i[s];return n.clock!==o.id.clock+o.length-1&&o.constructor!==Et&&i.splice(s+1,0,kn(e,o,n.clock-o.id.clock+1)),o},Lo=(e,t,n)=>{const i=e.clients.get(t.id.client);i[Ft(i,t.id.clock)]=n},_i=(e,t,n,i,s)=>{if(i===0)return;const o=n+i;let h=ir(e,t,n),c;do c=t[h++],ot.deleteSet.clients.size===0&&!ps(t.afterState,(n,i)=>t.beforeState.get(i)!==n)?!1:(tr(t.deleteSet),wo(e,t),me(e,t.deleteSet),!0),Si=(e,t,n)=>{const i=t._item;(i===null||i.id.clock<(e.beforeState.get(i.id.client)||0)&&!i.deleted)&&St(e.changed,t,Ie).add(n)},dn=(e,t)=>{const n=e[t-1],i=e[t];n.deleted===i.deleted&&n.constructor===i.constructor&&n.mergeWith(i)&&(e.splice(t,1),i instanceof rt&&i.parentSub!==null&&i.parent._map.get(i.parentSub)===i&&i.parent._map.set(i.parentSub,n))},xo=(e,t,n)=>{for(const[i,s]of e.clients.entries()){const o=t.clients.get(i);for(let h=s.length-1;h>=0;h--){const c=s[h],l=c.clock+c.len;for(let m=Ft(o,c.clock),b=o[m];m{e.clients.forEach((n,i)=>{const s=t.clients.get(i);for(let o=n.length-1;o>=0;o--){const h=n[o],c=xn(s.length-1,1+Ft(s,h.clock+h.len-1));for(let l=c,m=s[l];l>0&&m.id.clock>=h.clock;m=s[--l])dn(s,l)}})},Ei=(e,t)=>{if(tc.push(()=>{(m._item===null||!m._item.deleted)&&m._callObserver(n,l)})),c.push(()=>{n.changedParentTypes.forEach((l,m)=>c.push(()=>{(m._item===null||!m._item.deleted)&&(l=l.filter(b=>b.target._item===null||!b.target._item.deleted),l.forEach(b=>{b.currentTarget=m}),l.sort((b,u)=>b.path.length-u.path.length),yi(m._dEH,l,n))})),c.push(()=>i.emit("afterTransaction",[n,i]))}),Yn(c,[])}finally{i.gc&&xo(o,s,i.gcFilter),Oo(o,s),n.afterState.forEach((b,u)=>{const p=n.beforeState.get(u)||0;if(p!==b){const g=s.clients.get(u),f=Zt(Ft(g,p),1);for(let v=g.length-1;v>=f;v--)dn(g,v)}});for(let b=0;b0&&dn(g,f)}if(!n.local&&n.afterState.get(i.clientID)!==n.beforeState.get(i.clientID)&&(Qr(sn,vt,"[yjs] ",Ht,Jn,"Changed the client-id because another client seems to be using it."),i.clientID=si()),i.emit("afterTransactionCleanup",[n,i]),i._observers.has("update")){const b=new Fe;vi(b,n)&&i.emit("update",[b.toUint8Array(),n.origin,i,n])}if(i._observers.has("updateV2")){const b=new re;vi(b,n)&&i.emit("updateV2",[b.toUint8Array(),n.origin,i,n])}const{subdocsAdded:c,subdocsLoaded:l,subdocsRemoved:m}=n;(c.size>0||m.size>0||l.size>0)&&(c.forEach(b=>{b.clientID=i.clientID,b.collectionid==null&&(b.collectionid=i.collectionid),i.subdocs.add(b)}),m.forEach(b=>i.subdocs.delete(b)),i.emit("subdocs",[{loaded:l,added:c,removed:m},i,n]),m.forEach(b=>b.destroy())),e.length<=t+1?(i._transactionCleanups=[],i.emit("afterAllTransactions",[i,e])):Ei(e,t+1)}}},tt=(e,t,n=null,i=!0)=>{const s=e._transactionCleanups;let o=!1;e._transaction===null&&(o=!0,e._transaction=new Mo(e,n,i),s.push(e._transaction),s.length===1&&e.emit("beforeAllTransactions",[e]),e.emit("beforeTransaction",[e._transaction,e]));try{t(e._transaction)}finally{o&&s[0]===e._transaction&&Ei(s,0)}};class No{constructor(t,n){this.insertions=n,this.deletions=t,this.meta=new Map}}const Ci=(e,t,n)=>{ne(e,n.deletions,i=>{i instanceof rt&&t.scope.some(s=>ln(s,i))&&gr(i,!1)})},ki=(e,t,n)=>{let i=null,s=null;const o=e.doc,h=e.scope;if(tt(o,c=>{for(;t.length>0&&i===null;){const l=o.store,m=t.pop(),b=new Set,u=[];let p=!1;ne(c,m.insertions,g=>{if(g instanceof rt){if(g.redone!==null){let{item:f,diff:v}=ka(l,g.id);v>0&&(f=bt(c,K(f.id.client,f.id.clock+v))),g=f}!g.deleted&&h.some(f=>ln(f,g))&&u.push(g)}}),ne(c,m.deletions,g=>{g instanceof rt&&h.some(f=>ln(f,g))&&!on(m.insertions,g.id)&&b.add(g)}),b.forEach(g=>{p=Yi(c,g,b,m.insertions)!==null||p});for(let g=u.length-1;g>=0;g--){const f=u[g];e.deleteFilter(f)&&(f.delete(c),p=!0)}i=p?m:null}c.changed.forEach((l,m)=>{l.has(null)&&m._searchMarker&&(m._searchMarker.length=0)}),s=c},e),i!=null){const c=s.changedParentTypes;e.emit("stack-item-popped",[{stackItem:i,type:n,changedParentTypes:c},e])}return i};class bl extends ue{constructor(t,{captureTimeout:n=500,deleteFilter:i=()=>!0,trackedOrigins:s=new Set([null])}={}){super();this.scope=[],this.addToScope(t),this.deleteFilter=i,s.add(this),this.trackedOrigins=s,this.undoStack=[],this.redoStack=[],this.undoing=!1,this.redoing=!1,this.doc=this.scope[0].doc,this.lastChange=0,this.doc.on("afterTransaction",o=>{if(!this.scope.some(g=>o.changedParentTypes.has(g))||!this.trackedOrigins.has(o.origin)&&(!o.origin||!this.trackedOrigins.has(o.origin.constructor)))return;const h=this.undoing,c=this.redoing,l=h?this.redoStack:this.undoStack;h?this.stopCapturing():c||this.clear(!1,!0);const m=new ye;o.afterState.forEach((g,f)=>{const v=o.beforeState.get(f)||0,x=g-v;x>0&&Ue(m,f,v,x)});const b=Ot();let u=!1;if(b-this.lastChange0&&!h&&!c){const g=l[l.length-1];g.deletions=er([g.deletions,o.deleteSet]),g.insertions=er([g.insertions,m])}else l.push(new No(o.deleteSet,m)),u=!0;!h&&!c&&(this.lastChange=b),ne(o,o.deleteSet,g=>{g instanceof rt&&this.scope.some(f=>ln(f,g))&&gr(g,!0)});const p=[{stackItem:l[l.length-1],origin:o.origin,type:h?"redo":"undo",changedParentTypes:o.changedParentTypes},this];u?this.emit("stack-item-added",p):this.emit("stack-item-updated",p)}),this.doc.on("destroy",()=>{this.destroy()})}addToScope(t){t=ys(t)?t:[t],t.forEach(n=>{this.scope.every(i=>i!==n)&&this.scope.push(n)})}clear(t=!0,n=!0){(t&&this.canUndo()||n&&this.canRedo())&&this.doc.transact(i=>{t&&(this.undoStack.forEach(s=>Ci(i,this,s)),this.undoStack=[]),n&&(this.redoStack.forEach(s=>Ci(i,this,s)),this.redoStack=[]),this.emit("stack-cleared",[{undoStackCleared:t,redoStackCleared:n}])})}stopCapturing(){this.lastChange=0}undo(){this.undoing=!0;let t;try{t=ki(this,this.undoStack,"undo")}finally{this.undoing=!1}return t}redo(){this.redoing=!0;let t;try{t=ki(this,this.redoStack,"redo")}finally{this.redoing=!1}return t}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}}function*Uo(e){const t=G(e.restDecoder);for(let n=0;nfn(e,ai,Fe),Po=(e,t)=>{if(e.constructor===Et){const{client:n,clock:i}=e.id;return new Et(K(n,i+t),e.length-t)}else if(e.constructor===Ct){const{client:n,clock:i}=e.id;return new Ct(K(n,i+t),e.length-t)}else{const n=e,{client:i,clock:s}=n.id;return new rt(K(i,s+t),null,K(i,s+t-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(t))}},fn=(e,t=be,n=re)=>{if(e.length===1)return e[0];const i=e.map(b=>new t(Mt(b)));let s=i.map(b=>new sr(b,!0)),o=null;const h=new n,c=new or(h);for(;s=s.filter(p=>p.curr!==null),s.sort((p,g)=>{if(p.curr.id.client===g.curr.id.client){const f=p.curr.id.clock-g.curr.id.clock;return f===0?p.curr.constructor===g.curr.constructor?0:p.curr.constructor===Ct?1:-1:f}else return g.curr.id.client-p.curr.id.client}),s.length!==0;){const b=s[0],u=b.curr.id.client;if(o!==null){let p=b.curr,g=!1;for(;p!==null&&p.id.clock+p.length<=o.struct.id.clock+o.struct.length&&p.id.client>=o.struct.id.client;)p=b.next(),g=!0;if(p===null||p.id.client!==u||g&&p.id.clock>o.struct.id.clock+o.struct.length)continue;if(u!==o.struct.id.client)$t(c,o.struct,o.offset),o={struct:p,offset:0},b.next();else if(o.struct.id.clock+o.struct.length0&&(o.struct.constructor===Ct?o.struct.length-=f:p=Po(p,f)),o.struct.mergeWith(p)||($t(c,o.struct,o.offset),o={struct:p,offset:0},b.next())}}else o={struct:b.curr,offset:0},b.next();for(let p=b.curr;p!==null&&p.id.client===u&&p.id.clock===o.struct.id.clock+o.struct.length&&p.constructor!==Ct;p=b.next())$t(c,o.struct,o.offset),o={struct:p,offset:0}}o!==null&&($t(c,o.struct,o.offset),o=null),ar(c);const l=i.map(b=>nr(b)),m=er(l);return me(h,m),h.toUint8Array()},Bo=(e,t,n=be,i=re)=>{const s=ui(t),o=new i,h=new or(o),c=new n(Mt(e)),l=new sr(c,!1);for(;l.curr;){const b=l.curr,u=b.id.client,p=s.get(u)||0;if(l.curr.constructor===Ct){l.next();continue}if(b.id.clock+b.length>p)for($t(h,b,Zt(p-b.id.clock,0)),l.next();l.curr&&l.curr.id.client===u;)$t(h,l.curr,0),l.next();else for(;l.curr&&l.curr.id.client===u&&l.curr.id.clock+l.curr.length<=p;)l.next()}ar(h);const m=nr(c);return me(o,m),o.toUint8Array()},Ri=e=>{e.written>0&&(e.clientStructs.push({written:e.written,restEncoder:st(e.encoder.restEncoder)}),e.encoder.restEncoder=dt(),e.written=0)},$t=(e,t,n)=>{e.written>0&&e.currClient!==t.id.client&&Ri(e),e.written===0&&(e.currClient=t.id.client,e.encoder.writeClient(t.id.client),q(e.encoder.restEncoder,t.id.clock+n)),t.write(e.encoder,n),e.written++},ar=e=>{Ri(e);const t=e.encoder.restEncoder;q(t,e.clientStructs.length);for(let n=0;n{const i=new t(Mt(e)),s=new sr(i,!1),o=new n,h=new or(o);for(let l=s.curr;l!==null;l=s.next())$t(h,l,0);ar(h);const c=nr(i);return me(o,c),o.toUint8Array()},Vo=e=>jo(e,be,Fe);class pn{constructor(t,n){this.target=t,this.currentTarget=t,this.transaction=n,this._changes=null,this._keys=null,this._delta=null}get path(){return qo(this.currentTarget,this.target)}deletes(t){return on(this.transaction.deleteSet,t.id)}get keys(){if(this._keys===null){const t=new Map,n=this.target;this.transaction.changed.get(n).forEach(s=>{if(s!==null){const o=n._map.get(s);let h,c;if(this.adds(o)){let l=o.left;for(;l!==null&&this.adds(l);)l=l.left;if(this.deletes(o))if(l!==null&&this.deletes(l))h="delete",c=Ln(l.content.getContent());else return;else l!==null&&this.deletes(l)?(h="update",c=Ln(l.content.getContent())):(h="add",c=void 0)}else if(this.deletes(o))h="delete",c=Ln(o.content.getContent());else return;t.set(s,{action:h,oldValue:c})}}),this._keys=t}return this._keys}get delta(){return this.changes.delta}adds(t){return t.id.clock>=(this.transaction.beforeState.get(t.id.client)||0)}get changes(){let t=this._changes;if(t===null){const n=this.target,i=Ie(),s=Ie(),o=[];if(t={added:i,deleted:s,delta:o,keys:this.keys},this.transaction.changed.get(n).has(null)){let c=null;const l=()=>{c&&o.push(c)};for(let m=n._start;m!==null;m=m.right)m.deleted?this.deletes(m)&&!this.adds(m)&&((c===null||c.delete===void 0)&&(l(),c={delete:0}),c.delete+=m.length,s.add(m)):this.adds(m)?((c===null||c.insert===void 0)&&(l(),c={insert:[]}),c.insert=c.insert.concat(m.content.getContent()),i.add(m)):((c===null||c.retain===void 0)&&(l(),c={retain:0}),c.retain+=m.length);c!==null&&c.retain===void 0&&l()}this._changes=t}return t}}const qo=(e,t)=>{const n=[];for(;t._item!==null&&t!==e;){if(t._item.parentSub!==null)n.unshift(t._item.parentSub);else{let i=0,s=t._item.parent._start;for(;s!==t._item&&s!==null;)s.deleted||i++,s=s.right;n.unshift(i)}t=t._item.parent}return n},Ti=80;let lr=0;class Wo{constructor(t,n){t.marker=!0,this.p=t,this.index=n,this.timestamp=lr++}}const Ho=e=>{e.timestamp=lr++},Ai=(e,t,n)=>{e.p.marker=!1,e.p=t,t.marker=!0,e.index=n,e.timestamp=lr++},$o=(e,t,n)=>{if(e.length>=Ti){const i=e.reduce((s,o)=>s.timestamp{if(e._start===null||t===0||e._searchMarker===null)return null;const n=e._searchMarker.length===0?null:e._searchMarker.reduce((o,h)=>Mn(t-o.index)t;)i=i.left,!i.deleted&&i.countable&&(s-=i.length);for(;i.left!==null&&i.left.id.client===i.id.client&&i.left.id.clock+i.left.length===i.id.clock;)i=i.left,!i.deleted&&i.countable&&(s-=i.length);return n!==null&&Mn(n.index-s){for(let i=e.length-1;i>=0;i--){const s=e[i];if(n>0){let o=s.p;for(o.marker=!1;o&&(o.deleted||!o.countable);)o=o.left,o&&!o.deleted&&o.countable&&(s.index-=o.length);if(o===null||o.marker===!0){e.splice(i,1);continue}s.p=o,o.marker=!0}(t0&&t===s.index)&&(s.index=Zt(t,s.index+n))}},yn=(e,t,n)=>{const i=e,s=t.changedParentTypes;for(;St(s,e,()=>[]).push(n),e._item!==null;)e=e._item.parent;yi(i._eH,n,t)};class mt{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=fi(),this._dEH=fi(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(t,n){this.doc=t,this._item=n}_copy(){throw Nt()}clone(){throw Nt()}_write(t){}get _first(){let t=this._start;for(;t!==null&&t.deleted;)t=t.right;return t}_callObserver(t,n){!t.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(t){pi(this._eH,t)}observeDeep(t){pi(this._dEH,t)}unobserve(t){gi(this._eH,t)}unobserveDeep(t){gi(this._dEH,t)}toJSON(){}}const Di=(e,t,n)=>{t<0&&(t=e._length+t),n<0&&(n=e._length+n);let i=n-t;const s=[];let o=e._start;for(;o!==null&&i>0;){if(o.countable&&!o.deleted){const h=o.content.getContent();if(h.length<=t)t-=h.length;else{for(let c=t;c0;c++)s.push(h[c]),i--;t=0}}o=o.right}return s},Ii=e=>{const t=[];let n=e._start;for(;n!==null;){if(n.countable&&!n.deleted){const i=n.content.getContent();for(let s=0;s{let n=0,i=e._start;for(;i!==null;){if(i.countable&&!i.deleted){const s=i.content.getContent();for(let o=0;o{const n=[];return mn(e,(i,s)=>{n.push(t(i,s,e))}),n},Yo=e=>{let t=e._start,n=null,i=0;return{[Symbol.iterator](){return this},next:()=>{if(n===null){for(;t!==null&&t.deleted;)t=t.right;if(t===null)return{done:!0,value:void 0};n=t.content.getContent(),i=0,t=t.right}const s=n[i++];return n.length<=i&&(n=null),{done:!1,value:s}}}},Mi=(e,t)=>{const n=gn(e,t);let i=e._start;for(n!==null&&(i=n.p,t-=n.index);i!==null;i=i.right)if(!i.deleted&&i.countable){if(t{let s=n;const o=e.doc,h=o.clientID,c=o.store,l=n===null?t._start:n.right;let m=[];const b=()=>{m.length>0&&(s=new rt(K(h,ht(c,h)),s,s&&s.lastId,l,l&&l.id,t,null,new oe(m)),s.integrate(e,0),m=[])};i.forEach(u=>{if(u===null)m.push(u);else switch(u.constructor){case Number:case Object:case Boolean:case Array:case String:m.push(u);break;default:switch(b(),u.constructor){case Uint8Array:case ArrayBuffer:s=new rt(K(h,ht(c,h)),s,s&&s.lastId,l,l&&l.id,t,null,new Ve(new Uint8Array(u))),s.integrate(e,0);break;case we:s=new rt(K(h,ht(c,h)),s,s&&s.lastId,l,l&&l.id,t,null,new We(u)),s.integrate(e,0);break;default:if(u instanceof mt)s=new rt(K(h,ht(c,h)),s,s&&s.lastId,l,l&&l.id,t,null,new Wt(u)),s.integrate(e,0);else throw new Error("Unexpected content type in insert operation")}}}),b()},xi=ge("Length exceeded!"),Oi=(e,t,n,i)=>{if(n>t._length)throw xi;if(n===0)return t._searchMarker&&Be(t._searchMarker,n,i.length),wn(e,t,null,i);const s=n,o=gn(t,n);let h=t._start;for(o!==null&&(h=o.p,n-=o.index,n===0&&(h=h.prev,n+=h&&h.countable&&!h.deleted?h.length:0));h!==null;h=h.right)if(!h.deleted&&h.countable){if(n<=h.length){n{let s=(t._searchMarker||[]).reduce((o,h)=>h.index>o.index?h:o,{index:0,p:t._start}).p;if(s)for(;s.right;)s=s.right;return wn(e,t,s,n)},Ni=(e,t,n,i)=>{if(i===0)return;const s=n,o=i,h=gn(t,n);let c=t._start;for(h!==null&&(c=h.p,n-=h.index);c!==null&&n>0;c=c.right)!c.deleted&&c.countable&&(n0&&c!==null;)c.deleted||(i0)throw xi;t._searchMarker&&Be(t._searchMarker,s,-o+i)},bn=(e,t,n)=>{const i=t._map.get(n);i!==void 0&&i.delete(e)},cr=(e,t,n,i)=>{const s=t._map.get(n)||null,o=e.doc,h=o.clientID;let c;if(i==null)c=new oe([i]);else switch(i.constructor){case Number:case Object:case Boolean:case Array:case String:c=new oe([i]);break;case Uint8Array:c=new Ve(i);break;case we:c=new We(i);break;default:if(i instanceof mt)c=new Wt(i);else throw new Error("Unexpected content type")}new rt(K(h,ht(o.store,h)),s,s&&s.lastId,null,null,t,n,c).integrate(e,0)},hr=(e,t)=>{const n=e._map.get(t);return n!==void 0&&!n.deleted?n.content.getContent()[n.length-1]:void 0},Ui=e=>{const t={};return e._map.forEach((n,i)=>{n.deleted||(t[i]=n.content.getContent()[n.length-1])}),t},Fi=(e,t)=>{const n=e._map.get(t);return n!==void 0&&!n.deleted},_n=e=>ho(e.entries(),t=>!t[1].deleted);class Go extends pn{constructor(t,n){super(t,n);this._transaction=n}}class ve extends mt{constructor(){super();this._prelimContent=[],this._searchMarker=[]}static from(t){const n=new ve;return n.push(t),n}_integrate(t,n){super._integrate(t,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new ve}clone(){const t=new ve;return t.insert(0,this.toArray().map(n=>n instanceof mt?n.clone():n)),t}get length(){return this._prelimContent===null?this._length:this._prelimContent.length}_callObserver(t,n){super._callObserver(t,n),yn(this,t,new Go(this,t))}insert(t,n){this.doc!==null?tt(this.doc,i=>{Oi(i,this,t,n)}):this._prelimContent.splice(t,0,...n)}push(t){this.doc!==null?tt(this.doc,n=>{zo(n,this,t)}):this._prelimContent.push(...t)}unshift(t){this.insert(0,t)}delete(t,n=1){this.doc!==null?tt(this.doc,i=>{Ni(i,this,t,n)}):this._prelimContent.splice(t,n)}get(t){return Mi(this,t)}toArray(){return Ii(this)}slice(t=0,n=this.length){return Di(this,t,n)}toJSON(){return this.map(t=>t instanceof mt?t.toJSON():t)}map(t){return Li(this,t)}forEach(t){mn(this,t)}[Symbol.iterator](){return Yo(this)}_write(t){t.writeTypeRef(ma)}}const Jo=e=>new ve;class Ko extends pn{constructor(t,n,i){super(t,n);this.keysChanged=i}}class Se extends mt{constructor(t){super();this._prelimContent=null,t===void 0?this._prelimContent=new Map:this._prelimContent=new Map(t)}_integrate(t,n){super._integrate(t,n),this._prelimContent.forEach((i,s)=>{this.set(s,i)}),this._prelimContent=null}_copy(){return new Se}clone(){const t=new Se;return this.forEach((n,i)=>{t.set(i,n instanceof mt?n.clone():n)}),t}_callObserver(t,n){yn(this,t,new Ko(this,t,n))}toJSON(){const t={};return this._map.forEach((n,i)=>{if(!n.deleted){const s=n.content.getContent()[n.length-1];t[i]=s instanceof mt?s.toJSON():s}}),t}get size(){return[..._n(this._map)].length}keys(){return Zn(_n(this._map),t=>t[0])}values(){return Zn(_n(this._map),t=>t[1].content.getContent()[t[1].length-1])}entries(){return Zn(_n(this._map),t=>[t[0],t[1].content.getContent()[t[1].length-1]])}forEach(t){const n={};return this._map.forEach((i,s)=>{i.deleted||t(i.content.getContent()[i.length-1],s,this)}),n}[Symbol.iterator](){return this.entries()}delete(t){this.doc!==null?tt(this.doc,n=>{bn(n,this,t)}):this._prelimContent.delete(t)}set(t,n){return this.doc!==null?tt(this.doc,i=>{cr(i,this,t,n)}):this._prelimContent.set(t,n),n}get(t){return hr(this,t)}has(t){return Fi(this,t)}clear(){this.doc!==null?tt(this.doc,t=>{this.forEach(function(n,i,s){bn(t,s,i)})}):this._prelimContent.clear()}_write(t){t.writeTypeRef(wa)}}const Xo=e=>new Se,Yt=(e,t)=>e===t||typeof e=="object"&&typeof t=="object"&&e&&t&&to(e,t);class ur{constructor(t,n,i,s){this.left=t,this.right=n,this.index=i,this.currentAttributes=s}forward(){switch(this.right===null&&Ut(),this.right.content.constructor){case ut:this.right.deleted||Ee(this.currentAttributes,this.right.content);break;default:this.right.deleted||(this.index+=this.right.length);break}this.left=this.right,this.right=this.right.right}}const Pi=(e,t,n)=>{for(;t.right!==null&&n>0;){switch(t.right.content.constructor){case ut:t.right.deleted||Ee(t.currentAttributes,t.right.content);break;default:t.right.deleted||(n{const i=new Map,s=gn(t,n);if(s){const o=new ur(s.p.left,s.p,s.index,i);return Pi(e,o,n-s.index)}else{const o=new ur(null,t._start,0,i);return Pi(e,o,n)}},Bi=(e,t,n,i)=>{for(;n.right!==null&&(n.right.deleted===!0||n.right.content.constructor===ut&&Yt(i.get(n.right.content.key),n.right.content.value));)n.right.deleted||i.delete(n.right.content.key),n.forward();const s=e.doc,o=s.clientID;i.forEach((h,c)=>{const l=n.left,m=n.right,b=new rt(K(o,ht(s.store,o)),l,l&&l.lastId,m,m&&m.id,t,null,new ut(c,h));b.integrate(e,0),n.right=b,n.forward()})},Ee=(e,t)=>{const{key:n,value:i}=t;i===null?e.delete(n):e.set(n,i)},ji=(e,t)=>{for(;e.right!==null;){if(!(e.right.deleted||e.right.content.constructor===ut&&Yt(t[e.right.content.key]||null,e.right.content.value)))break;e.forward()}},Vi=(e,t,n,i)=>{const s=e.doc,o=s.clientID,h=new Map;for(const c in i){const l=i[c],m=n.currentAttributes.get(c)||null;if(!Yt(m,l)){h.set(c,m);const{left:b,right:u}=n;n.right=new rt(K(o,ht(s.store,o)),b,b&&b.lastId,u,u&&u.id,t,null,new ut(c,l)),n.right.integrate(e,0),n.forward()}}return h},dr=(e,t,n,i,s)=>{n.currentAttributes.forEach((p,g)=>{s[g]===void 0&&(s[g]=null)});const o=e.doc,h=o.clientID;ji(n,s);const c=Vi(e,t,n,s),l=i.constructor===String?new Pt(i):i instanceof mt?new Wt(i):new se(i);let{left:m,right:b,index:u}=n;t._searchMarker&&Be(t._searchMarker,n.index,l.getLength()),b=new rt(K(h,ht(o.store,h)),m,m&&m.lastId,b,b&&b.id,t,null,l),b.integrate(e,0),n.right=b,n.index=u,n.forward(),Bi(e,t,n,c)},qi=(e,t,n,i,s)=>{const o=e.doc,h=o.clientID;ji(n,s);const c=Vi(e,t,n,s);for(;n.right!==null&&(i>0||n.right.content.constructor===ut);){if(!n.right.deleted)switch(n.right.content.constructor){case ut:{const{key:l,value:m}=n.right.content,b=s[l];b!==void 0&&(Yt(b,m)?c.delete(l):c.set(l,m),n.right.delete(e));break}default:i0){let l="";for(;i>0;i--)l+=` +`;n.right=new rt(K(h,ht(o.store,h)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,t,null,new Pt(l)),n.right.integrate(e,0),n.forward()}Bi(e,t,n,c)},Wi=(e,t,n,i,s)=>{let o=n;const h=Je(s);for(;o&&(!o.countable||o.deleted);)!o.deleted&&o.content.constructor===ut&&Ee(h,o.content),o=o.right;let c=0,l=!1;for(;t!==o;){if(n===t&&(l=!0),!t.deleted){const m=t.content;switch(m.constructor){case ut:{const{key:b,value:u}=m;((h.get(b)||null)!==u||(i.get(b)||null)===u)&&(t.delete(e),c++,!l&&(s.get(b)||null)===u&&(i.get(b)||null)!==u&&s.delete(b));break}}}t=t.right}return c},Zo=(e,t)=>{for(;t&&t.right&&(t.right.deleted||!t.right.countable);)t=t.right;const n=new Set;for(;t&&(t.deleted||!t.countable);){if(!t.deleted&&t.content.constructor===ut){const i=t.content.key;n.has(i)?t.delete(e):n.add(i)}t=t.left}},Qo=e=>{let t=0;return tt(e.doc,n=>{let i=e._start,s=e._start,o=lt();const h=Je(o);for(;s;){if(s.deleted===!1)switch(s.content.constructor){case ut:Ee(h,s.content);break;default:t+=Wi(n,i,s,o,h),o=Je(h),i=s;break}s=s.right}}),t},Hi=(e,t,n)=>{const i=n,s=Je(t.currentAttributes),o=t.right;for(;n>0&&t.right!==null;){if(t.right.deleted===!1)switch(t.right.content.constructor){case Wt:case se:case Pt:n{s===null?this.childListChanged=!0:this.keysChanged.add(s)})}get changes(){if(this._changes===null){const t={keys:this.keys,delta:this.delta,added:new Set,deleted:new Set};this._changes=t}return this._changes}get delta(){if(this._delta===null){const t=this.target.doc,n=[];tt(t,i=>{const s=new Map,o=new Map;let h=this.target._start,c=null;const l={};let m="",b=0,u=0;const p=()=>{if(c!==null){let g;switch(c){case"delete":g={delete:u},u=0;break;case"insert":g={insert:m},s.size>0&&(g.attributes={},s.forEach((f,v)=>{f!==null&&(g.attributes[v]=f)})),m="";break;case"retain":if(g={retain:b},Object.keys(l).length>0){g.attributes={};for(const f in l)g.attributes[f]=l[f]}b=0;break}n.push(g),c=null}};for(;h!==null;){switch(h.content.constructor){case Wt:case se:this.adds(h)?this.deletes(h)||(p(),c="insert",m=h.content.getContent()[0],p()):this.deletes(h)?(c!=="delete"&&(p(),c="delete"),u+=1):h.deleted||(c!=="retain"&&(p(),c="retain"),b+=1);break;case Pt:this.adds(h)?this.deletes(h)||(c!=="insert"&&(p(),c="insert"),m+=h.content.str):this.deletes(h)?(c!=="delete"&&(p(),c="delete"),u+=h.length):h.deleted||(c!=="retain"&&(p(),c="retain"),b+=h.length);break;case ut:{const{key:g,value:f}=h.content;if(this.adds(h)){if(!this.deletes(h)){const v=s.get(g)||null;Yt(v,f)?f!==null&&h.delete(i):(c==="retain"&&p(),Yt(f,o.get(g)||null)?delete l[g]:l[g]=f)}}else if(this.deletes(h)){o.set(g,f);const v=s.get(g)||null;Yt(v,f)||(c==="retain"&&p(),l[g]=v)}else if(!h.deleted){o.set(g,f);const v=l[g];v!==void 0&&(Yt(v,f)?v!==null&&h.delete(i):(c==="retain"&&p(),f===null?delete l[g]:l[g]=f))}h.deleted||(c==="insert"&&p(),Ee(s,h.content));break}}h=h.right}for(p();n.length>0;){const g=n[n.length-1];if(g.retain!==void 0&&g.attributes===void 0)n.pop();else break}}),this._delta=n}return this._delta}}class Ce extends mt{constructor(t){super();this._pending=t!==void 0?[()=>this.insert(0,t)]:[],this._searchMarker=[]}get length(){return this._length}_integrate(t,n){super._integrate(t,n);try{this._pending.forEach(i=>i())}catch(i){console.error(i)}this._pending=null}_copy(){return new Ce}clone(){const t=new Ce;return t.applyDelta(this.toDelta()),t}_callObserver(t,n){super._callObserver(t,n);const i=new ta(this,t,n),s=t.doc;if(yn(this,t,i),!t.local){let o=!1;for(const[h,c]of t.afterState.entries()){const l=t.beforeState.get(h)||0;if(c!==l&&(_i(t,s.store.clients.get(h),l,c,m=>{!m.deleted&&m.content.constructor===ut&&(o=!0)}),o))break}o||ne(t,t.deleteSet,h=>{h instanceof Et||o||h.parent===this&&h.content.constructor===ut&&(o=!0)}),tt(s,h=>{o?Qo(this):ne(h,h.deleteSet,c=>{c instanceof Et||c.parent===this&&Zo(h,c)})})}}toString(){let t="",n=this._start;for(;n!==null;)!n.deleted&&n.countable&&n.content.constructor===Pt&&(t+=n.content.str),n=n.right;return t}toJSON(){return this.toString()}applyDelta(t,{sanitize:n=!0}={}){this.doc!==null?tt(this.doc,i=>{const s=new ur(null,this._start,0,new Map);for(let o=0;o0)&&dr(i,this,s,c,h.attributes||{})}else h.retain!==void 0?qi(i,this,s,h.retain,h.attributes||{}):h.delete!==void 0&&Hi(i,s,h.delete)}}):this._pending.push(()=>this.applyDelta(t))}toDelta(t,n,i){const s=[],o=new Map,h=this.doc;let c="",l=this._start;function m(){if(c.length>0){const b={};let u=!1;o.forEach((g,f)=>{u=!0,b[f]=g});const p={insert:c};u&&(p.attributes=b),s.push(p),c=""}}return tt(h,b=>{for(t&&cn(b,t),n&&cn(b,n);l!==null;){if(Pe(l,t)||n!==void 0&&Pe(l,n))switch(l.content.constructor){case Pt:{const u=o.get("ychange");t!==void 0&&!Pe(l,t)?(u===void 0||u.user!==l.id.client||u.state!=="removed")&&(m(),o.set("ychange",i?i("removed",l.id):{type:"removed"})):n!==void 0&&!Pe(l,n)?(u===void 0||u.user!==l.id.client||u.state!=="added")&&(m(),o.set("ychange",i?i("added",l.id):{type:"added"})):u!==void 0&&(m(),o.delete("ychange")),c+=l.content.str;break}case Wt:case se:{m();const u={insert:l.content.getContent()[0]};if(o.size>0){const p={};u.attributes=p,o.forEach((g,f)=>{p[f]=g})}s.push(u);break}case ut:Pe(l,t)&&(m(),Ee(o,l.content));break}l=l.right}m()},cn),s}insert(t,n,i){if(n.length<=0)return;const s=this.doc;s!==null?tt(s,o=>{const h=vn(o,this,t);i||(i={},h.currentAttributes.forEach((c,l)=>{i[l]=c})),dr(o,this,h,n,i)}):this._pending.push(()=>this.insert(t,n,i))}insertEmbed(t,n,i={}){const s=this.doc;s!==null?tt(s,o=>{const h=vn(o,this,t);dr(o,this,h,n,i)}):this._pending.push(()=>this.insertEmbed(t,n,i))}delete(t,n){if(n===0)return;const i=this.doc;i!==null?tt(i,s=>{Hi(s,vn(s,this,t),n)}):this._pending.push(()=>this.delete(t,n))}format(t,n,i){if(n===0)return;const s=this.doc;s!==null?tt(s,o=>{const h=vn(o,this,t);h.right!==null&&qi(o,this,h,n,i)}):this._pending.push(()=>this.format(t,n,i))}removeAttribute(t){this.doc!==null?tt(this.doc,n=>{bn(n,this,t)}):this._pending.push(()=>this.removeAttribute(t))}setAttribute(t,n){this.doc!==null?tt(this.doc,i=>{cr(i,this,t,n)}):this._pending.push(()=>this.setAttribute(t,n))}getAttribute(t){return hr(this,t)}getAttributes(t){return Ui(this)}_write(t){t.writeTypeRef(ba)}}const ea=e=>new Ce;class fr{constructor(t,n=()=>!0){this._filter=n,this._root=t,this._currentNode=t._start,this._firstCall=!0}[Symbol.iterator](){return this}next(){let t=this._currentNode,n=t&&t.content&&t.content.type;if(t!==null&&(!this._firstCall||t.deleted||!this._filter(n)))do if(n=t.content.type,!t.deleted&&(n.constructor===je||n.constructor===ie)&&n._start!==null)t=n._start;else for(;t!==null;)if(t.right!==null){t=t.right;break}else t.parent===this._root?t=null:t=t.parent._item;while(t!==null&&(t.deleted||!this._filter(t.content.type)));return this._firstCall=!1,t===null?{value:void 0,done:!0}:(this._currentNode=t,{value:t.content.type,done:!1})}}class ie extends mt{constructor(){super();this._prelimContent=[]}get firstChild(){const t=this._first;return t?t.content.getContent()[0]:null}_integrate(t,n){super._integrate(t,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new ie}clone(){const t=new ie;return t.insert(0,this.toArray().map(n=>n instanceof mt?n.clone():n)),t}get length(){return this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(t){return new fr(this,t)}querySelector(t){t=t.toUpperCase();const i=new fr(this,s=>s.nodeName&&s.nodeName.toUpperCase()===t).next();return i.done?null:i.value}querySelectorAll(t){return t=t.toUpperCase(),Array.from(new fr(this,n=>n.nodeName&&n.nodeName.toUpperCase()===t))}_callObserver(t,n){yn(this,t,new ia(this,n,t))}toString(){return Li(this,t=>t.toString()).join("")}toJSON(){return this.toString()}toDOM(t=document,n={},i){const s=t.createDocumentFragment();return i!==void 0&&i._createAssociation(s,this),mn(this,o=>{s.insertBefore(o.toDOM(t,n,i),null)}),s}insert(t,n){this.doc!==null?tt(this.doc,i=>{Oi(i,this,t,n)}):this._prelimContent.splice(t,0,...n)}insertAfter(t,n){if(this.doc!==null)tt(this.doc,i=>{const s=t&&t instanceof mt?t._item:t;wn(i,this,s,n)});else{const i=this._prelimContent,s=t===null?0:i.findIndex(o=>o===t)+1;if(s===0&&t!==null)throw ge("Reference item not found");i.splice(s,0,...n)}}delete(t,n=1){this.doc!==null?tt(this.doc,i=>{Ni(i,this,t,n)}):this._prelimContent.splice(t,n)}toArray(){return Ii(this)}push(t){this.insert(this.length,t)}unshift(t){this.insert(0,t)}get(t){return Mi(this,t)}slice(t=0,n=this.length){return Di(this,t,n)}_write(t){t.writeTypeRef(va)}}const na=e=>new ie;class je extends ie{constructor(t="UNDEFINED"){super();this.nodeName=t,this._prelimAttrs=new Map}get nextSibling(){const t=this._item?this._item.next:null;return t?t.content.type:null}get prevSibling(){const t=this._item?this._item.prev:null;return t?t.content.type:null}_integrate(t,n){super._integrate(t,n),this._prelimAttrs.forEach((i,s)=>{this.setAttribute(s,i)}),this._prelimAttrs=null}_copy(){return new je(this.nodeName)}clone(){const t=new je(this.nodeName),n=this.getAttributes();for(const i in n)t.setAttribute(i,n[i]);return t.insert(0,this.toArray().map(i=>i instanceof mt?i.clone():i)),t}toString(){const t=this.getAttributes(),n=[],i=[];for(const c in t)i.push(c);i.sort();const s=i.length;for(let c=0;c0?" "+n.join(" "):"";return`<${o}${h}>${super.toString()}`}removeAttribute(t){this.doc!==null?tt(this.doc,n=>{bn(n,this,t)}):this._prelimAttrs.delete(t)}setAttribute(t,n){this.doc!==null?tt(this.doc,i=>{cr(i,this,t,n)}):this._prelimAttrs.set(t,n)}getAttribute(t){return hr(this,t)}hasAttribute(t){return Fi(this,t)}getAttributes(t){return Ui(this)}toDOM(t=document,n={},i){const s=t.createElement(this.nodeName),o=this.getAttributes();for(const h in o)s.setAttribute(h,o[h]);return mn(this,h=>{s.appendChild(h.toDOM(t,n,i))}),i!==void 0&&i._createAssociation(s,this),s}_write(t){t.writeTypeRef(_a),t.writeKey(this.nodeName)}}const ra=e=>new je(e.readKey());class ia extends pn{constructor(t,n,i){super(t,i);this.childListChanged=!1,this.attributesChanged=new Set,n.forEach(s=>{s===null?this.childListChanged=!0:this.attributesChanged.add(s)})}}class Sn extends Se{constructor(t){super();this.hookName=t}_copy(){return new Sn(this.hookName)}clone(){const t=new Sn(this.hookName);return this.forEach((n,i)=>{t.set(i,n)}),t}toDOM(t=document,n={},i){const s=n[this.hookName];let o;return s!==void 0?o=s.createDom(this):o=document.createElement(this.hookName),o.setAttribute("data-yjs-hook",this.hookName),i!==void 0&&i._createAssociation(o,this),o}_write(t){t.writeTypeRef(Sa),t.writeKey(this.hookName)}}const sa=e=>new Sn(e.readKey());class En extends Ce{get nextSibling(){const t=this._item?this._item.next:null;return t?t.content.type:null}get prevSibling(){const t=this._item?this._item.prev:null;return t?t.content.type:null}_copy(){return new En}clone(){const t=new En;return t.applyDelta(this.toDelta()),t}toDOM(t=document,n,i){const s=t.createTextNode(this.toString());return i!==void 0&&i._createAssociation(s,this),s}toString(){return this.toDelta().map(t=>{const n=[];for(const s in t.attributes){const o=[];for(const h in t.attributes[s])o.push({key:h,value:t.attributes[s][h]});o.sort((h,c)=>h.keys.nodeName=0;s--)i+=``;return i}).join("")}toJSON(){return this.toString()}_write(t){t.writeTypeRef(Ea)}}const oa=e=>new En;class pr{constructor(t,n){this.id=t,this.length=n}get deleted(){throw Nt()}mergeWith(t){return!1}write(t,n,i){throw Nt()}integrate(t,n){throw Nt()}}const aa=0;class Et extends pr{get deleted(){return!0}delete(){}mergeWith(t){return this.constructor!==t.constructor?!1:(this.length+=t.length,!0)}integrate(t,n){n>0&&(this.id.clock+=n,this.length-=n),wi(t.doc.store,this)}write(t,n){t.writeInfo(aa),t.writeLen(this.length-n)}getMissing(t,n){return null}}class Ve{constructor(t){this.content=t}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new Ve(this.content)}splice(t){throw Nt()}mergeWith(t){return!1}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeBuf(this.content)}getRef(){return 3}}const la=e=>new Ve(e.readBuf());class qe{constructor(t){this.len=t}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new qe(this.len)}splice(t){const n=new qe(this.len-t);return this.len=t,n}mergeWith(t){return this.len+=t.len,!0}integrate(t,n){Ue(t.deleteSet,n.id.client,n.id.clock,this.len),n.markDeleted()}delete(t){}gc(t){}write(t,n){t.writeLen(this.len-n)}getRef(){return 1}}const ca=e=>new qe(e.readLen()),$i=(e,t)=>new we(In(Ge({guid:e},t),{shouldLoad:t.shouldLoad||t.autoLoad||!1}));class We{constructor(t){t._item&&console.error("This document was already integrated as a sub-document. You should create a second instance instead with the same guid."),this.doc=t;const n={};this.opts=n,t.gc||(n.gc=!1),t.autoLoad&&(n.autoLoad=!0),t.meta!==null&&(n.meta=t.meta)}getLength(){return 1}getContent(){return[this.doc]}isCountable(){return!0}copy(){return new We($i(this.doc.guid,this.opts))}splice(t){throw Nt()}mergeWith(t){return!1}integrate(t,n){this.doc._item=n,t.subdocsAdded.add(this.doc),this.doc.shouldLoad&&t.subdocsLoaded.add(this.doc)}delete(t){t.subdocsAdded.has(this.doc)?t.subdocsAdded.delete(this.doc):t.subdocsRemoved.add(this.doc)}gc(t){}write(t,n){t.writeString(this.doc.guid),t.writeAny(this.opts)}getRef(){return 9}}const ha=e=>new We($i(e.readString(),e.readAny()));class se{constructor(t){this.embed=t}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new se(this.embed)}splice(t){throw Nt()}mergeWith(t){return!1}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeJSON(this.embed)}getRef(){return 5}}const ua=e=>new se(e.readJSON());class ut{constructor(t,n){this.key=t,this.value=n}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new ut(this.key,this.value)}splice(t){throw Nt()}mergeWith(t){return!1}integrate(t,n){n.parent._searchMarker=null}delete(t){}gc(t){}write(t,n){t.writeKey(this.key),t.writeJSON(this.value)}getRef(){return 6}}const da=e=>new ut(e.readKey(),e.readJSON());class Cn{constructor(t){this.arr=t}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new Cn(this.arr)}splice(t){const n=new Cn(this.arr.slice(t));return this.arr=this.arr.slice(0,t),n}mergeWith(t){return this.arr=this.arr.concat(t.arr),!0}integrate(t,n){}delete(t){}gc(t){}write(t,n){const i=this.arr.length;t.writeLen(i-n);for(let s=n;s{const t=e.readLen(),n=[];for(let i=0;i{const t=e.readLen(),n=[];for(let i=0;i=55296&&i<=56319&&(this.str=this.str.slice(0,t-1)+"\uFFFD",n.str="\uFFFD"+n.str.slice(1)),n}mergeWith(t){return this.str+=t.str,!0}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeString(n===0?this.str:this.str.slice(n))}getRef(){return 4}}const ga=e=>new Pt(e.readString()),ya=[Jo,Xo,ea,ra,na,sa,oa],ma=0,wa=1,ba=2,_a=3,va=4,Sa=5,Ea=6;class Wt{constructor(t){this.type=t}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new Wt(this.type._copy())}splice(t){throw Nt()}mergeWith(t){return!1}integrate(t,n){this.type._integrate(t.doc,n)}delete(t){let n=this.type._start;for(;n!==null;)n.deleted?t._mergeStructs.push(n):n.delete(t),n=n.right;this.type._map.forEach(i=>{i.deleted?t._mergeStructs.push(i):i.delete(t)}),t.changed.delete(this.type)}gc(t){let n=this.type._start;for(;n!==null;)n.gc(t,!0),n=n.right;this.type._start=null,this.type._map.forEach(i=>{for(;i!==null;)i.gc(t,!0),i=i.left}),this.type._map=new Map}write(t,n){this.type._write(t)}getRef(){return 7}}const Ca=e=>new Wt(ya[e.readTypeRef()](e)),ka=(e,t)=>{let n=t,i=0,s;do i>0&&(n=K(n.client,n.clock+i)),s=un(e,n),i=n.clock-s.id.clock,n=s.redone;while(n!==null&&s instanceof rt);return{item:s,diff:i}},gr=(e,t)=>{for(;e!==null&&e.keep!==t;)e.keep=t,e=e.parent._item},kn=(e,t,n)=>{const{client:i,clock:s}=t.id,o=new rt(K(i,s+n),t,K(i,s+n-1),t.right,t.rightOrigin,t.parent,t.parentSub,t.content.splice(n));return t.deleted&&o.markDeleted(),t.keep&&(o.keep=!0),t.redone!==null&&(o.redone=K(t.redone.client,t.redone.clock+n)),t.right=o,o.right!==null&&(o.right.left=o),e._mergeStructs.push(o),o.parentSub!==null&&o.right===null&&o.parent._map.set(o.parentSub,o),t.length=n,o},Yi=(e,t,n,i)=>{const s=e.doc,o=s.store,h=s.clientID,c=t.redone;if(c!==null)return bt(e,c);let l=t.parent._item,m=null,b;if(l!==null&&l.deleted===!0){if(l.redone===null&&(!n.has(l)||Yi(e,l,n,i)===null))return null;for(;l.redone!==null;)l=bt(e,l.redone)}const u=l===null?t.parent:l.content.type;if(t.parentSub===null){for(m=t.left,b=t;m!==null;){let v=m;for(;v!==null&&v.parent._item!==l;)v=v.redone===null?null:bt(e,v.redone);if(v!==null&&v.parent._item===l){m=v;break}m=m.left}for(;b!==null;){let v=b;for(;v!==null&&v.parent._item!==l;)v=v.redone===null?null:bt(e,v.redone);if(v!==null&&v.parent._item===l){b=v;break}b=b.right}}else if(b=null,t.right){for(m=t;m!==null&&m.right!==null&&on(i,m.right.id);)m=m.right;for(;m!==null&&m.redone!==null;)m=bt(e,m.redone);if(m===null||m.parent._item!==l||m&&m.right!==null)return null}else m=u._map.get(t.parentSub)||null;const p=ht(o,h),g=K(h,p),f=new rt(g,m,m&&m.lastId,b,b&&b.id,u,t.parentSub,t.content.copy());return t.redone=g,gr(f,!0),f.integrate(e,0),f};class rt extends pr{constructor(t,n,i,s,o,h,c,l){super(t,l.getLength());this.origin=i,this.left=n,this.right=s,this.rightOrigin=o,this.parent=h,this.parentSub=c,this.redone=null,this.content=l,this.info=this.content.isCountable()?jr:0}set marker(t){(this.info&Un)>0!==t&&(this.info^=Un)}get marker(){return(this.info&Un)>0}get keep(){return(this.info&Br)>0}set keep(t){this.keep!==t&&(this.info^=Br)}get countable(){return(this.info&jr)>0}get deleted(){return(this.info&Nn)>0}set deleted(t){this.deleted!==t&&(this.info^=Nn)}markDeleted(){this.info|=Nn}getMissing(t,n){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=ht(n,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=ht(n,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===_e&&this.id.client!==this.parent.client&&this.parent.clock>=ht(n,this.parent.client))return this.parent.client;if(this.origin&&(this.left=bi(t,n,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=bt(t,this.rightOrigin),this.rightOrigin=this.right.id),(this.left&&this.left.constructor===Et||this.right&&this.right.constructor===Et)&&(this.parent=null),!this.parent)this.left&&this.left.constructor===rt&&(this.parent=this.left.parent,this.parentSub=this.left.parentSub),this.right&&this.right.constructor===rt&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);else if(this.parent.constructor===_e){const i=un(n,this.parent);i.constructor===Et?this.parent=null:this.parent=i.content.type}return null}integrate(t,n){if(n>0&&(this.id.clock+=n,this.left=bi(t,t.doc.store,K(this.id.client,this.id.clock-1)),this.origin=this.left.lastId,this.content=this.content.splice(n),this.length-=n),this.parent){if(!this.left&&(!this.right||this.right.left!==null)||this.left&&this.left.right!==this.right){let i=this.left,s;if(i!==null)s=i.right;else if(this.parentSub!==null)for(s=this.parent._map.get(this.parentSub)||null;s!==null&&s.left!==null;)s=s.left;else s=this.parent._start;const o=new Set,h=new Set;for(;s!==null&&s!==this.right;){if(h.add(s),o.add(s),an(this.origin,s.origin)){if(s.id.client{i.p===t&&(i.p=this,!this.deleted&&this.countable&&(i.index-=this.length))}),t.keep&&(this.keep=!0),this.right=t.right,this.right!==null&&(this.right.left=this),this.length+=t.length,!0}return!1}delete(t){if(!this.deleted){const n=this.parent;this.countable&&this.parentSub===null&&(n._length-=this.length),this.markDeleted(),Ue(t.deleteSet,this.id.client,this.id.clock,this.length),Si(t,n,this.parentSub),this.content.delete(t)}}gc(t,n){if(!this.deleted)throw Ut();this.content.gc(t),n?Lo(t,this,new Et(this.id,this.length)):this.content=new qe(this.length)}write(t,n){const i=n>0?K(this.id.client,this.id.clock+n-1):this.origin,s=this.rightOrigin,o=this.parentSub,h=this.content.getRef()&Xe|(i===null?0:_t)|(s===null?0:Bt)|(o===null?0:Le);if(t.writeInfo(h),i!==null&&t.writeLeftID(i),s!==null&&t.writeRightID(s),i===null&&s===null){const c=this.parent;if(c._item!==void 0){const l=c._item;if(l===null){const m=Do(c);t.writeParentInfo(!0),t.writeString(m)}else t.writeParentInfo(!1),t.writeLeftID(l.id)}else c.constructor===String?(t.writeParentInfo(!0),t.writeString(c)):c.constructor===_e?(t.writeParentInfo(!1),t.writeLeftID(c)):Ut();o!==null&&t.writeString(o)}this.content.write(t,n)}}const zi=(e,t)=>Ra[t&Xe](e),Ra=[()=>{Ut()},ca,fa,la,ga,ua,da,Ca,pa,ha,()=>{Ut()}],Ta=10;class Ct extends pr{get deleted(){return!0}delete(){}mergeWith(t){return this.constructor!==t.constructor?!1:(this.length+=t.length,!0)}integrate(t,n){Ut()}write(t,n){t.writeInfo(Ta),q(t.restEncoder,this.length-n)}getMissing(t,n){return null}}const Gi=typeof window!="undefined"?window:typeof global!="undefined"?global:{},Ji="__ $YJS$ __";Gi[Ji]===!0&&console.warn("Yjs was already imported. Importing different versions of Yjs often leads to issues."),Gi[Ji]=!0;const Aa=1200,Da=2500,Rn=3e4,yr=e=>{if(e.shouldConnect&&e.ws===null){const t=new WebSocket(e.url),n=e.binaryType;let i=null;n&&(t.binaryType=n),e.ws=t,e.connecting=!0,e.connected=!1,t.onmessage=h=>{e.lastMessageReceived=Ot();const c=h.data,l=typeof c=="string"?JSON.parse(c):c;l&&l.type==="pong"&&(clearTimeout(i),i=setTimeout(o,Rn/2)),e.emit("message",[l,e])};const s=h=>{e.ws!==null&&(e.ws=null,e.connecting=!1,e.connected?(e.connected=!1,e.emit("disconnect",[{type:"disconnect",error:h},e])):e.unsuccessfulReconnects++,setTimeout(yr,xn(ms(e.unsuccessfulReconnects+1)*Aa,Da),e)),clearTimeout(i)},o=()=>{e.ws===t&&e.send({type:"ping"})};t.onclose=()=>s(null),t.onerror=h=>s(h),t.onopen=()=>{e.lastMessageReceived=Ot(),e.connecting=!1,e.connected=!0,e.unsuccessfulReconnects=0,e.emit("connect",[{type:"connect"},e]),i=setTimeout(o,Rn/2)}}};class Ia extends ue{constructor(t,{binaryType:n}={}){super();this.url=t,this.ws=null,this.binaryType=n||null,this.connected=!1,this.connecting=!1,this.unsuccessfulReconnects=0,this.lastMessageReceived=0,this.shouldConnect=!0,this._checkInterval=setInterval(()=>{this.connected&&Rnn.key===t&&this.onmessage!==null&&this.onmessage({data:Hr(n.newValue||"")}))}postMessage(t){Ur.setItem(this.room,Wr(xs(t)))}}const xa=typeof BroadcastChannel=="undefined"?Ma:BroadcastChannel,mr=e=>St(La,e,()=>{const t=new Set,n=new xa(e);return n.onmessage=i=>t.forEach(s=>s(i.data)),{bc:n,subs:t}}),Oa=(e,t)=>mr(e).subs.add(t),Na=(e,t)=>mr(e).subs.delete(t),Ua=(e,t)=>{const n=mr(e);n.bc.postMessage(t),n.subs.forEach(i=>i(t))},Fa=()=>{let e=!0;return(t,n)=>{if(e){e=!1;try{t()}finally{e=!0}}else n!==void 0&&n()}};var kt=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function Tn(e){throw new Error('Could not dynamically require "'+e+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var Ki={exports:{}};(function(e,t){(function(n){e.exports=n()})(function(){var n=Math.floor,i=Math.abs,s=Math.pow;return function(){function o(h,c,l){function m(p,g){if(!c[p]){if(!h[p]){var f=typeof Tn=="function"&&Tn;if(!g&&f)return f(p,!0);if(b)return b(p,!0);var v=new Error("Cannot find module '"+p+"'");throw v.code="MODULE_NOT_FOUND",v}var x=c[p]={exports:{}};h[p][0].call(x.exports,function(M){var F=h[p][1][M];return m(F||M)},x,x.exports,o,h,c,l)}return c[p].exports}for(var b=typeof Tn=="function"&&Tn,u=0;u>16,S[R++]=255&C>>8,S[R++]=255&C;return A===2&&(C=v[E.charCodeAt(D)]<<2|v[E.charCodeAt(D+1)]>>4,S[R++]=255&C),A===1&&(C=v[E.charCodeAt(D)]<<10|v[E.charCodeAt(D+1)]<<4|v[E.charCodeAt(D+2)]>>2,S[R++]=255&C>>8,S[R++]=255&C),S}function u(E){return f[63&E>>18]+f[63&E>>12]+f[63&E>>6]+f[63&E]}function p(E,C,D){for(var y,k=[],A=C;AR?R:S+A));return y===1?(C=E[D-1],k.push(f[C>>2]+f[63&C<<4]+"==")):y===2&&(C=(E[D-2]<<8)+E[D-1],k.push(f[C>>10]+f[63&C>>4]+f[63&C<<2]+"=")),k.join("")}c.byteLength=function(E){var C=l(E),D=C[0],y=C[1];return 3*(D+y)/4-y},c.toByteArray=b,c.fromByteArray=g;for(var f=[],v=[],x=typeof Uint8Array=="undefined"?Array:Uint8Array,M="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",F=0,w=M.length;Fr)throw new RangeError('The value "'+r+'" is invalid for option "size"')}function f(r,a,d){return g(r),0>=r||a===void 0?b(r):typeof d=="string"?b(r).fill(a,d):b(r).fill(a)}function v(r){return g(r),b(0>r?0:0|E(r))}function x(r,a){if((typeof a!="string"||a==="")&&(a="utf8"),!u.isEncoding(a))throw new TypeError("Unknown encoding: "+a);var d=0|C(r,a),T=b(d),I=T.write(r,a);return I!==d&&(T=T.slice(0,I)),T}function M(r){for(var a=0>r.length?0:0|E(r.length),d=b(a),T=0;Ta||r.byteLength=2147483647)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+2147483647 .toString(16)+" bytes");return 0|r}function C(r,a){if(u.isBuffer(r))return r.length;if(ArrayBuffer.isView(r)||L(r,ArrayBuffer))return r.byteLength;if(typeof r!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof r);var d=r.length,T=2>>1;case"base64":return Dt(r).length;default:if(I)return T?-1:ce(r).length;a=(""+a).toLowerCase(),I=!0}}function D(r,a,d){var T=!1;if((a===void 0||0>a)&&(a=0),a>this.length||((d===void 0||d>this.length)&&(d=this.length),0>=d)||(d>>>=0,a>>>=0,d<=a))return"";for(r||(r="utf8");;)switch(r){case"hex":return Tt(this,a,d);case"utf8":case"utf-8":return et(this,a,d);case"ascii":return Y(this,a,d);case"latin1":case"binary":return Re(this,a,d);case"base64":return J(this,a,d);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Gt(this,a,d);default:if(T)throw new TypeError("Unknown encoding: "+r);r=(r+"").toLowerCase(),T=!0}}function y(r,a,d){var T=r[a];r[a]=r[d],r[d]=T}function k(r,a,d,T,I){if(r.length===0)return-1;if(typeof d=="string"?(T=d,d=0):2147483647d&&(d=-2147483648),d=+d,N(d)&&(d=I?0:r.length-1),0>d&&(d=r.length+d),d>=r.length){if(I)return-1;d=r.length-1}else if(0>d)if(I)d=0;else return-1;if(typeof a=="string"&&(a=u.from(a,T)),u.isBuffer(a))return a.length===0?-1:A(r,a,d,T,I);if(typeof a=="number")return a&=255,typeof Uint8Array.prototype.indexOf=="function"?I?Uint8Array.prototype.indexOf.call(r,a,d):Uint8Array.prototype.lastIndexOf.call(r,a,d):A(r,[a],d,T,I);throw new TypeError("val must be string, number or Buffer")}function A(r,a,d,T,I){function U(Te,ze){return j===1?Te[ze]:Te.readUInt16BE(ze*j)}var j=1,Z=r.length,it=a.length;if(T!==void 0&&(T=(T+"").toLowerCase(),T==="ucs2"||T==="ucs-2"||T==="utf16le"||T==="utf-16le")){if(2>r.length||2>a.length)return-1;j=2,Z/=2,it/=2,d/=2}var Q;if(I){var X=-1;for(Q=d;QZ&&(d=Z-it),Q=d;0<=Q;Q--){for(var wt=!0,he=0;heI&&(T=I)):T=I;var U=a.length;T>U/2&&(T=U/2);for(var j,Z=0;ZU&&(j=U):Z===2?(it=r[I+1],(192&it)==128&&(wt=(31&U)<<6|63&it,127wt||57343wt&&(j=wt)))}j===null?(j=65533,Z=1):65535>>10),j=56320|1023&j),T.push(j),I+=Z}return ot(T)}function ot(r){var a=r.length;if(a<=4096)return l.apply(String,r);for(var d="",T=0;Ta)&&(a=0),(!d||0>d||d>T)&&(d=T);for(var I="",U=a;Ur)throw new RangeError("offset is not uint");if(r+a>d)throw new RangeError("Trying to access beyond buffer length")}function nt(r,a,d,T,I,U){if(!u.isBuffer(r))throw new TypeError('"buffer" argument must be a Buffer instance');if(a>I||ar.length)throw new RangeError("Index out of range")}function At(r,a,d,T){if(d+T>r.length)throw new RangeError("Index out of range");if(0>d)throw new RangeError("Index out of range")}function Jt(r,a,d,T,I){return a=+a,d>>>=0,I||At(r,a,d,4),V.write(r,a,d,T,23,4),d+4}function Kt(r,a,d,T,I){return a=+a,d>>>=0,I||At(r,a,d,8),V.write(r,a,d,T,52,8),d+8}function $e(r){if(r=r.split("=")[0],r=r.trim().replace(_,""),2>r.length)return"";for(;r.length%4!=0;)r+="=";return r}function le(r){return 16>r?"0"+r.toString(16):r.toString(16)}function ce(r,a){a=a||1/0;for(var d,T=r.length,I=null,U=[],j=0;jd){if(!I){if(56319d){-1<(a-=3)&&U.push(239,191,189),I=d;continue}d=(I-55296<<10|d-56320)+65536}else I&&-1<(a-=3)&&U.push(239,191,189);if(I=null,128>d){if(0>(a-=1))break;U.push(d)}else if(2048>d){if(0>(a-=2))break;U.push(192|d>>6,128|63&d)}else if(65536>d){if(0>(a-=3))break;U.push(224|d>>12,128|63&d>>6,128|63&d)}else if(1114112>d){if(0>(a-=4))break;U.push(240|d>>18,128|63&d>>12,128|63&d>>6,128|63&d)}else throw new Error("Invalid code point")}return U}function Ye(r){for(var a=[],d=0;d(a-=2));++j)d=r.charCodeAt(j),T=d>>8,I=d%256,U.push(I),U.push(T);return U}function Dt(r){return B.toByteArray($e(r))}function It(r,a,d,T){for(var I=0;I=a.length||I>=r.length);++I)a[I+d]=r[I];return I}function L(r,a){return r instanceof a||r!=null&&r.constructor!=null&&r.constructor.name!=null&&r.constructor.name===a.name}function N(r){return r!==r}var B=o("base64-js"),V=o("ieee754");c.Buffer=u,c.SlowBuffer=function(r){return+r!=r&&(r=0),u.alloc(+r)},c.INSPECT_MAX_BYTES=50,c.kMaxLength=2147483647,u.TYPED_ARRAY_SUPPORT=function(){try{var r=new Uint8Array(1);return r.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},r.foo()===42}catch{return!1}}(),u.TYPED_ARRAY_SUPPORT||typeof console=="undefined"||typeof console.error!="function"||console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."),Object.defineProperty(u.prototype,"parent",{enumerable:!0,get:function(){return u.isBuffer(this)?this.buffer:void 0}}),Object.defineProperty(u.prototype,"offset",{enumerable:!0,get:function(){return u.isBuffer(this)?this.byteOffset:void 0}}),typeof Symbol!="undefined"&&Symbol.species!=null&&u[Symbol.species]===u&&Object.defineProperty(u,Symbol.species,{value:null,configurable:!0,enumerable:!1,writable:!1}),u.poolSize=8192,u.from=function(r,a,d){return p(r,a,d)},u.prototype.__proto__=Uint8Array.prototype,u.__proto__=Uint8Array,u.alloc=function(r,a,d){return f(r,a,d)},u.allocUnsafe=function(r){return v(r)},u.allocUnsafeSlow=function(r){return v(r)},u.isBuffer=function(r){return r!=null&&r._isBuffer===!0&&r!==u.prototype},u.compare=function(r,a){if(L(r,Uint8Array)&&(r=u.from(r,r.offset,r.byteLength)),L(a,Uint8Array)&&(a=u.from(a,a.offset,a.byteLength)),!u.isBuffer(r)||!u.isBuffer(a))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(r===a)return 0;for(var d=r.length,T=a.length,I=0,U=m(d,T);Ia&&(r+=" ... "),""},u.prototype.compare=function(r,a,d,T,I){if(L(r,Uint8Array)&&(r=u.from(r,r.offset,r.byteLength)),!u.isBuffer(r))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof r);if(a===void 0&&(a=0),d===void 0&&(d=r?r.length:0),T===void 0&&(T=0),I===void 0&&(I=this.length),0>a||d>r.length||0>T||I>this.length)throw new RangeError("out of range index");if(T>=I&&a>=d)return 0;if(T>=I)return-1;if(a>=d)return 1;if(a>>>=0,d>>>=0,T>>>=0,I>>>=0,this===r)return 0;for(var U=I-T,j=d-a,Z=m(U,j),it=this.slice(T,I),Q=r.slice(a,d),X=0;X>>=0,isFinite(d)?(d>>>=0,T===void 0&&(T="utf8")):(T=d,d=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");var I=this.length-a;if((d===void 0||d>I)&&(d=I),0d||0>a)||a>this.length)throw new RangeError("Attempt to write outside buffer bounds");T||(T="utf8");for(var U=!1;;)switch(T){case"hex":return S(this,r,a,d);case"utf8":case"utf-8":return R(this,r,a,d);case"ascii":return O(this,r,a,d);case"latin1":case"binary":return P(this,r,a,d);case"base64":return W(this,r,a,d);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return z(this,r,a,d);default:if(U)throw new TypeError("Unknown encoding: "+T);T=(""+T).toLowerCase(),U=!0}},u.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}},u.prototype.slice=function(r,a){var d=this.length;r=~~r,a=a===void 0?d:~~a,0>r?(r+=d,0>r&&(r=0)):r>d&&(r=d),0>a?(a+=d,0>a&&(a=0)):a>d&&(a=d),a>>=0,a>>>=0,d||at(r,a,this.length);for(var T=this[r],I=1,U=0;++U>>=0,a>>>=0,d||at(r,a,this.length);for(var T=this[r+--a],I=1;0>>=0,a||at(r,1,this.length),this[r]},u.prototype.readUInt16LE=function(r,a){return r>>>=0,a||at(r,2,this.length),this[r]|this[r+1]<<8},u.prototype.readUInt16BE=function(r,a){return r>>>=0,a||at(r,2,this.length),this[r]<<8|this[r+1]},u.prototype.readUInt32LE=function(r,a){return r>>>=0,a||at(r,4,this.length),(this[r]|this[r+1]<<8|this[r+2]<<16)+16777216*this[r+3]},u.prototype.readUInt32BE=function(r,a){return r>>>=0,a||at(r,4,this.length),16777216*this[r]+(this[r+1]<<16|this[r+2]<<8|this[r+3])},u.prototype.readIntLE=function(r,a,d){r>>>=0,a>>>=0,d||at(r,a,this.length);for(var T=this[r],I=1,U=0;++U=I&&(T-=s(2,8*a)),T},u.prototype.readIntBE=function(r,a,d){r>>>=0,a>>>=0,d||at(r,a,this.length);for(var T=a,I=1,U=this[r+--T];0=I&&(U-=s(2,8*a)),U},u.prototype.readInt8=function(r,a){return r>>>=0,a||at(r,1,this.length),128&this[r]?-1*(255-this[r]+1):this[r]},u.prototype.readInt16LE=function(r,a){r>>>=0,a||at(r,2,this.length);var d=this[r]|this[r+1]<<8;return 32768&d?4294901760|d:d},u.prototype.readInt16BE=function(r,a){r>>>=0,a||at(r,2,this.length);var d=this[r+1]|this[r]<<8;return 32768&d?4294901760|d:d},u.prototype.readInt32LE=function(r,a){return r>>>=0,a||at(r,4,this.length),this[r]|this[r+1]<<8|this[r+2]<<16|this[r+3]<<24},u.prototype.readInt32BE=function(r,a){return r>>>=0,a||at(r,4,this.length),this[r]<<24|this[r+1]<<16|this[r+2]<<8|this[r+3]},u.prototype.readFloatLE=function(r,a){return r>>>=0,a||at(r,4,this.length),V.read(this,r,!0,23,4)},u.prototype.readFloatBE=function(r,a){return r>>>=0,a||at(r,4,this.length),V.read(this,r,!1,23,4)},u.prototype.readDoubleLE=function(r,a){return r>>>=0,a||at(r,8,this.length),V.read(this,r,!0,52,8)},u.prototype.readDoubleBE=function(r,a){return r>>>=0,a||at(r,8,this.length),V.read(this,r,!1,52,8)},u.prototype.writeUIntLE=function(r,a,d,T){if(r=+r,a>>>=0,d>>>=0,!T){var I=s(2,8*d)-1;nt(this,r,a,d,I,0)}var U=1,j=0;for(this[a]=255&r;++j>>=0,d>>>=0,!T){var I=s(2,8*d)-1;nt(this,r,a,d,I,0)}var U=d-1,j=1;for(this[a+U]=255&r;0<=--U&&(j*=256);)this[a+U]=255&r/j;return a+d},u.prototype.writeUInt8=function(r,a,d){return r=+r,a>>>=0,d||nt(this,r,a,1,255,0),this[a]=255&r,a+1},u.prototype.writeUInt16LE=function(r,a,d){return r=+r,a>>>=0,d||nt(this,r,a,2,65535,0),this[a]=255&r,this[a+1]=r>>>8,a+2},u.prototype.writeUInt16BE=function(r,a,d){return r=+r,a>>>=0,d||nt(this,r,a,2,65535,0),this[a]=r>>>8,this[a+1]=255&r,a+2},u.prototype.writeUInt32LE=function(r,a,d){return r=+r,a>>>=0,d||nt(this,r,a,4,4294967295,0),this[a+3]=r>>>24,this[a+2]=r>>>16,this[a+1]=r>>>8,this[a]=255&r,a+4},u.prototype.writeUInt32BE=function(r,a,d){return r=+r,a>>>=0,d||nt(this,r,a,4,4294967295,0),this[a]=r>>>24,this[a+1]=r>>>16,this[a+2]=r>>>8,this[a+3]=255&r,a+4},u.prototype.writeIntLE=function(r,a,d,T){if(r=+r,a>>>=0,!T){var I=s(2,8*d-1);nt(this,r,a,d,I-1,-I)}var U=0,j=1,Z=0;for(this[a]=255&r;++Ur&&Z===0&&this[a+U-1]!==0&&(Z=1),this[a+U]=255&(r/j>>0)-Z;return a+d},u.prototype.writeIntBE=function(r,a,d,T){if(r=+r,a>>>=0,!T){var I=s(2,8*d-1);nt(this,r,a,d,I-1,-I)}var U=d-1,j=1,Z=0;for(this[a+U]=255&r;0<=--U&&(j*=256);)0>r&&Z===0&&this[a+U+1]!==0&&(Z=1),this[a+U]=255&(r/j>>0)-Z;return a+d},u.prototype.writeInt8=function(r,a,d){return r=+r,a>>>=0,d||nt(this,r,a,1,127,-128),0>r&&(r=255+r+1),this[a]=255&r,a+1},u.prototype.writeInt16LE=function(r,a,d){return r=+r,a>>>=0,d||nt(this,r,a,2,32767,-32768),this[a]=255&r,this[a+1]=r>>>8,a+2},u.prototype.writeInt16BE=function(r,a,d){return r=+r,a>>>=0,d||nt(this,r,a,2,32767,-32768),this[a]=r>>>8,this[a+1]=255&r,a+2},u.prototype.writeInt32LE=function(r,a,d){return r=+r,a>>>=0,d||nt(this,r,a,4,2147483647,-2147483648),this[a]=255&r,this[a+1]=r>>>8,this[a+2]=r>>>16,this[a+3]=r>>>24,a+4},u.prototype.writeInt32BE=function(r,a,d){return r=+r,a>>>=0,d||nt(this,r,a,4,2147483647,-2147483648),0>r&&(r=4294967295+r+1),this[a]=r>>>24,this[a+1]=r>>>16,this[a+2]=r>>>8,this[a+3]=255&r,a+4},u.prototype.writeFloatLE=function(r,a,d){return Jt(this,r,a,!0,d)},u.prototype.writeFloatBE=function(r,a,d){return Jt(this,r,a,!1,d)},u.prototype.writeDoubleLE=function(r,a,d){return Kt(this,r,a,!0,d)},u.prototype.writeDoubleBE=function(r,a,d){return Kt(this,r,a,!1,d)},u.prototype.copy=function(r,a,d,T){if(!u.isBuffer(r))throw new TypeError("argument should be a Buffer");if(d||(d=0),T||T===0||(T=this.length),a>=r.length&&(a=r.length),a||(a=0),0a)throw new RangeError("targetStart out of bounds");if(0>d||d>=this.length)throw new RangeError("Index out of range");if(0>T)throw new RangeError("sourceEnd out of bounds");T>this.length&&(T=this.length),r.length-aI||T==="latin1")&&(r=I)}}else typeof r=="number"&&(r&=255);if(0>a||this.length>>=0,d=d===void 0?this.length:d>>>0,r||(r=0);var U;if(typeof r=="number")for(U=a;U{v==="%%"||(g++,v==="%c"&&(f=g))}),u.splice(f,0,p)},c.save=function(u){try{u?c.storage.setItem("debug",u):c.storage.removeItem("debug")}catch{}},c.load=m,c.useColors=function(){return!!(typeof window!="undefined"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))||!(typeof navigator!="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))&&(typeof document!="undefined"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window!="undefined"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator!="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&31<=parseInt(RegExp.$1,10)||typeof navigator!="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))},c.storage=function(){try{return localStorage}catch{}}(),c.destroy=(()=>{let u=!1;return()=>{u||(u=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),c.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],c.log=console.debug||console.log||(()=>{}),h.exports=o("./common")(c);const{formatters:b}=h.exports;b.j=function(u){try{return JSON.stringify(u)}catch(p){return"[UnexpectedJSONParseError]: "+p.message}}}).call(this)}).call(this,o("_process"))},{"./common":5,_process:12}],5:[function(o,h){h.exports=function(c){function l(u){function p(...v){if(!p.enabled)return;const x=p,M=+new Date,F=M-(g||M);x.diff=F,x.prev=g,x.curr=M,g=M,v[0]=l.coerce(v[0]),typeof v[0]!="string"&&v.unshift("%O");let w=0;v[0]=v[0].replace(/%([a-zA-Z%])/g,(C,D)=>{if(C==="%%")return"%";w++;const y=l.formatters[D];if(typeof y=="function"){const k=v[w];C=y.call(x,k),v.splice(w,1),w--}return C}),l.formatArgs.call(x,v),(x.log||l.log).apply(x,v)}let g,f=null;return p.namespace=u,p.useColors=l.useColors(),p.color=l.selectColor(u),p.extend=m,p.destroy=l.destroy,Object.defineProperty(p,"enabled",{enumerable:!0,configurable:!1,get:()=>f===null?l.enabled(u):f,set:v=>{f=v}}),typeof l.init=="function"&&l.init(p),p}function m(u,p){const g=l(this.namespace+(typeof p=="undefined"?":":p)+u);return g.log=this.log,g}function b(u){return u.toString().substring(2,u.toString().length-2).replace(/\.\*\?$/,"*")}return l.debug=l,l.default=l,l.coerce=function(u){return u instanceof Error?u.stack||u.message:u},l.disable=function(){const u=[...l.names.map(b),...l.skips.map(b).map(p=>"-"+p)].join(",");return l.enable(""),u},l.enable=function(u){l.save(u),l.names=[],l.skips=[];let p;const g=(typeof u=="string"?u:"").split(/[\s,]+/),f=g.length;for(p=0;p{l[u]=c[u]}),l.names=[],l.skips=[],l.formatters={},l.selectColor=function(u){let p=0;for(let g=0;gW&&!J.warned){J.warned=!0;var et=new Error("Possible EventEmitter memory leak detected. "+J.length+" "+(R+" listeners added. Use emitter.setMaxListeners() to increase limit"));et.name="MaxListenersExceededWarning",et.emitter=S,et.type=R,et.count=J.length,c(et)}return S}function p(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function g(S,R,O){var P={fired:!1,wrapFn:void 0,target:S,type:R,listener:O},W=p.bind(P);return W.listener=O,P.wrapFn=W,W}function f(S,R,O){var P=S._events;if(P===void 0)return[];var W=P[R];return W===void 0?[]:typeof W=="function"?O?[W.listener||W]:[W]:O?F(W):x(W,W.length)}function v(S){var R=this._events;if(R!==void 0){var O=R[S];if(typeof O=="function")return 1;if(O!==void 0)return O.length}return 0}function x(S,R){for(var O=Array(R),P=0;PS||k(S))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+S+".");A=S}}),l.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},l.prototype.setMaxListeners=function(S){if(typeof S!="number"||0>S||k(S))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+S+".");return this._maxListeners=S,this},l.prototype.getMaxListeners=function(){return b(this)},l.prototype.emit=function(S){for(var R=[],O=1;OW)return this;W===0?O.shift():M(O,W),O.length===1&&(P[S]=O[0]),P.removeListener!==void 0&&this.emit("removeListener",S,J||R)}return this},l.prototype.off=l.prototype.removeListener,l.prototype.removeAllListeners=function(S){var R,O,P;if(O=this._events,O===void 0)return this;if(O.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):O[S]!==void 0&&(--this._eventsCount==0?this._events=Object.create(null):delete O[S]),this;if(arguments.length===0){var W,z=Object.keys(O);for(P=0;P */c.read=function(l,m,b,u,p){var g,f,v=8*p-u-1,x=(1<>1,F=-7,w=b?p-1:0,E=b?-1:1,C=l[m+w];for(w+=E,g=C&(1<<-F)-1,C>>=-F,F+=v;0>=-F,F+=u;0>1,D=p===23?s(2,-24)-s(2,-77):0,y=u?0:g-1,k=u?1:-1,A=0>m||m===0&&0>1/m?1:0;for(m=i(m),isNaN(m)||m===1/0?(v=isNaN(m)?1:0,f=E):(f=n(F(m)/M),1>m*(x=s(2,-f))&&(f--,x*=2),m+=1<=f+C?D/x:D*s(2,1-C),2<=m*x&&(f++,x/=2),f+C>=E?(v=0,f=E):1<=f+C?(v=(m*x-1)*s(2,p),f+=C):(v=m*s(2,C-1)*s(2,p),f=0));8<=p;l[b+y]=255&v,y+=k,v/=256,p-=8);for(f=f<=1.5*f?"s":"")}h.exports=function(p,g){g=g||{};var f=typeof p;if(f=="string"&&0 */let l;h.exports=typeof queueMicrotask=="function"?queueMicrotask.bind(typeof window=="undefined"?c:window):m=>(l||(l=Promise.resolve())).then(m).catch(b=>setTimeout(()=>{throw b},0))}).call(this)}).call(this,typeof kt=="undefined"?typeof self=="undefined"?typeof window=="undefined"?{}:window:self:kt)},{}],14:[function(o,h){(function(c,l){(function(){var m=o("safe-buffer").Buffer,b=l.crypto||l.msCrypto;h.exports=b&&b.getRandomValues?function(u,p){if(u>4294967295)throw new RangeError("requested too many random bytes");var g=m.allocUnsafe(u);if(0x?0:+x,v.length)===v}function u(f,v,x){return(x===void 0||x>f.length)&&(x=f.length),f.substring(x-v.length,x)===v}function p(f,v,x){return typeof x!="number"&&(x=0),!(x+v.length>f.length)&&f.indexOf(v,x)!==-1}var g={};l("ERR_INVALID_OPT_VALUE",function(f,v){return'The value "'+v+'" is invalid for option "'+f+'"'},TypeError),l("ERR_INVALID_ARG_TYPE",function(f,v,x){var M;typeof v=="string"&&b(v,"not ")?(M="must not be",v=v.replace(/^not /,"")):M="must be";var F;if(u(f," argument"))F="The ".concat(f," ").concat(M," ").concat(m(v,"type"));else{var w=p(f,".")?"property":"argument";F='The "'.concat(f,'" ').concat(w," ").concat(M," ").concat(m(v,"type"))}return F+=". Received type ".concat(typeof x),F},TypeError),l("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),l("ERR_METHOD_NOT_IMPLEMENTED",function(f){return"The "+f+" method is not implemented"}),l("ERR_STREAM_PREMATURE_CLOSE","Premature close"),l("ERR_STREAM_DESTROYED",function(f){return"Cannot call "+f+" after a stream was destroyed"}),l("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),l("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),l("ERR_STREAM_WRITE_AFTER_END","write after end"),l("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),l("ERR_UNKNOWN_ENCODING",function(f){return"Unknown encoding: "+f},TypeError),l("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),h.exports.codes=g},{}],16:[function(o,h){(function(c){(function(){function l(M){return this instanceof l?(p.call(this,M),g.call(this,M),this.allowHalfOpen=!0,void(M&&(M.readable===!1&&(this.readable=!1),M.writable===!1&&(this.writable=!1),M.allowHalfOpen===!1&&(this.allowHalfOpen=!1,this.once("end",m))))):new l(M)}function m(){this._writableState.ended||c.nextTick(b,this)}function b(M){M.end()}var u=Object.keys||function(M){var F=[];for(var w in M)F.push(w);return F};h.exports=l;var p=o("./_stream_readable"),g=o("./_stream_writable");o("inherits")(l,p);for(var f,v=u(g.prototype),x=0;x>>1,_|=_>>>2,_|=_>>>4,_|=_>>>8,_|=_>>>16,_++),_}function F(_,r){return 0>=_||r.length===0&&r.ended?0:r.objectMode?1:_===_?(_>r.highWaterMark&&(r.highWaterMark=M(_)),_<=r.length?_:r.ended?r.length:(r.needReadable=!0,0)):r.flowing&&r.length?r.buffer.head.data.length:r.length}function w(_,r){if(Y("onEofChunk"),!r.ended){if(r.decoder){var a=r.decoder.end();a&&a.length&&(r.buffer.push(a),r.length+=r.objectMode?1:a.length)}r.ended=!0,r.sync?E(_):(r.needReadable=!1,!r.emittedReadable&&(r.emittedReadable=!0,C(_)))}}function E(_){var r=_._readableState;Y("emitReadable",r.needReadable,r.emittedReadable),r.needReadable=!1,r.emittedReadable||(Y("emitReadable",r.flowing),r.emittedReadable=!0,c.nextTick(C,_))}function C(_){var r=_._readableState;Y("emitReadable_",r.destroyed,r.length,r.ended),!r.destroyed&&(r.length||r.ended)&&(_.emit("readable"),r.emittedReadable=!1),r.needReadable=!r.flowing&&!r.ended&&r.length<=r.highWaterMark,P(_)}function D(_,r){r.readingMore||(r.readingMore=!0,c.nextTick(y,_,r))}function y(_,r){for(;!r.reading&&!r.ended&&(r.length=r.length?(a=r.decoder?r.buffer.join(""):r.buffer.length===1?r.buffer.first():r.buffer.concat(r.length),r.buffer.clear()):a=r.buffer.consume(_,r.decoder),a}function z(_){var r=_._readableState;Y("endReadable",r.endEmitted),r.endEmitted||(r.ended=!0,c.nextTick(J,r,_))}function J(_,r){if(Y("endReadableNT",_.endEmitted,_.length),!_.endEmitted&&_.length===0&&(_.endEmitted=!0,r.readable=!1,r.emit("end"),_.autoDestroy)){var a=r._writableState;(!a||a.autoDestroy&&a.finished)&&r.destroy()}}function et(_,r){for(var a=0,d=_.length;a=r.highWaterMark)||r.ended))return Y("read: emitReadable",r.length,r.ended),r.length===0&&r.ended?z(this):E(this),null;if(_=F(_,r),_===0&&r.ended)return r.length===0&&z(this),null;var d=r.needReadable;Y("need readable",d),(r.length===0||r.length-_>>0),D=this.head,y=0;D;)g(D.data,C,y),y+=D.data.length,D=D.next;return C}},{key:"consume",value:function(E,C){var D;return Ek.length?k.length:E;if(y+=A===k.length?k:k.slice(0,E),E-=A,E===0){A===k.length?(++D,this.head=C.next?C.next:this.tail=null):(this.head=C,C.data=k.slice(A));break}++D}return this.length-=D,y}},{key:"_getBuffer",value:function(E){var C=v.allocUnsafe(E),D=this.head,y=1;for(D.data.copy(C),E-=D.data.length;D=D.next;){var k=D.data,A=E>k.length?k.length:E;if(k.copy(C,C.length-E,0,A),E-=A,E===0){A===k.length?(++y,this.head=D.next?D.next:this.tail=null):(this.head=D,D.data=k.slice(A));break}++y}return this.length-=y,C}},{key:F,value:function(E,C){return M(this,l({},C,{depth:0,customInspect:!1}))}}]),w}()},{buffer:3,util:2}],23:[function(o,h){(function(c){(function(){function l(u,p){b(u,p),m(u)}function m(u){u._writableState&&!u._writableState.emitClose||u._readableState&&!u._readableState.emitClose||u.emit("close")}function b(u,p){u.emit("error",p)}h.exports={destroy:function(u,p){var g=this,f=this._readableState&&this._readableState.destroyed,v=this._writableState&&this._writableState.destroyed;return f||v?(p?p(u):u&&(this._writableState?!this._writableState.errorEmitted&&(this._writableState.errorEmitted=!0,c.nextTick(b,this,u)):c.nextTick(b,this,u)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(u||null,function(x){!p&&x?g._writableState?g._writableState.errorEmitted?c.nextTick(m,g):(g._writableState.errorEmitted=!0,c.nextTick(l,g,x)):c.nextTick(l,g,x):p?(c.nextTick(m,g),p(x)):c.nextTick(m,g)}),this)},undestroy:function(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)},errorOrDestroy:function(u,p){var g=u._readableState,f=u._writableState;g&&g.autoDestroy||f&&f.autoDestroy?u.destroy(p):u.emit("error",p)}}}).call(this)}).call(this,o("_process"))},{_process:12}],24:[function(o,h){function c(p){var g=!1;return function(){if(!g){g=!0;for(var f=arguments.length,v=Array(f),x=0;xw.length)throw new x("streams");var D,y=w.map(function(k,A){var S=Ag){var f=p?u:"highWaterMark";throw new l(f,g)}return n(g)}return m.objectMode?16:16384}}},{"../../../errors":15}],28:[function(o,h){h.exports=o("events").EventEmitter},{events:7}],29:[function(o,h,c){c=h.exports=o("./lib/_stream_readable.js"),c.Stream=c,c.Readable=c,c.Writable=o("./lib/_stream_writable.js"),c.Duplex=o("./lib/_stream_duplex.js"),c.Transform=o("./lib/_stream_transform.js"),c.PassThrough=o("./lib/_stream_passthrough.js"),c.finished=o("./lib/internal/streams/end-of-stream.js"),c.pipeline=o("./lib/internal/streams/pipeline.js")},{"./lib/_stream_duplex.js":16,"./lib/_stream_passthrough.js":17,"./lib/_stream_readable.js":18,"./lib/_stream_transform.js":19,"./lib/_stream_writable.js":20,"./lib/internal/streams/end-of-stream.js":24,"./lib/internal/streams/pipeline.js":26}],30:[function(o,h,c){function l(p,g){for(var f in p)g[f]=p[f]}function m(p,g,f){return u(p,g,f)}/*! safe-buffer. MIT License. Feross Aboukhadijeh */var b=o("buffer"),u=b.Buffer;u.from&&u.alloc&&u.allocUnsafe&&u.allocUnsafeSlow?h.exports=b:(l(b,c),c.Buffer=m),m.prototype=Object.create(u.prototype),l(u,m),m.from=function(p,g,f){if(typeof p=="number")throw new TypeError("Argument must not be a number");return u(p,g,f)},m.alloc=function(p,g,f){if(typeof p!="number")throw new TypeError("Argument must be a number");var v=u(p);return g===void 0?v.fill(0):typeof f=="string"?v.fill(g,f):v.fill(g),v},m.allocUnsafe=function(p){if(typeof p!="number")throw new TypeError("Argument must be a number");return u(p)},m.allocUnsafeSlow=function(p){if(typeof p!="number")throw new TypeError("Argument must be a number");return b.SlowBuffer(p)}},{buffer:3}],31:[function(o,h,c){function l(y){if(!y)return"utf8";for(var k;;)switch(y){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return y;default:if(k)return;y=(""+y).toLowerCase(),k=!0}}function m(y){var k=l(y);if(typeof k!="string"&&(C.isEncoding===D||!D(y)))throw new Error("Unknown encoding: "+y);return k||y}function b(y){this.encoding=m(y);var k;switch(this.encoding){case"utf16le":this.text=v,this.end=x,k=4;break;case"utf8":this.fillLast=f,k=4;break;case"base64":this.text=M,this.end=F,k=3;break;default:return this.write=w,void(this.end=E)}this.lastNeed=0,this.lastTotal=0,this.lastChar=C.allocUnsafe(k)}function u(y){return 127>=y?0:y>>5==6?2:y>>4==14?3:y>>3==30?4:y>>6==2?-1:-2}function p(y,k,A){var S=k.length-1;if(S=S)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=y[y.length-2],this.lastChar[1]=y[y.length-1],A.slice(0,-1)}return A}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=y[y.length-1],y.toString("utf16le",k,y.length-1)}function x(y){var k=y&&y.length?this.write(y):"";if(this.lastNeed){var A=this.lastTotal-this.lastNeed;return k+this.lastChar.toString("utf16le",0,A)}return k}function M(y,k){var A=(y.length-k)%3;return A==0?y.toString("base64",k):(this.lastNeed=3-A,this.lastTotal=3,A==1?this.lastChar[0]=y[y.length-1]:(this.lastChar[0]=y[y.length-2],this.lastChar[1]=y[y.length-1]),y.toString("base64",k,y.length-A))}function F(y){var k=y&&y.length?this.write(y):"";return this.lastNeed?k+this.lastChar.toString("base64",0,3-this.lastNeed):k}function w(y){return y.toString(this.encoding)}function E(y){return y&&y.length?this.write(y):""}var C=o("safe-buffer").Buffer,D=C.isEncoding||function(y){switch(y=""+y,y&&y.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};c.StringDecoder=b,b.prototype.write=function(y){if(y.length===0)return"";var k,A;if(this.lastNeed){if(k=this.fillLast(y),k===void 0)return"";A=this.lastNeed,this.lastNeed=0}else A=0;return A */const m=o("debug")("simple-peer"),b=o("get-browser-rtc"),u=o("randombytes"),p=o("readable-stream"),g=o("queue-microtask"),f=o("err-code"),{Buffer:v}=o("buffer"),x=65536;class M extends p.Duplex{constructor(w){if(w=Object.assign({allowHalfOpen:!1},w),super(w),this._id=u(4).toString("hex").slice(0,7),this._debug("new peer %o",w),this.channelName=w.initiator?w.channelName||u(20).toString("hex"):null,this.initiator=w.initiator||!1,this.channelConfig=w.channelConfig||M.channelConfig,this.channelNegotiated=this.channelConfig.negotiated,this.config=Object.assign({},M.config,w.config),this.offerOptions=w.offerOptions||{},this.answerOptions=w.answerOptions||{},this.sdpTransform=w.sdpTransform||(E=>E),this.streams=w.streams||(w.stream?[w.stream]:[]),this.trickle=w.trickle===void 0||w.trickle,this.allowHalfTrickle=w.allowHalfTrickle!==void 0&&w.allowHalfTrickle,this.iceCompleteTimeout=w.iceCompleteTimeout||5e3,this.destroyed=!1,this.destroying=!1,this._connected=!1,this.remoteAddress=void 0,this.remoteFamily=void 0,this.remotePort=void 0,this.localAddress=void 0,this.localFamily=void 0,this.localPort=void 0,this._wrtc=w.wrtc&&typeof w.wrtc=="object"?w.wrtc:b(),!this._wrtc)throw f(typeof window=="undefined"?new Error("No WebRTC support: Specify `opts.wrtc` option in this environment"):new Error("No WebRTC support: Not a supported browser"),"ERR_WEBRTC_SUPPORT");this._pcReady=!1,this._channelReady=!1,this._iceComplete=!1,this._iceCompleteTimer=null,this._channel=null,this._pendingCandidates=[],this._isNegotiating=!1,this._firstNegotiation=!0,this._batchedNegotiation=!1,this._queuedNegotiation=!1,this._sendersAwaitingStable=[],this._senderMap=new Map,this._closingInterval=null,this._remoteTracks=[],this._remoteStreams=[],this._chunk=null,this._cb=null,this._interval=null;try{this._pc=new this._wrtc.RTCPeerConnection(this.config)}catch(E){return void this.destroy(f(E,"ERR_PC_CONSTRUCTOR"))}this._isReactNativeWebrtc=typeof this._pc._peerConnectionId=="number",this._pc.oniceconnectionstatechange=()=>{this._onIceStateChange()},this._pc.onicegatheringstatechange=()=>{this._onIceStateChange()},this._pc.onconnectionstatechange=()=>{this._onConnectionStateChange()},this._pc.onsignalingstatechange=()=>{this._onSignalingStateChange()},this._pc.onicecandidate=E=>{this._onIceCandidate(E)},typeof this._pc.peerIdentity=="object"&&this._pc.peerIdentity.catch(E=>{this.destroy(f(E,"ERR_PC_PEER_IDENTITY"))}),this.initiator||this.channelNegotiated?this._setupData({channel:this._pc.createDataChannel(this.channelName,this.channelConfig)}):this._pc.ondatachannel=E=>{this._setupData(E)},this.streams&&this.streams.forEach(E=>{this.addStream(E)}),this._pc.ontrack=E=>{this._onTrack(E)},this._debug("initial negotiation"),this._needsNegotiation(),this._onFinishBound=()=>{this._onFinish()},this.once("finish",this._onFinishBound)}get bufferSize(){return this._channel&&this._channel.bufferedAmount||0}get connected(){return this._connected&&this._channel.readyState==="open"}address(){return{port:this.localPort,family:this.localFamily,address:this.localAddress}}signal(w){if(!this.destroying){if(this.destroyed)throw f(new Error("cannot signal after peer is destroyed"),"ERR_DESTROYED");if(typeof w=="string")try{w=JSON.parse(w)}catch{w={}}this._debug("signal()"),w.renegotiate&&this.initiator&&(this._debug("got request to renegotiate"),this._needsNegotiation()),w.transceiverRequest&&this.initiator&&(this._debug("got request for transceiver"),this.addTransceiver(w.transceiverRequest.kind,w.transceiverRequest.init)),w.candidate&&(this._pc.remoteDescription&&this._pc.remoteDescription.type?this._addIceCandidate(w.candidate):this._pendingCandidates.push(w.candidate)),w.sdp&&this._pc.setRemoteDescription(new this._wrtc.RTCSessionDescription(w)).then(()=>{this.destroyed||(this._pendingCandidates.forEach(E=>{this._addIceCandidate(E)}),this._pendingCandidates=[],this._pc.remoteDescription.type==="offer"&&this._createAnswer())}).catch(E=>{this.destroy(f(E,"ERR_SET_REMOTE_DESCRIPTION"))}),w.sdp||w.candidate||w.renegotiate||w.transceiverRequest||this.destroy(f(new Error("signal() called with invalid signal data"),"ERR_SIGNALING"))}}_addIceCandidate(w){const E=new this._wrtc.RTCIceCandidate(w);this._pc.addIceCandidate(E).catch(C=>{!E.address||E.address.endsWith(".local")?l("Ignoring unsupported ICE candidate."):this.destroy(f(C,"ERR_ADD_ICE_CANDIDATE"))})}send(w){if(!this.destroying){if(this.destroyed)throw f(new Error("cannot send after peer is destroyed"),"ERR_DESTROYED");this._channel.send(w)}}addTransceiver(w,E){if(!this.destroying){if(this.destroyed)throw f(new Error("cannot addTransceiver after peer is destroyed"),"ERR_DESTROYED");if(this._debug("addTransceiver()"),this.initiator)try{this._pc.addTransceiver(w,E),this._needsNegotiation()}catch(C){this.destroy(f(C,"ERR_ADD_TRANSCEIVER"))}else this.emit("signal",{type:"transceiverRequest",transceiverRequest:{kind:w,init:E}})}}addStream(w){if(!this.destroying){if(this.destroyed)throw f(new Error("cannot addStream after peer is destroyed"),"ERR_DESTROYED");this._debug("addStream()"),w.getTracks().forEach(E=>{this.addTrack(E,w)})}}addTrack(w,E){if(this.destroying)return;if(this.destroyed)throw f(new Error("cannot addTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("addTrack()");const C=this._senderMap.get(w)||new Map;let D=C.get(E);if(!D)D=this._pc.addTrack(w,E),C.set(E,D),this._senderMap.set(w,C),this._needsNegotiation();else throw D.removed?f(new Error("Track has been removed. You should enable/disable tracks that you want to re-add."),"ERR_SENDER_REMOVED"):f(new Error("Track has already been added to that stream."),"ERR_SENDER_ALREADY_ADDED")}replaceTrack(w,E,C){if(this.destroying)return;if(this.destroyed)throw f(new Error("cannot replaceTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("replaceTrack()");const D=this._senderMap.get(w),y=D?D.get(C):null;if(!y)throw f(new Error("Cannot replace track that was never added."),"ERR_TRACK_NOT_ADDED");E&&this._senderMap.set(E,D),y.replaceTrack==null?this.destroy(f(new Error("replaceTrack is not supported in this browser"),"ERR_UNSUPPORTED_REPLACETRACK")):y.replaceTrack(E)}removeTrack(w,E){if(this.destroying)return;if(this.destroyed)throw f(new Error("cannot removeTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("removeSender()");const C=this._senderMap.get(w),D=C?C.get(E):null;if(!D)throw f(new Error("Cannot remove track that was never added."),"ERR_TRACK_NOT_ADDED");try{D.removed=!0,this._pc.removeTrack(D)}catch(y){y.name==="NS_ERROR_UNEXPECTED"?this._sendersAwaitingStable.push(D):this.destroy(f(y,"ERR_REMOVE_TRACK"))}this._needsNegotiation()}removeStream(w){if(!this.destroying){if(this.destroyed)throw f(new Error("cannot removeStream after peer is destroyed"),"ERR_DESTROYED");this._debug("removeSenders()"),w.getTracks().forEach(E=>{this.removeTrack(E,w)})}}_needsNegotiation(){this._debug("_needsNegotiation"),this._batchedNegotiation||(this._batchedNegotiation=!0,g(()=>{this._batchedNegotiation=!1,this.initiator||!this._firstNegotiation?(this._debug("starting batched negotiation"),this.negotiate()):this._debug("non-initiator initial negotiation request discarded"),this._firstNegotiation=!1}))}negotiate(){if(!this.destroying){if(this.destroyed)throw f(new Error("cannot negotiate after peer is destroyed"),"ERR_DESTROYED");this.initiator?this._isNegotiating?(this._queuedNegotiation=!0,this._debug("already negotiating, queueing")):(this._debug("start negotiation"),setTimeout(()=>{this._createOffer()},0)):this._isNegotiating?(this._queuedNegotiation=!0,this._debug("already negotiating, queueing")):(this._debug("requesting negotiation from initiator"),this.emit("signal",{type:"renegotiate",renegotiate:!0})),this._isNegotiating=!0}}destroy(w){this._destroy(w,()=>{})}_destroy(w,E){this.destroyed||this.destroying||(this.destroying=!0,this._debug("destroying (error: %s)",w&&(w.message||w)),g(()=>{if(this.destroyed=!0,this.destroying=!1,this._debug("destroy (error: %s)",w&&(w.message||w)),this.readable=this.writable=!1,this._readableState.ended||this.push(null),this._writableState.finished||this.end(),this._connected=!1,this._pcReady=!1,this._channelReady=!1,this._remoteTracks=null,this._remoteStreams=null,this._senderMap=null,clearInterval(this._closingInterval),this._closingInterval=null,clearInterval(this._interval),this._interval=null,this._chunk=null,this._cb=null,this._onFinishBound&&this.removeListener("finish",this._onFinishBound),this._onFinishBound=null,this._channel){try{this._channel.close()}catch{}this._channel.onmessage=null,this._channel.onopen=null,this._channel.onclose=null,this._channel.onerror=null}if(this._pc){try{this._pc.close()}catch{}this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ontrack=null,this._pc.ondatachannel=null}this._pc=null,this._channel=null,w&&this.emit("error",w),this.emit("close"),E()}))}_setupData(w){if(!w.channel)return this.destroy(f(new Error("Data channel event is missing `channel` property"),"ERR_DATA_CHANNEL"));this._channel=w.channel,this._channel.binaryType="arraybuffer",typeof this._channel.bufferedAmountLowThreshold=="number"&&(this._channel.bufferedAmountLowThreshold=x),this.channelName=this._channel.label,this._channel.onmessage=C=>{this._onChannelMessage(C)},this._channel.onbufferedamountlow=()=>{this._onChannelBufferedAmountLow()},this._channel.onopen=()=>{this._onChannelOpen()},this._channel.onclose=()=>{this._onChannelClose()},this._channel.onerror=C=>{const D=C.error instanceof Error?C.error:new Error(`Datachannel error: ${C.message} ${C.filename}:${C.lineno}:${C.colno}`);this.destroy(f(D,"ERR_DATA_CHANNEL"))};let E=!1;this._closingInterval=setInterval(()=>{this._channel&&this._channel.readyState==="closing"?(E&&this._onChannelClose(),E=!0):E=!1},5e3)}_read(){}_write(w,E,C){if(this.destroyed)return C(f(new Error("cannot write after peer is destroyed"),"ERR_DATA_CHANNEL"));if(this._connected){try{this.send(w)}catch(D){return this.destroy(f(D,"ERR_DATA_CHANNEL"))}this._channel.bufferedAmount>x?(this._debug("start backpressure: bufferedAmount %d",this._channel.bufferedAmount),this._cb=C):C(null)}else this._debug("write before connect"),this._chunk=w,this._cb=C}_onFinish(){if(!this.destroyed){const w=()=>{setTimeout(()=>this.destroy(),1e3)};this._connected?w():this.once("connect",w)}}_startIceCompleteTimeout(){this.destroyed||this._iceCompleteTimer||(this._debug("started iceComplete timeout"),this._iceCompleteTimer=setTimeout(()=>{this._iceComplete||(this._iceComplete=!0,this._debug("iceComplete timeout completed"),this.emit("iceTimeout"),this.emit("_iceComplete"))},this.iceCompleteTimeout))}_createOffer(){this.destroyed||this._pc.createOffer(this.offerOptions).then(w=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(w.sdp=c(w.sdp)),w.sdp=this.sdpTransform(w.sdp);const E=()=>{if(!this.destroyed){const C=this._pc.localDescription||w;this._debug("signal"),this.emit("signal",{type:C.type,sdp:C.sdp})}};this._pc.setLocalDescription(w).then(()=>{this._debug("createOffer success"),this.destroyed||(this.trickle||this._iceComplete?E():this.once("_iceComplete",E))}).catch(C=>{this.destroy(f(C,"ERR_SET_LOCAL_DESCRIPTION"))})}).catch(w=>{this.destroy(f(w,"ERR_CREATE_OFFER"))})}_requestMissingTransceivers(){this._pc.getTransceivers&&this._pc.getTransceivers().forEach(w=>{w.mid||!w.sender.track||w.requested||(w.requested=!0,this.addTransceiver(w.sender.track.kind))})}_createAnswer(){this.destroyed||this._pc.createAnswer(this.answerOptions).then(w=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(w.sdp=c(w.sdp)),w.sdp=this.sdpTransform(w.sdp);const E=()=>{if(!this.destroyed){const C=this._pc.localDescription||w;this._debug("signal"),this.emit("signal",{type:C.type,sdp:C.sdp}),this.initiator||this._requestMissingTransceivers()}};this._pc.setLocalDescription(w).then(()=>{this.destroyed||(this.trickle||this._iceComplete?E():this.once("_iceComplete",E))}).catch(C=>{this.destroy(f(C,"ERR_SET_LOCAL_DESCRIPTION"))})}).catch(w=>{this.destroy(f(w,"ERR_CREATE_ANSWER"))})}_onConnectionStateChange(){this.destroyed||this._pc.connectionState==="failed"&&this.destroy(f(new Error("Connection failed."),"ERR_CONNECTION_FAILURE"))}_onIceStateChange(){if(this.destroyed)return;const w=this._pc.iceConnectionState,E=this._pc.iceGatheringState;this._debug("iceStateChange (connection: %s) (gathering: %s)",w,E),this.emit("iceStateChange",w,E),(w==="connected"||w==="completed")&&(this._pcReady=!0,this._maybeReady()),w==="failed"&&this.destroy(f(new Error("Ice connection failed."),"ERR_ICE_CONNECTION_FAILURE")),w==="closed"&&this.destroy(f(new Error("Ice connection closed."),"ERR_ICE_CONNECTION_CLOSED"))}getStats(w){const E=C=>(Object.prototype.toString.call(C.values)==="[object Array]"&&C.values.forEach(D=>{Object.assign(C,D)}),C);this._pc.getStats.length===0||this._isReactNativeWebrtc?this._pc.getStats().then(C=>{const D=[];C.forEach(y=>{D.push(E(y))}),w(null,D)},C=>w(C)):0{if(this.destroyed)return;const D=[];C.result().forEach(y=>{const k={};y.names().forEach(A=>{k[A]=y.stat(A)}),k.id=y.id,k.type=y.type,k.timestamp=y.timestamp,D.push(E(k))}),w(null,D)},C=>w(C)):w(null,[])}_maybeReady(){if(this._debug("maybeReady pc %s channel %s",this._pcReady,this._channelReady),this._connected||this._connecting||!this._pcReady||!this._channelReady)return;this._connecting=!0;const w=()=>{this.destroyed||this.getStats((E,C)=>{if(this.destroyed)return;E&&(C=[]);const D={},y={},k={};let A=!1;C.forEach(R=>{(R.type==="remotecandidate"||R.type==="remote-candidate")&&(D[R.id]=R),(R.type==="localcandidate"||R.type==="local-candidate")&&(y[R.id]=R),(R.type==="candidatepair"||R.type==="candidate-pair")&&(k[R.id]=R)});const S=R=>{A=!0;let O=y[R.localCandidateId];O&&(O.ip||O.address)?(this.localAddress=O.ip||O.address,this.localPort=+O.port):O&&O.ipAddress?(this.localAddress=O.ipAddress,this.localPort=+O.portNumber):typeof R.googLocalAddress=="string"&&(O=R.googLocalAddress.split(":"),this.localAddress=O[0],this.localPort=+O[1]),this.localAddress&&(this.localFamily=this.localAddress.includes(":")?"IPv6":"IPv4");let P=D[R.remoteCandidateId];P&&(P.ip||P.address)?(this.remoteAddress=P.ip||P.address,this.remotePort=+P.port):P&&P.ipAddress?(this.remoteAddress=P.ipAddress,this.remotePort=+P.portNumber):typeof R.googRemoteAddress=="string"&&(P=R.googRemoteAddress.split(":"),this.remoteAddress=P[0],this.remotePort=+P[1]),this.remoteAddress&&(this.remoteFamily=this.remoteAddress.includes(":")?"IPv6":"IPv4"),this._debug("connect local: %s:%s remote: %s:%s",this.localAddress,this.localPort,this.remoteAddress,this.remotePort)};if(C.forEach(R=>{R.type==="transport"&&R.selectedCandidatePairId&&S(k[R.selectedCandidatePairId]),(R.type==="googCandidatePair"&&R.googActiveConnection==="true"||(R.type==="candidatepair"||R.type==="candidate-pair")&&R.selected)&&S(R)}),!A&&(!Object.keys(k).length||Object.keys(y).length))return void setTimeout(w,100);if(this._connecting=!1,this._connected=!0,this._chunk){try{this.send(this._chunk)}catch(O){return this.destroy(f(O,"ERR_DATA_CHANNEL"))}this._chunk=null,this._debug('sent chunk from "write before connect"');const R=this._cb;this._cb=null,R(null)}typeof this._channel.bufferedAmountLowThreshold!="number"&&(this._interval=setInterval(()=>this._onInterval(),150),this._interval.unref&&this._interval.unref()),this._debug("connect"),this.emit("connect")})};w()}_onInterval(){this._cb&&this._channel&&!(this._channel.bufferedAmount>x)&&this._onChannelBufferedAmountLow()}_onSignalingStateChange(){this.destroyed||(this._pc.signalingState==="stable"&&(this._isNegotiating=!1,this._debug("flushing sender queue",this._sendersAwaitingStable),this._sendersAwaitingStable.forEach(w=>{this._pc.removeTrack(w),this._queuedNegotiation=!0}),this._sendersAwaitingStable=[],this._queuedNegotiation?(this._debug("flushing negotiation queue"),this._queuedNegotiation=!1,this._needsNegotiation()):(this._debug("negotiated"),this.emit("negotiated"))),this._debug("signalingStateChange %s",this._pc.signalingState),this.emit("signalingStateChange",this._pc.signalingState))}_onIceCandidate(w){this.destroyed||(w.candidate&&this.trickle?this.emit("signal",{type:"candidate",candidate:{candidate:w.candidate.candidate,sdpMLineIndex:w.candidate.sdpMLineIndex,sdpMid:w.candidate.sdpMid}}):!w.candidate&&!this._iceComplete&&(this._iceComplete=!0,this.emit("_iceComplete")),w.candidate&&this._startIceCompleteTimeout())}_onChannelMessage(w){if(this.destroyed)return;let E=w.data;E instanceof ArrayBuffer&&(E=v.from(E)),this.push(E)}_onChannelBufferedAmountLow(){if(!this.destroyed&&this._cb){this._debug("ending backpressure: bufferedAmount %d",this._channel.bufferedAmount);const w=this._cb;this._cb=null,w(null)}}_onChannelOpen(){this._connected||this.destroyed||(this._debug("on channel open"),this._channelReady=!0,this._maybeReady())}_onChannelClose(){this.destroyed||(this._debug("on channel close"),this.destroy())}_onTrack(w){this.destroyed||w.streams.forEach(E=>{this._debug("on track"),this.emit("track",w.track,E),this._remoteTracks.push({track:w.track,stream:E}),this._remoteStreams.some(C=>C.id===E.id)||(this._remoteStreams.push(E),g(()=>{this._debug("on stream"),this.emit("stream",E)}))})}_debug(){const w=[].slice.call(arguments);w[0]="["+this._id+"] "+w[0],m.apply(null,w)}}M.WEBRTC_SUPPORT=!!b(),M.config={iceServers:[{urls:["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478"]}],sdpSemantics:"unified-plan"},M.channelConfig={},h.exports=M},{buffer:3,debug:4,"err-code":6,"get-browser-rtc":8,"queue-microtask":13,randombytes:14,"readable-stream":29}]},{},[])("/")})})(Ki);var Pa=Ki.exports;const wr=0,br=1,Xi=2,Zi=(e,t)=>{q(e,wr);const n=To(t);ct(e,n)},Qi=(e,t,n)=>{q(e,br),ct(e,Eo(t,n))},Ba=(e,t,n)=>Qi(t,n,gt(e)),ts=(e,t,n)=>{try{_o(t,gt(e),n)}catch(i){console.error("Caught error while handling a Yjs update",i)}},ja=(e,t)=>{q(e,Xi),ct(e,t)},Va=ts,qa=(e,t,n,i)=>{const s=G(e);switch(s){case wr:Ba(e,t,n);break;case br:ts(e,n,i);break;case Xi:Va(e,n,i);break;default:throw new Error("Unknown message type")}return s},_r=3e4;class Wa extends ue{constructor(t){super();this.doc=t,this.clientID=t.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{const n=Ot();this.getLocalState()!==null&&_r/2<=n-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());const i=[];this.meta.forEach((s,o)=>{o!==this.clientID&&_r<=n-s.lastUpdated&&this.states.has(o)&&i.push(o)}),i.length>0&&vr(this,i,"timeout")},de(_r/10)),t.on("destroy",()=>{this.destroy()}),this.setLocalState({})}destroy(){this.emit("destroy",[this]),this.setLocalState(null),super.destroy(),clearInterval(this._checkInterval)}getLocalState(){return this.states.get(this.clientID)||null}setLocalState(t){const n=this.clientID,i=this.meta.get(n),s=i===void 0?0:i.clock+1,o=this.states.get(n);t===null?this.states.delete(n):this.states.set(n,t),this.meta.set(n,{clock:s,lastUpdated:Ot()});const h=[],c=[],l=[],m=[];t===null?m.push(n):o==null?t!=null&&h.push(n):(c.push(n),Oe(o,t)||l.push(n)),(h.length>0||l.length>0||m.length>0)&&this.emit("change",[{added:h,updated:l,removed:m},"local"]),this.emit("update",[{added:h,updated:c,removed:m},"local"])}setLocalStateField(t,n){const i=this.getLocalState();i!==null&&this.setLocalState(In(Ge({},i),{[t]:n}))}getStates(){return this.states}}const vr=(e,t,n)=>{const i=[];for(let s=0;s0&&(e.emit("change",[{added:[],updated:[],removed:i},n]),e.emit("update",[{added:[],updated:[],removed:i},n]))},An=(e,t,n=e.states)=>{const i=t.length,s=dt();q(s,i);for(let o=0;o{const i=Mt(t),s=Ot(),o=[],h=[],c=[],l=[],m=G(i);for(let b=0;b0||c.length>0||l.length>0)&&e.emit("change",[{added:o,updated:c,removed:l},n]),(o.length>0||h.length>0||l.length>0)&&e.emit("update",[{added:o,updated:h,removed:l},n])},$a=(e,t)=>{const n=Mr(e).buffer,i=Mr(t).buffer;return crypto.subtle.importKey("raw",n,"PBKDF2",!1,["deriveKey"]).then(s=>crypto.subtle.deriveKey({name:"PBKDF2",salt:i,iterations:1e5,hash:"SHA-256"},s,{name:"AES-GCM",length:256},!0,["encrypt","decrypt"]))},es=(e,t)=>{if(!t)return $n(e);const n=crypto.getRandomValues(new Uint8Array(12));return crypto.subtle.encrypt({name:"AES-GCM",iv:n},t,e).then(i=>{const s=dt();return xt(s,"AES-GCM"),ct(s,n),ct(s,new Uint8Array(i)),st(s)})},Ya=(e,t)=>{const n=dt();return pe(n,e),es(st(n),t)},ns=(e,t)=>{if(!t)return $n(e);const n=Mt(e);jt(n)!=="AES-GCM"&&Xs(ge("Unknown encryption algorithm"));const s=gt(n),o=gt(n);return crypto.subtle.decrypt({name:"AES-GCM",iv:s},t,o).then(h=>new Uint8Array(h))},za=(e,t)=>ns(e,t).then(n=>fe(Mt(new Uint8Array(n)))),Rt=co("y-webrtc"),ke=0,rs=3,He=1,Sr=4,Dn=new Map,ae=new Map,is=e=>{let t=!0;e.webrtcConns.forEach(n=>{n.synced||(t=!1)}),(!t&&e.synced||t&&!e.synced)&&(e.synced=t,e.provider.emit("synced",[{synced:t}]),Rt("synced ",vt,e.name,Ht," with all peers"))},ss=(e,t,n)=>{const i=Mt(t),s=dt(),o=G(i);if(e===void 0)return null;const h=e.awareness,c=e.doc;let l=!1;switch(o){case ke:{q(s,ke);const m=qa(i,s,c,e);m===br&&!e.synced&&n(),m===wr&&(l=!0);break}case rs:q(s,He),ct(s,An(h,Array.from(h.getStates().keys()))),l=!0;break;case He:Ha(h,gt(i),e);break;case Sr:{const m=te(i)===1,b=jt(i);if(b!==e.peerId&&(e.bcConns.has(b)&&!m||!e.bcConns.has(b)&&m)){const u=[],p=[];m?(e.bcConns.add(b),p.push(b)):(e.bcConns.delete(b),u.push(b)),e.provider.emit("peers",[{added:p,removed:u,webrtcPeers:Array.from(e.webrtcConns.keys()),bcPeers:Array.from(e.bcConns)}]),ls(e)}break}default:return console.error("Unable to compute message"),s}return l?s:null},Ga=(e,t)=>{const n=e.room;return Rt("received message from ",vt,e.remotePeerId,rn," (",n.name,")",Ht,Ne),ss(n,t,()=>{e.synced=!0,Rt("synced ",vt,n.name,Ht," with ",vt,e.remotePeerId),is(n)})},Er=(e,t)=>{Rt("send message to ",vt,e.remotePeerId,Ht,rn," (",e.room.name,")",Ne);try{e.peer.send(st(t))}catch{}},Ja=(e,t)=>{Rt("broadcast message in ",vt,e.name,Ht),e.webrtcConns.forEach(n=>{try{n.peer.send(t)}catch{}})};class os{constructor(t,n,i,s){Rt("establishing connection to ",vt,i),this.room=s,this.remotePeerId=i,this.closed=!1,this.connected=!1,this.synced=!1,this.peer=new Pa(Ge({initiator:n},s.provider.peerOpts)),this.peer.on("signal",o=>{kr(t,s,{to:i,from:s.peerId,type:"signal",signal:o})}),this.peer.on("connect",()=>{Rt("connected to ",vt,i),this.connected=!0;const h=s.provider.doc,c=s.awareness,l=dt();q(l,ke),Zi(l,h),Er(this,l);const m=c.getStates();if(m.size>0){const b=dt();q(b,He),ct(b,An(c,Array.from(m.keys()))),Er(this,b)}}),this.peer.on("close",()=>{this.connected=!1,this.closed=!0,s.webrtcConns.has(this.remotePeerId)&&(s.webrtcConns.delete(this.remotePeerId),s.provider.emit("peers",[{removed:[this.remotePeerId],added:[],webrtcPeers:Array.from(s.webrtcConns.keys()),bcPeers:Array.from(s.bcConns)}])),is(s),this.peer.destroy(),Rt("closed connection to ",vt,i),Cr(s)}),this.peer.on("error",o=>{Rt("Error in connection to ",vt,i,": ",o),Cr(s)}),this.peer.on("data",o=>{const h=Ga(this,o);h!==null&&Er(this,h)})}destroy(){this.peer.destroy()}}const zt=(e,t)=>es(t,e.key).then(n=>e.mux(()=>Ua(e.name,n))),as=(e,t)=>{e.bcconnected&&zt(e,t),Ja(e,t)},Cr=e=>{Dn.forEach(t=>{t.connected&&(t.send({type:"subscribe",topics:[e.name]}),e.webrtcConns.size{if(e.provider.filterBcConns){const t=dt();q(t,Sr),xe(t,1),xt(t,e.peerId),zt(e,st(t))}};class Ka{constructor(t,n,i,s){this.peerId=Xr(),this.doc=t,this.awareness=n.awareness,this.provider=n,this.synced=!1,this.name=i,this.key=s,this.webrtcConns=new Map,this.bcConns=new Set,this.mux=Fa(),this.bcconnected=!1,this._bcSubscriber=o=>ns(new Uint8Array(o),s).then(h=>this.mux(()=>{const c=ss(this,h,()=>{});c&&zt(this,st(c))})),this._docUpdateHandler=(o,h)=>{const c=dt();q(c,ke),ja(c,o),as(this,st(c))},this._awarenessUpdateHandler=({added:o,updated:h,removed:c},l)=>{const m=o.concat(h).concat(c),b=dt();q(b,He),ct(b,An(this.awareness,m)),as(this,st(b))},this._beforeUnloadHandler=()=>{vr(this.awareness,[t.clientID],"window unload"),ae.forEach(o=>{o.disconnect()})},typeof window!="undefined"?window.addEventListener("beforeunload",this._beforeUnloadHandler):typeof process!="undefined"&&process.on("exit",this._beforeUnloadHandler)}connect(){this.doc.on("update",this._docUpdateHandler),this.awareness.on("update",this._awarenessUpdateHandler),Cr(this);const t=this.name;Oa(t,this._bcSubscriber),this.bcconnected=!0,ls(this);const n=dt();q(n,ke),Zi(n,this.doc),zt(this,st(n));const i=dt();q(i,ke),Qi(i,this.doc),zt(this,st(i));const s=dt();q(s,rs),zt(this,st(s));const o=dt();q(o,He),ct(o,An(this.awareness,[this.doc.clientID])),zt(this,st(o))}disconnect(){Dn.forEach(n=>{n.connected&&n.send({type:"unsubscribe",topics:[this.name]})}),vr(this.awareness,[this.doc.clientID],"disconnect");const t=dt();q(t,Sr),xe(t,0),xt(t,this.peerId),zt(this,st(t)),Na(this.name,this._bcSubscriber),this.bcconnected=!1,this.doc.off("update",this._docUpdateHandler),this.awareness.off("update",this._awarenessUpdateHandler),this.webrtcConns.forEach(n=>n.destroy())}destroy(){this.disconnect(),typeof window!="undefined"?window.removeEventListener("beforeunload",this._beforeUnloadHandler):typeof process!="undefined"&&process.off("exit",this._beforeUnloadHandler)}}const Xa=(e,t,n,i)=>{if(ae.has(n))throw ge(`A Yjs Doc connected to room "${n}" already exists!`);const s=new Ka(e,t,n,i);return ae.set(n,s),s},kr=(e,t,n)=>{t.key?Ya(n,t.key).then(i=>{e.send({type:"publish",topic:t.name,data:Wr(i)})}):e.send({type:"publish",topic:t.name,data:n})};class Za extends Ia{constructor(t){super(t);this.providers=new Set,this.on("connect",()=>{Rt(`connected (${t})`);const n=Array.from(ae.keys());this.send({type:"subscribe",topics:n}),ae.forEach(i=>kr(this,i,{type:"announce",from:i.peerId}))}),this.on("message",n=>{switch(n.type){case"publish":{const i=n.topic,s=ae.get(i);if(s==null||typeof i!="string")return;const o=h=>{const c=s.webrtcConns,l=s.peerId;if(h==null||h.from===l||h.to!==void 0&&h.to!==l||s.bcConns.has(h.from))return;const m=c.has(h.from)?()=>{}:()=>s.provider.emit("peers",[{removed:[],added:[h.from],webrtcPeers:Array.from(s.webrtcConns.keys()),bcPeers:Array.from(s.bcConns)}]);switch(h.type){case"announce":c.sizenew os(this,!0,h.from,s)),m());break;case"signal":h.to===l&&(St(c,h.from,()=>new os(this,!1,h.from,s)).peer.signal(h.signal),m());break}};s.key?typeof n.data=="string"&&za(Hr(n.data),s.key).then(o):o(n.data)}}}),this.on("disconnect",()=>Rt(`disconnect (${t})`))}}class Qa extends ue{constructor(t,n,{signaling:i=["wss://signaling.yjs.dev","wss://y-webrtc-signaling-eu.herokuapp.com","wss://y-webrtc-signaling-us.herokuapp.com"],password:s=null,awareness:o=new Wa(n),maxConns:h=20+de(Gs()*15),filterBcConns:c=!0,peerOpts:l={}}={}){super();this.roomName=t,this.doc=n,this.filterBcConns=c,this.awareness=o,this.shouldConnect=!1,this.signalingUrls=i,this.signalingConns=[],this.maxConns=h,this.peerOpts=l,this.key=s?$a(s,t):$n(null),this.room=null,this.key.then(m=>{this.room=Xa(n,this,t,m),this.shouldConnect?this.room.connect():this.room.disconnect()}),this.connect(),this.destroy=this.destroy.bind(this),n.on("destroy",this.destroy)}get connected(){return this.room!==null&&this.shouldConnect}connect(){this.shouldConnect=!0,this.signalingUrls.forEach(t=>{const n=St(Dn,t,()=>new Za(t));this.signalingConns.push(n),n.providers.add(this)}),this.room&&this.room.connect()}disconnect(){this.shouldConnect=!1,this.signalingConns.forEach(t=>{t.providers.delete(this),t.providers.size===0&&(t.destroy(),Dn.delete(t.url))}),this.room&&this.room.disconnect()}destroy(){this.doc.off("destroy",this.destroy),this.key.then(()=>{this.room.destroy(),ae.delete(this.roomName)}),super.destroy()}}var $=class{static clamp(e,t,n){return Math.max(t,typeof n!="undefined"?Math.min(e,n):e)}static clampV(e,t,n){return e.map(i=>n?$.clamp(i,t,n):$.clamp(i,t))}static cross(e,t,n){return(t[0]-e[0])*(n[1]-e[1])-(n[0]-e[0])*(t[1]-e[1])}static snap(e,t=1){return[Math.round(e[0]/t)*t,Math.round(e[1]/t)*t]}},H=$;H.neg=e=>[-e[0],-e[1]],H.add=(e,t)=>[e[0]+t[0],e[1]+t[1]],H.addScalar=(e,t)=>[e[0]+t,e[1]+t],H.sub=(e,t)=>[e[0]-t[0],e[1]-t[1]],H.subScalar=(e,t)=>[e[0]-t,e[1]-t],H.vec=(e,t)=>[t[0]-e[0],t[1]-e[1]],H.mul=(e,t)=>[e[0]*t,e[1]*t],H.mulV=(e,t)=>[e[0]*t[0],e[1]*t[1]],H.div=(e,t)=>[e[0]/t,e[1]/t],H.divV=(e,t)=>[e[0]/t[0],e[1]/t[1]],H.per=e=>[e[1],-e[0]],H.dpr=(e,t)=>e[0]*t[0]+e[1]*t[1],H.cpr=(e,t)=>e[0]*t[1]-t[0]*e[1],H.len2=e=>e[0]*e[0]+e[1]*e[1],H.len=e=>Math.hypot(e[0],e[1]),H.pry=(e,t)=>$.dpr(e,t)/$.len(t),H.uni=e=>$.div(e,$.len(e)),H.normalize=e=>$.uni(e),H.tangent=(e,t)=>$.uni($.sub(e,t)),H.dist2=(e,t)=>$.len2($.sub(e,t)),H.dist=(e,t)=>Math.hypot(e[1]-t[1],e[0]-t[0]),H.fastDist=(e,t)=>{const n=[t[0]-e[0],t[1]-e[1]],i=[Math.abs(n[0]),Math.abs(n[1])];let s=1/Math.max(i[0],i[1]);return s=s*(1.29289-(i[0]+i[1])*s*.29289),[n[0]*s,n[1]*s]},H.ang=(e,t)=>Math.atan2($.cpr(e,t),$.dpr(e,t)),H.angle=(e,t)=>Math.atan2(t[1]-e[1],t[0]-e[0]),H.med=(e,t)=>$.mul($.add(e,t),.5),H.rot=(e,t=0)=>[e[0]*Math.cos(t)-e[1]*Math.sin(t),e[0]*Math.sin(t)+e[1]*Math.cos(t)],H.rotWith=(e,t,n=0)=>{if(n===0)return e;const i=Math.sin(n),s=Math.cos(n),o=e[0]-t[0],h=e[1]-t[1],c=o*s-h*i,l=o*i+h*s;return[c+t[0],l+t[1]]},H.isEqual=(e,t)=>e[0]===t[0]&&e[1]===t[1],H.lrp=(e,t,n)=>$.add(e,$.mul($.sub(t,e),n)),H.int=(e,t,n,i,s=1)=>{const o=($.clamp(n,i)-n)/(i-n);return $.add($.mul(e,1-o),$.mul(t,s))},H.ang3=(e,t,n)=>{const i=$.vec(t,e),s=$.vec(t,n);return $.ang(i,s)},H.abs=e=>[Math.abs(e[0]),Math.abs(e[1])],H.rescale=(e,t)=>{const n=$.len(e);return[t*e[0]/n,t*e[1]/n]},H.isLeft=(e,t,n)=>(t[0]-e[0])*(n[1]-e[1])-(n[0]-e[0])*(t[1]-e[1]),H.clockwise=(e,t,n)=>$.isLeft(e,t,n)>0,H.toFixed=(e,t=2)=>e.map(n=>+n.toFixed(t)),H.nearestPointOnLineThroughPoint=(e,t,n)=>$.add(e,$.mul(t,$.pry($.sub(n,e),t))),H.distanceToLineThroughPoint=(e,t,n)=>$.dist(n,$.nearestPointOnLineThroughPoint(e,t,n)),H.nearestPointOnLineSegment=(e,t,n,i=!0)=>{const s=$.uni($.sub(t,e)),o=$.add(e,$.mul(s,$.pry($.sub(n,e),s)));if(i){if(o[0]Math.max(e[0],t[0]))return e[0]>t[0]?e:t;if(o[1]Math.max(e[1],t[1]))return e[1]>t[1]?e:t}return o},H.distanceToLineSegment=(e,t,n,i=!0)=>$.dist(n,$.nearestPointOnLineSegment(e,t,n,i)),H.nudge=(e,t,n)=>$.isEqual(e,t)?e:$.add(e,$.mul($.uni($.sub(t,e)),n)),H.nudgeAtAngle=(e,t,n)=>[Math.cos(t)*n+e[0],Math.sin(t)*n+e[1]],H.toPrecision=(e,t=4)=>[+e[0].toPrecision(t),+e[1].toPrecision(t)],H.pointsBetween=(e,t,n=6)=>Array.from(Array(n)).map((i,s)=>{const o=s/(n-1),h=Math.min(1,.5+Math.abs(.5-o));return[...$.lrp(e,t,o),h]}),H.slope=(e,t)=>e[0]===t[0]?NaN:(e[1]-t[1])/(e[0]-t[0]),H.max=(...e)=>[Math.max(...e.map(t=>t[0])),Math.max(...e.map(t=>t[1]))],H.min=(...e)=>[Math.max(...e.map(t=>t[0])),Math.max(...e.map(t=>t[1]))];var tl=class{constructor(e=[]){this.points=[],this.lengths=[],this.totalLength=0,this.addPoint=t=>{if(this.prev){const n=H.dist(this.prev,t);this.lengths.push(n),this.totalLength+=n,this.points.push(t)}this.prev=t},this.clear=()=>{this.points=this.prev?[this.prev]:[],this.totalLength=0},this.getSplinePoint=t=>{const{points:n}=this,i=n.length-1,s=Math.trunc(t),o=Math.min(s+1,i),h=Math.min(o+1,i),c=Math.min(h+1,i),l=o-1,m=t-s,b=m*m,u=b*m,p=-u+2*b-m,g=3*u-5*b+2,f=-3*u+4*b+m,v=u-b;return[(n[l][0]*p+n[o][0]*g+n[h][0]*f+n[c][0]*v)/2,(n[l][1]*p+n[o][1]*g+n[h][1]*f+n[c][1]*v)/2]},this.points=e,this.lengths=e.map((t,n,i)=>n===0?0:H.dist(t,i[n-1])),this.totalLength=this.lengths.reduce((t,n)=>t+n,0)}},Rr=class{constructor(e){this.state="idle",this.queue=[],this.timestamp=performance.now(),this.lastRequestId=0,this.timeoutId=0,this.spline=new tl,this.addPoint=t=>{clearTimeout(this.timeoutId);const n=performance.now(),i=Math.min(n-this.timestamp,Rr.MAX_INTERVAL);if(!this.prevPoint){this.spline.clear(),this.prevPoint=t,this.spline.addPoint(t),this.cb(t),this.state="stopped";return}if(this.state==="stopped"){if(H.dist(this.prevPoint,t)<4){this.cb(t);return}this.spline.clear(),this.spline.addPoint(this.prevPoint),this.spline.addPoint(this.prevPoint),this.spline.addPoint(t),this.state="idle"}else this.spline.addPoint(t);if(i<16){this.prevPoint=t,this.timestamp=n,this.cb(t);return}const s={start:this.spline.points.length-3,from:this.prevPoint,to:t,duration:i};switch(this.prevPoint=t,this.timestamp=n,this.state){case"idle":{this.state="animating",this.animateNext(s);break}case"animating":{this.queue.push(s);break}}},this.animateNext=t=>{const n=performance.now(),i=()=>{const s=(performance.now()-n)/t.duration;if(s<=1&&this.spline.points.length>0){try{this.cb(this.spline.getSplinePoint(s+t.start))}catch(h){console.warn(h)}this.lastRequestId=requestAnimationFrame(i);return}const o=this.queue.shift();o?(this.state="animating",this.animateNext(o)):(this.state="idle",this.timeoutId=setTimeout(()=>{this.state="stopped"},Rr.MAX_INTERVAL))};i()},this.dispose=()=>{clearTimeout(this.timeoutId)},this.cb=e}},cs=Rr;cs.MAX_INTERVAL=300;let el=(e=21)=>crypto.getRandomValues(new Uint8Array(e)).reduce((t,n)=>(n&=63,n<36?t+=n.toString(36):n<62?t+=(n-26).toString(36).toUpperCase():n>62?t+="-":t+="_",t),"");var Tr={exports:{}};(function(e,t){(function(n,i){{var s=i();e&&e.exports&&(t=e.exports=s),t.randomColor=s}})(kt,function(){var n=null,i={};M();var s=[],o=function(y){if(y=y||{},y.seed!==void 0&&y.seed!==null&&y.seed===parseInt(y.seed,10))n=y.seed;else if(typeof y.seed=="string")n=C(y.seed);else{if(y.seed!==void 0&&y.seed!==null)throw new TypeError("The seed value must be an integer or string");n=null}var k,A,S;if(y.count!==null&&y.count!==void 0){for(var R=y.count,O=[],P=0;PO.length;){var W=o(y);n!==null&&(y.seed=n),O.push(W)}return y.count=R,O}return k=h(y),A=c(k,y),S=l(k,A,y),m([k,A,S],y)};function h(y){if(s.length>0){var k=D(y.hue),A=f(k),S=(k[1]-k[0])/s.length,R=parseInt((A-k[0])/S);s[R]===!0?R=(R+2)%s.length:s[R]=!0;var O=(k[0]+R*S)%359,P=(k[0]+(R+1)*S)%359;return k=[O,P],A=f(k),A<0&&(A=360+A),A}else{var k=u(y.hue);return A=f(k),A<0&&(A=360+A),A}}function c(y,k){if(k.hue==="monochrome")return 0;if(k.luminosity==="random")return f([0,100]);var A=p(y),S=A[0],R=A[1];switch(k.luminosity){case"bright":S=55;break;case"dark":S=R-10;break;case"light":R=55;break}return f([S,R])}function l(y,k,A){var S=b(y,k),R=100;switch(A.luminosity){case"dark":R=S+20;break;case"light":S=(R+S)/2;break;case"random":S=0,R=100;break}return f([S,R])}function m(y,k){switch(k.format){case"hsvArray":return y;case"hslArray":return E(y);case"hsl":var A=E(y);return"hsl("+A[0]+", "+A[1]+"%, "+A[2]+"%)";case"hsla":var S=E(y),P=k.alpha||Math.random();return"hsla("+S[0]+", "+S[1]+"%, "+S[2]+"%, "+P+")";case"rgbArray":return F(y);case"rgb":var R=F(y);return"rgb("+R.join(", ")+")";case"rgba":var O=F(y),P=k.alpha||Math.random();return"rgba("+O.join(", ")+", "+P+")";default:return v(y)}}function b(y,k){for(var A=g(y).lowerBounds,S=0;S=R&&k<=P){var z=(W-O)/(P-R),J=O-z*R;return z*k+J}}return 0}function u(y){if(typeof parseInt(y)=="number"){var k=parseInt(y);if(k<360&&k>0)return[k,k]}if(typeof y=="string"){if(i[y]){var A=i[y];if(A.hueRange)return A.hueRange}else if(y.match(/^#?([0-9A-F]{3}|[0-9A-F]{6})$/i)){var S=w(y)[0];return[S,S]}}return[0,360]}function p(y){return g(y).saturationRange}function g(y){y>=334&&y<=360&&(y-=360);for(var k in i){var A=i[k];if(A.hueRange&&y>=A.hueRange[0]&&y<=A.hueRange[1])return i[k]}return"Color not found"}function f(y){if(n===null){var k=.618033988749895,A=Math.random();return A+=k,A%=1,Math.floor(y[0]+A*(y[1]+1-y[0]))}else{var S=y[1]||1,R=y[0]||0;n=(n*9301+49297)%233280;var O=n/233280;return Math.floor(R+O*(S-R))}}function v(y){var k=F(y);function A(R){var O=R.toString(16);return O.length==1?"0"+O:O}var S="#"+A(k[0])+A(k[1])+A(k[2]);return S}function x(y,k,A){var S=A[0][0],R=A[A.length-1][0],O=A[A.length-1][1],P=A[0][1];i[y]={hueRange:k,lowerBounds:A,saturationRange:[S,R],brightnessRange:[O,P]}}function M(){x("monochrome",null,[[0,0],[100,0]]),x("red",[-26,18],[[20,100],[30,92],[40,89],[50,85],[60,78],[70,70],[80,60],[90,55],[100,50]]),x("orange",[18,46],[[20,100],[30,93],[40,88],[50,86],[60,85],[70,70],[100,70]]),x("yellow",[46,62],[[25,100],[40,94],[50,89],[60,86],[70,84],[80,82],[90,80],[100,75]]),x("green",[62,178],[[30,100],[40,90],[50,85],[60,81],[70,74],[80,64],[90,50],[100,40]]),x("blue",[178,257],[[20,100],[30,86],[40,80],[50,74],[60,60],[70,52],[80,44],[90,39],[100,35]]),x("purple",[257,282],[[20,100],[30,87],[40,79],[50,70],[60,65],[70,59],[80,52],[90,45],[100,42]]),x("pink",[282,334],[[20,100],[30,90],[40,86],[60,84],[80,80],[90,75],[100,73]])}function F(y){var k=y[0];k===0&&(k=1),k===360&&(k=359),k=k/360;var A=y[1]/100,S=y[2]/100,R=Math.floor(k*6),O=k*6-R,P=S*(1-A),W=S*(1-O*A),z=S*(1-(1-O)*A),J=256,et=256,ot=256;switch(R){case 0:J=S,et=z,ot=P;break;case 1:J=W,et=S,ot=P;break;case 2:J=P,et=S,ot=z;break;case 3:J=P,et=W,ot=S;break;case 4:J=z,et=P,ot=S;break;case 5:J=S,et=P,ot=W;break}var Y=[Math.floor(J*255),Math.floor(et*255),Math.floor(ot*255)];return Y}function w(y){y=y.replace(/^#/,""),y=y.length===3?y.replace(/(.)/g,"$1$1"):y;var k=parseInt(y.substr(0,2),16)/255,A=parseInt(y.substr(2,2),16)/255,S=parseInt(y.substr(4,2),16)/255,R=Math.max(k,A,S),O=R-Math.min(k,A,S),P=R?O/R:0;switch(R){case k:return[60*((A-S)/O%6)||0,P,R];case A:return[60*((S-k)/O+2)||0,P,R];case S:return[60*((k-A)/O+4)||0,P,R]}}function E(y){var k=y[0],A=y[1]/100,S=y[2]/100,R=(2-A)*S;return[k,Math.round(A*S/(R<1?R:2-R)*1e4)/100,R/2*100]}function C(y){for(var k=0,A=0;A!==y.length&&!(k>=Number.MAX_SAFE_INTEGER);A++)k+=y.charCodeAt(A);return k}function D(y){if(isNaN(y)){if(typeof y=="string"){if(i[y]){var A=i[y];if(A.hueRange)return A.hueRange}else if(y.match(/^#?([0-9A-F]{3}|[0-9A-F]{6})$/i)){var S=w(y)[0];return g(S).hueRange}}}else{var k=parseInt(y);if(k<360&&k>0)return g(y).hueRange}return[0,360]}return o})})(Tr,Tr.exports);var nl=Tr.exports;function hs(e){const t=`

${e.chat}

-
`,n=document.createElement("template");return n.innerHTML=t,n.content.firstChild}const rl=(e,t="/",n="cursor-chat-layer",i="cursor-chat-box")=>{const s=document.getElementById(n),o=document.getElementById(i);if(!s||!o)throw"Couldn't find cursor-chat-related divs! Make sure DOM content is fully loaded before initializing";const c={id:tl(),color:el(),x:0,y:0,chat:""};e=e||`cursor-chat-room-${window.location.host+window.location.pathname}`;const h=new we,l=new Za(e,h),y=h.getMap("state");let w=!1;const u=()=>{y.delete(c.id),l.disconnect()};addEventListener("beforeunload",u),setInterval(()=>{w&&(y.set(c.id,c),w=!1)},80),document.onmousemove=f=>{c.x!==f.pageX&&c.y!==f.pageY&&(w=!0,c.x=f.pageX,c.y=f.pageY,o.style.setProperty("transform",`translate(${c.x}px, ${c.y}px)`))},document.addEventListener("keydown",f=>{f.key===t?o.style.getPropertyValue("display")==="block"&&o.value===""?(f.preventDefault(),o.style.setProperty("display","none")):(f.preventDefault(),o.style.setProperty("display","block"),o.focus()):f.key==="Escape"?(f.preventDefault(),o.value="",o.style.setProperty("display","none")):f.key==="Enter"&&f.preventDefault()}),document.addEventListener("keyup",()=>{c.chat=o.value,w=!0});const g=new Map;return y.observe(f=>{f.changes.keys.forEach((S,M)=>{if(M!==c.id)switch(S.action){case"add":const x=y.get(M),F=nl(x);F.classList.add("new"),s.appendChild(F);const b=([A,v])=>F.style.setProperty("transform",`translate(${A}px, ${v}px)`),E=new cs(b);E.addPoint([x.x,x.y]),g.set(M,E);break;case"update":const C=y.get(M),D=document.getElementById(`cursor_${M}`),m=document.getElementById(`chat_${M}`);C.chat===""?m.classList.remove("show"):m.classList.add("show"),m.innerText=C.chat,D.classList.remove("new"),g.get(M).addPoint([C.x,C.y]);break;case"delete":const k=document.getElementById(`cursor_${M}`);k.classList.add("expiring"),setTimeout(()=>{k.remove(),g.delete(M)},1e3);break}})}),u};wt.initCursorChat=rl,Object.defineProperties(wt,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}); +
`,n=document.createElement("template");return n.innerHTML=t,n.content.firstChild}const rl=(e=`cursor-chat-room-${window.location.host+window.location.pathname}`,t="/",n="cursor-chat-layer",i="cursor-chat-box",s={},o=hs)=>{const h=document.getElementById(n),c=document.getElementById(i);if(!h||!c)throw"Couldn't find cursor-chat-related divs! Make sure DOM content is fully loaded before initializing";const l={id:el(),x:0,y:0,chat:"",color:nl(),userMetaData:s},m=new we,b=new Qa(e,m),u=m.getMap("state");let p=!1;const g=()=>{u.delete(l.id),b.disconnect()};addEventListener("beforeunload",g),setInterval(()=>{p&&(u.set(l.id,l),p=!1)},80),document.onmousemove=v=>{l.x!==v.pageX&&l.y!==v.pageY&&(p=!0,l.x=v.pageX,l.y=v.pageY,c.style.setProperty("transform",`translate(${l.x}px, ${l.y}px)`))},document.addEventListener("keydown",v=>{v.key===t?c.style.getPropertyValue("display")==="block"&&c.value===""?(v.preventDefault(),c.style.setProperty("display","none")):(v.preventDefault(),c.style.setProperty("display","block"),c.focus()):v.key==="Escape"?(v.preventDefault(),c.value="",c.style.setProperty("display","none")):v.key==="Enter"&&v.preventDefault()}),document.addEventListener("keyup",()=>{l.chat=c.value,p=!0});const f=new Map;return u.observe(v=>{v.changes.keys.forEach((M,F)=>{if(F!==l.id)switch(M.action){case"add":const w=u.get(F),E=o(w);E.classList.add("new"),h.appendChild(E);const C=([R,O])=>E.style.setProperty("transform",`translate(${R}px, ${O}px)`),D=new cs(C);D.addPoint([w.x,w.y]),f.set(F,D);break;case"update":const y=u.get(F),k=document.getElementById(`cursor_${F}`),A=document.getElementById(`chat_${F}`);y.chat===""?A.classList.remove("show"):A.classList.add("show"),A.innerText=y.chat,k.classList.remove("new"),f.get(F).addPoint([y.x,y.y]);break;case"delete":const S=document.getElementById(`cursor_${F}`);S.classList.add("expiring"),setTimeout(()=>{S.remove(),f.delete(F)},1e3);break}})}),g};ft.defaultCursorRenderer=hs,ft.initCursorChat=rl,Object.defineProperties(ft,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}); diff --git a/dist/main.d.ts b/dist/main.d.ts index aeae58e..15939a5 100644 --- a/dist/main.d.ts +++ b/dist/main.d.ts @@ -1 +1,14 @@ -export declare const initCursorChat: (room_id?: string, triggerKey?: string, cursorDivId?: string, chatDivId?: string) => () => void; +declare type UserMetadata = { + [key: string]: T; +}; +interface Cursor { + id: string; + x: number; + y: number; + chat: string; + color: string; + userMetaData: UserMetadata; +} +export declare function defaultCursorRenderer(cursor: Cursor): HTMLElement; +export declare const initCursorChat: (room_id?: string, triggerKey?: string, cursorDivId?: string, chatDivId?: string, userMetaData?: UserMetadata, renderCursor?: (cursor: Cursor) => HTMLElement) => () => void; +export {}; diff --git a/package.json b/package.json index 8b0899f..087bafe 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "cursor-chat", - "version": "0.4.9", + "version": "0.5.0", "license": "MIT", "files": [ "dist" diff --git a/src/main.ts b/src/main.ts index 20f0e82..f9a6d65 100644 --- a/src/main.ts +++ b/src/main.ts @@ -6,15 +6,18 @@ import { PerfectCursor } from 'perfect-cursors' import { nanoid } from 'nanoid' import randomcolor from 'randomcolor' -interface Cursor { +type UserMetadata = { [key: string]: T } + +interface Cursor { id: string - color: string x: number y: number chat: string + color: string + userMetaData: UserMetadata } -function cursorFactory(cursor: Cursor): HTMLElement { +export function defaultCursorRenderer(cursor: Cursor): HTMLElement { const htmlFragment = `
{ +export const initCursorChat = ( + room_id: string = `cursor-chat-room-${window.location.host + window.location.pathname}`, + triggerKey: string = "/", + cursorDivId: string = "cursor-chat-layer", + chatDivId: string = "cursor-chat-box", + userMetaData: UserMetadata = {}, + renderCursor: (cursor: Cursor) => HTMLElement = defaultCursorRenderer, +) => { const cursorDiv = document.getElementById(cursorDivId)! const chatDiv = document.getElementById(chatDivId)! as HTMLInputElement @@ -51,22 +61,22 @@ export const initCursorChat = (room_id?: string, triggerKey = "/", cursorDivId = throw `Couldn't find cursor-chat-related divs! Make sure DOM content is fully loaded before initializing` } - const me: Cursor = { + const me: Cursor = { id: nanoid(), - color: randomcolor(), x: 0, y: 0, - chat: "" + chat: "", + color: randomcolor(), + userMetaData, } - room_id = room_id || `cursor-chat-room-${window.location.host + window.location.pathname}` const doc = new Y.Doc() const provider = new WebrtcProvider( room_id, doc ) - const others: Y.Map = doc.getMap("state") + const others: Y.Map> = doc.getMap("state") let sendUpdate = false const cleanup = () => { @@ -125,7 +135,7 @@ export const initCursorChat = (room_id?: string, triggerKey = "/", cursorDivId = case 'add': // make a new cursor const new_cursor = others.get(cursor_id)!; - const new_cursor_div = cursorFactory(new_cursor); + const new_cursor_div = renderCursor(new_cursor); new_cursor_div.classList.add("new") cursorDiv.appendChild(new_cursor_div); const add_point_closure = ([x, y]: number[]) => new_cursor_div.style.setProperty("transform", `translate(${x}px, ${y}px)`);