collabmd 0.1.20 → 0.1.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/README.md +4 -2
  2. package/package.json +1 -1
  3. package/public/assets/css/style.css +1 -1
  4. package/public/assets/js/chunks/chunk-GFDM7YCF.js +1 -0
  5. package/public/assets/js/chunks/editor-session-EAUBJCHH.js +22 -0
  6. package/public/assets/js/chunks/{preview-render-compiler-UZ4SZDQQ.js → preview-render-compiler-6Y7TKXFJ.js} +1 -1
  7. package/public/assets/js/chunks/{quick-switcher-controller-J7I3CUET.js → quick-switcher-controller-A6SKH5HI.js} +1 -1
  8. package/public/assets/js/{excalidraw-editor-ZDYKMZOL.js → excalidraw-editor-TCIH6GJL.js} +1 -1
  9. package/public/assets/js/excalidraw-editor.js +1 -1
  10. package/public/assets/js/main.js +68 -68
  11. package/public/assets/js/preview-render-worker.js +15 -15
  12. package/src/client/application/app-shell/git-feature.js +57 -18
  13. package/src/client/application/app-shell/ui-feature.js +4 -0
  14. package/src/client/bootstrap/collabmd-app-shell.js +12 -0
  15. package/src/client/domain/vault-utils.js +2 -2
  16. package/src/client/excalidraw-editor.js +2 -1
  17. package/src/client/infrastructure/editor-session.js +4 -0
  18. package/src/client/infrastructure/editor-view-adapter.js +181 -1
  19. package/src/client/infrastructure/workspace-sync-client.js +324 -0
  20. package/src/client/presentation/comment-ui-controller.js +192 -5
  21. package/src/client/presentation/file-explorer-controller.js +15 -3
  22. package/src/client/presentation/file-explorer-view.js +152 -11
  23. package/src/client/styles/style.css +46 -2
  24. package/src/domain/wiki-link-resolver.js +16 -5
  25. package/src/domain/workspace-change.js +68 -0
  26. package/src/domain/workspace-room.js +3 -0
  27. package/src/server/create-app-server.js +41 -10
  28. package/src/server/domain/backlink-index.js +94 -1
  29. package/src/server/domain/collaboration/collaboration-room.js +191 -22
  30. package/src/server/domain/collaboration/room-registry.js +64 -10
  31. package/src/server/infrastructure/git/responses.js +12 -19
  32. package/src/server/infrastructure/http/create-git-api-command-handler.js +53 -43
  33. package/src/server/infrastructure/http/create-git-api-handler.js +2 -0
  34. package/src/server/infrastructure/http/create-request-handler.js +7 -0
  35. package/src/server/infrastructure/http/create-vault-api-command-handler.js +58 -14
  36. package/src/server/infrastructure/http/create-vault-api-handler.js +3 -0
  37. package/src/server/infrastructure/http/create-vault-api-query-handler.js +3 -1
  38. package/src/server/infrastructure/http/http-response.js +65 -28
  39. package/src/server/infrastructure/persistence/vault-file-store.js +163 -52
  40. package/src/server/infrastructure/workspace/file-system-sync-service.js +488 -0
  41. package/src/server/infrastructure/workspace/workspace-mutation-coordinator.js +551 -0
  42. package/public/assets/js/chunks/chunk-R3DDMJHH.js +0 -1
  43. package/public/assets/js/chunks/editor-session-TAV2VXTA.js +0 -22
@@ -287,7 +287,7 @@ Please fix the Mermaid syntax and regenerate a valid diagram.`;await g({prompt:q
287
287
  ${n.toString()}`)},gT=class{constructor(t){this.patterns=[],this.$state=t}if(t,n){return this.patterns.push({if:m0(t),h:n}),this}else(t){return this.if(Pw,t)}done(){return(t,n)=>{for(let r=0;r<this.patterns.length;r++){let a=this.patterns[r];if(a.if.check(t))return a.h(t,n)}throw ai("Unhandled pattern")}}},ghe=e=>new gT(e),jG=ghe(Pw).if(BG,(e,t)=>Tw(t,Gk,rp)).if(FG,(e,t)=>IG(t)).if(mhe,(e,t)=>sT(t)).if(hhe,(e,t)=>BigInt(Tw(t,Gk,rp))).if(zw,(e,t)=>mp(t,Mw(t,e.shape))).if(the,(e,t)=>{let n={};for(let r in e.shape){let a=e.shape[r];if(Jue.check(a)){if(sT(t))continue;a=a.shape}n[r]=jG(a,t)}return n}).if(ihe,(e,t)=>{let n=[],r=cT(t,0,42);for(let a=0;a<r;a++)n.push(mp(t,e.shape));return n}).if(RG,(e,t)=>Mw(t,e.shape)).if(phe,(e,t)=>null).if(che,(e,t)=>{let n=mp(t,e.res);return()=>n}).if(uhe,(e,t)=>mp(t,Mw(t,[pp,gp,Fw,HG,bT,Bw,zG(pp),OG(bp("a","b","c"),pp)]))).if(rhe,(e,t)=>{let n={},r=Tw(t,0,3);for(let a=0;a<r;a++){let i=mp(t,e.shape.keys),o=mp(t,e.shape.values);n[i]=o}return n}).done(),mp=(e,t)=>jG(m0(t),e);var ku=typeof document<"u"?document:{};var uMe=$n(e=>e.nodeType===whe);var hMe=typeof DOMParser<"u"?new DOMParser:null;var mMe=$n(e=>e.nodeType===vhe);var pMe=$n(e=>e.nodeType===yhe);var VG=e=>$V(e,(t,n)=>`${n}:${t};`).join("");var vhe=ku.ELEMENT_NODE,yhe=ku.TEXT_NODE,fMe=ku.CDATA_SECTION_NODE,gMe=ku.COMMENT_NODE,xhe=ku.DOCUMENT_NODE,bMe=ku.DOCUMENT_TYPE_NODE,whe=ku.DOCUMENT_FRAGMENT_NODE,vMe=$n(e=>e.nodeType===xhe);var hl=Symbol;var p0=hl(),f0=hl(),vT=hl(),yT=hl(),xT=hl(),g0=hl(),wT=hl(),vp=hl(),ET=hl(),GG=e=>{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());let t=[],n=[],r=0;for(;r<e.length;r++){let a=e[r];if(a===void 0)break;if(a.constructor===String||a.constructor===Number)t.push(a);else if(a.constructor===Object)break}for(r>0&&n.push(t.join(""));r<e.length;r++){let a=e[r];a instanceof Symbol||n.push(a)}return n};var yMe=Mo();var _he={[p0]:ul("font-weight","bold"),[f0]:ul("font-weight","normal"),[vT]:ul("color","blue"),[xT]:ul("color","green"),[yT]:ul("color","grey"),[g0]:ul("color","red"),[wT]:ul("color","purple"),[vp]:ul("color","orange"),[ET]:ul("color","black")},khe=e=>{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());let t=[],n=[],r=sr(),a=[],i=0;for(;i<e.length;i++){let o=e[i],l=_he[o];if(l!==void 0)r.set(l.left,l.right);else{if(o===void 0)break;if(o.constructor===String||o.constructor===Number){let c=VG(r);i>0||c.length>0?(t.push("%c"+o),n.push(c)):t.push(o)}else break}}for(i>0&&(a=n,a.unshift(t.join("")));i<e.length;i++){let o=e[i];o instanceof Symbol||a.push(o)}return a},YG=CG?khe:GG,WG=(...e)=>{console.log(...YG(e)),$G.forEach(t=>t.print(e))},KG=(...e)=>{console.warn(...YG(e)),e.unshift(vp),$G.forEach(t=>t.print(e))};var $G=Ki();var XG=e=>({[Symbol.iterator](){return this},next:e}),ZG=(e,t)=>XG(()=>{let n;do n=e.next();while(!n.done&&!t(n.value));return n}),Hw=(e,t)=>XG(()=>{let{done:n,value:r}=e.next();return{done:n,value:n?void 0:t(r)}});var v0=class{constructor(t,n){this.clock=t,this.len=n}},Tu=class{constructor(){this.clients=new Map}},dY=(e,t,n)=>t.clients.forEach((r,a)=>{let i=e.doc.store.clients.get(a);if(i!=null){let o=i[i.length-1],l=o.id.clock+o.length;for(let c=0,s=r[c];c<r.length&&s.clock<l;s=r[++c])EY(e,i,s.clock,s.len,n)}}),Ihe=(e,t)=>{let n=0,r=e.length-1;for(;n<=r;){let a=Er((n+r)/2),i=e[a],o=i.clock;if(o<=t){if(t<o+i.len)return a;n=a+1}else r=a-1}return null},uY=(e,t)=>{let n=e.clients.get(t.client);return n!==void 0&&Ihe(n,t.clock)!==null},FT=e=>{e.clients.forEach(t=>{t.sort((a,i)=>a.clock-i.clock);let n,r;for(n=1,r=1;n<t.length;n++){let a=t[r-1],i=t[n];a.clock+a.len>=i.clock?a.len=vs(a.len,i.clock+i.len-a.clock):(r<n&&(t[r]=i),r++)}t.length=r})},Lhe=e=>{let t=new Tu;for(let n=0;n<e.length;n++)e[n].clients.forEach((r,a)=>{if(!t.clients.has(a)){let i=r.slice();for(let o=n+1;o<e.length;o++)ZV(i,e[o].clients.get(a)||[]);t.clients.set(a,i)}});return FT(t),t},Kw=(e,t,n,r)=>{ri(e.clients,t,()=>[]).push(new v0(n,r))},hY=()=>new Tu,Rhe=e=>{let t=hY();return e.clients.forEach((n,r)=>{let a=[];for(let i=0;i<n.length;i++){let o=n[i];if(o.deleted){let l=o.id.clock,c=o.length;if(i+1<n.length)for(let s=n[i+1];i+1<n.length&&s.deleted;s=n[++i+1])c+=s.length;a.push(new v0(l,c))}}a.length>0&&t.clients.set(r,a)}),t},Sp=(e,t)=>{ue(e.restEncoder,t.clients.size),_o(t.clients.entries()).sort((n,r)=>r[0]-n[0]).forEach(([n,r])=>{e.resetDsCurVal(),ue(e.restEncoder,n);let a=r.length;ue(e.restEncoder,a);for(let i=0;i<a;i++){let o=r[i];e.writeDsClock(o.clock),e.writeDsLen(o.len)}})},HT=e=>{let t=new Tu,n=ve(e.restDecoder);for(let r=0;r<n;r++){e.resetDsCurVal();let a=ve(e.restDecoder),i=ve(e.restDecoder);if(i>0){let o=ri(t.clients,a,()=>[]);for(let l=0;l<i;l++)o.push(new v0(e.readDsClock(),e.readDsLen()))}}return t},JG=(e,t,n)=>{let r=new Tu,a=ve(e.restDecoder);for(let i=0;i<a;i++){e.resetDsCurVal();let o=ve(e.restDecoder),l=ve(e.restDecoder),c=n.clients.get(o)||[],s=dr(n,o);for(let d=0;d<l;d++){let u=e.readDsClock(),h=u+e.readDsLen();if(u<s){s<h&&Kw(r,o,s,h-s);let m=ml(c,u),p=c[m];for(!p.deleted&&p.id.clock<u&&(c.splice(m+1,0,aE(t,p,u-p.id.clock)),m++);m<c.length&&(p=c[m++],p.id.clock<h);)p.deleted||(h<p.id.clock+p.length&&c.splice(m,0,aE(t,p,h-p.id.clock)),p.delete(t))}else Kw(r,o,u,h-u)}}if(r.clients.size>0){let i=new ws;return ue(i.restEncoder,0),Sp(i,r),i.toUint8Array()}return null};var mY=qk,Mu=class e extends tp{constructor({guid:t=dG(),collectionid:n=null,gc:r=!0,gcFilter:a=()=>!0,meta:i=null,autoLoad:o=!1,shouldLoad:l=!0}={}){super(),this.gc=r,this.gcFilter=a,this.clientID=mY(),this.guid=t,this.collectionid=n,this.share=new Map,this.store=new Qw,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=l,this.autoLoad=o,this.meta=i,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=Jk(s=>{this.on("load",()=>{this.isLoaded=!0,s(this)})});let c=()=>Jk(s=>{let d=u=>{(u===void 0||u===!0)&&(this.off("sync",d),s())};this.on("sync",d)});this.on("sync",s=>{s===!1&&this.isSynced&&(this.whenSynced=c()),this.isSynced=s===void 0||s===!0,this.isSynced&&!this.isLoaded&&this.emit("load",[this])}),this.whenSynced=c()}load(){let t=this._item;t!==null&&!this.shouldLoad&&Nt(t.parent.doc,n=>{n.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(_o(this.subdocs).map(t=>t.guid))}transact(t,n=null){return Nt(this,t,n)}get(t,n=Xn){let r=ri(this.share,t,()=>{let i=new n;return i._integrate(this,null),i}),a=r.constructor;if(n!==Xn&&a!==n)if(a===Xn){let i=new n;i._map=r._map,r._map.forEach(o=>{for(;o!==null;o=o.left)o.parent=i}),i._start=r._start;for(let o=i._start;o!==null;o=o.right)o.parent=i;return i._length=r._length,this.share.set(t,i),i._integrate(this,null),i}else throw new Error(`Type with the name ${t} has already been defined with a different constructor`);return r}getArray(t=""){return this.get(t,nE)}getText(t=""){return this.get(t,C0)}getMap(t=""){return this.get(t,pl)}getXmlElement(t=""){return this.get(t,_0)}getXmlFragment(t=""){return this.get(t,wp)}toJSON(){let t={};return this.share.forEach((n,r)=>{t[r]=n.toJSON()}),t}destroy(){this.isDestroyed=!0,_o(this.subdocs).forEach(n=>n.destroy());let t=this._item;if(t!==null){this._item=null;let n=t.content;n.doc=new e({guid:this.guid,...n.opts,shouldLoad:!1}),n.doc._item=t,Nt(t.parent.doc,r=>{let a=n.doc;t.deleted||r.subdocsAdded.add(a),r.subdocsRemoved.add(this)},null,!0)}this.emit("destroyed",[!0]),this.emit("destroy",[this]),super.destroy()}},$w=class{constructor(t){this.restDecoder=t}resetDsCurVal(){}readDsClock(){return ve(this.restDecoder)}readDsLen(){return ve(this.restDecoder)}},Xw=class extends $w{readLeftID(){return qe(ve(this.restDecoder),ve(this.restDecoder))}readRightID(){return qe(ve(this.restDecoder),ve(this.restDecoder))}readClient(){return ve(this.restDecoder)}readInfo(){return Su(this.restDecoder)}readString(){return ko(this.restDecoder)}readParentInfo(){return ve(this.restDecoder)===1}readTypeRef(){return ve(this.restDecoder)}readLen(){return ve(this.restDecoder)}readAny(){return dp(this.restDecoder)}readBuf(){return AG(Kn(this.restDecoder))}readJSON(){return JSON.parse(ko(this.restDecoder))}readKey(){return ko(this.restDecoder)}},_T=class{constructor(t){this.dsCurrVal=0,this.restDecoder=t}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=ve(this.restDecoder),this.dsCurrVal}readDsLen(){let t=ve(this.restDecoder)+1;return this.dsCurrVal+=t,t}},Hc=class extends _T{constructor(t){super(t),this.keys=[],ve(t),this.keyClockDecoder=new up(Kn(t)),this.clientDecoder=new Cu(Kn(t)),this.leftClockDecoder=new up(Kn(t)),this.rightClockDecoder=new up(Kn(t)),this.infoDecoder=new r0(Kn(t),Su),this.stringDecoder=new xw(Kn(t)),this.parentInfoDecoder=new r0(Kn(t),Su),this.typeRefDecoder=new Cu(Kn(t)),this.lenDecoder=new Cu(Kn(t))}readLeftID(){return new Fc(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new Fc(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 dp(this.restDecoder)}readBuf(){return Kn(this.restDecoder)}readJSON(){return dp(this.restDecoder)}readKey(){let t=this.keyClockDecoder.read();if(t<this.keys.length)return this.keys[t];{let n=this.stringDecoder.read();return this.keys.push(n),n}}},Zw=class{constructor(){this.restEncoder=Wn()}toUint8Array(){return Rt(this.restEncoder)}resetDsCurVal(){}writeDsClock(t){ue(this.restEncoder,t)}writeDsLen(t){ue(this.restEncoder,t)}},Au=class extends Zw{writeLeftID(t){ue(this.restEncoder,t.client),ue(this.restEncoder,t.clock)}writeRightID(t){ue(this.restEncoder,t.client),ue(this.restEncoder,t.clock)}writeClient(t){ue(this.restEncoder,t)}writeInfo(t){bw(this.restEncoder,t)}writeString(t){ys(this.restEncoder,t)}writeParentInfo(t){ue(this.restEncoder,t?1:0)}writeTypeRef(t){ue(this.restEncoder,t)}writeLen(t){ue(this.restEncoder,t)}writeAny(t){lp(this.restEncoder,t)}writeBuf(t){Xt(this.restEncoder,t)}writeJSON(t){ys(this.restEncoder,JSON.stringify(t))}writeKey(t){ys(this.restEncoder,t)}},qw=class{constructor(){this.restEncoder=Wn(),this.dsCurrVal=0}toUint8Array(){return Rt(this.restEncoder)}resetDsCurVal(){this.dsCurrVal=0}writeDsClock(t){let n=t-this.dsCurrVal;this.dsCurrVal=t,ue(this.restEncoder,n)}writeDsLen(t){t===0&&Pa(),ue(this.restEncoder,t-1),this.dsCurrVal+=t}},ws=class extends qw{constructor(){super(),this.keyMap=new Map,this.keyClock=0,this.keyClockEncoder=new sp,this.clientEncoder=new Eu,this.leftClockEncoder=new sp,this.rightClockEncoder=new sp,this.infoEncoder=new t0(bw),this.stringEncoder=new fw,this.parentInfoEncoder=new t0(bw),this.typeRefEncoder=new Eu,this.lenEncoder=new Eu}toUint8Array(){let t=Wn();return ue(t,0),Xt(t,this.keyClockEncoder.toUint8Array()),Xt(t,this.clientEncoder.toUint8Array()),Xt(t,this.leftClockEncoder.toUint8Array()),Xt(t,this.rightClockEncoder.toUint8Array()),Xt(t,Rt(this.infoEncoder)),Xt(t,this.stringEncoder.toUint8Array()),Xt(t,Rt(this.parentInfoEncoder)),Xt(t,this.typeRefEncoder.toUint8Array()),Xt(t,this.lenEncoder.toUint8Array()),n0(t,Rt(this.restEncoder)),Rt(t)}writeLeftID(t){this.clientEncoder.write(t.client),this.leftClockEncoder.write(t.clock)}writeRightID(t){this.clientEncoder.write(t.client),this.rightClockEncoder.write(t.clock)}writeClient(t){this.clientEncoder.write(t)}writeInfo(t){this.infoEncoder.write(t)}writeString(t){this.stringEncoder.write(t)}writeParentInfo(t){this.parentInfoEncoder.write(t?1:0)}writeTypeRef(t){this.typeRefEncoder.write(t)}writeLen(t){this.lenEncoder.write(t)}writeAny(t){lp(this.restEncoder,t)}writeBuf(t){Xt(this.restEncoder,t)}writeJSON(t){lp(this.restEncoder,t)}writeKey(t){let n=this.keyMap.get(t);n===void 0?(this.keyClockEncoder.write(this.keyClock++),this.stringEncoder.write(t)):this.keyClockEncoder.write(n)}},Nhe=(e,t,n,r)=>{r=vs(r,t[0].id.clock);let a=ml(t,r);ue(e.restEncoder,t.length-a),e.writeClient(n),ue(e.restEncoder,r);let i=t[a];i.write(e,r-i.id.clock);for(let o=a+1;o<t.length;o++)t[o].write(e,0)},jT=(e,t,n)=>{let r=new Map;n.forEach((a,i)=>{dr(t,i)>a&&r.set(i,a)}),iE(t).forEach((a,i)=>{n.has(i)||r.set(i,0)}),ue(e.restEncoder,r.size),_o(r.entries()).sort((a,i)=>i[0]-a[0]).forEach(([a,i])=>{Nhe(e,t.clients.get(a),a,i)})},Ohe=(e,t)=>{let n=sr(),r=ve(e.restDecoder);for(let a=0;a<r;a++){let i=ve(e.restDecoder),o=new Array(i),l=e.readClient(),c=ve(e.restDecoder);n.set(l,{i:0,refs:o});for(let s=0;s<i;s++){let d=e.readInfo();switch(31&d){case 0:{let u=e.readLen();o[s]=new Ua(qe(l,c),u),c+=u;break}case 10:{let u=ve(e.restDecoder);o[s]=new Ba(qe(l,c),u),c+=u;break}default:{let u=(d&192)===0,h=new ur(qe(l,c),null,(d&128)===128?e.readLeftID():null,null,(d&64)===64?e.readRightID():null,u?e.readParentInfo()?t.get(e.readString()):e.readLeftID():null,u&&(d&32)===32?e.readString():null,HY(e,d));o[s]=h,c+=h.length}}}}return n},zhe=(e,t,n)=>{let r=[],a=_o(n.keys()).sort((m,p)=>m-p);if(a.length===0)return null;let i=()=>{if(a.length===0)return null;let m=n.get(a[a.length-1]);for(;m.refs.length===m.i;)if(a.pop(),a.length>0)m=n.get(a[a.length-1]);else return null;return m},o=i();if(o===null)return null;let l=new Qw,c=new Map,s=(m,p)=>{let f=c.get(m);(f==null||f>p)&&c.set(m,p)},d=o.refs[o.i++],u=new Map,h=()=>{for(let m of r){let p=m.id.client,f=n.get(p);f?(f.i--,l.clients.set(p,f.refs.slice(f.i)),n.delete(p),f.i=0,f.refs=[]):l.clients.set(p,[m]),a=a.filter(x=>x!==p)}r.length=0};for(;;){if(d.constructor!==Ba){let p=ri(u,d.id.client,()=>dr(t,d.id.client))-d.id.clock;if(p<0)r.push(d),s(d.id.client,d.id.clock-1),h();else{let f=d.getMissing(e,t);if(f!==null){r.push(d);let x=n.get(f)||{refs:[],i:0};if(x.refs.length===x.i)s(f,dr(t,f)),h();else{d=x.refs[x.i++];continue}}else(p===0||p<d.length)&&(d.integrate(e,p),u.set(d.id.client,d.id.clock+d.length))}}if(r.length>0)d=r.pop();else if(o!==null&&o.i<o.refs.length)d=o.refs[o.i++];else{if(o=i(),o===null)break;d=o.refs[o.i++]}}if(l.clients.size>0){let m=new ws;return jT(m,l,new Map),ue(m.restEncoder,0),{missing:c,update:m.toUint8Array()}}return null},Phe=(e,t)=>jT(e,t.doc.store,t.beforeState),Uhe=(e,t,n,r=new Hc(e))=>Nt(t,a=>{a.local=!1;let i=!1,o=a.doc,l=o.store,c=Ohe(r,o),s=zhe(a,l,c),d=l.pendingStructs;if(d){for(let[h,m]of d.missing)if(m<dr(l,h)){i=!0;break}if(s){for(let[h,m]of s.missing){let p=d.missing.get(h);(p==null||p>m)&&d.missing.set(h,m)}d.update=Jw([d.update,s.update])}}else l.pendingStructs=s;let u=JG(r,a,l);if(l.pendingDs){let h=new Hc(To(l.pendingDs));ve(h.restDecoder);let m=JG(h,a,l);u&&m?l.pendingDs=Jw([u,m]):l.pendingDs=u||m}else l.pendingDs=u;if(i){let h=l.pendingStructs.update;l.pendingStructs=null,pY(a.doc,h)}},n,!1);var pY=(e,t,n,r=Hc)=>{let a=To(t);Uhe(a,e,n,new r(a))},fY=(e,t,n)=>pY(e,t,n,Xw),Bhe=(e,t,n=new Map)=>{jT(e,t.store,n),Sp(e,Rhe(t.store))},Fhe=(e,t=new Uint8Array([0]),n=new ws)=>{let r=bY(t);Bhe(n,e,r);let a=[n.toUint8Array()];if(e.store.pendingDs&&a.push(e.store.pendingDs),e.store.pendingStructs&&a.push(Jhe(e.store.pendingStructs.update,t)),a.length>1){if(n.constructor===Au)return qhe(a.map((i,o)=>o===0?i:tme(i)));if(n.constructor===ws)return Jw(a)}return a[0]},gY=(e,t)=>Fhe(e,t,new Au),Hhe=e=>{let t=new Map,n=ve(e.restDecoder);for(let r=0;r<n;r++){let a=ve(e.restDecoder),i=ve(e.restDecoder);t.set(a,i)}return t},bY=e=>Hhe(new $w(To(e))),vY=(e,t)=>(ue(e.restEncoder,t.size),_o(t.entries()).sort((n,r)=>r[0]-n[0]).forEach(([n,r])=>{ue(e.restEncoder,n),ue(e.restEncoder,r)}),e),jhe=(e,t)=>vY(e,iE(t.store)),Vhe=(e,t=new qw)=>(e instanceof Map?vY(t,e):jhe(t,e),t.toUint8Array()),yY=e=>Vhe(e,new Zw),kT=class{constructor(){this.l=[]}},eY=()=>new kT,tY=(e,t)=>e.l.push(t),nY=(e,t)=>{let n=e.l,r=n.length;e.l=n.filter(a=>t!==a),r===e.l.length&&console.error("[yjs] Tried to remove event handler that doesn't exist.")},xY=(e,t,n)=>l0(e.l,[t,n]),Fc=class{constructor(t,n){this.client=t,this.clock=n}},jw=(e,t)=>e===t||e!==null&&t!==null&&e.client===t.client&&e.clock===t.clock,qe=(e,t)=>new Fc(e,t);var Ghe=e=>{for(let[t,n]of e.doc.share.entries())if(n===e)return t;throw Pa()};var TT=class{constructor(t,n){this.ds=t,this.sv=n}};var Yhe=(e,t)=>new TT(e,t),AMe=Yhe(hY(),new Map);var yp=(e,t)=>t===void 0?!e.deleted:t.sv.has(e.id.client)&&(t.sv.get(e.id.client)||0)>e.id.clock&&!uY(t.ds,e.id),MT=(e,t)=>{let n=ri(e.meta,MT,Ki),r=e.doc.store;n.has(t)||(t.sv.forEach((a,i)=>{a<dr(r,i)&&jc(e,qe(i,a))}),dY(e,t.ds,a=>{}),n.add(t))};var Qw=class{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}},iE=e=>{let t=new Map;return e.clients.forEach((n,r)=>{let a=n[n.length-1];t.set(r,a.id.clock+a.length)}),t},dr=(e,t)=>{let n=e.clients.get(t);if(n===void 0)return 0;let r=n[n.length-1];return r.id.clock+r.length},wY=(e,t)=>{let n=e.clients.get(t.id.client);if(n===void 0)n=[],e.clients.set(t.id.client,n);else{let r=n[n.length-1];if(r.id.clock+r.length!==t.id.clock)throw Pa()}n.push(t)},ml=(e,t)=>{let n=0,r=e.length-1,a=e[r],i=a.id.clock;if(i===t)return r;let o=Er(t/(i+a.length-1)*r);for(;n<=r;){if(a=e[o],i=a.id.clock,i<=t){if(t<i+a.length)return o;n=o+1}else r=o-1;o=Er((n+r)/2)}throw Pa()},Whe=(e,t)=>{let n=e.clients.get(t.client);return n[ml(n,t.clock)]},ST=Whe,AT=(e,t,n)=>{let r=ml(t,n),a=t[r];return a.id.clock<n&&a instanceof ur?(t.splice(r+1,0,aE(e,a,n-a.id.clock)),r+1):r},jc=(e,t)=>{let n=e.doc.store.clients.get(t.client);return n[AT(e,n,t.clock)]},rY=(e,t,n)=>{let r=t.clients.get(n.client),a=ml(r,n.clock),i=r[a];return n.clock!==i.id.clock+i.length-1&&i.constructor!==Ua&&r.splice(a+1,0,aE(e,i,n.clock-i.id.clock+1)),i},Khe=(e,t,n)=>{let r=e.clients.get(t.id.client);r[ml(r,t.id.clock)]=n},EY=(e,t,n,r,a)=>{if(r===0)return;let i=n+r,o=AT(e,t,n),l;do l=t[o++],i<l.id.clock+l.length&&AT(e,t,i),a(l);while(o<t.length&&t[o].id.clock<i)},DT=class{constructor(t,n,r){this.doc=t,this.deleteSet=new Tu,this.beforeState=iE(t.store),this.afterState=new Map,this.changed=new Map,this.changedParentTypes=new Map,this._mergeStructs=[],this.origin=n,this.meta=new Map,this.local=r,this.subdocsAdded=new Set,this.subdocsRemoved=new Set,this.subdocsLoaded=new Set,this._needFormattingCleanup=!1}},aY=(e,t)=>t.deleteSet.clients.size===0&&!XV(t.afterState,(n,r)=>t.beforeState.get(r)!==n)?!1:(FT(t.deleteSet),Phe(e,t),Sp(e,t.deleteSet),!0),iY=(e,t,n)=>{let r=t._item;(r===null||r.id.clock<(e.beforeState.get(r.id.client)||0)&&!r.deleted)&&ri(e.changed,t,Ki).add(n)},Yw=(e,t)=>{let n=e[t],r=e[t-1],a=t;for(;a>0;n=r,r=e[--a-1]){if(r.deleted===n.deleted&&r.constructor===n.constructor&&r.mergeWith(n)){n instanceof ur&&n.parentSub!==null&&n.parent._map.get(n.parentSub)===n&&n.parent._map.set(n.parentSub,r);continue}break}let i=t-a;return i&&e.splice(t+1-i,i),i},$he=(e,t,n)=>{for(let[r,a]of e.clients.entries()){let i=t.clients.get(r);for(let o=a.length-1;o>=0;o--){let l=a[o],c=l.clock+l.len;for(let s=ml(i,l.clock),d=i[s];s<i.length&&d.id.clock<c;d=i[++s]){let u=i[s];if(l.clock+l.len<=u.id.clock)break;u instanceof ur&&u.deleted&&!u.keep&&n(u)&&u.gc(t,!1)}}}},Xhe=(e,t)=>{e.clients.forEach((n,r)=>{let a=t.clients.get(r);for(let i=n.length-1;i>=0;i--){let o=n[i],l=np(a.length-1,1+ml(a,o.clock+o.len-1));for(let c=l,s=a[c];c>0&&s.id.clock>=o.clock;s=a[c])c-=1+Yw(a,c)}})};var SY=(e,t)=>{if(t<e.length){let n=e[t],r=n.doc,a=r.store,i=n.deleteSet,o=n._mergeStructs;try{FT(i),n.afterState=iE(n.doc.store),r.emit("beforeObserverCalls",[n,r]);let l=[];n.changed.forEach((c,s)=>l.push(()=>{(s._item===null||!s._item.deleted)&&s._callObserver(n,c)})),l.push(()=>{n.changedParentTypes.forEach((c,s)=>{s._dEH.l.length>0&&(s._item===null||!s._item.deleted)&&(c=c.filter(d=>d.target._item===null||!d.target._item.deleted),c.forEach(d=>{d.currentTarget=s,d._path=null}),c.sort((d,u)=>d.path.length-u.path.length),l.push(()=>{xY(s._dEH,c,n)}))}),l.push(()=>r.emit("afterTransaction",[n,r])),l.push(()=>{n._needFormattingCleanup&&hme(n)})}),l0(l,[])}finally{r.gc&&$he(i,a,r.gcFilter),Xhe(i,a),n.afterState.forEach((d,u)=>{let h=n.beforeState.get(u)||0;if(h!==d){let m=a.clients.get(u),p=vs(ml(m,h),1);for(let f=m.length-1;f>=p;)f-=1+Yw(m,f)}});for(let d=o.length-1;d>=0;d--){let{client:u,clock:h}=o[d].id,m=a.clients.get(u),p=ml(m,h);p+1<m.length&&Yw(m,p+1)>1||p>0&&Yw(m,p)}if(!n.local&&n.afterState.get(r.clientID)!==n.beforeState.get(r.clientID)&&(WG(vp,p0,"[yjs] ",f0,g0,"Changed the client-id because another client seems to be using it."),r.clientID=mY()),r.emit("afterTransactionCleanup",[n,r]),r._observers.has("update")){let d=new Au;aY(d,n)&&r.emit("update",[d.toUint8Array(),n.origin,r,n])}if(r._observers.has("updateV2")){let d=new ws;aY(d,n)&&r.emit("updateV2",[d.toUint8Array(),n.origin,r,n])}let{subdocsAdded:l,subdocsLoaded:c,subdocsRemoved:s}=n;(l.size>0||s.size>0||c.size>0)&&(l.forEach(d=>{d.clientID=r.clientID,d.collectionid==null&&(d.collectionid=r.collectionid),r.subdocs.add(d)}),s.forEach(d=>r.subdocs.delete(d)),r.emit("subdocs",[{loaded:c,added:l,removed:s},r,n]),s.forEach(d=>d.destroy())),e.length<=t+1?(r._transactionCleanups=[],r.emit("afterAllTransactions",[r,e])):SY(e,t+1)}}},Nt=(e,t,n=null,r=!0)=>{let a=e._transactionCleanups,i=!1,o=null;e._transaction===null&&(i=!0,e._transaction=new DT(e,n,r),a.push(e._transaction),a.length===1&&e.emit("beforeAllTransactions",[e]),e.emit("beforeTransaction",[e._transaction,e]));try{o=t(e._transaction)}finally{if(i){let l=e._transaction===a[0];e._transaction=null,l&&SY(a,0)}}return o};function*Zhe(e){let t=ve(e.restDecoder);for(let n=0;n<t;n++){let r=ve(e.restDecoder),a=e.readClient(),i=ve(e.restDecoder);for(let o=0;o<r;o++){let l=e.readInfo();if(l===10){let c=ve(e.restDecoder);yield new Ba(qe(a,i),c),i+=c}else if((31&l)!==0){let c=(l&192)===0,s=new ur(qe(a,i),null,(l&128)===128?e.readLeftID():null,null,(l&64)===64?e.readRightID():null,c?e.readParentInfo()?e.readString():e.readLeftID():null,c&&(l&32)===32?e.readString():null,HY(e,l));yield s,i+=s.length}else{let c=e.readLen();yield new Ua(qe(a,i),c),i+=c}}}}var y0=class{constructor(t,n){this.gen=Zhe(t),this.curr=null,this.done=!1,this.filterSkips=n,this.next()}next(){do this.curr=this.gen.next().value||null;while(this.filterSkips&&this.curr!==null&&this.curr.constructor===Ba);return this.curr}};var x0=class{constructor(t){this.currClient=0,this.startClock=0,this.written=0,this.encoder=t,this.clientStructs=[]}},qhe=e=>Jw(e,Xw,Au);var Qhe=(e,t)=>{if(e.constructor===Ua){let{client:n,clock:r}=e.id;return new Ua(qe(n,r+t),e.length-t)}else if(e.constructor===Ba){let{client:n,clock:r}=e.id;return new Ba(qe(n,r+t),e.length-t)}else{let n=e,{client:r,clock:a}=n.id;return new ur(qe(r,a+t),null,qe(r,a+t-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(t))}},Jw=(e,t=Hc,n=ws)=>{if(e.length===1)return e[0];let r=e.map(d=>new t(To(d))),a=r.map(d=>new y0(d,!0)),i=null,o=new n,l=new x0(o);for(;a=a.filter(h=>h.curr!==null),a.sort((h,m)=>{if(h.curr.id.client===m.curr.id.client){let p=h.curr.id.clock-m.curr.id.clock;return p===0?h.curr.constructor===m.curr.constructor?0:h.curr.constructor===Ba?1:-1:p}else return m.curr.id.client-h.curr.id.client}),a.length!==0;){let d=a[0],u=d.curr.id.client;if(i!==null){let h=d.curr,m=!1;for(;h!==null&&h.id.clock+h.length<=i.struct.id.clock+i.struct.length&&h.id.client>=i.struct.id.client;)h=d.next(),m=!0;if(h===null||h.id.client!==u||m&&h.id.clock>i.struct.id.clock+i.struct.length)continue;if(u!==i.struct.id.client)Uc(l,i.struct,i.offset),i={struct:h,offset:0},d.next();else if(i.struct.id.clock+i.struct.length<h.id.clock)if(i.struct.constructor===Ba)i.struct.length=h.id.clock+h.length-i.struct.id.clock;else{Uc(l,i.struct,i.offset);let p=h.id.clock-i.struct.id.clock-i.struct.length;i={struct:new Ba(qe(u,i.struct.id.clock+i.struct.length),p),offset:0}}else{let p=i.struct.id.clock+i.struct.length-h.id.clock;p>0&&(i.struct.constructor===Ba?i.struct.length-=p:h=Qhe(h,p)),i.struct.mergeWith(h)||(Uc(l,i.struct,i.offset),i={struct:h,offset:0},d.next())}}else i={struct:d.curr,offset:0},d.next();for(let h=d.curr;h!==null&&h.id.client===u&&h.id.clock===i.struct.id.clock+i.struct.length&&h.constructor!==Ba;h=d.next())Uc(l,i.struct,i.offset),i={struct:h,offset:0}}i!==null&&(Uc(l,i.struct,i.offset),i=null),VT(l);let c=r.map(d=>HT(d)),s=Lhe(c);return Sp(o,s),o.toUint8Array()},Jhe=(e,t,n=Hc,r=ws)=>{let a=bY(t),i=new r,o=new x0(i),l=new n(To(e)),c=new y0(l,!1);for(;c.curr;){let d=c.curr,u=d.id.client,h=a.get(u)||0;if(c.curr.constructor===Ba){c.next();continue}if(d.id.clock+d.length>h)for(Uc(o,d,vs(h-d.id.clock,0)),c.next();c.curr&&c.curr.id.client===u;)Uc(o,c.curr,0),c.next();else for(;c.curr&&c.curr.id.client===u&&c.curr.id.clock+c.curr.length<=h;)c.next()}VT(o);let s=HT(l);return Sp(i,s),i.toUint8Array()};var CY=e=>{e.written>0&&(e.clientStructs.push({written:e.written,restEncoder:Rt(e.encoder.restEncoder)}),e.encoder.restEncoder=Wn(),e.written=0)},Uc=(e,t,n)=>{e.written>0&&e.currClient!==t.id.client&&CY(e),e.written===0&&(e.currClient=t.id.client,e.encoder.writeClient(t.id.client),ue(e.encoder.restEncoder,t.id.clock+n)),t.write(e.encoder,n),e.written++},VT=e=>{CY(e);let t=e.encoder.restEncoder;ue(t,e.clientStructs.length);for(let n=0;n<e.clientStructs.length;n++){let r=e.clientStructs[n];ue(t,r.written),n0(t,r.restEncoder)}},eme=(e,t,n,r)=>{let a=new n(To(e)),i=new y0(a,!1),o=new r,l=new x0(o);for(let s=i.curr;s!==null;s=i.next())Uc(l,t(s),0);VT(l);let c=HT(a);return Sp(o,c),o.toUint8Array()};var tme=e=>eme(e,xG,Hc,Au),oY="You must not compute changes after the event-handler fired.",xp=class{constructor(t,n){this.target=t,this.currentTarget=t,this.transaction=n,this._changes=null,this._keys=null,this._delta=null,this._path=null}get path(){return this._path||(this._path=nme(this.currentTarget,this.target))}deletes(t){return uY(this.transaction.deleteSet,t.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw ai(oY);let t=new Map,n=this.target;this.transaction.changed.get(n).forEach(a=>{if(a!==null){let i=n._map.get(a),o,l;if(this.adds(i)){let c=i.left;for(;c!==null&&this.adds(c);)c=c.left;if(this.deletes(i))if(c!==null&&this.deletes(c))o="delete",l=dw(c.content.getContent());else return;else c!==null&&this.deletes(c)?(o="update",l=dw(c.content.getContent())):(o="add",l=void 0)}else if(this.deletes(i))o="delete",l=dw(i.content.getContent());else return;t.set(a,{action:o,oldValue:l})}}),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){if(this.transaction.doc._transactionCleanups.length===0)throw ai(oY);let n=this.target,r=Ki(),a=Ki(),i=[];if(t={added:r,deleted:a,delta:i,keys:this.keys},this.transaction.changed.get(n).has(null)){let l=null,c=()=>{l&&i.push(l)};for(let s=n._start;s!==null;s=s.right)s.deleted?this.deletes(s)&&!this.adds(s)&&((l===null||l.delete===void 0)&&(c(),l={delete:0}),l.delete+=s.length,a.add(s)):this.adds(s)?((l===null||l.insert===void 0)&&(c(),l={insert:[]}),l.insert=l.insert.concat(s.content.getContent()),r.add(s)):((l===null||l.retain===void 0)&&(c(),l={retain:0}),l.retain+=s.length);l!==null&&l.retain===void 0&&c()}this._changes=t}return t}},nme=(e,t)=>{let n=[];for(;t._item!==null&&t!==e;){if(t._item.parentSub!==null)n.unshift(t._item.parentSub);else{let r=0,a=t._item.parent._start;for(;a!==t._item&&a!==null;)!a.deleted&&a.countable&&(r+=a.length),a=a.right;n.unshift(r)}t=t._item.parent}return n},Fr=()=>{KG("Invalid access: Add Yjs type to a document before reading data.")},_Y=80,GT=0,IT=class{constructor(t,n){t.marker=!0,this.p=t,this.index=n,this.timestamp=GT++}},rme=e=>{e.timestamp=GT++},kY=(e,t,n)=>{e.p.marker=!1,e.p=t,t.marker=!0,e.index=n,e.timestamp=GT++},ame=(e,t,n)=>{if(e.length>=_Y){let r=e.reduce((a,i)=>a.timestamp<i.timestamp?a:i);return kY(r,t,n),r}else{let r=new IT(t,n);return e.push(r),r}},oE=(e,t)=>{if(e._start===null||t===0||e._searchMarker===null)return null;let n=e._searchMarker.length===0?null:e._searchMarker.reduce((i,o)=>yu(t-i.index)<yu(t-o.index)?i:o),r=e._start,a=0;for(n!==null&&(r=n.p,a=n.index,rme(n));r.right!==null&&a<t;){if(!r.deleted&&r.countable){if(t<a+r.length)break;a+=r.length}r=r.right}for(;r.left!==null&&a>t;)r=r.left,!r.deleted&&r.countable&&(a-=r.length);for(;r.left!==null&&r.left.id.client===r.id.client&&r.left.id.clock+r.left.length===r.id.clock;)r=r.left,!r.deleted&&r.countable&&(a-=r.length);return n!==null&&yu(n.index-a)<r.parent.length/_Y?(kY(n,r,a),n):ame(e._searchMarker,r,a)},w0=(e,t,n)=>{for(let r=e.length-1;r>=0;r--){let a=e[r];if(n>0){let i=a.p;for(i.marker=!1;i&&(i.deleted||!i.countable);)i=i.left,i&&!i.deleted&&i.countable&&(a.index-=i.length);if(i===null||i.marker===!0){e.splice(r,1);continue}a.p=i,i.marker=!0}(t<a.index||n>0&&t===a.index)&&(a.index=vs(t,a.index+n))}};var lE=(e,t,n)=>{let r=e,a=t.changedParentTypes;for(;ri(a,e,()=>[]).push(n),e._item!==null;)e=e._item.parent;xY(r._eH,n,t)},Xn=class{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=eY(),this._dEH=eY(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(t,n){this.doc=t,this._item=n}_copy(){throw ii()}clone(){throw ii()}_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){tY(this._eH,t)}observeDeep(t){tY(this._dEH,t)}unobserve(t){nY(this._eH,t)}unobserveDeep(t){nY(this._dEH,t)}toJSON(){}},TY=(e,t,n)=>{e.doc??Fr(),t<0&&(t=e._length+t),n<0&&(n=e._length+n);let r=n-t,a=[],i=e._start;for(;i!==null&&r>0;){if(i.countable&&!i.deleted){let o=i.content.getContent();if(o.length<=t)t-=o.length;else{for(let l=t;l<o.length&&r>0;l++)a.push(o[l]),r--;t=0}}i=i.right}return a},MY=e=>{e.doc??Fr();let t=[],n=e._start;for(;n!==null;){if(n.countable&&!n.deleted){let r=n.content.getContent();for(let a=0;a<r.length;a++)t.push(r[a])}n=n.right}return t};var E0=(e,t)=>{let n=0,r=e._start;for(e.doc??Fr();r!==null;){if(r.countable&&!r.deleted){let a=r.content.getContent();for(let i=0;i<a.length;i++)t(a[i],n++,e)}r=r.right}},AY=(e,t)=>{let n=[];return E0(e,(r,a)=>{n.push(t(r,a,e))}),n},ime=e=>{let t=e._start,n=null,r=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(),r=0,t=t.right}let a=n[r++];return n.length<=r&&(n=null),{done:!1,value:a}}}},DY=(e,t)=>{e.doc??Fr();let n=oE(e,t),r=e._start;for(n!==null&&(r=n.p,t-=n.index);r!==null;r=r.right)if(!r.deleted&&r.countable){if(t<r.length)return r.content.getContent()[t];t-=r.length}},eE=(e,t,n,r)=>{let a=n,i=e.doc,o=i.clientID,l=i.store,c=n===null?t._start:n.right,s=[],d=()=>{s.length>0&&(a=new ur(qe(o,dr(l,o)),a,a&&a.lastId,c,c&&c.id,t,null,new Ep(s)),a.integrate(e,0),s=[])};r.forEach(u=>{if(u===null)s.push(u);else switch(u.constructor){case Number:case Object:case Boolean:case Array:case String:s.push(u);break;default:switch(d(),u.constructor){case Uint8Array:case ArrayBuffer:a=new ur(qe(o,dr(l,o)),a,a&&a.lastId,c,c&&c.id,t,null,new T0(new Uint8Array(u))),a.integrate(e,0);break;case Mu:a=new ur(qe(o,dr(l,o)),a,a&&a.lastId,c,c&&c.id,t,null,new M0(u)),a.integrate(e,0);break;default:if(u instanceof Xn)a=new ur(qe(o,dr(l,o)),a,a&&a.lastId,c,c&&c.id,t,null,new Ss(u)),a.integrate(e,0);else throw new Error("Unexpected content type in insert operation")}}}),d()},IY=()=>ai("Length exceeded!"),LY=(e,t,n,r)=>{if(n>t._length)throw IY();if(n===0)return t._searchMarker&&w0(t._searchMarker,n,r.length),eE(e,t,null,r);let a=n,i=oE(t,n),o=t._start;for(i!==null&&(o=i.p,n-=i.index,n===0&&(o=o.prev,n+=o&&o.countable&&!o.deleted?o.length:0));o!==null;o=o.right)if(!o.deleted&&o.countable){if(n<=o.length){n<o.length&&jc(e,qe(o.id.client,o.id.clock+n));break}n-=o.length}return t._searchMarker&&w0(t._searchMarker,a,r.length),eE(e,t,o,r)},ome=(e,t,n)=>{let a=(t._searchMarker||[]).reduce((i,o)=>o.index>i.index?o:i,{index:0,p:t._start}).p;if(a)for(;a.right;)a=a.right;return eE(e,t,a,n)},RY=(e,t,n,r)=>{if(r===0)return;let a=n,i=r,o=oE(t,n),l=t._start;for(o!==null&&(l=o.p,n-=o.index);l!==null&&n>0;l=l.right)!l.deleted&&l.countable&&(n<l.length&&jc(e,qe(l.id.client,l.id.clock+n)),n-=l.length);for(;r>0&&l!==null;)l.deleted||(r<l.length&&jc(e,qe(l.id.client,l.id.clock+r)),l.delete(e),r-=l.length),l=l.right;if(r>0)throw IY();t._searchMarker&&w0(t._searchMarker,a,-i+r)},tE=(e,t,n)=>{let r=t._map.get(n);r!==void 0&&r.delete(e)},YT=(e,t,n,r)=>{let a=t._map.get(n)||null,i=e.doc,o=i.clientID,l;if(r==null)l=new Ep([r]);else switch(r.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:l=new Ep([r]);break;case Uint8Array:l=new T0(r);break;case Mu:l=new M0(r);break;default:if(r instanceof Xn)l=new Ss(r);else throw new Error("Unexpected content type")}new ur(qe(o,dr(i.store,o)),a,a&&a.lastId,null,null,t,n,l).integrate(e,0)},WT=(e,t)=>{e.doc??Fr();let n=e._map.get(t);return n!==void 0&&!n.deleted?n.content.getContent()[n.length-1]:void 0},NY=e=>{let t={};return e.doc??Fr(),e._map.forEach((n,r)=>{n.deleted||(t[r]=n.content.getContent()[n.length-1])}),t},OY=(e,t)=>{e.doc??Fr();let n=e._map.get(t);return n!==void 0&&!n.deleted};var lme=(e,t)=>{let n={};return e._map.forEach((r,a)=>{let i=r;for(;i!==null&&(!t.sv.has(i.id.client)||i.id.clock>=(t.sv.get(i.id.client)||0));)i=i.left;i!==null&&yp(i,t)&&(n[a]=i.content.getContent()[i.length-1])}),n},Vw=e=>(e.doc??Fr(),ZG(e._map.entries(),t=>!t[1].deleted)),LT=class extends xp{},nE=class e extends Xn{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(t){let n=new e;return n.push(t),n}_integrate(t,n){super._integrate(t,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new e}clone(){let t=new e;return t.insert(0,this.toArray().map(n=>n instanceof Xn?n.clone():n)),t}get length(){return this.doc??Fr(),this._length}_callObserver(t,n){super._callObserver(t,n),lE(this,t,new LT(this,t))}insert(t,n){this.doc!==null?Nt(this.doc,r=>{LY(r,this,t,n)}):this._prelimContent.splice(t,0,...n)}push(t){this.doc!==null?Nt(this.doc,n=>{ome(n,this,t)}):this._prelimContent.push(...t)}unshift(t){this.insert(0,t)}delete(t,n=1){this.doc!==null?Nt(this.doc,r=>{RY(r,this,t,n)}):this._prelimContent.splice(t,n)}get(t){return DY(this,t)}toArray(){return MY(this)}slice(t=0,n=this.length){return TY(this,t,n)}toJSON(){return this.map(t=>t instanceof Xn?t.toJSON():t)}map(t){return AY(this,t)}forEach(t){E0(this,t)}[Symbol.iterator](){return ime(this)}_write(t){t.writeTypeRef(Ame)}},sme=e=>new nE,RT=class extends xp{constructor(t,n,r){super(t,n),this.keysChanged=r}},pl=class e extends Xn{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((r,a)=>{this.set(a,r)}),this._prelimContent=null}_copy(){return new e}clone(){let t=new e;return this.forEach((n,r)=>{t.set(r,n instanceof Xn?n.clone():n)}),t}_callObserver(t,n){lE(this,t,new RT(this,t,n))}toJSON(){this.doc??Fr();let t={};return this._map.forEach((n,r)=>{if(!n.deleted){let a=n.content.getContent()[n.length-1];t[r]=a instanceof Xn?a.toJSON():a}}),t}get size(){return[...Vw(this)].length}keys(){return Hw(Vw(this),t=>t[0])}values(){return Hw(Vw(this),t=>t[1].content.getContent()[t[1].length-1])}entries(){return Hw(Vw(this),t=>[t[0],t[1].content.getContent()[t[1].length-1]])}forEach(t){this.doc??Fr(),this._map.forEach((n,r)=>{n.deleted||t(n.content.getContent()[n.length-1],r,this)})}[Symbol.iterator](){return this.entries()}delete(t){this.doc!==null?Nt(this.doc,n=>{tE(n,this,t)}):this._prelimContent.delete(t)}set(t,n){return this.doc!==null?Nt(this.doc,r=>{YT(r,this,t,n)}):this._prelimContent.set(t,n),n}get(t){return WT(this,t)}has(t){return OY(this,t)}clear(){this.doc!==null?Nt(this.doc,t=>{this.forEach(function(n,r,a){tE(t,a,r)})}):this._prelimContent.clear()}_write(t){t.writeTypeRef(Dme)}},cme=e=>new pl,Bc=(e,t)=>e===t||typeof e=="object"&&typeof t=="object"&&e&&t&&aT(e,t),S0=class{constructor(t,n,r,a){this.left=t,this.right=n,this.index=r,this.currentAttributes=a}forward(){this.right===null&&Pa(),this.right.content.constructor===Zn?this.right.deleted||Cp(this.currentAttributes,this.right.content):this.right.deleted||(this.index+=this.right.length),this.left=this.right,this.right=this.right.right}},lY=(e,t,n)=>{for(;t.right!==null&&n>0;)t.right.content.constructor===Zn?t.right.deleted||Cp(t.currentAttributes,t.right.content):t.right.deleted||(n<t.right.length&&jc(e,qe(t.right.id.client,t.right.id.clock+n)),t.index+=t.right.length,n-=t.right.length),t.left=t.right,t.right=t.right.right;return t},Gw=(e,t,n,r)=>{let a=new Map,i=r?oE(t,n):null;if(i){let o=new S0(i.p.left,i.p,i.index,a);return lY(e,o,n-i.index)}else{let o=new S0(null,t._start,0,a);return lY(e,o,n)}},zY=(e,t,n,r)=>{for(;n.right!==null&&(n.right.deleted===!0||n.right.content.constructor===Zn&&Bc(r.get(n.right.content.key),n.right.content.value));)n.right.deleted||r.delete(n.right.content.key),n.forward();let a=e.doc,i=a.clientID;r.forEach((o,l)=>{let c=n.left,s=n.right,d=new ur(qe(i,dr(a.store,i)),c,c&&c.lastId,s,s&&s.id,t,null,new Zn(l,o));d.integrate(e,0),n.right=d,n.forward()})},Cp=(e,t)=>{let{key:n,value:r}=t;r===null?e.delete(n):e.set(n,r)},PY=(e,t)=>{for(;e.right!==null;){if(!(e.right.deleted||e.right.content.constructor===Zn&&Bc(t[e.right.content.key]??null,e.right.content.value)))break;e.forward()}},UY=(e,t,n,r)=>{let a=e.doc,i=a.clientID,o=new Map;for(let l in r){let c=r[l],s=n.currentAttributes.get(l)??null;if(!Bc(s,c)){o.set(l,s);let{left:d,right:u}=n;n.right=new ur(qe(i,dr(a.store,i)),d,d&&d.lastId,u,u&&u.id,t,null,new Zn(l,c)),n.right.integrate(e,0),n.forward()}}return o},CT=(e,t,n,r,a)=>{n.currentAttributes.forEach((h,m)=>{a[m]===void 0&&(a[m]=null)});let i=e.doc,o=i.clientID;PY(n,a);let l=UY(e,t,n,a),c=r.constructor===String?new Es(r):r instanceof Xn?new Ss(r):new Du(r),{left:s,right:d,index:u}=n;t._searchMarker&&w0(t._searchMarker,n.index,c.getLength()),d=new ur(qe(o,dr(i.store,o)),s,s&&s.lastId,d,d&&d.id,t,null,c),d.integrate(e,0),n.right=d,n.index=u,n.forward(),zY(e,t,n,l)},sY=(e,t,n,r,a)=>{let i=e.doc,o=i.clientID;PY(n,a);let l=UY(e,t,n,a);e:for(;n.right!==null&&(r>0||l.size>0&&(n.right.deleted||n.right.content.constructor===Zn));){if(!n.right.deleted)switch(n.right.content.constructor){case Zn:{let{key:c,value:s}=n.right.content,d=a[c];if(d!==void 0){if(Bc(d,s))l.delete(c);else{if(r===0)break e;l.set(c,s)}n.right.delete(e)}else n.currentAttributes.set(c,s);break}default:r<n.right.length&&jc(e,qe(n.right.id.client,n.right.id.clock+r)),r-=n.right.length;break}n.forward()}if(r>0){let c="";for(;r>0;r--)c+=`
288
288
  `;n.right=new ur(qe(o,dr(i.store,o)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,t,null,new Es(c)),n.right.integrate(e,0),n.forward()}zY(e,t,n,l)},BY=(e,t,n,r,a)=>{let i=t,o=sr();for(;i&&(!i.countable||i.deleted);){if(!i.deleted&&i.content.constructor===Zn){let s=i.content;o.set(s.key,s)}i=i.right}let l=0,c=!1;for(;t!==i;){if(n===t&&(c=!0),!t.deleted){let s=t.content;if(s.constructor===Zn){let{key:d,value:u}=s,h=r.get(d)??null;(o.get(d)!==s||h===u)&&(t.delete(e),l++,!c&&(a.get(d)??null)===u&&h!==u&&(h===null?a.delete(d):a.set(d,h))),!c&&!t.deleted&&Cp(a,s)}}t=t.right}return l},dme=(e,t)=>{for(;t&&t.right&&(t.right.deleted||!t.right.countable);)t=t.right;let n=new Set;for(;t&&(t.deleted||!t.countable);){if(!t.deleted&&t.content.constructor===Zn){let r=t.content.key;n.has(r)?t.delete(e):n.add(r)}t=t.left}},ume=e=>{let t=0;return Nt(e.doc,n=>{let r=e._start,a=e._start,i=sr(),o=sw(i);for(;a;)a.deleted===!1&&(a.content.constructor===Zn?Cp(o,a.content):(t+=BY(n,r,a,i,o),i=sw(o),r=a)),a=a.right}),t},hme=e=>{let t=new Set,n=e.doc;for(let[r,a]of e.afterState.entries()){let i=e.beforeState.get(r)||0;a!==i&&EY(e,n.store.clients.get(r),i,a,o=>{!o.deleted&&o.content.constructor===Zn&&o.constructor!==Ua&&t.add(o.parent)})}Nt(n,r=>{dY(e,e.deleteSet,a=>{if(a instanceof Ua||!a.parent._hasFormatting||t.has(a.parent))return;let i=a.parent;a.content.constructor===Zn?t.add(i):dme(r,a)});for(let a of t)ume(a)})},cY=(e,t,n)=>{let r=n,a=sw(t.currentAttributes),i=t.right;for(;n>0&&t.right!==null;){if(t.right.deleted===!1)switch(t.right.content.constructor){case Ss:case Du:case Es:n<t.right.length&&jc(e,qe(t.right.id.client,t.right.id.clock+n)),n-=t.right.length,t.right.delete(e);break}t.forward()}i&&BY(e,i,t.right,a,t.currentAttributes);let o=(t.left||t.right).parent;return o._searchMarker&&w0(o._searchMarker,t.index,-r+n),t},NT=class extends xp{constructor(t,n,r){super(t,n),this.childListChanged=!1,this.keysChanged=new Set,r.forEach(a=>{a===null?this.childListChanged=!0:this.keysChanged.add(a)})}get changes(){if(this._changes===null){let 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){let t=this.target.doc,n=[];Nt(t,r=>{let a=new Map,i=new Map,o=this.target._start,l=null,c={},s="",d=0,u=0,h=()=>{if(l!==null){let m=null;switch(l){case"delete":u>0&&(m={delete:u}),u=0;break;case"insert":(typeof s=="object"||s.length>0)&&(m={insert:s},a.size>0&&(m.attributes={},a.forEach((p,f)=>{p!==null&&(m.attributes[f]=p)}))),s="";break;case"retain":d>0&&(m={retain:d},yG(c)||(m.attributes=gG({},c))),d=0;break}m&&n.push(m),l=null}};for(;o!==null;){switch(o.content.constructor){case Ss:case Du:this.adds(o)?this.deletes(o)||(h(),l="insert",s=o.content.getContent()[0],h()):this.deletes(o)?(l!=="delete"&&(h(),l="delete"),u+=1):o.deleted||(l!=="retain"&&(h(),l="retain"),d+=1);break;case Es:this.adds(o)?this.deletes(o)||(l!=="insert"&&(h(),l="insert"),s+=o.content.str):this.deletes(o)?(l!=="delete"&&(h(),l="delete"),u+=o.length):o.deleted||(l!=="retain"&&(h(),l="retain"),d+=o.length);break;case Zn:{let{key:m,value:p}=o.content;if(this.adds(o)){if(!this.deletes(o)){let f=a.get(m)??null;Bc(f,p)?p!==null&&o.delete(r):(l==="retain"&&h(),Bc(p,i.get(m)??null)?delete c[m]:c[m]=p)}}else if(this.deletes(o)){i.set(m,p);let f=a.get(m)??null;Bc(f,p)||(l==="retain"&&h(),c[m]=f)}else if(!o.deleted){i.set(m,p);let f=c[m];f!==void 0&&(Bc(f,p)?f!==null&&o.delete(r):(l==="retain"&&h(),p===null?delete c[m]:c[m]=p))}o.deleted||(l==="insert"&&h(),Cp(a,o.content));break}}o=o.right}for(h();n.length>0;){let m=n[n.length-1];if(m.retain!==void 0&&m.attributes===void 0)n.pop();else break}}),this._delta=n}return this._delta}},C0=class e extends Xn{constructor(t){super(),this._pending=t!==void 0?[()=>this.insert(0,t)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??Fr(),this._length}_integrate(t,n){super._integrate(t,n);try{this._pending.forEach(r=>r())}catch(r){console.error(r)}this._pending=null}_copy(){return new e}clone(){let t=new e;return t.applyDelta(this.toDelta()),t}_callObserver(t,n){super._callObserver(t,n);let r=new NT(this,t,n);lE(this,t,r),!t.local&&this._hasFormatting&&(t._needFormattingCleanup=!0)}toString(){this.doc??Fr();let t="",n=this._start;for(;n!==null;)!n.deleted&&n.countable&&n.content.constructor===Es&&(t+=n.content.str),n=n.right;return t}toJSON(){return this.toString()}applyDelta(t,{sanitize:n=!0}={}){this.doc!==null?Nt(this.doc,r=>{let a=new S0(null,this._start,0,new Map);for(let i=0;i<t.length;i++){let o=t[i];if(o.insert!==void 0){let l=!n&&typeof o.insert=="string"&&i===t.length-1&&a.right===null&&o.insert.slice(-1)===`
289
289
  `?o.insert.slice(0,-1):o.insert;(typeof l!="string"||l.length>0)&&CT(r,this,a,l,o.attributes||{})}else o.retain!==void 0?sY(r,this,a,o.retain,o.attributes||{}):o.delete!==void 0&&cY(r,a,o.delete)}}):this._pending.push(()=>this.applyDelta(t))}toDelta(t,n,r){this.doc??Fr();let a=[],i=new Map,o=this.doc,l="",c=this._start;function s(){if(l.length>0){let u={},h=!1;i.forEach((p,f)=>{h=!0,u[f]=p});let m={insert:l};h&&(m.attributes=u),a.push(m),l=""}}let d=()=>{for(;c!==null;){if(yp(c,t)||n!==void 0&&yp(c,n))switch(c.content.constructor){case Es:{let u=i.get("ychange");t!==void 0&&!yp(c,t)?(u===void 0||u.user!==c.id.client||u.type!=="removed")&&(s(),i.set("ychange",r?r("removed",c.id):{type:"removed"})):n!==void 0&&!yp(c,n)?(u===void 0||u.user!==c.id.client||u.type!=="added")&&(s(),i.set("ychange",r?r("added",c.id):{type:"added"})):u!==void 0&&(s(),i.delete("ychange")),l+=c.content.str;break}case Ss:case Du:{s();let u={insert:c.content.getContent()[0]};if(i.size>0){let h={};u.attributes=h,i.forEach((m,p)=>{h[p]=m})}a.push(u);break}case Zn:yp(c,t)&&(s(),Cp(i,c.content));break}c=c.right}s()};return t||n?Nt(o,u=>{t&&MT(u,t),n&&MT(u,n),d()},"cleanup"):d(),a}insert(t,n,r){if(n.length<=0)return;let a=this.doc;a!==null?Nt(a,i=>{let o=Gw(i,this,t,!r);r||(r={},o.currentAttributes.forEach((l,c)=>{r[c]=l})),CT(i,this,o,n,r)}):this._pending.push(()=>this.insert(t,n,r))}insertEmbed(t,n,r){let a=this.doc;a!==null?Nt(a,i=>{let o=Gw(i,this,t,!r);CT(i,this,o,n,r||{})}):this._pending.push(()=>this.insertEmbed(t,n,r||{}))}delete(t,n){if(n===0)return;let r=this.doc;r!==null?Nt(r,a=>{cY(a,Gw(a,this,t,!0),n)}):this._pending.push(()=>this.delete(t,n))}format(t,n,r){if(n===0)return;let a=this.doc;a!==null?Nt(a,i=>{let o=Gw(i,this,t,!1);o.right!==null&&sY(i,this,o,n,r)}):this._pending.push(()=>this.format(t,n,r))}removeAttribute(t){this.doc!==null?Nt(this.doc,n=>{tE(n,this,t)}):this._pending.push(()=>this.removeAttribute(t))}setAttribute(t,n){this.doc!==null?Nt(this.doc,r=>{YT(r,this,t,n)}):this._pending.push(()=>this.setAttribute(t,n))}getAttribute(t){return WT(this,t)}getAttributes(){return NY(this)}_write(t){t.writeTypeRef(Ime)}},mme=e=>new C0,b0=class{constructor(t,n=()=>!0){this._filter=n,this._root=t,this._currentNode=t._start,this._firstCall=!0,t.doc??Fr()}[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===_0||n.constructor===wp)&&n._start!==null)t=n._start;else for(;t!==null;){let r=t.next;if(r!==null){t=r;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})}},wp=class e extends Xn{constructor(){super(),this._prelimContent=[]}get firstChild(){let 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 e}clone(){let t=new e;return t.insert(0,this.toArray().map(n=>n instanceof Xn?n.clone():n)),t}get length(){return this.doc??Fr(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(t){return new b0(this,t)}querySelector(t){t=t.toUpperCase();let r=new b0(this,a=>a.nodeName&&a.nodeName.toUpperCase()===t).next();return r.done?null:r.value}querySelectorAll(t){return t=t.toUpperCase(),_o(new b0(this,n=>n.nodeName&&n.nodeName.toUpperCase()===t))}_callObserver(t,n){lE(this,t,new OT(this,n,t))}toString(){return AY(this,t=>t.toString()).join("")}toJSON(){return this.toString()}toDOM(t=document,n={},r){let a=t.createDocumentFragment();return r!==void 0&&r._createAssociation(a,this),E0(this,i=>{a.insertBefore(i.toDOM(t,n,r),null)}),a}insert(t,n){this.doc!==null?Nt(this.doc,r=>{LY(r,this,t,n)}):this._prelimContent.splice(t,0,...n)}insertAfter(t,n){if(this.doc!==null)Nt(this.doc,r=>{let a=t&&t instanceof Xn?t._item:t;eE(r,this,a,n)});else{let r=this._prelimContent,a=t===null?0:r.findIndex(i=>i===t)+1;if(a===0&&t!==null)throw ai("Reference item not found");r.splice(a,0,...n)}}delete(t,n=1){this.doc!==null?Nt(this.doc,r=>{RY(r,this,t,n)}):this._prelimContent.splice(t,n)}toArray(){return MY(this)}push(t){this.insert(this.length,t)}unshift(t){this.insert(0,t)}get(t){return DY(this,t)}slice(t=0,n=this.length){return TY(this,t,n)}forEach(t){E0(this,t)}_write(t){t.writeTypeRef(Rme)}},pme=e=>new wp,_0=class e extends wp{constructor(t="UNDEFINED"){super(),this.nodeName=t,this._prelimAttrs=new Map}get nextSibling(){let t=this._item?this._item.next:null;return t?t.content.type:null}get prevSibling(){let t=this._item?this._item.prev:null;return t?t.content.type:null}_integrate(t,n){super._integrate(t,n),this._prelimAttrs.forEach((r,a)=>{this.setAttribute(a,r)}),this._prelimAttrs=null}_copy(){return new e(this.nodeName)}clone(){let t=new e(this.nodeName),n=this.getAttributes();return bG(n,(r,a)=>{t.setAttribute(a,r)}),t.insert(0,this.toArray().map(r=>r instanceof Xn?r.clone():r)),t}toString(){let t=this.getAttributes(),n=[],r=[];for(let l in t)r.push(l);r.sort();let a=r.length;for(let l=0;l<a;l++){let c=r[l];n.push(c+'="'+t[c]+'"')}let i=this.nodeName.toLocaleLowerCase(),o=n.length>0?" "+n.join(" "):"";return`<${i}${o}>${super.toString()}</${i}>`}removeAttribute(t){this.doc!==null?Nt(this.doc,n=>{tE(n,this,t)}):this._prelimAttrs.delete(t)}setAttribute(t,n){this.doc!==null?Nt(this.doc,r=>{YT(r,this,t,n)}):this._prelimAttrs.set(t,n)}getAttribute(t){return WT(this,t)}hasAttribute(t){return OY(this,t)}getAttributes(t){return t?lme(this,t):NY(this)}toDOM(t=document,n={},r){let a=t.createElement(this.nodeName),i=this.getAttributes();for(let o in i){let l=i[o];typeof l=="string"&&a.setAttribute(o,l)}return E0(this,o=>{a.appendChild(o.toDOM(t,n,r))}),r!==void 0&&r._createAssociation(a,this),a}_write(t){t.writeTypeRef(Lme),t.writeKey(this.nodeName)}},fme=e=>new _0(e.readKey()),OT=class extends xp{constructor(t,n,r){super(t,r),this.childListChanged=!1,this.attributesChanged=new Set,n.forEach(a=>{a===null?this.childListChanged=!0:this.attributesChanged.add(a)})}},zT=class e extends pl{constructor(t){super(),this.hookName=t}_copy(){return new e(this.hookName)}clone(){let t=new e(this.hookName);return this.forEach((n,r)=>{t.set(r,n)}),t}toDOM(t=document,n={},r){let a=n[this.hookName],i;return a!==void 0?i=a.createDom(this):i=document.createElement(this.hookName),i.setAttribute("data-yjs-hook",this.hookName),r!==void 0&&r._createAssociation(i,this),i}_write(t){t.writeTypeRef(Nme),t.writeKey(this.hookName)}},gme=e=>new zT(e.readKey()),PT=class e extends C0{get nextSibling(){let t=this._item?this._item.next:null;return t?t.content.type:null}get prevSibling(){let t=this._item?this._item.prev:null;return t?t.content.type:null}_copy(){return new e}clone(){let t=new e;return t.applyDelta(this.toDelta()),t}toDOM(t=document,n,r){let a=t.createTextNode(this.toString());return r!==void 0&&r._createAssociation(a,this),a}toString(){return this.toDelta().map(t=>{let n=[];for(let a in t.attributes){let i=[];for(let o in t.attributes[a])i.push({key:o,value:t.attributes[a][o]});i.sort((o,l)=>o.key<l.key?-1:1),n.push({nodeName:a,attrs:i})}n.sort((a,i)=>a.nodeName<i.nodeName?-1:1);let r="";for(let a=0;a<n.length;a++){let i=n[a];r+=`<${i.nodeName}`;for(let o=0;o<i.attrs.length;o++){let l=i.attrs[o];r+=` ${l.key}="${l.value}"`}r+=">"}r+=t.insert;for(let a=n.length-1;a>=0;a--)r+=`</${n[a].nodeName}>`;return r}).join("")}toJSON(){return this.toString()}_write(t){t.writeTypeRef(Ome)}},bme=e=>new PT,k0=class{constructor(t,n){this.id=t,this.length=n}get deleted(){throw ii()}mergeWith(t){return!1}write(t,n,r){throw ii()}integrate(t,n){throw ii()}},vme=0,Ua=class extends k0{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),wY(t.doc.store,this)}write(t,n){t.writeInfo(vme),t.writeLen(this.length-n)}getMissing(t,n){return null}},T0=class e{constructor(t){this.content=t}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new e(this.content)}splice(t){throw ii()}mergeWith(t){return!1}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeBuf(this.content)}getRef(){return 3}},yme=e=>new T0(e.readBuf()),rE=class e{constructor(t){this.len=t}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new e(this.len)}splice(t){let n=new e(this.len-t);return this.len=t,n}mergeWith(t){return this.len+=t.len,!0}integrate(t,n){Kw(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}},xme=e=>new rE(e.readLen()),FY=(e,t)=>new Mu({guid:e,...t,shouldLoad:t.shouldLoad||t.autoLoad||!1}),M0=class e{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;let 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 e(FY(this.doc.guid,this.opts))}splice(t){throw ii()}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}},wme=e=>new M0(FY(e.readString(),e.readAny())),Du=class e{constructor(t){this.embed=t}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new e(this.embed)}splice(t){throw ii()}mergeWith(t){return!1}integrate(t,n){}delete(t){}gc(t){}write(t,n){t.writeJSON(this.embed)}getRef(){return 5}},Eme=e=>new Du(e.readJSON()),Zn=class e{constructor(t,n){this.key=t,this.value=n}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new e(this.key,this.value)}splice(t){throw ii()}mergeWith(t){return!1}integrate(t,n){let r=n.parent;r._searchMarker=null,r._hasFormatting=!0}delete(t){}gc(t){}write(t,n){t.writeKey(this.key),t.writeJSON(this.value)}getRef(){return 6}},Sme=e=>new Zn(e.readKey(),e.readJSON()),UT=class e{constructor(t){this.arr=t}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new e(this.arr)}splice(t){let n=new e(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){let r=this.arr.length;t.writeLen(r-n);for(let a=n;a<r;a++){let i=this.arr[a];t.writeString(i===void 0?"undefined":JSON.stringify(i))}}getRef(){return 2}},Cme=e=>{let t=e.readLen(),n=[];for(let r=0;r<t;r++){let a=e.readString();a==="undefined"?n.push(void 0):n.push(JSON.parse(a))}return new UT(n)},_me=s0("node_env")==="development",Ep=class e{constructor(t){this.arr=t,_me&&iT(t)}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new e(this.arr)}splice(t){let n=new e(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){let r=this.arr.length;t.writeLen(r-n);for(let a=n;a<r;a++){let i=this.arr[a];t.writeAny(i)}}getRef(){return 8}},kme=e=>{let t=e.readLen(),n=[];for(let r=0;r<t;r++)n.push(e.readAny());return new Ep(n)},Es=class e{constructor(t){this.str=t}getLength(){return this.str.length}getContent(){return this.str.split("")}isCountable(){return!0}copy(){return new e(this.str)}splice(t){let n=new e(this.str.slice(t));this.str=this.str.slice(0,t);let r=this.str.charCodeAt(t-1);return r>=55296&&r<=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}},Tme=e=>new Es(e.readString()),Mme=[sme,cme,mme,fme,pme,gme,bme],Ame=0,Dme=1,Ime=2,Lme=3,Rme=4,Nme=5,Ome=6,Ss=class e{constructor(t){this.type=t}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new e(this.type._copy())}splice(t){throw ii()}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?n.id.clock<(t.beforeState.get(n.id.client)||0)&&t._mergeStructs.push(n):n.delete(t),n=n.right;this.type._map.forEach(r=>{r.deleted?r.id.clock<(t.beforeState.get(r.id.client)||0)&&t._mergeStructs.push(r):r.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(r=>{for(;r!==null;)r.gc(t,!0),r=r.left}),this.type._map=new Map}write(t,n){this.type._write(t)}getRef(){return 7}},zme=e=>new Ss(Mme[e.readTypeRef()](e));var aE=(e,t,n)=>{let{client:r,clock:a}=t.id,i=new ur(qe(r,a+n),t,qe(r,a+n-1),t.right,t.rightOrigin,t.parent,t.parentSub,t.content.splice(n));return t.deleted&&i.markDeleted(),t.keep&&(i.keep=!0),t.redone!==null&&(i.redone=qe(t.redone.client,t.redone.clock+n)),t.right=i,i.right!==null&&(i.right.left=i),e._mergeStructs.push(i),i.parentSub!==null&&i.right===null&&i.parent._map.set(i.parentSub,i),t.length=n,i};var ur=class e extends k0{constructor(t,n,r,a,i,o,l,c){super(t,c.getLength()),this.origin=r,this.left=n,this.right=a,this.rightOrigin=i,this.parent=o,this.parentSub=l,this.redone=null,this.content=c,this.info=this.content.isCountable()?2:0}set marker(t){(this.info&8)>0!==t&&(this.info^=8)}get marker(){return(this.info&8)>0}get keep(){return(this.info&1)>0}set keep(t){this.keep!==t&&(this.info^=1)}get countable(){return(this.info&2)>0}get deleted(){return(this.info&4)>0}set deleted(t){this.deleted!==t&&(this.info^=4)}markDeleted(){this.info|=4}getMissing(t,n){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=dr(n,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=dr(n,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===Fc&&this.id.client!==this.parent.client&&this.parent.clock>=dr(n,this.parent.client))return this.parent.client;if(this.origin&&(this.left=rY(t,n,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=jc(t,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===Ua||this.right&&this.right.constructor===Ua)this.parent=null;else if(!this.parent)this.left&&this.left.constructor===e?(this.parent=this.left.parent,this.parentSub=this.left.parentSub):this.right&&this.right.constructor===e&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);else if(this.parent.constructor===Fc){let r=ST(n,this.parent);r.constructor===Ua?this.parent=null:this.parent=r.content.type}return null}integrate(t,n){if(n>0&&(this.id.clock+=n,this.left=rY(t,t.doc.store,qe(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 r=this.left,a;if(r!==null)a=r.right;else if(this.parentSub!==null)for(a=this.parent._map.get(this.parentSub)||null;a!==null&&a.left!==null;)a=a.left;else a=this.parent._start;let i=new Set,o=new Set;for(;a!==null&&a!==this.right;){if(o.add(a),i.add(a),jw(this.origin,a.origin)){if(a.id.client<this.id.client)r=a,i.clear();else if(jw(this.rightOrigin,a.rightOrigin))break}else if(a.origin!==null&&o.has(ST(t.doc.store,a.origin)))i.has(ST(t.doc.store,a.origin))||(r=a,i.clear());else break;a=a.right}this.left=r}if(this.left!==null){let r=this.left.right;this.right=r,this.left.right=this}else{let r;if(this.parentSub!==null)for(r=this.parent._map.get(this.parentSub)||null;r!==null&&r.left!==null;)r=r.left;else r=this.parent._start,this.parent._start=this;this.right=r}this.right!==null?this.right.left=this:this.parentSub!==null&&(this.parent._map.set(this.parentSub,this),this.left!==null&&this.left.delete(t)),this.parentSub===null&&this.countable&&!this.deleted&&(this.parent._length+=this.length),wY(t.doc.store,this),this.content.integrate(t,this),iY(t,this.parent,this.parentSub),(this.parent._item!==null&&this.parent._item.deleted||this.parentSub!==null&&this.right!==null)&&this.delete(t)}else new Ua(this.id,this.length).integrate(t,0)}get next(){let t=this.right;for(;t!==null&&t.deleted;)t=t.right;return t}get prev(){let t=this.left;for(;t!==null&&t.deleted;)t=t.left;return t}get lastId(){return this.length===1?this.id:qe(this.id.client,this.id.clock+this.length-1)}mergeWith(t){if(this.constructor===t.constructor&&jw(t.origin,this.lastId)&&this.right===t&&jw(this.rightOrigin,t.rightOrigin)&&this.id.client===t.id.client&&this.id.clock+this.length===t.id.clock&&this.deleted===t.deleted&&this.redone===null&&t.redone===null&&this.content.constructor===t.content.constructor&&this.content.mergeWith(t.content)){let n=this.parent._searchMarker;return n&&n.forEach(r=>{r.p===t&&(r.p=this,!this.deleted&&this.countable&&(r.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){let n=this.parent;this.countable&&this.parentSub===null&&(n._length-=this.length),this.markDeleted(),Kw(t.deleteSet,this.id.client,this.id.clock,this.length),iY(t,n,this.parentSub),this.content.delete(t)}}gc(t,n){if(!this.deleted)throw Pa();this.content.gc(t),n?Khe(t,this,new Ua(this.id,this.length)):this.content=new rE(this.length)}write(t,n){let r=n>0?qe(this.id.client,this.id.clock+n-1):this.origin,a=this.rightOrigin,i=this.parentSub,o=this.content.getRef()&31|(r===null?0:128)|(a===null?0:64)|(i===null?0:32);if(t.writeInfo(o),r!==null&&t.writeLeftID(r),a!==null&&t.writeRightID(a),r===null&&a===null){let l=this.parent;if(l._item!==void 0){let c=l._item;if(c===null){let s=Ghe(l);t.writeParentInfo(!0),t.writeString(s)}else t.writeParentInfo(!1),t.writeLeftID(c.id)}else l.constructor===String?(t.writeParentInfo(!0),t.writeString(l)):l.constructor===Fc?(t.writeParentInfo(!1),t.writeLeftID(l)):Pa();i!==null&&t.writeString(i)}this.content.write(t,n)}},HY=(e,t)=>Pme[t&31](e),Pme=[()=>{Pa()},xme,Cme,yme,Tme,Eme,Sme,zme,kme,wme,()=>{Pa()}],Ume=10,Ba=class extends k0{get deleted(){return!0}delete(){}mergeWith(t){return this.constructor!==t.constructor?!1:(this.length+=t.length,!0)}integrate(t,n){Pa()}write(t,n){t.writeInfo(Ume),ue(t.restEncoder,this.length-n)}getMissing(t,n){return null}},jY=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:{},VY="__ $YJS$ __";jY[VY]===!0&&console.error("Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438");jY[VY]=!0;var YY=new Map,KT=class{constructor(t){this.room=t,this.onmessage=null,this._onChange=n=>n.key===t&&this.onmessage!==null&&this.onmessage({data:MG(n.newValue||"")}),hG(this._onChange)}postMessage(t){Ew.setItem(this.room,TG(kG(t)))}close(){mG(this._onChange)}},Bme=typeof BroadcastChannel>"u"?KT:BroadcastChannel,$T=e=>ri(YY,e,()=>{let t=Ki(),n=new Bme(e);return n.onmessage=r=>t.forEach(a=>a(r.data,"broadcastchannel")),{bc:n,subs:t}}),WY=(e,t)=>($T(e).subs.add(t),t),KY=(e,t)=>{let n=$T(e),r=n.subs.delete(t);return r&&n.subs.size===0&&(n.bc.close(),YY.delete(e)),r},Iu=(e,t,n=null)=>{let r=$T(e);r.bc.postMessage(t),r.subs.forEach(a=>a(t,n))};var $Y=0,sE=1,XY=2,cE=(e,t)=>{ue(e,$Y);let n=yY(t);Xt(e,n)},XT=(e,t,n)=>{ue(e,sE),Xt(e,gY(t,n))},Hme=(e,t,n)=>XT(t,n,Kn(e)),ZY=(e,t,n,r)=>{try{fY(t,Kn(e),n)}catch(a){r?.(a),console.error("Caught error while handling a Yjs update",a)}},qY=(e,t)=>{ue(e,XY),Xt(e,t)},jme=ZY,QY=(e,t,n,r,a)=>{let i=ve(e);switch(i){case $Y:Hme(e,t,n);break;case sE:ZY(e,n,r,a);break;case XY:jme(e,n,r,a);break;default:throw new Error("Unknown message type")}return i};var Gme=0;var JY=(e,t,n)=>{ve(e)===Gme&&n(t,ko(e))};var ZT=3e4,dE=class extends mw{constructor(t){super(),this.doc=t,this.clientID=t.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{let n=Mo();this.getLocalState()!==null&&ZT/2<=n-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());let r=[];this.meta.forEach((a,i)=>{i!==this.clientID&&ZT<=n-a.lastUpdated&&this.states.has(i)&&r.push(i)}),r.length>0&&uE(this,r,"timeout")},Er(ZT/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){let n=this.clientID,r=this.meta.get(n),a=r===void 0?0:r.clock+1,i=this.states.get(n);t===null?this.states.delete(n):this.states.set(n,t),this.meta.set(n,{clock:a,lastUpdated:Mo()});let o=[],l=[],c=[],s=[];t===null?s.push(n):i==null?t!=null&&o.push(n):(l.push(n),Pc(i,t)||c.push(n)),(o.length>0||c.length>0||s.length>0)&&this.emit("change",[{added:o,updated:c,removed:s},"local"]),this.emit("update",[{added:o,updated:l,removed:s},"local"])}setLocalStateField(t,n){let r=this.getLocalState();r!==null&&this.setLocalState({...r,[t]:n})}getStates(){return this.states}},uE=(e,t,n)=>{let r=[];for(let a=0;a<t.length;a++){let i=t[a];if(e.states.has(i)){if(e.states.delete(i),i===e.clientID){let o=e.meta.get(i);e.meta.set(i,{clock:o.clock+1,lastUpdated:Mo()})}r.push(i)}}r.length>0&&(e.emit("change",[{added:[],updated:[],removed:r},n]),e.emit("update",[{added:[],updated:[],removed:r},n]))},_p=(e,t,n=e.states)=>{let r=t.length,a=Wn();ue(a,r);for(let i=0;i<r;i++){let o=t[i],l=n.get(o)||null,c=e.meta.get(o).clock;ue(a,o),ue(a,c),ys(a,JSON.stringify(l))}return Rt(a)};var eW=(e,t,n)=>{let r=To(t),a=Mo(),i=[],o=[],l=[],c=[],s=ve(r);for(let d=0;d<s;d++){let u=ve(r),h=ve(r),m=JSON.parse(ko(r)),p=e.meta.get(u),f=e.states.get(u),x=p===void 0?0:p.clock;(x<h||x===h&&m===null&&e.states.has(u))&&(m===null?u===e.clientID&&e.getLocalState()!=null?h++:e.states.delete(u):e.states.set(u,m),e.meta.set(u,{clock:h,lastUpdated:a}),p===void 0&&m!==null?i.push(u):p!==void 0&&m===null?c.push(u):m!==null&&(Pc(m,f)||l.push(u),o.push(u)))}(i.length>0||l.length>0||c.length>0)&&e.emit("change",[{added:i,updated:l,removed:c},n]),(i.length>0||o.length>0||c.length>0)&&e.emit("update",[{added:i,updated:o,removed:c},n])};var tW=e=>vG(e,(t,n)=>`${encodeURIComponent(n)}=${encodeURIComponent(t)}`).join("&");var Lu=0,rW=3,kp=1,$me=2,A0=[];A0[Lu]=(e,t,n,r,a)=>{ue(e,Lu);let i=QY(t,e,n.doc,n);r&&i===sE&&!n.synced&&(n.synced=!0)};A0[rW]=(e,t,n,r,a)=>{ue(e,kp),Xt(e,_p(n.awareness,Array.from(n.awareness.getStates().keys())))};A0[kp]=(e,t,n,r,a)=>{eW(n.awareness,Kn(t),n)};A0[$me]=(e,t,n,r,a)=>{JY(t,n.doc,(i,o)=>Xme(n,o))};var nW=3e4,Xme=(e,t)=>console.warn(`Permission denied to access ${e.url}.
290
- ${t}`),aW=(e,t,n)=>{let r=To(t),a=Wn(),i=ve(r),o=e.messageHandlers[i];return o?o(a,r,e,n,i):console.error("Unable to compute message"),a},QT=(e,t,n)=>{t===e.ws&&(e.emit("connection-close",[n,e]),e.ws=null,t.close(),e.wsconnecting=!1,e.wsconnected?(e.wsconnected=!1,e.synced=!1,uE(e.awareness,Array.from(e.awareness.getStates().keys()).filter(r=>r!==e.doc.clientID),e),e.emit("status",[{status:"disconnected"}])):e.wsUnsuccessfulReconnects++,setTimeout(iW,np(QV(2,e.wsUnsuccessfulReconnects)*100,e.maxBackoffTime),e))},iW=e=>{if(e.shouldConnect&&e.ws===null){let t=new e._WS(e.url,e.protocols);t.binaryType="arraybuffer",e.ws=t,e.wsconnecting=!0,e.wsconnected=!1,e.synced=!1,t.onmessage=n=>{e.wsLastMessageReceived=Mo();let r=aW(e,new Uint8Array(n.data),!0);gw(r)>1&&t.send(Rt(r))},t.onerror=n=>{e.emit("connection-error",[n,e])},t.onclose=n=>{QT(e,t,n)},t.onopen=()=>{e.wsLastMessageReceived=Mo(),e.wsconnecting=!1,e.wsconnected=!0,e.wsUnsuccessfulReconnects=0,e.emit("status",[{status:"connected"}]);let n=Wn();if(ue(n,Lu),cE(n,e.doc),t.send(Rt(n)),e.awareness.getLocalState()!==null){let r=Wn();ue(r,kp),Xt(r,_p(e.awareness,[e.doc.clientID])),t.send(Rt(r))}},e.emit("status",[{status:"connecting"}])}},qT=(e,t)=>{let n=e.ws;e.wsconnected&&n&&n.readyState===n.OPEN&&n.send(t),e.bcconnected&&Iu(e.bcChannel,t,e)},hE=class extends tp{constructor(t,n,r,{connect:a=!0,awareness:i=new dE(r),params:o={},protocols:l=[],WebSocketPolyfill:c=WebSocket,resyncInterval:s=-1,maxBackoffTime:d=2500,disableBc:u=!1}={}){for(super();t[t.length-1]==="/";)t=t.slice(0,t.length-1);this.serverUrl=t,this.bcChannel=t+"/"+n,this.maxBackoffTime=d,this.params=o,this.protocols=l,this.roomname=n,this.doc=r,this._WS=c,this.awareness=i,this.wsconnected=!1,this.wsconnecting=!1,this.bcconnected=!1,this.disableBc=u,this.wsUnsuccessfulReconnects=0,this.messageHandlers=A0.slice(),this._synced=!1,this.ws=null,this.wsLastMessageReceived=0,this.shouldConnect=a,this._resyncInterval=0,s>0&&(this._resyncInterval=setInterval(()=>{if(this.ws&&this.ws.readyState===WebSocket.OPEN){let h=Wn();ue(h,Lu),cE(h,r),this.ws.send(Rt(h))}},s)),this._bcSubscriber=(h,m)=>{if(m!==this){let p=aW(this,new Uint8Array(h),!1);gw(p)>1&&Iu(this.bcChannel,Rt(p),this)}},this._updateHandler=(h,m)=>{if(m!==this){let p=Wn();ue(p,Lu),qY(p,h),qT(this,Rt(p))}},this.doc.on("update",this._updateHandler),this._awarenessUpdateHandler=({added:h,updated:m,removed:p},f)=>{let x=h.concat(m).concat(p),g=Wn();ue(g,kp),Xt(g,_p(i,x)),qT(this,Rt(g))},this._exitHandler=()=>{uE(this.awareness,[r.clientID],"app closed")},xs&&typeof process<"u"&&process.on("exit",this._exitHandler),i.on("update",this._awarenessUpdateHandler),this._checkInterval=setInterval(()=>{this.wsconnected&&nW<Mo()-this.wsLastMessageReceived&&QT(this,this.ws,null)},nW/10),a&&this.connect()}get url(){let t=tW(this.params);return this.serverUrl+"/"+this.roomname+(t.length===0?"":"?"+t)}get synced(){return this._synced}set synced(t){this._synced!==t&&(this._synced=t,this.emit("synced",[t]),this.emit("sync",[t]))}destroy(){this._resyncInterval!==0&&clearInterval(this._resyncInterval),clearInterval(this._checkInterval),this.disconnect(),xs&&typeof process<"u"&&process.off("exit",this._exitHandler),this.awareness.off("update",this._awarenessUpdateHandler),this.doc.off("update",this._updateHandler),super.destroy()}connectBc(){if(this.disableBc)return;this.bcconnected||(WY(this.bcChannel,this._bcSubscriber),this.bcconnected=!0);let t=Wn();ue(t,Lu),cE(t,this.doc),Iu(this.bcChannel,Rt(t),this);let n=Wn();ue(n,Lu),XT(n,this.doc),Iu(this.bcChannel,Rt(n),this);let r=Wn();ue(r,rW),Iu(this.bcChannel,Rt(r),this);let a=Wn();ue(a,kp),Xt(a,_p(this.awareness,[this.doc.clientID])),Iu(this.bcChannel,Rt(a),this)}disconnectBc(){let t=Wn();ue(t,kp),Xt(t,_p(this.awareness,[this.doc.clientID],new Map)),qT(this,Rt(t)),this.bcconnected&&(KY(this.bcChannel,this._bcSubscriber),this.bcconnected=!1)}disconnect(){this.shouldConnect=!1,this.disconnectBc(),this.ws!==null&&QT(this,this.ws,null)}connect(){this.shouldConnect=!0,!this.wsconnected&&this.ws===null&&(iW(this),this.connectBc())}};var oW="excalidraw",lW=2,sW="collabmd",Tp="excalidraw-app-state",Mp="excalidraw-elements",Ap="excalidraw-files",mE="excalidraw-meta",JT=1,Zme="codemirror",eM="schemaVersion";function D0(){return{type:oW,version:lW,source:sW,elements:[],appState:{gridSize:null,viewBackgroundColor:"#ffffff"},files:{}}}function tM(e={}){return{gridSize:e?.gridSize??null,viewBackgroundColor:e?.viewBackgroundColor??"#ffffff"}}function pE(e){return!e||typeof e!="object"?D0():{type:oW,version:lW,source:sW,elements:Array.isArray(e.elements)?e.elements:[],appState:tM(e.appState),files:e.files&&typeof e.files=="object"?e.files:{}}}function qme(e,{fallbackToEmpty:t=!0}={}){if(!e)return t?D0():null;try{return pE(JSON.parse(e))}catch{return t?D0():null}}function I0(e){if(e!==void 0)return JSON.parse(JSON.stringify(e))}function Qme(e){let t=Number.isFinite(Number(e?.version))?Number(e.version):0,n=Number.isFinite(Number(e?.versionNonce))?Number(e.versionNonce):0,r=Number.isFinite(Number(e?.updated))?Number(e.updated):0;return`${t}:${n}:${r}`}function cW(e,t){let n=Number(e?.version)||0,r=Number(t?.version)||0;if(n!==r)return n-r;let a=Number(e?.versionNonce)||0,i=Number(t?.versionNonce)||0;if(a!==i)return a-i;let o=Number(e?.updated)||0,l=Number(t?.updated)||0;return o!==l?o-l:String(e?.id||"").localeCompare(String(t?.id||""))}function Jme(e,t){let n=e?.index??"",r=t?.index??"";return n!==r?String(n).localeCompare(String(r)):String(e?.id||"").localeCompare(String(t?.id||""))}function dW(e,t,{create:n=!1}={}){let r=e.get(t);if(r instanceof pl)return r;if(!n)return null;let a=new pl;return e.set(t,a),a}function uW(e){if(typeof e=="string")try{return JSON.parse(e)}catch{return null}return!e||typeof e!="object"?null:I0(e)}function epe(e){if(!(e instanceof pl)||e.size===0)return null;let t=null;return e.forEach(n=>{let r=uW(n);!r||!r.id||(!t||cW(r,t)>0)&&(t=r)}),t}function hW(e,t,{maxRevisions:n=2}={}){let r=Qme(t),a=I0(t),i=e.get(r),o=i&&typeof i=="object"?JSON.stringify(i):"",l=JSON.stringify(a);return o===l?!1:(e.set(r,a),tpe(e,n),!0)}function tpe(e,t=2){if(!(e instanceof pl)||e.size<=t)return;let n=[];for(e.forEach((r,a)=>{let i=uW(r);if(!i){n.push({element:null,key:a});return}n.push({element:i,key:a})}),n.sort((r,a)=>r.element?a.element?cW(r.element,a.element):1:-1);n.length>t;){let r=n.shift();r?.key&&e.delete(r.key)}}function npe(e){return[...e].sort(Jme)}function nM(e){if(!e)return!1;let t=e.getMap(mE);return Number(t.get(eM))===JT?!0:e.getMap(Mp).size>0||e.getMap(Ap).size>0||e.getMap(Tp).size>0}function fE(e){let t=e.getMap(mE);return Number(t.get(eM))!==JT&&t.set(eM,JT),t}function mW(e,{includeDeleted:t=!0}={}){if(!e)return D0();let n=e.getMap(Mp),r=e.getMap(Ap),a=e.getMap(Tp),i=[];n.forEach(c=>{let s=epe(c);s&&(!t&&s.isDeleted||i.push(s))});let o={};return r.forEach((c,s)=>{!c||typeof c!="object"||(o[s]=I0(c))}),pE({appState:{gridSize:a.get("gridSize"),viewBackgroundColor:a.get("viewBackgroundColor")},elements:npe(i),files:o})}function pW(e,t,{maxRevisionsPerElement:n=2}={}){if(!e)return D0();let r=pE(t);fE(e);let a=e.getMap(Mp),i=e.getMap(Ap),o=e.getMap(Tp);Array.from(a.keys()).forEach(c=>a.delete(c)),Array.from(i.keys()).forEach(c=>i.delete(c)),Array.from(o.keys()).forEach(c=>o.delete(c)),r.elements.forEach(c=>{if(!c?.id)return;let s=dW(a,c.id,{create:!0});hW(s,c,{maxRevisions:n})}),Object.entries(r.files||{}).forEach(([c,s])=>{i.set(c,I0(s))});let l=tM(r.appState);return o.set("gridSize",l.gridSize),o.set("viewBackgroundColor",l.viewBackgroundColor),r}function fW(e,t,{maxRevisionsPerElement:n=2}={}){if(!e)return!1;let r=pE(t);fE(e);let a=e.getMap(Mp),i=e.getMap(Ap),o=e.getMap(Tp),l=new Set,c=!1;r.elements.forEach(u=>{if(!u?.id)return;l.add(u.id);let h=dW(a,u.id,{create:!0});c=hW(h,u,{maxRevisions:n})||c}),Array.from(a.keys()).forEach(u=>{l.has(u)||(a.delete(u),c=!0)});let s=r.files||{};Object.entries(s).forEach(([u,h])=>{let m=I0(h),p=i.get(u);JSON.stringify(p)!==JSON.stringify(m)&&(i.set(u,m),c=!0)}),Array.from(i.keys()).forEach(u=>{u in s||(i.delete(u),c=!0)});let d=tM(r.appState);return Object.entries(d).forEach(([u,h])=>{o.get(u)!==h&&(o.set(u,h),c=!0)}),Array.from(o.keys()).forEach(u=>{u in d||(o.delete(u),c=!0)}),c}function gW(e){if(!e)return null;let t=e.getText(Zme).toString();return qme(t,{fallbackToEmpty:!1})}var rpe=new Set(["Room reset","Server shutting down"]);function bW(e){!e||typeof e.on!="function"||typeof e.disconnect!="function"||e.on("connection-close",t=>{let n=String(t?.reason||"");rpe.has(n)&&e.disconnect()})}var ape=250,ipe=48,vW=4e3,gE=class{constructor({cancelAnimationFrameFn:t=x=>cancelAnimationFrame(x),clearTimeoutFn:n=x=>clearTimeout(x),emptySceneGuardMs:r=ape,filePath:a="",now:i=()=>Date.now(),onCollaboratorsChange:o=()=>{},onRemoteSceneJson:l=()=>{},requestAnimationFrameFn:c=x=>requestAnimationFrame(x),resolveWsBaseUrlFn:s=jk,saveThrottleMs:d=ipe,setTimeoutFn:u=(x,g)=>window.setTimeout(x,g),syncTimeoutMs:h=vW,vaultClient:m,websocketProviderFactory:p=(x,g,v,b)=>new hE(x,g,v,b),ydocFactory:f=()=>new Mu}){this.cancelAnimationFrameFn=t,this.clearTimeoutFn=n,this.emptySceneGuardMs=r,this.filePath=a,this.now=i,this.onCollaboratorsChange=o,this.onRemoteSceneJson=l,this.requestAnimationFrameFn=c,this.resolveWsBaseUrlFn=s,this.saveThrottleMs=d,this.setTimeoutFn=u,this.syncTimeoutMs=h,this.vaultClient=m,this.websocketProviderFactory=p,this.ydocFactory=f,this.ydoc=null,this.roomMeta=null,this.roomElements=null,this.roomFiles=null,this.roomAppState=null,this.provider=null,this.awareness=null,this.localUser=null,this.handleProviderSync=null,this.lastSceneJson="",this.sceneSyncTimer=null,this.lastSceneSyncAt=0,this.pendingSceneSyncPayload=null,this.pointerAwarenessFrame=0,this.pendingPointerPayload=null,this.viewportAwarenessFrame=0,this.pendingViewportPayload=null,this.lastViewportSignature="",this.lastSelectedIdsSignature="",this.pendingEmptySceneCandidate=null,this.canWriteToRoom=!1,this.waitingForAuthoritativeSync=!1,this.applyingSharedSnapshotDepth=0,this.handleAwarenessChange=()=>{this.onCollaboratorsChange(FV(this.awareness))},this.handleStructuredSceneUpdate=()=>{if(!this.ydoc)return;let x=this.getStructuredSceneJson();!x||x===this.lastSceneJson||(this.unlockRoomWrites(),this.pendingEmptySceneCandidate=null,this.lastSceneJson=JSON.stringify(ni(x)),this.onRemoteSceneJson(this.lastSceneJson))}}getLastSceneJson(){return this.lastSceneJson}getLocalUser(){return this.localUser}getHistoryState(){return{canRedo:!1,canUndo:!1,head:null,length:null}}canRedo(){return this.getHistoryState().canRedo}canUndo(){return this.getHistoryState().canUndo}isApplyingSharedSnapshot(){return this.applyingSharedSnapshotDepth>0}beginApplyingSharedSnapshot(){this.applyingSharedSnapshotDepth+=1}endApplyingSharedSnapshot(){this.applyingSharedSnapshotDepth=Math.max(0,this.applyingSharedSnapshotDepth-1)}subscribeHistoryState(t){return typeof t=="function"&&t(this.getHistoryState()),()=>{}}setLocalUser(t={}){return this.localUser=ow({currentUser:this.localUser,nextUser:t}),this.awareness&&this.awareness.setLocalStateField("user",this.localUser),this.handleAwarenessChange(),this.localUser}async connect({initialUser:t=null}={}){if(this.localUser=t,!this.filePath){let i=bu();return this.lastSceneJson=JSON.stringify(i),i}this.ydoc=this.ydocFactory(),this.roomMeta=this.ydoc.getMap(mE),this.roomElements=this.ydoc.getMap(Mp),this.roomFiles=this.ydoc.getMap(Ap),this.roomAppState=this.ydoc.getMap(Tp),this.provider=this.websocketProviderFactory(this.resolveWsBaseUrlFn(),this.filePath,this.ydoc,{disableBc:!0,maxBackoffTime:5e3}),bW(this.provider),this.awareness=this.provider.awareness,this.localUser&&this.awareness.setLocalStateField("user",this.localUser),this.awareness.setLocalStateField("pointerButton","up"),this.awareness.setLocalStateField("selectedElementIds",{}),this.awareness.on("change",this.handleAwarenessChange),this.handleProviderSync=i=>{i&&(this.unlockRoomWrites(),this.handleStructuredSceneUpdate())},this.provider.on("sync",this.handleProviderSync);let n=await this.waitForSync(this.provider,this.syncTimeoutMs),r=this.getStructuredSceneJson(),a=!1;if(!r){let i=await this.loadSceneFromApi(),o=this.getStructuredSceneJson();o?r=o:(r=JSON.stringify(i),a=!0)}return r||(r=JSON.stringify(bu())),this.waitingForAuthoritativeSync=a&&!n,this.canWriteToRoom=!this.waitingForAuthoritativeSync,this.lastSceneJson=JSON.stringify(ni(r)),!a&&this.canWriteToRoom&&!nM(this.ydoc)&&this.ydoc.transact(()=>{this.replaceStructuredSceneWithinTransaction(this.lastSceneJson)},"excalidraw-legacy-migrate"),this.roomMeta.observe(this.handleStructuredSceneUpdate),this.roomElements.observeDeep(this.handleStructuredSceneUpdate),this.roomFiles.observeDeep(this.handleStructuredSceneUpdate),this.roomAppState.observe(this.handleStructuredSceneUpdate),a&&this.canWriteToRoom&&this.commitSceneJson(this.lastSceneJson,{origin:"excalidraw-api-fallback"}),this.handleStructuredSceneUpdate(),this.handleAwarenessChange(),ni(this.lastSceneJson)}async loadSceneFromApi({createIfMissing:t=!0}={}){if(!this.filePath)return bu();try{let r=await this.vaultClient.readFile(this.filePath);return ni(r.content)}catch(r){if(r?.status!==404||!t)throw r?.status===404?new Error(r.message||"Excalidraw file not found"):new Error(r?.message||"Failed to load Excalidraw file")}let n=bu();try{return await this.vaultClient.createFile({content:JSON.stringify(n),path:this.filePath}),n}catch(r){if(r?.status===409)try{let a=await this.vaultClient.readFile(this.filePath);return ni(a.content)}catch(a){throw new Error(a?.message||"Failed to load existing Excalidraw file after create conflict")}throw new Error(r?.message||"Failed to create Excalidraw file")}}waitForSync(t,n=vW){return t.synced?Promise.resolve(!0):new Promise(r=>{let a=!1,i=l=>{!l||a||(a=!0,this.clearTimeoutFn(o),t.off("sync",i),r(!0))},o=this.setTimeoutFn(()=>{a||(a=!0,t.off("sync",i),r(!1))},n);t.on("sync",i)})}unlockRoomWrites(){this.waitingForAuthoritativeSync=!1,this.canWriteToRoom=!0,!this.getStructuredSceneJson()&&this.lastSceneJson&&this.commitSceneJson(this.lastSceneJson,{origin:"excalidraw-authoritative-seed"}),this.pendingSceneSyncPayload&&this.scheduleSceneSyncFlush()}getStructuredSceneJson(){if(!this.ydoc)return"";if(nM(this.ydoc))return JSON.stringify(mW(this.ydoc));let t=gW(this.ydoc);return t?JSON.stringify(t):""}replaceStructuredSceneWithinTransaction(t){if(!this.ydoc)return;let n=Uk(t);n&&(fE(this.ydoc),pW(this.ydoc,n))}scheduleSceneSync(t,n,r){this.pendingSceneSyncPayload={appState:n,elements:t,files:r},this.canWriteToRoom&&this.scheduleSceneSyncFlush()}scheduleSceneSyncFlush(){if(this.sceneSyncTimer!==null)return;let t=this.now()-this.lastSceneSyncAt,n=Math.max(0,this.saveThrottleMs-t);this.sceneSyncTimer=this.setTimeoutFn(()=>{this.sceneSyncTimer=null,this.flushSceneSync()},n)}flushSceneSync(){if(!this.ydoc||!this.pendingSceneSyncPayload)return;let{elements:t,appState:n,files:r}=this.pendingSceneSyncPayload;this.pendingSceneSyncPayload=null;let a=OV(t,n,r),i=JSON.stringify(a);if(this.shouldDelayEmptySceneCommit(i)){this.pendingSceneSyncPayload={appState:n,elements:t,files:r},this.scheduleDelayedEmptySceneCommit();return}i!==this.lastSceneJson&&(this.lastSceneSyncAt=this.now(),this.commitSceneJson(i,{origin:"excalidraw-local-change"})),this.pendingEmptySceneCandidate=null,this.pendingSceneSyncPayload&&this.scheduleSceneSyncFlush()}hasRemoteCollaborators(){if(!this.awareness)return!1;for(let[t,n]of this.awareness.getStates())if(t!==this.awareness.clientID&&n?.user)return!0;return!1}shouldDelayEmptySceneCommit(t){if(!this.emptySceneGuardMs||!this.hasRemoteCollaborators())return this.pendingEmptySceneCandidate=null,!1;if(ni(t).elements.length>0)return this.pendingEmptySceneCandidate=null,!1;if(ni(this.lastSceneJson||this.getStructuredSceneJson()).elements.length===0)return this.pendingEmptySceneCandidate=null,!1;let a=this.now();return!this.pendingEmptySceneCandidate||this.pendingEmptySceneCandidate.previousSceneJson!==this.lastSceneJson?(this.pendingEmptySceneCandidate={firstSeenAt:a,previousSceneJson:this.lastSceneJson},console.warn(`[excalidraw:${this.filePath}] Delaying suspicious empty scene commit during active collaboration`),!0):a-this.pendingEmptySceneCandidate.firstSeenAt<this.emptySceneGuardMs}scheduleDelayedEmptySceneCommit(){if(this.sceneSyncTimer!==null)return;let t=this.pendingEmptySceneCandidate?.firstSeenAt??this.now(),n=this.now()-t,r=Math.max(0,this.emptySceneGuardMs-n);this.sceneSyncTimer=this.setTimeoutFn(()=>{this.sceneSyncTimer=null,this.flushSceneSync()},r)}flushPointerAwarenessPayload(){this.pointerAwarenessFrame=0,!(!this.awareness||!this.pendingPointerPayload)&&(this.awareness.setLocalStateField("pointer",this.pendingPointerPayload.pointer),this.awareness.setLocalStateField("pointerButton",this.pendingPointerPayload.button),this.pendingPointerPayload=null)}normalizeViewportAwareness(t){if(!t||typeof t!="object")return null;let n=Number(t.scrollX),r=Number(t.scrollY),a=Number(t.zoom);return!Number.isFinite(n)||!Number.isFinite(r)||!Number.isFinite(a)||a<=0?null:{scrollX:n,scrollY:r,zoom:a}}scheduleLocalPointerAwareness(t){!this.awareness||!t?.pointer||(this.pendingPointerPayload={button:t.button==="down"?"down":"up",pointer:{x:t.pointer.x,y:t.pointer.y,tool:t.pointer.tool==="laser"?"laser":"pointer"}},!this.pointerAwarenessFrame&&(this.pointerAwarenessFrame=this.requestAnimationFrameFn(()=>this.flushPointerAwarenessPayload())))}flushViewportAwarenessPayload(){this.viewportAwarenessFrame=0,!(!this.awareness||!this.pendingViewportPayload)&&(this.awareness.setLocalStateField("viewport",this.pendingViewportPayload),this.pendingViewportPayload=null)}scheduleLocalViewportAwareness(t){if(!this.awareness)return;let n=this.normalizeViewportAwareness(t);if(!n)return;let r=`${n.scrollX}:${n.scrollY}:${n.zoom}`;r!==this.lastViewportSignature&&(this.lastViewportSignature=r,this.pendingViewportPayload=n,!this.viewportAwarenessFrame&&(this.viewportAwarenessFrame=this.requestAnimationFrameFn(()=>this.flushViewportAwarenessPayload())))}syncLocalSelectionAwareness(t){if(!this.awareness)return;let n=t?.selectedElementIds||{},r=Object.keys(n).sort().join(",");r!==this.lastSelectedIdsSignature&&(this.lastSelectedIdsSignature=r,this.awareness.setLocalStateField("selectedElementIds",n))}commitSceneJson(t,{origin:n="excalidraw-room-write"}={}){let r=JSON.stringify(ni(t));if(!this.ydoc){let i=r!==this.lastSceneJson;return this.lastSceneJson=r,i}let a=this.getStructuredSceneJson();return r===a&&r===this.lastSceneJson?!1:(this.lastSceneJson=r,this.ydoc.transact(()=>{fW(this.ydoc,ni(r))},n),!0)}disconnect(){this.flushSceneSync(),this.clearTimeoutFn(this.sceneSyncTimer),this.sceneSyncTimer=null,this.pendingSceneSyncPayload=null,this.pointerAwarenessFrame&&this.cancelAnimationFrameFn(this.pointerAwarenessFrame),this.pointerAwarenessFrame=0,this.pendingPointerPayload=null,this.viewportAwarenessFrame&&this.cancelAnimationFrameFn(this.viewportAwarenessFrame),this.viewportAwarenessFrame=0,this.pendingViewportPayload=null,this.lastViewportSignature="",this.lastSelectedIdsSignature="",this.pendingEmptySceneCandidate=null,this.roomMeta?.unobserve(this.handleStructuredSceneUpdate),this.roomElements?.unobserveDeep(this.handleStructuredSceneUpdate),this.roomFiles?.unobserveDeep(this.handleStructuredSceneUpdate),this.roomAppState?.unobserve(this.handleStructuredSceneUpdate),this.awareness&&(this.awareness.off("change",this.handleAwarenessChange),this.awareness.setLocalState(null)),this.awareness=null,this.provider&&this.handleProviderSync&&this.provider.off("sync",this.handleProviderSync),this.handleProviderSync=null,this.provider?.disconnect(),this.provider?.destroy(),this.provider=null,this.ydoc?.destroy(),this.ydoc=null,this.roomMeta=null,this.roomElements=null,this.roomFiles=null,this.roomAppState=null,this.localUser=null,this.canWriteToRoom=!1,this.waitingForAuthoritativeSync=!1,this.applyingSharedSnapshotDepth=0}};function yW(e){return encodeURIComponent(String(e??""))}async function Ru(e,t){let n=await e.json().catch(()=>({}));if(!e.ok||n.ok===!1){let r=new Error(n.error||t);throw r.status=e.status,r.body=n,r}return n}var rM=class{async readTree(){let t=await fetch(bs("/files"));return Ru(t,"Failed to load file tree")}async readFile(t){let n=await fetch(bs(`/file?path=${encodeURIComponent(t)}`));return Ru(n,"Failed to read file")}async createFile({content:t,path:n}){let r=await fetch(bs("/file"),{body:JSON.stringify({content:t,path:n}),headers:{"Content-Type":"application/json"},method:"POST"});return Ru(r,"Failed to create file")}async renameFile({oldPath:t,newPath:n}){let r=await fetch(bs("/file"),{body:JSON.stringify({newPath:n,oldPath:t}),headers:{"Content-Type":"application/json"},method:"PATCH"});return Ru(r,"Failed to rename file")}async deleteFile(t){let n=await fetch(bs(`/file?path=${encodeURIComponent(t)}`),{method:"DELETE"});return Ru(n,"Failed to delete file")}async createDirectory(t){let n=await fetch(bs("/directory"),{body:JSON.stringify({path:t}),headers:{"Content-Type":"application/json"},method:"POST"});return Ru(n,"Failed to create folder")}async uploadImageAttachment({file:t,fileName:n="",sourcePath:r}){let a=await fetch(bs("/attachments"),{body:t,headers:{"Content-Type":t?.type||"application/octet-stream","X-CollabMD-File-Name":yW(n),"X-CollabMD-Source-Path":yW(r)},method:"POST"});return Ru(a,"Failed to upload image")}},xW=new rM;var Rp=new URLSearchParams(window.location.search),ope=Rp.get("file"),lpe=Rp.get("test")==="1",aM=Rp.get("mode")==="preview",kW=window.location.origin,wW=Number.parseInt(Rp.get("syncTimeoutMs")||"",10),Ke=null,R0=Rp.get("theme")||"dark",Dp=BV({params:Rp,storedUserName:localStorage.getItem("collabmd-user-name")}),xE="",fl=!1,SE=!1,N0="",Ip=null,bE=0,Vc=new Map,Nu=null,Yc=null,CE=!1,L0=0,wE="",Gc=[],Lp=0,yE=null,EW=!0,aa=new gE({filePath:ope,onCollaboratorsChange:e=>{if(!fl){Ip=e;return}upe(e)},onRemoteSceneJson:e=>{TW(e)},syncTimeoutMs:Number.isFinite(wW)?wW:void 0,vaultClient:xW});function O0(e){let t=document.querySelector(`[data-testid="button-${e}"]`);return t instanceof HTMLButtonElement?t:null}function spe(){let e=O0("undo"),t=O0("redo");return{canRedo:!!t&&!t.disabled,canUndo:!!e&&!e.disabled,head:null,length:null}}function SW(e){let t=O0(e);return!t||t.disabled?!1:(t.click(),!0)}function cpe(e={}){Dp=ow({currentUser:Dp,nextUser:e}),aa.setLocalUser(Dp)}lpe&&(window.__COLLABMD_EXCALIDRAW_TEST__={getElementBounds:e=>{let t=Ke?.getSceneElementsIncludingDeleted?.()?.find(n=>n.id===e&&!n.isDeleted);return t?{centerX:t.x+t.width/2,centerY:t.y+t.height/2,height:t.height,width:t.width,x:t.x,y:t.y}:null},getElementCount:()=>Ke?.getSceneElementsIncludingDeleted?.()?.filter(e=>!e.isDeleted).length??0,getElementIds:()=>Ke?.getSceneElementsIncludingDeleted?.()?.filter(e=>!e.isDeleted).map(e=>e.id).sort()??[],getHistoryState:()=>spe(),getLocalUserName:()=>Dp?.name||"",getLocalPeerId:()=>Dp?.peerId||"",getViewport:()=>{let e=Ke?.getAppState?.();return e?{scrollX:e.scrollX,scrollY:e.scrollY,zoom:e.zoom?.value??null}:null},isViewMode:()=>!!Ke?.getAppState?.().viewModeEnabled,getSceneJson:()=>aa.getLastSceneJson(),isAuthoritativeReady:()=>!!Ke&&fl&&aa.canWriteToRoom===!0&&aa.waitingForAuthoritativeSync===!1,isReady:()=>fl&&!!Ke&&!!O0("undo")&&!!O0("redo"),redoShared:()=>SW("redo"),setScene:e=>{mpe(Jm(e),{captureUpdate:U.IMMEDIATELY})},setViewport:e=>{if(!Ke)return;let t=Ke.getAppState();Ke.updateScene({appState:{scrollX:Number.isFinite(e?.scrollX)?e.scrollX:t.scrollX,scrollY:Number.isFinite(e?.scrollY)?e.scrollY:t.scrollY,zoom:Number.isFinite(e?.zoom)&&e.zoom>0?{value:e.zoom}:t.zoom},captureUpdate:U.NEVER})},undoShared:()=>SW("undo")});function dpe(e){if(Vc=e instanceof Map?e:new Map,!Ke){Ip=Vc;return}if(Ke.updateScene({collaborators:Vc,captureUpdate:U.NEVER}),Yc){iM(Yc);return}RW(Vc)}function upe(e){yE=e,!Lp&&(Lp=requestAnimationFrame(()=>{Lp=0;let t=yE;yE=null,dpe(t)}))}function TW(e){let t=ni(e),n=JSON.stringify(t);if(!(n===xE&&!N0)){if(xE=n,!Ke||!fl){N0=n;return}DW(t)}}function MW({trackedSharedSnapshot:e=!1}={}){bE+=1,requestAnimationFrame(()=>{requestAnimationFrame(()=>{bE=Math.max(0,bE-1),e&&aa.endApplyingSharedSnapshot(),bE===0&&(SE=!1)})})}function hpe(){L0+=1,requestAnimationFrame(()=>{requestAnimationFrame(()=>{L0=Math.max(0,L0-1),L0===0&&(CE=!1)})})}function AW(e){let t=Ke.getAppState(),n=Ke.getSceneElementsIncludingDeleted?.()||Ke.getSceneElements(),r=cd(e?.elements||[],n,{repairBindings:!0}),a=sh(e?.appState||{},t),i=RV(n,r,t);return{appState:{theme:R0,viewBackgroundColor:a.viewBackgroundColor??"#ffffff",gridSize:a.gridSize??null},elements:i,files:e?.files||{}}}function DW(e,{captureUpdate:t=U.NEVER,trackedSharedSnapshot:n=!0}={}){let r=AW(e);SE=!0,n&&aa.beginApplyingSharedSnapshot();try{Ke.updateScene({...r,captureUpdate:t})}finally{MW({trackedSharedSnapshot:n})}LW()}function mpe(e,{captureUpdate:t=U.IMMEDIATELY}={}){let n=Jm(e),r=JSON.stringify(n);if(xE=r,!Ke||!fl){N0=r;return}Ke.updateScene({...AW(n),captureUpdate:t})}function ppe(){TW(aa.getLastSceneJson())}function IW(e,t={}){window.parent.postMessage({source:"excalidraw-editor",type:e,...t},kW)}function fpe(){return Ke?.getSceneElementsIncludingDeleted?.()?.filter(e=>!e.isDeleted)??[]}function LW(){if(!EW||!Ke)return;let e=fpe();e.length!==0&&(EW=!1,requestAnimationFrame(()=>{requestAnimationFrame(()=>{Ke&&Ke.scrollToContent(e,{animate:!1,fitToViewport:!0,maxZoom:2,viewportZoomFactor:aM?.92:.88})})}))}function CW(){if(!fl||!Ke||CE)return;let e=Ke.getAppState();aa.scheduleLocalViewportAwareness({scrollX:e.scrollX,scrollY:e.scrollY,zoom:e.zoom?.value})}function EE(e,{force:t=!1}={}){let n=e?String(e):null,r=Nu!==n;Nu=n,r&&(wE=""),Nu&&RW(Vc,{force:t||r})}function RW(e=Vc,{force:t=!1}={}){if(!Ke||!Nu)return;let r=e?.get?.(String(Nu))?.viewport;if(!r)return;let a=`${Nu}:${r.scrollX}:${r.scrollY}:${r.zoom}`;!t&&a===wE||(wE=a,CE=!0,Ke.updateScene({appState:{scrollX:r.scrollX,scrollY:r.scrollY,zoom:{value:r.zoom}},captureUpdate:U.NEVER}),hpe())}function iM(e){if(Yc=e||null,!Ke)return;if(!e){Ke.updateScene({appState:{userToFollow:null},captureUpdate:U.NEVER}),EE(null,{force:!0}),Yc=null;return}let t=HV(Vc,e);t?.socketId&&(Ke.updateScene({appState:{userToFollow:{socketId:t.socketId,username:t.username||""}},captureUpdate:U.NEVER}),EE(t.socketId,{force:!0}),Yc=null)}function gpe(){fl=!1,Ip=null,Vc=new Map,Nu=null,Yc=null,CE=!1,L0=0,wE="",Lp&&cancelAnimationFrame(Lp),Lp=0,yE=null,Gc.forEach(e=>e()),Gc=[],aa.disconnect()}window.addEventListener("pagehide",()=>{gpe()});window.addEventListener("message",e=>{if(e.origin!==kW)return;let t=e.data;if(!(!t||t.source!=="collabmd-host")){if(t.type==="set-theme"){R0=t.theme||"dark",Ke&&(SE=!0,Ke.updateScene({appState:{theme:R0},captureUpdate:U.NEVER}),MW());return}if(t.type==="set-user"){cpe(t.user);return}t.type==="follow-user"&&iM(t.peerId||null)}});function bpe(e,t,n){!fl||SE||aa.isApplyingSharedSnapshot()||(xE=JSON.stringify(Jm({elements:e,appState:t,files:n})),aa.scheduleSceneSync(e,t,n))}function vpe(e){Ke=e,Gc.forEach(n=>n()),Gc=[],Gc.push(e.onStateChange(["scrollX","scrollY","zoom"],()=>{CW()})),Gc.push(e.onStateChange("userToFollow",n=>{if(n?.socketId){EE(n.socketId,{force:!0});return}EE(null,{force:!0})}));let t=N0||aa.getLastSceneJson();N0="",DW(ni(t)),Ip&&(Ke.updateScene({collaborators:Ip,captureUpdate:U.NEVER}),Ip=null),fl=!0,CW(),ppe(),Yc&&iM(Yc),LW(),IW("ready")}function ype({excalidrawAPI:e}){Ke=e}async function xpe(){let e=document.getElementById("loadingState");try{await KV();let t=await aa.connect({initialUser:Dp}),n=NV(t,{theme:R0});e?.remove();let r={onMount:ype,onInitialize:o=>{vpe(o)},onUnmount:()=>{Gc.forEach(o=>o()),Gc=[],Ke=null,fl=!1},initialData:n,aiEnabled:!1,isCollaborating:!0,onChange:(o,l,c)=>{bpe(o,l,c),aa.syncLocalSelectionAwareness(l)},onPointerUpdate:o=>{aa.scheduleLocalPointerAwareness(o)},theme:R0,viewModeEnabled:aM,zenModeEnabled:aM,UIOptions:{canvasActions:{export:!1,loadScene:!1,saveToActiveFile:!1,toggleTheme:!1}}},a=()=>vE.default.createElement("div",{style:{height:"100vh",width:"100%"}},vE.default.createElement(Pk,r));(0,_W.createRoot)(document.getElementById("root")).render(vE.default.createElement(a))}catch(t){console.error("[excalidraw] Failed to initialize:",t),IW("error",{message:t instanceof Error?t.message:"Failed to load Excalidraw"}),e&&(e.className="loading-state error",e.textContent=`Failed to load Excalidraw: ${t instanceof Error?t.message:String(t)}`)}}xpe();
290
+ ${t}`),aW=(e,t,n)=>{let r=To(t),a=Wn(),i=ve(r),o=e.messageHandlers[i];return o?o(a,r,e,n,i):console.error("Unable to compute message"),a},QT=(e,t,n)=>{t===e.ws&&(e.emit("connection-close",[n,e]),e.ws=null,t.close(),e.wsconnecting=!1,e.wsconnected?(e.wsconnected=!1,e.synced=!1,uE(e.awareness,Array.from(e.awareness.getStates().keys()).filter(r=>r!==e.doc.clientID),e),e.emit("status",[{status:"disconnected"}])):e.wsUnsuccessfulReconnects++,setTimeout(iW,np(QV(2,e.wsUnsuccessfulReconnects)*100,e.maxBackoffTime),e))},iW=e=>{if(e.shouldConnect&&e.ws===null){let t=new e._WS(e.url,e.protocols);t.binaryType="arraybuffer",e.ws=t,e.wsconnecting=!0,e.wsconnected=!1,e.synced=!1,t.onmessage=n=>{e.wsLastMessageReceived=Mo();let r=aW(e,new Uint8Array(n.data),!0);gw(r)>1&&t.send(Rt(r))},t.onerror=n=>{e.emit("connection-error",[n,e])},t.onclose=n=>{QT(e,t,n)},t.onopen=()=>{e.wsLastMessageReceived=Mo(),e.wsconnecting=!1,e.wsconnected=!0,e.wsUnsuccessfulReconnects=0,e.emit("status",[{status:"connected"}]);let n=Wn();if(ue(n,Lu),cE(n,e.doc),t.send(Rt(n)),e.awareness.getLocalState()!==null){let r=Wn();ue(r,kp),Xt(r,_p(e.awareness,[e.doc.clientID])),t.send(Rt(r))}},e.emit("status",[{status:"connecting"}])}},qT=(e,t)=>{let n=e.ws;e.wsconnected&&n&&n.readyState===n.OPEN&&n.send(t),e.bcconnected&&Iu(e.bcChannel,t,e)},hE=class extends tp{constructor(t,n,r,{connect:a=!0,awareness:i=new dE(r),params:o={},protocols:l=[],WebSocketPolyfill:c=WebSocket,resyncInterval:s=-1,maxBackoffTime:d=2500,disableBc:u=!1}={}){for(super();t[t.length-1]==="/";)t=t.slice(0,t.length-1);this.serverUrl=t,this.bcChannel=t+"/"+n,this.maxBackoffTime=d,this.params=o,this.protocols=l,this.roomname=n,this.doc=r,this._WS=c,this.awareness=i,this.wsconnected=!1,this.wsconnecting=!1,this.bcconnected=!1,this.disableBc=u,this.wsUnsuccessfulReconnects=0,this.messageHandlers=A0.slice(),this._synced=!1,this.ws=null,this.wsLastMessageReceived=0,this.shouldConnect=a,this._resyncInterval=0,s>0&&(this._resyncInterval=setInterval(()=>{if(this.ws&&this.ws.readyState===WebSocket.OPEN){let h=Wn();ue(h,Lu),cE(h,r),this.ws.send(Rt(h))}},s)),this._bcSubscriber=(h,m)=>{if(m!==this){let p=aW(this,new Uint8Array(h),!1);gw(p)>1&&Iu(this.bcChannel,Rt(p),this)}},this._updateHandler=(h,m)=>{if(m!==this){let p=Wn();ue(p,Lu),qY(p,h),qT(this,Rt(p))}},this.doc.on("update",this._updateHandler),this._awarenessUpdateHandler=({added:h,updated:m,removed:p},f)=>{let x=h.concat(m).concat(p),g=Wn();ue(g,kp),Xt(g,_p(i,x)),qT(this,Rt(g))},this._exitHandler=()=>{uE(this.awareness,[r.clientID],"app closed")},xs&&typeof process<"u"&&process.on("exit",this._exitHandler),i.on("update",this._awarenessUpdateHandler),this._checkInterval=setInterval(()=>{this.wsconnected&&nW<Mo()-this.wsLastMessageReceived&&QT(this,this.ws,null)},nW/10),a&&this.connect()}get url(){let t=tW(this.params);return this.serverUrl+"/"+this.roomname+(t.length===0?"":"?"+t)}get synced(){return this._synced}set synced(t){this._synced!==t&&(this._synced=t,this.emit("synced",[t]),this.emit("sync",[t]))}destroy(){this._resyncInterval!==0&&clearInterval(this._resyncInterval),clearInterval(this._checkInterval),this.disconnect(),xs&&typeof process<"u"&&process.off("exit",this._exitHandler),this.awareness.off("update",this._awarenessUpdateHandler),this.doc.off("update",this._updateHandler),super.destroy()}connectBc(){if(this.disableBc)return;this.bcconnected||(WY(this.bcChannel,this._bcSubscriber),this.bcconnected=!0);let t=Wn();ue(t,Lu),cE(t,this.doc),Iu(this.bcChannel,Rt(t),this);let n=Wn();ue(n,Lu),XT(n,this.doc),Iu(this.bcChannel,Rt(n),this);let r=Wn();ue(r,rW),Iu(this.bcChannel,Rt(r),this);let a=Wn();ue(a,kp),Xt(a,_p(this.awareness,[this.doc.clientID])),Iu(this.bcChannel,Rt(a),this)}disconnectBc(){let t=Wn();ue(t,kp),Xt(t,_p(this.awareness,[this.doc.clientID],new Map)),qT(this,Rt(t)),this.bcconnected&&(KY(this.bcChannel,this._bcSubscriber),this.bcconnected=!1)}disconnect(){this.shouldConnect=!1,this.disconnectBc(),this.ws!==null&&QT(this,this.ws,null)}connect(){this.shouldConnect=!0,!this.wsconnected&&this.ws===null&&(iW(this),this.connectBc())}};var oW="excalidraw",lW=2,sW="collabmd",Tp="excalidraw-app-state",Mp="excalidraw-elements",Ap="excalidraw-files",mE="excalidraw-meta",JT=1,Zme="codemirror",eM="schemaVersion";function D0(){return{type:oW,version:lW,source:sW,elements:[],appState:{gridSize:null,viewBackgroundColor:"#ffffff"},files:{}}}function tM(e={}){return{gridSize:e?.gridSize??null,viewBackgroundColor:e?.viewBackgroundColor??"#ffffff"}}function pE(e){return!e||typeof e!="object"?D0():{type:oW,version:lW,source:sW,elements:Array.isArray(e.elements)?e.elements:[],appState:tM(e.appState),files:e.files&&typeof e.files=="object"?e.files:{}}}function qme(e,{fallbackToEmpty:t=!0}={}){if(!e)return t?D0():null;try{return pE(JSON.parse(e))}catch{return t?D0():null}}function I0(e){if(e!==void 0)return JSON.parse(JSON.stringify(e))}function Qme(e){let t=Number.isFinite(Number(e?.version))?Number(e.version):0,n=Number.isFinite(Number(e?.versionNonce))?Number(e.versionNonce):0,r=Number.isFinite(Number(e?.updated))?Number(e.updated):0;return`${t}:${n}:${r}`}function cW(e,t){let n=Number(e?.version)||0,r=Number(t?.version)||0;if(n!==r)return n-r;let a=Number(e?.versionNonce)||0,i=Number(t?.versionNonce)||0;if(a!==i)return a-i;let o=Number(e?.updated)||0,l=Number(t?.updated)||0;return o!==l?o-l:String(e?.id||"").localeCompare(String(t?.id||""))}function Jme(e,t){let n=e?.index??"",r=t?.index??"";return n!==r?String(n).localeCompare(String(r)):String(e?.id||"").localeCompare(String(t?.id||""))}function dW(e,t,{create:n=!1}={}){let r=e.get(t);if(r instanceof pl)return r;if(!n)return null;let a=new pl;return e.set(t,a),a}function uW(e){if(typeof e=="string")try{return JSON.parse(e)}catch{return null}return!e||typeof e!="object"?null:I0(e)}function epe(e){if(!(e instanceof pl)||e.size===0)return null;let t=null;return e.forEach(n=>{let r=uW(n);!r||!r.id||(!t||cW(r,t)>0)&&(t=r)}),t}function hW(e,t,{maxRevisions:n=2}={}){let r=Qme(t),a=I0(t),i=e.get(r),o=i&&typeof i=="object"?JSON.stringify(i):"",l=JSON.stringify(a);return o===l?!1:(e.set(r,a),tpe(e,n),!0)}function tpe(e,t=2){if(!(e instanceof pl)||e.size<=t)return;let n=[];for(e.forEach((r,a)=>{let i=uW(r);if(!i){n.push({element:null,key:a});return}n.push({element:i,key:a})}),n.sort((r,a)=>r.element?a.element?cW(r.element,a.element):1:-1);n.length>t;){let r=n.shift();r?.key&&e.delete(r.key)}}function npe(e){return[...e].sort(Jme)}function nM(e){if(!e)return!1;let t=e.getMap(mE);return Number(t.get(eM))===JT?!0:e.getMap(Mp).size>0||e.getMap(Ap).size>0||e.getMap(Tp).size>0}function fE(e){let t=e.getMap(mE);return Number(t.get(eM))!==JT&&t.set(eM,JT),t}function mW(e,{includeDeleted:t=!0}={}){if(!e)return D0();let n=e.getMap(Mp),r=e.getMap(Ap),a=e.getMap(Tp),i=[];n.forEach(c=>{let s=epe(c);s&&(!t&&s.isDeleted||i.push(s))});let o={};return r.forEach((c,s)=>{!c||typeof c!="object"||(o[s]=I0(c))}),pE({appState:{gridSize:a.get("gridSize"),viewBackgroundColor:a.get("viewBackgroundColor")},elements:npe(i),files:o})}function pW(e,t,{maxRevisionsPerElement:n=2}={}){if(!e)return D0();let r=pE(t);fE(e);let a=e.getMap(Mp),i=e.getMap(Ap),o=e.getMap(Tp);Array.from(a.keys()).forEach(c=>a.delete(c)),Array.from(i.keys()).forEach(c=>i.delete(c)),Array.from(o.keys()).forEach(c=>o.delete(c)),r.elements.forEach(c=>{if(!c?.id)return;let s=dW(a,c.id,{create:!0});hW(s,c,{maxRevisions:n})}),Object.entries(r.files||{}).forEach(([c,s])=>{i.set(c,I0(s))});let l=tM(r.appState);return o.set("gridSize",l.gridSize),o.set("viewBackgroundColor",l.viewBackgroundColor),r}function fW(e,t,{maxRevisionsPerElement:n=2}={}){if(!e)return!1;let r=pE(t);fE(e);let a=e.getMap(Mp),i=e.getMap(Ap),o=e.getMap(Tp),l=new Set,c=!1;r.elements.forEach(u=>{if(!u?.id)return;l.add(u.id);let h=dW(a,u.id,{create:!0});c=hW(h,u,{maxRevisions:n})||c}),Array.from(a.keys()).forEach(u=>{l.has(u)||(a.delete(u),c=!0)});let s=r.files||{};Object.entries(s).forEach(([u,h])=>{let m=I0(h),p=i.get(u);JSON.stringify(p)!==JSON.stringify(m)&&(i.set(u,m),c=!0)}),Array.from(i.keys()).forEach(u=>{u in s||(i.delete(u),c=!0)});let d=tM(r.appState);return Object.entries(d).forEach(([u,h])=>{o.get(u)!==h&&(o.set(u,h),c=!0)}),Array.from(o.keys()).forEach(u=>{u in d||(o.delete(u),c=!0)}),c}function gW(e){if(!e)return null;let t=e.getText(Zme).toString();return qme(t,{fallbackToEmpty:!1})}var rpe=new Set(["Room reset","Server shutting down"]);function bW(e){!e||typeof e.on!="function"||typeof e.disconnect!="function"||e.on("connection-close",t=>{let n=String(t?.reason||"");rpe.has(n)&&e.disconnect()})}var ape=250,ipe=48,vW=4e3,gE=class{constructor({cancelAnimationFrameFn:t=x=>cancelAnimationFrame(x),clearTimeoutFn:n=x=>clearTimeout(x),emptySceneGuardMs:r=ape,filePath:a="",now:i=()=>Date.now(),onCollaboratorsChange:o=()=>{},onRemoteSceneJson:l=()=>{},requestAnimationFrameFn:c=x=>requestAnimationFrame(x),resolveWsBaseUrlFn:s=jk,saveThrottleMs:d=ipe,setTimeoutFn:u=(x,g)=>window.setTimeout(x,g),syncTimeoutMs:h=vW,vaultClient:m,websocketProviderFactory:p=(x,g,v,b)=>new hE(x,g,v,b),ydocFactory:f=()=>new Mu}){this.cancelAnimationFrameFn=t,this.clearTimeoutFn=n,this.emptySceneGuardMs=r,this.filePath=a,this.now=i,this.onCollaboratorsChange=o,this.onRemoteSceneJson=l,this.requestAnimationFrameFn=c,this.resolveWsBaseUrlFn=s,this.saveThrottleMs=d,this.setTimeoutFn=u,this.syncTimeoutMs=h,this.vaultClient=m,this.websocketProviderFactory=p,this.ydocFactory=f,this.ydoc=null,this.roomMeta=null,this.roomElements=null,this.roomFiles=null,this.roomAppState=null,this.provider=null,this.awareness=null,this.localUser=null,this.handleProviderSync=null,this.lastSceneJson="",this.sceneSyncTimer=null,this.lastSceneSyncAt=0,this.pendingSceneSyncPayload=null,this.pointerAwarenessFrame=0,this.pendingPointerPayload=null,this.viewportAwarenessFrame=0,this.pendingViewportPayload=null,this.lastViewportSignature="",this.lastSelectedIdsSignature="",this.pendingEmptySceneCandidate=null,this.canWriteToRoom=!1,this.waitingForAuthoritativeSync=!1,this.applyingSharedSnapshotDepth=0,this.handleAwarenessChange=()=>{this.onCollaboratorsChange(FV(this.awareness))},this.handleStructuredSceneUpdate=()=>{if(!this.ydoc)return;let x=this.getStructuredSceneJson();!x||x===this.lastSceneJson||(this.unlockRoomWrites(),this.pendingEmptySceneCandidate=null,this.lastSceneJson=JSON.stringify(ni(x)),this.onRemoteSceneJson(this.lastSceneJson))}}getLastSceneJson(){return this.lastSceneJson}getLocalUser(){return this.localUser}getHistoryState(){return{canRedo:!1,canUndo:!1,head:null,length:null}}canRedo(){return this.getHistoryState().canRedo}canUndo(){return this.getHistoryState().canUndo}isApplyingSharedSnapshot(){return this.applyingSharedSnapshotDepth>0}beginApplyingSharedSnapshot(){this.applyingSharedSnapshotDepth+=1}endApplyingSharedSnapshot(){this.applyingSharedSnapshotDepth=Math.max(0,this.applyingSharedSnapshotDepth-1)}subscribeHistoryState(t){return typeof t=="function"&&t(this.getHistoryState()),()=>{}}setLocalUser(t={}){return this.localUser=ow({currentUser:this.localUser,nextUser:t}),this.awareness&&this.awareness.setLocalStateField("user",this.localUser),this.handleAwarenessChange(),this.localUser}async connect({initialUser:t=null}={}){if(this.localUser=t,!this.filePath){let i=bu();return this.lastSceneJson=JSON.stringify(i),i}this.ydoc=this.ydocFactory(),this.roomMeta=this.ydoc.getMap(mE),this.roomElements=this.ydoc.getMap(Mp),this.roomFiles=this.ydoc.getMap(Ap),this.roomAppState=this.ydoc.getMap(Tp),this.provider=this.websocketProviderFactory(this.resolveWsBaseUrlFn(),this.filePath,this.ydoc,{disableBc:!0,maxBackoffTime:5e3}),bW(this.provider),this.awareness=this.provider.awareness,this.localUser&&this.awareness.setLocalStateField("user",this.localUser),this.awareness.setLocalStateField("pointerButton","up"),this.awareness.setLocalStateField("selectedElementIds",{}),this.awareness.on("change",this.handleAwarenessChange),this.handleProviderSync=i=>{i&&(this.unlockRoomWrites(),this.handleStructuredSceneUpdate())},this.provider.on("sync",this.handleProviderSync);let n=await this.waitForSync(this.provider,this.syncTimeoutMs),r=this.getStructuredSceneJson(),a=!1;if(!r){let i=await this.loadSceneFromApi(),o=this.getStructuredSceneJson();o?r=o:(r=JSON.stringify(i),a=!0)}return r||(r=JSON.stringify(bu())),this.waitingForAuthoritativeSync=a&&!n,this.canWriteToRoom=!this.waitingForAuthoritativeSync,this.lastSceneJson=JSON.stringify(ni(r)),!a&&this.canWriteToRoom&&!nM(this.ydoc)&&this.ydoc.transact(()=>{this.replaceStructuredSceneWithinTransaction(this.lastSceneJson)},"excalidraw-legacy-migrate"),this.roomMeta.observe(this.handleStructuredSceneUpdate),this.roomElements.observeDeep(this.handleStructuredSceneUpdate),this.roomFiles.observeDeep(this.handleStructuredSceneUpdate),this.roomAppState.observe(this.handleStructuredSceneUpdate),a&&this.canWriteToRoom&&this.commitSceneJson(this.lastSceneJson,{origin:"excalidraw-api-fallback"}),this.handleStructuredSceneUpdate(),this.handleAwarenessChange(),ni(this.lastSceneJson)}async loadSceneFromApi({createIfMissing:t=!0}={}){if(!this.filePath)return bu();try{let r=await this.vaultClient.readFile(this.filePath);return ni(r.content)}catch(r){if(r?.status!==404||!t)throw r?.status===404?new Error(r.message||"Excalidraw file not found"):new Error(r?.message||"Failed to load Excalidraw file")}let n=bu();try{return await this.vaultClient.createFile({content:JSON.stringify(n),path:this.filePath}),n}catch(r){if(r?.status===409)try{let a=await this.vaultClient.readFile(this.filePath);return ni(a.content)}catch(a){throw new Error(a?.message||"Failed to load existing Excalidraw file after create conflict")}throw new Error(r?.message||"Failed to create Excalidraw file")}}waitForSync(t,n=vW){return t.synced?Promise.resolve(!0):new Promise(r=>{let a=!1,i=l=>{!l||a||(a=!0,this.clearTimeoutFn(o),t.off("sync",i),r(!0))},o=this.setTimeoutFn(()=>{a||(a=!0,t.off("sync",i),r(!1))},n);t.on("sync",i)})}unlockRoomWrites(){this.waitingForAuthoritativeSync=!1,this.canWriteToRoom=!0,!this.getStructuredSceneJson()&&this.lastSceneJson&&this.commitSceneJson(this.lastSceneJson,{origin:"excalidraw-authoritative-seed"}),this.pendingSceneSyncPayload&&this.scheduleSceneSyncFlush()}getStructuredSceneJson(){if(!this.ydoc)return"";if(nM(this.ydoc))return JSON.stringify(mW(this.ydoc));let t=gW(this.ydoc);return t?JSON.stringify(t):""}replaceStructuredSceneWithinTransaction(t){if(!this.ydoc)return;let n=Uk(t);n&&(fE(this.ydoc),pW(this.ydoc,n))}scheduleSceneSync(t,n,r){this.pendingSceneSyncPayload={appState:n,elements:t,files:r},this.canWriteToRoom&&this.scheduleSceneSyncFlush()}scheduleSceneSyncFlush(){if(this.sceneSyncTimer!==null)return;let t=this.now()-this.lastSceneSyncAt,n=Math.max(0,this.saveThrottleMs-t);this.sceneSyncTimer=this.setTimeoutFn(()=>{this.sceneSyncTimer=null,this.flushSceneSync()},n)}flushSceneSync(){if(!this.ydoc||!this.pendingSceneSyncPayload)return;let{elements:t,appState:n,files:r}=this.pendingSceneSyncPayload;this.pendingSceneSyncPayload=null;let a=OV(t,n,r),i=JSON.stringify(a);if(this.shouldDelayEmptySceneCommit(i)){this.pendingSceneSyncPayload={appState:n,elements:t,files:r},this.scheduleDelayedEmptySceneCommit();return}i!==this.lastSceneJson&&(this.lastSceneSyncAt=this.now(),this.commitSceneJson(i,{origin:"excalidraw-local-change"})),this.pendingEmptySceneCandidate=null,this.pendingSceneSyncPayload&&this.scheduleSceneSyncFlush()}hasRemoteCollaborators(){if(!this.awareness)return!1;for(let[t,n]of this.awareness.getStates())if(t!==this.awareness.clientID&&n?.user)return!0;return!1}shouldDelayEmptySceneCommit(t){if(!this.emptySceneGuardMs||!this.hasRemoteCollaborators())return this.pendingEmptySceneCandidate=null,!1;if(ni(t).elements.length>0)return this.pendingEmptySceneCandidate=null,!1;if(ni(this.lastSceneJson||this.getStructuredSceneJson()).elements.length===0)return this.pendingEmptySceneCandidate=null,!1;let a=this.now();return!this.pendingEmptySceneCandidate||this.pendingEmptySceneCandidate.previousSceneJson!==this.lastSceneJson?(this.pendingEmptySceneCandidate={firstSeenAt:a,previousSceneJson:this.lastSceneJson},console.warn(`[excalidraw:${this.filePath}] Delaying suspicious empty scene commit during active collaboration`),!0):a-this.pendingEmptySceneCandidate.firstSeenAt<this.emptySceneGuardMs}scheduleDelayedEmptySceneCommit(){if(this.sceneSyncTimer!==null)return;let t=this.pendingEmptySceneCandidate?.firstSeenAt??this.now(),n=this.now()-t,r=Math.max(0,this.emptySceneGuardMs-n);this.sceneSyncTimer=this.setTimeoutFn(()=>{this.sceneSyncTimer=null,this.flushSceneSync()},r)}flushPointerAwarenessPayload(){this.pointerAwarenessFrame=0,!(!this.awareness||!this.pendingPointerPayload)&&(this.awareness.setLocalStateField("pointer",this.pendingPointerPayload.pointer),this.awareness.setLocalStateField("pointerButton",this.pendingPointerPayload.button),this.pendingPointerPayload=null)}normalizeViewportAwareness(t){if(!t||typeof t!="object")return null;let n=Number(t.scrollX),r=Number(t.scrollY),a=Number(t.zoom);return!Number.isFinite(n)||!Number.isFinite(r)||!Number.isFinite(a)||a<=0?null:{scrollX:n,scrollY:r,zoom:a}}scheduleLocalPointerAwareness(t){!this.awareness||!t?.pointer||(this.pendingPointerPayload={button:t.button==="down"?"down":"up",pointer:{x:t.pointer.x,y:t.pointer.y,tool:t.pointer.tool==="laser"?"laser":"pointer"}},!this.pointerAwarenessFrame&&(this.pointerAwarenessFrame=this.requestAnimationFrameFn(()=>this.flushPointerAwarenessPayload())))}flushViewportAwarenessPayload(){this.viewportAwarenessFrame=0,!(!this.awareness||!this.pendingViewportPayload)&&(this.awareness.setLocalStateField("viewport",this.pendingViewportPayload),this.pendingViewportPayload=null)}scheduleLocalViewportAwareness(t){if(!this.awareness)return;let n=this.normalizeViewportAwareness(t);if(!n)return;let r=`${n.scrollX}:${n.scrollY}:${n.zoom}`;r!==this.lastViewportSignature&&(this.lastViewportSignature=r,this.pendingViewportPayload=n,!this.viewportAwarenessFrame&&(this.viewportAwarenessFrame=this.requestAnimationFrameFn(()=>this.flushViewportAwarenessPayload())))}syncLocalSelectionAwareness(t){if(!this.awareness)return;let n=t?.selectedElementIds||{},r=Object.keys(n).sort().join(",");r!==this.lastSelectedIdsSignature&&(this.lastSelectedIdsSignature=r,this.awareness.setLocalStateField("selectedElementIds",n))}commitSceneJson(t,{origin:n="excalidraw-room-write"}={}){let r=JSON.stringify(ni(t));if(!this.ydoc){let i=r!==this.lastSceneJson;return this.lastSceneJson=r,i}let a=this.getStructuredSceneJson();return r===a&&r===this.lastSceneJson?!1:(this.lastSceneJson=r,this.ydoc.transact(()=>{fW(this.ydoc,ni(r))},n),!0)}disconnect(){this.flushSceneSync(),this.clearTimeoutFn(this.sceneSyncTimer),this.sceneSyncTimer=null,this.pendingSceneSyncPayload=null,this.pointerAwarenessFrame&&this.cancelAnimationFrameFn(this.pointerAwarenessFrame),this.pointerAwarenessFrame=0,this.pendingPointerPayload=null,this.viewportAwarenessFrame&&this.cancelAnimationFrameFn(this.viewportAwarenessFrame),this.viewportAwarenessFrame=0,this.pendingViewportPayload=null,this.lastViewportSignature="",this.lastSelectedIdsSignature="",this.pendingEmptySceneCandidate=null,this.roomMeta?.unobserve(this.handleStructuredSceneUpdate),this.roomElements?.unobserveDeep(this.handleStructuredSceneUpdate),this.roomFiles?.unobserveDeep(this.handleStructuredSceneUpdate),this.roomAppState?.unobserve(this.handleStructuredSceneUpdate),this.awareness&&(this.awareness.off("change",this.handleAwarenessChange),this.awareness.setLocalState(null)),this.awareness=null,this.provider&&this.handleProviderSync&&this.provider.off("sync",this.handleProviderSync),this.handleProviderSync=null,this.provider?.disconnect(),this.provider?.destroy(),this.provider=null,this.ydoc?.destroy(),this.ydoc=null,this.roomMeta=null,this.roomElements=null,this.roomFiles=null,this.roomAppState=null,this.localUser=null,this.canWriteToRoom=!1,this.waitingForAuthoritativeSync=!1,this.applyingSharedSnapshotDepth=0}};function yW(e){return encodeURIComponent(String(e??""))}async function Ru(e,t){let n=await e.json().catch(()=>({}));if(!e.ok||n.ok===!1){let r=new Error(n.error||t);throw r.status=e.status,r.body=n,r}return n}var rM=class{async readTree(){let t=await fetch(bs("/files"));return Ru(t,"Failed to load file tree")}async readFile(t){let n=await fetch(bs(`/file?path=${encodeURIComponent(t)}`));return Ru(n,"Failed to read file")}async createFile({content:t,path:n}){let r=await fetch(bs("/file"),{body:JSON.stringify({content:t,path:n}),headers:{"Content-Type":"application/json"},method:"POST"});return Ru(r,"Failed to create file")}async renameFile({oldPath:t,newPath:n}){let r=await fetch(bs("/file"),{body:JSON.stringify({newPath:n,oldPath:t}),headers:{"Content-Type":"application/json"},method:"PATCH"});return Ru(r,"Failed to rename file")}async deleteFile(t){let n=await fetch(bs(`/file?path=${encodeURIComponent(t)}`),{method:"DELETE"});return Ru(n,"Failed to delete file")}async createDirectory(t){let n=await fetch(bs("/directory"),{body:JSON.stringify({path:t}),headers:{"Content-Type":"application/json"},method:"POST"});return Ru(n,"Failed to create folder")}async uploadImageAttachment({file:t,fileName:n="",sourcePath:r}){let a=await fetch(bs("/attachments"),{body:t,headers:{"Content-Type":t?.type||"application/octet-stream","X-CollabMD-File-Name":yW(n),"X-CollabMD-Source-Path":yW(r)},method:"POST"});return Ru(a,"Failed to upload image")}},xW=new rM;var Rp=new URLSearchParams(window.location.search),ope=Rp.get("file"),lpe=Rp.get("test")==="1",aM=Rp.get("mode")==="preview",kW=window.location.origin,wW=Number.parseInt(Rp.get("syncTimeoutMs")||"",10),Ke=null,R0=Rp.get("theme")||"dark",Dp=BV({params:Rp,storedUserName:localStorage.getItem("collabmd-user-name")}),xE="",fl=!1,SE=!1,N0="",Ip=null,bE=0,Vc=new Map,Nu=null,Yc=null,CE=!1,L0=0,wE="",Gc=[],Lp=0,yE=null,EW=!0,aa=new gE({filePath:ope,onCollaboratorsChange:e=>{if(!fl){Ip=e;return}upe(e)},onRemoteSceneJson:e=>{TW(e)},syncTimeoutMs:Number.isFinite(wW)?wW:void 0,vaultClient:xW});function O0(e){let t=document.querySelector(`[data-testid="button-${e}"]`);return t instanceof HTMLButtonElement?t:null}function spe(){let e=O0("undo"),t=O0("redo");return{canRedo:!!t&&!t.disabled,canUndo:!!e&&!e.disabled,head:null,length:null}}function SW(e){let t=O0(e);return!t||t.disabled?!1:(t.click(),!0)}function cpe(e={}){Dp=ow({currentUser:Dp,nextUser:e}),aa.setLocalUser(Dp)}lpe&&(window.__COLLABMD_EXCALIDRAW_TEST__={getElementBounds:e=>{let t=Ke?.getSceneElementsIncludingDeleted?.()?.find(n=>n.id===e&&!n.isDeleted);return t?{centerX:t.x+t.width/2,centerY:t.y+t.height/2,height:t.height,width:t.width,x:t.x,y:t.y}:null},getElementCount:()=>Ke?.getSceneElementsIncludingDeleted?.()?.filter(e=>!e.isDeleted).length??0,getElementIds:()=>Ke?.getSceneElementsIncludingDeleted?.()?.filter(e=>!e.isDeleted).map(e=>e.id).sort()??[],getHistoryState:()=>spe(),getLocalUserName:()=>Dp?.name||"",getLocalPeerId:()=>Dp?.peerId||"",getViewport:()=>{let e=Ke?.getAppState?.();return e?{scrollX:e.scrollX,scrollY:e.scrollY,zoom:e.zoom?.value??null}:null},isViewMode:()=>!!Ke?.getAppState?.().viewModeEnabled,getSceneJson:()=>aa.getLastSceneJson(),isAuthoritativeReady:()=>!!Ke&&fl&&aa.canWriteToRoom===!0&&aa.waitingForAuthoritativeSync===!1&&aa.isApplyingSharedSnapshot()===!1,isReady:()=>fl&&!!Ke&&!!O0("undo")&&!!O0("redo"),redoShared:()=>SW("redo"),setScene:e=>{mpe(Jm(e),{captureUpdate:U.IMMEDIATELY})},setViewport:e=>{if(!Ke)return;let t=Ke.getAppState();Ke.updateScene({appState:{scrollX:Number.isFinite(e?.scrollX)?e.scrollX:t.scrollX,scrollY:Number.isFinite(e?.scrollY)?e.scrollY:t.scrollY,zoom:Number.isFinite(e?.zoom)&&e.zoom>0?{value:e.zoom}:t.zoom},captureUpdate:U.NEVER})},undoShared:()=>SW("undo")});function dpe(e){if(Vc=e instanceof Map?e:new Map,!Ke){Ip=Vc;return}if(Ke.updateScene({collaborators:Vc,captureUpdate:U.NEVER}),Yc){iM(Yc);return}RW(Vc)}function upe(e){yE=e,!Lp&&(Lp=requestAnimationFrame(()=>{Lp=0;let t=yE;yE=null,dpe(t)}))}function TW(e){let t=ni(e),n=JSON.stringify(t);if(!(n===xE&&!N0)){if(xE=n,!Ke||!fl){N0=n;return}DW(t)}}function MW({trackedSharedSnapshot:e=!1}={}){bE+=1,requestAnimationFrame(()=>{requestAnimationFrame(()=>{bE=Math.max(0,bE-1),e&&aa.endApplyingSharedSnapshot(),bE===0&&(SE=!1)})})}function hpe(){L0+=1,requestAnimationFrame(()=>{requestAnimationFrame(()=>{L0=Math.max(0,L0-1),L0===0&&(CE=!1)})})}function AW(e){let t=Ke.getAppState(),n=Ke.getSceneElementsIncludingDeleted?.()||Ke.getSceneElements(),r=cd(e?.elements||[],n,{repairBindings:!0}),a=sh(e?.appState||{},t),i=RV(n,r,t);return{appState:{theme:R0,viewBackgroundColor:a.viewBackgroundColor??"#ffffff",gridSize:a.gridSize??null},elements:i,files:e?.files||{}}}function DW(e,{captureUpdate:t=U.NEVER,trackedSharedSnapshot:n=!0}={}){let r=AW(e);SE=!0,n&&aa.beginApplyingSharedSnapshot();try{Ke.updateScene({...r,captureUpdate:t})}finally{MW({trackedSharedSnapshot:n})}LW()}function mpe(e,{captureUpdate:t=U.IMMEDIATELY}={}){let n=Jm(e),r=JSON.stringify(n);if(xE=r,!Ke||!fl){N0=r;return}Ke.updateScene({...AW(n),captureUpdate:t})}function ppe(){TW(aa.getLastSceneJson())}function IW(e,t={}){window.parent.postMessage({source:"excalidraw-editor",type:e,...t},kW)}function fpe(){return Ke?.getSceneElementsIncludingDeleted?.()?.filter(e=>!e.isDeleted)??[]}function LW(){if(!EW||!Ke)return;let e=fpe();e.length!==0&&(EW=!1,requestAnimationFrame(()=>{requestAnimationFrame(()=>{Ke&&Ke.scrollToContent(e,{animate:!1,fitToViewport:!0,maxZoom:2,viewportZoomFactor:aM?.92:.88})})}))}function CW(){if(!fl||!Ke||CE)return;let e=Ke.getAppState();aa.scheduleLocalViewportAwareness({scrollX:e.scrollX,scrollY:e.scrollY,zoom:e.zoom?.value})}function EE(e,{force:t=!1}={}){let n=e?String(e):null,r=Nu!==n;Nu=n,r&&(wE=""),Nu&&RW(Vc,{force:t||r})}function RW(e=Vc,{force:t=!1}={}){if(!Ke||!Nu)return;let r=e?.get?.(String(Nu))?.viewport;if(!r)return;let a=`${Nu}:${r.scrollX}:${r.scrollY}:${r.zoom}`;!t&&a===wE||(wE=a,CE=!0,Ke.updateScene({appState:{scrollX:r.scrollX,scrollY:r.scrollY,zoom:{value:r.zoom}},captureUpdate:U.NEVER}),hpe())}function iM(e){if(Yc=e||null,!Ke)return;if(!e){Ke.updateScene({appState:{userToFollow:null},captureUpdate:U.NEVER}),EE(null,{force:!0}),Yc=null;return}let t=HV(Vc,e);t?.socketId&&(Ke.updateScene({appState:{userToFollow:{socketId:t.socketId,username:t.username||""}},captureUpdate:U.NEVER}),EE(t.socketId,{force:!0}),Yc=null)}function gpe(){fl=!1,Ip=null,Vc=new Map,Nu=null,Yc=null,CE=!1,L0=0,wE="",Lp&&cancelAnimationFrame(Lp),Lp=0,yE=null,Gc.forEach(e=>e()),Gc=[],aa.disconnect()}window.addEventListener("pagehide",()=>{gpe()});window.addEventListener("message",e=>{if(e.origin!==kW)return;let t=e.data;if(!(!t||t.source!=="collabmd-host")){if(t.type==="set-theme"){R0=t.theme||"dark",Ke&&(SE=!0,Ke.updateScene({appState:{theme:R0},captureUpdate:U.NEVER}),MW());return}if(t.type==="set-user"){cpe(t.user);return}t.type==="follow-user"&&iM(t.peerId||null)}});function bpe(e,t,n){!fl||SE||(xE=JSON.stringify(Jm({elements:e,appState:t,files:n})),aa.scheduleSceneSync(e,t,n))}function vpe(e){Ke=e,Gc.forEach(n=>n()),Gc=[],Gc.push(e.onStateChange(["scrollX","scrollY","zoom"],()=>{CW()})),Gc.push(e.onStateChange("userToFollow",n=>{if(n?.socketId){EE(n.socketId,{force:!0});return}EE(null,{force:!0})}));let t=N0||aa.getLastSceneJson();N0="",DW(ni(t)),Ip&&(Ke.updateScene({collaborators:Ip,captureUpdate:U.NEVER}),Ip=null),fl=!0,CW(),ppe(),Yc&&iM(Yc),LW(),IW("ready")}function ype({excalidrawAPI:e}){Ke=e}async function xpe(){let e=document.getElementById("loadingState");try{await KV();let t=await aa.connect({initialUser:Dp}),n=NV(t,{theme:R0});e?.remove();let r={onMount:ype,onInitialize:o=>{vpe(o)},onUnmount:()=>{Gc.forEach(o=>o()),Gc=[],Ke=null,fl=!1},initialData:n,aiEnabled:!1,isCollaborating:!0,onChange:(o,l,c)=>{bpe(o,l,c),aa.syncLocalSelectionAwareness(l)},onPointerUpdate:o=>{aa.scheduleLocalPointerAwareness(o)},theme:R0,viewModeEnabled:aM,zenModeEnabled:aM,UIOptions:{canvasActions:{export:!1,loadScene:!1,saveToActiveFile:!1,toggleTheme:!1}}},a=()=>vE.default.createElement("div",{style:{height:"100vh",width:"100%"}},vE.default.createElement(Pk,r));(0,_W.createRoot)(document.getElementById("root")).render(vE.default.createElement(a))}catch(t){console.error("[excalidraw] Failed to initialize:",t),IW("error",{message:t instanceof Error?t.message:"Failed to load Excalidraw"}),e&&(e.className="loading-state error",e.textContent=`Failed to load Excalidraw: ${t instanceof Error?t.message:String(t)}`)}}xpe();
291
291
  /*! Bundled license information:
292
292
 
293
293
  scheduler/cjs/scheduler.production.js:
@@ -1 +1 @@
1
- import "./excalidraw-editor-ZDYKMZOL.js";
1
+ import "./excalidraw-editor-TCIH6GJL.js";