@liveblocks/core 1.1.1-dual4 → 1.1.1-dual5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +2 -2
- package/dist/index.mjs +2 -2
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var Xn=Object.defineProperty,qn=Object.defineProperties;var Zn=Object.getOwnPropertyDescriptors;var Rt=Object.getOwnPropertySymbols;var Qn=Object.prototype.hasOwnProperty,eo=Object.prototype.propertyIsEnumerable;var wt=(t,o,e)=>o in t?Xn(t,o,{enumerable:!0,configurable:!0,writable:!0,value:e}):t[o]=e,C=(t,o)=>{for(var e in o||(o={}))Qn.call(o,e)&&wt(t,e,o[e]);if(Rt)for(var e of Rt(o))eo.call(o,e)&&wt(t,e,o[e]);return t},P=(t,o)=>qn(t,Zn(o));var j=(t,o,e)=>new Promise((n,r)=>{var i=d=>{try{a(e.next(d))}catch(c){r(c)}},s=d=>{try{a(e.throw(d))}catch(c){r(c)}},a=d=>d.done?n(d.value):Promise.resolve(d.value).then(i,s);a((e=e.apply(t,o)).next())});function O(){let t=new Set,o=new Set,e=null;function n(){e=[]}function r(){if(e!==null){for(let b of e)c(b);e=null}}function i(b){return o.add(b),()=>o.delete(b)}function s(b){return t.add(b),()=>t.delete(b)}function a(b){return j(this,null,function*(){let E;return new Promise(G=>{E=i(K=>{(b===void 0||b(K))&&G(K)})}).finally(()=>E==null?void 0:E())})}function d(b){e!==null?e.push(b):c(b)}function c(b){t.forEach(E=>E(b)),t.clear(),o.forEach(E=>E(b))}function f(){t.clear(),o.clear()}function y(){return t.size+o.size}return{notify:d,subscribe:i,subscribeOnce:s,clear:f,count:y,waitUntil:a,pause:n,unpause:r,observable:{subscribe:i,subscribeOnce:s,waitUntil:a}}}var Mt=!1;function Ut(t){Mt=t}function W(t,o){if(process.env.NODE_ENV==="production"||typeof window=="undefined")return;let e=P(C({},t),{source:"liveblocks-devtools-client"});(o!=null&&o.force||Mt)&&window.postMessage(e,"*")}var At=O();process.env.NODE_ENV!=="production"&&typeof window!="undefined"&&window.addEventListener("message",t=>{var o;t.source===window&&((o=t.data)==null?void 0:o.source)==="liveblocks-devtools-panel"&&At.notify(t.data)});var Ge=At.observable;var jt="1.1.1-dual4",Nt=!1;function Jt(t){process.env.NODE_ENV==="production"||typeof window=="undefined"||Nt||(Nt=!0,Ge.subscribe(o=>{switch(o.msg){case"connect":{Ut(!0);for(let e of t())W({msg:"room::available",roomId:e,clientVersion:jt});break}}}),W({msg:"wake-up-devtools"},{force:!0}))}var Ye=new Map;function qe(t){var e;let o=(e=Ye.get(t))!=null?e:[];Ye.delete(t);for(let n of o)n()}function to(t){qe(t.id),so(t),Ye.set(t.id,[t.events.status.subscribe(()=>no(t)),t.events.storageDidLoad.subscribeOnce(()=>Dt(t)),t.events.storage.subscribe(()=>Dt(t)),t.events.me.subscribe(()=>oo(t)),t.events.others.subscribe(()=>ro(t))])}function no(t){W({msg:"room::sync::partial",roomId:t.id,status:t.getStatus()})}function Dt(t){let o=t.getStorageSnapshot();o&&W({msg:"room::sync::partial",roomId:t.id,storage:o.toTreeNode("root").payload})}function oo(t){let o=t.__internal.getSelf_forDevTools();o&&W({msg:"room::sync::partial",roomId:t.id,me:o})}function ro(t){let o=t.__internal.getOthers_forDevTools();o&&W({msg:"room::sync::partial",roomId:t.id,others:o})}function so(t){var r;let o=t.getStorageSnapshot(),e=t.__internal.getSelf_forDevTools(),n=t.__internal.getOthers_forDevTools();W({msg:"room::sync::full",roomId:t.id,status:t.getStatus(),storage:(r=o==null?void 0:o.toTreeNode("root").payload)!=null?r:null,me:e,others:n})}var Xe=new Map;function Kt(t){let o=Xe.get(t);Xe.delete(t),o&&o()}function Bt(t,o){process.env.NODE_ENV==="production"||typeof window=="undefined"||(W({msg:"room::available",roomId:t,clientVersion:jt}),Kt(t),Xe.set(t,Ge.subscribe(e=>{switch(e.msg){case"room::subscribe":{e.roomId===t&&to(o);break}case"room::unsubscribe":{e.roomId===t&&qe(t);break}}})))}function zt(t){process.env.NODE_ENV==="production"||typeof window=="undefined"||(qe(t),Kt(t),W({msg:"room::unavailable",roomId:t}))}var Vt="background:#0e0d12;border-radius:9999px;color:#fff;padding:3px 7px;font-family:sans-serif;font-weight:600;",io="font-weight:600";function Wt(t){return typeof window=="undefined"||process.env.NODE_ENV==="test"?console[t]:(o,...e)=>console[t]("%cLiveblocks",Vt,o,...e)}var F=Wt("warn"),le=Wt("error");function Ft(t){return typeof window=="undefined"||process.env.NODE_ENV==="test"?console[t]:(o,e,...n)=>console[t](`%cLiveblocks%c ${o}`,Vt,io,e,...n)}var Ht=Ft("warn"),ve=Ft("error");var $t=new Set;function Gt(t,o=t){process.env.NODE_ENV!=="production"&&($t.has(o)||($t.add(o),ve("Deprecation warning",t)))}function Ze(t,o,e=o){process.env.NODE_ENV!=="production"&&t&&Gt(o,e)}function Yt(t){if(process.env.NODE_ENV!=="production"){let o=new Error(t);throw o.name="Usage error",ve("Usage error",t),o}}function ao(t,o){process.env.NODE_ENV!=="production"&&t&&Yt(o)}function U(t,o){throw new Error(o)}function Xt(t,o){if(process.env.NODE_ENV!=="production"&&!t){let e=new Error(o);throw e.name="Assertion failure",e}}function T(t,o="Expected value to be non-nullable"){return Xt(t!=null,o),t}function co(t,o){if(t===o)return[0,0];let e=t.split("."),n=o.split("."),r=Math.min(e.length,n.length),i=0;for(;i<r&&e[i]===n[i];i++);let s=e.length-i,a=n.length-i;return[s,a]}function lo(t,o){let e=t.split(".");if(o<1||o>e.length+1)throw new Error("Invalid number of levels");let n=[];o>e.length&&n.push("*");for(let r=e.length-o+1;r<e.length;r++){let i=e.slice(0,r);i.length>0&&n.push(i.join(".")+".*")}return n.push(t),n}var Qe=class{constructor(o){this.curr=o}get current(){return this.curr}allowPatching(o){let e=this,n=!0,r=P(C({},this.curr),{patch(i){if(n){e.curr=Object.assign({},e.curr,i);for(let s of Object.entries(i)){let[a,d]=s;a!=="patch"&&(this[a]=d)}}else throw new Error("Can no longer patch stale context")}});o(r),n=!1}};var po=1,ke=class{get initialState(){let o=this.states.values()[Symbol.iterator]().next();if(o.done)throw new Error("No states defined yet");return o.value}get currentState(){if(this.currentStateOrNull===null)throw this.runningState===0?new Error("Not started yet"):new Error("Already stopped");return this.currentStateOrNull}start(){if(this.runningState!==0)throw new Error("State machine has already started");return this.runningState=1,this.currentStateOrNull=this.initialState,this.enter(null),this}stop(){if(this.runningState!==1)throw new Error("Cannot stop a state machine that hasn't started yet");this.exit(null),this.runningState=2,this.currentStateOrNull=null}constructor(o){this.id=po++,this.runningState=0,this.currentStateOrNull=null,this.states=new Set,this.enterFns=new Map,this.cleanupStack=[],this.knownEventTypes=new Set,this.allowedTransitions=new Map,this.currentContext=new Qe(o),this.eventHub={didReceiveEvent:O(),willTransition:O(),didIgnoreEvent:O(),willExitState:O(),didEnterState:O()},this.events={didReceiveEvent:this.eventHub.didReceiveEvent.observable,willTransition:this.eventHub.willTransition.observable,didIgnoreEvent:this.eventHub.didIgnoreEvent.observable,willExitState:this.eventHub.willExitState.observable,didEnterState:this.eventHub.didEnterState.observable}}get context(){return this.currentContext.current}addState(o){if(this.runningState!==0)throw new Error("Already started");return this.states.add(o),this}onEnter(o,e){if(this.runningState!==0)throw new Error("Already started");if(this.enterFns.has(o))throw new Error(`enter/exit function for ${o} already exists`);return this.enterFns.set(o,e),this}onEnterAsync(o,e,n,r){return this.onEnter(o,()=>{let i=!1;return e(this.currentContext.current).then(s=>{i||this.transition({type:"ASYNC_OK",data:s},n)},s=>{i||this.transition({type:"ASYNC_ERROR",reason:s},r)}),()=>{i=!0}})}getStatesMatching(o){let e=[];if(o==="*")for(let n of this.states)e.push(n);else if(o.endsWith(".*")){let n=o.slice(0,-1);for(let r of this.states)r.startsWith(n)&&e.push(r)}else{let n=o;this.states.has(n)&&e.push(n)}if(e.length===0)throw new Error(`No states match ${JSON.stringify(o)}`);return e}addTransitions(o,e){if(this.runningState!==0)throw new Error("Already started");for(let n of this.getStatesMatching(o)){let r=this.allowedTransitions.get(n);r===void 0&&(r=new Map,this.allowedTransitions.set(n,r));for(let[i,s]of Object.entries(e)){if(r.has(i))throw new Error(`Trying to set transition "${i}" on "${n}" (via "${o}"), but a transition already exists there.`);let a=s;if(this.knownEventTypes.add(i),a!==void 0){let d=typeof a=="function"?a:()=>a;r.set(i,d)}}}return this}addTimedTransition(o,e,n){return this.onEnter(o,()=>{let r=typeof e=="function"?e(this.currentContext.current):e,i=setTimeout(()=>{this.transition({type:"TIMER"},n)},r);return()=>{clearTimeout(i)}})}getTargetFn(o){var e;return(e=this.allowedTransitions.get(this.currentState))==null?void 0:e.get(o)}exit(o){this.eventHub.willExitState.notify(this.currentState),this.currentContext.allowPatching(e=>{var n;o=o!=null?o:this.cleanupStack.length;for(let r=0;r<o;r++)(n=this.cleanupStack.pop())==null||n(e)})}enter(o){let e=lo(this.currentState,o!=null?o:this.currentState.split(".").length+1);this.currentContext.allowPatching(n=>{for(let r of e){let i=this.enterFns.get(r),s=i==null?void 0:i(n);typeof s=="function"?this.cleanupStack.push(s):this.cleanupStack.push(null)}}),this.eventHub.didEnterState.notify(this.currentState)}send(o){if(!this.knownEventTypes.has(o.type))throw new Error(`Invalid event ${JSON.stringify(o.type)}`);if(this.runningState===2)return;let e=this.getTargetFn(o.type);if(e!==void 0)return this.transition(o,e);this.eventHub.didIgnoreEvent.notify(o)}transition(o,e){this.eventHub.didReceiveEvent.notify(o);let n=this.currentState,i=(typeof e=="function"?e:()=>e)(o,this.currentContext.current),s,a;if(i===null){this.eventHub.didIgnoreEvent.notify(o);return}if(typeof i=="string"?s=i:(s=i.target,a=Array.isArray(i.effect)?i.effect:[i.effect]),!this.states.has(s))throw new Error(`Invalid next state name: ${JSON.stringify(s)}`);this.eventHub.willTransition.notify({from:n,to:s});let[d,c]=co(this.currentState,s);if(d>0&&this.exit(d),this.currentStateOrNull=s,a!==void 0){let f=a;this.currentContext.allowPatching(y=>{for(let b of f)typeof b=="function"?b(y,o):y.patch(b)})}c>0&&this.enter(c)}};function A(t){return t!==null&&typeof t=="object"&&Object.prototype.toString.call(t)==="[object Object]"}function qt(t){let o={};for(let[e,n]of t)o[e]=n;return o}function et(t){return Object.entries(t)}function ge(t){try{return JSON.parse(t)}catch(o){return}}function tt(t){try{let o=t.replace(/-/g,"+").replace(/_/g,"/");return decodeURIComponent(atob(o).split("").map(function(n){return"%"+("00"+n.charCodeAt(0).toString(16)).slice(-2)}).join(""))}catch(o){return atob(t)}}function _e(t){return t.filter(o=>o!=null)}function Oe(t){let o=C({},t);return Object.keys(t).forEach(e=>{let n=e;o[n]===void 0&&delete o[n]}),o}function xe(t,o,e="Timed out"){return j(this,null,function*(){let n,r=new Promise((i,s)=>{n=setTimeout(()=>{s(new Error(e))},o)});return Promise.race([t,r]).finally(()=>clearTimeout(n))})}function rt(t){switch(t){case"connecting":return"connecting";case"connected":return"open";case"reconnecting":return"unavailable";case"disconnected":return"failed";case"initial":return"closed";default:return"closed"}}function nn(t){let o=t.currentState;switch(o){case"@ok.connected":case"@ok.awaiting-pong":return"connected";case"@idle.initial":return"initial";case"@auth.busy":case"@auth.backoff":case"@connecting.busy":case"@connecting.backoff":return t.context.successCount>0?"reconnecting":"connecting";case"@idle.failed":return"disconnected";default:return U(o,"Unknown state")}}var on=[250,500,1e3,2e3,4e3,8e3,1e4],Ee=on[0]-1,uo=[2e3,3e4,6e4,3e5],fo=3e4,ho=2e3,yo=1e4,mo=1e4,q=class extends Error{constructor(o){super(o)}},ot=class extends Error{constructor(e,n){super(e);this.code=n}};function rn(t,o=on){var e;return(e=o.find(n=>n>t))!=null?e:o[o.length-1]}function pe(t){t.patch({backoffDelay:rn(t.backoffDelay)})}function Zt(t){t.patch({backoffDelay:rn(t.backoffDelay,uo)})}function Qt(t){t.patch({successCount:0})}function ue(t,o){let e=t===2?le:t===1?F:()=>{};return()=>{e(o)}}function en(t){let o="Connection to Liveblocks websocket server";return e=>{t instanceof Error?F(`${o} could not be established. ${String(t)}`):F(st(t)?`${o} closed prematurely (code: ${t.code}). Retrying in ${e.backoffDelay}ms.`:`${o} could not be established.`)}}function nt(t){return o=>{F(`Connection to Liveblocks websocket server closed (code: ${t.code}). Retrying in ${o.backoffDelay}ms.`)}}var To=ue(1,"Connection to WebSocket closed permanently. Won't retry.");function st(t){return!(t instanceof Error)&&t.type==="close"}function tn(t){return st(t)&&t.code>=4e3&&t.code<4100}function bo(t){let o=new Date().getTime();function e(...r){F(`${((new Date().getTime()-o)/1e3).toFixed(2)} [FSM #${t.id}]`,...r)}let n=[t.events.didReceiveEvent.subscribe(r=>e(`Event ${r.type}`)),t.events.willTransition.subscribe(({from:r,to:i})=>e("Transitioning",r,"\u2192",i)),t.events.didIgnoreEvent.subscribe(r=>e("Ignored event",r.type,r,"(current state won't handle it)"))];return()=>{for(let r of n)r()}}function vo(t){let o=O(),e=O(),n=O(),r=null,i=t.events.didEnterState.subscribe(()=>{let s=nn(t);s!==r&&o.notify(s),r==="connected"&&s!=="connected"?n.notify():r!=="connected"&&s==="connected"&&e.notify(),r=s});return{statusDidChange:o.observable,didConnect:e.observable,didDisconnect:n.observable,unsubscribe:i}}var Pe=t=>o=>o.patch(t);function go(t,o){let e=O();e.pause();let n=O(),r={successCount:0,token:null,socket:null,backoffDelay:Ee},i=new ke(r).addState("@idle.initial").addState("@idle.failed").addState("@auth.busy").addState("@auth.backoff").addState("@connecting.busy").addState("@connecting.backoff").addState("@ok.connected").addState("@ok.awaiting-pong");i.addTransitions("*",{RECONNECT:{target:"@auth.backoff",effect:[pe,Qt]},DISCONNECT:"@idle.initial"}),i.onEnter("@idle.*",Qt).addTransitions("@idle.*",{CONNECT:(m,h)=>h.token!==null?"@connecting.busy":"@auth.busy"}),i.addTransitions("@auth.backoff",{NAVIGATOR_ONLINE:{target:"@auth.busy",effect:Pe({backoffDelay:Ee})}}).addTimedTransition("@auth.backoff",m=>m.backoffDelay,"@auth.busy").onEnterAsync("@auth.busy",()=>xe(t.authenticate(),yo),m=>({target:"@connecting.busy",effect:Pe({token:m.data,backoffDelay:Ee})}),m=>m.reason instanceof q?{target:"@idle.failed",effect:ue(2,m.reason.message)}:{target:"@auth.backoff",effect:[pe,ue(2,`Authentication failed: ${m.reason instanceof Error?m.reason.message:String(m.reason)}`)]});let s=m=>i.send({type:"EXPLICIT_SOCKET_ERROR",event:m}),a=m=>i.send({type:"EXPLICIT_SOCKET_CLOSE",event:m}),d=m=>m.data==="pong"?i.send({type:"PONG"}):e.notify(m);function c(m){m&&(m.removeEventListener("error",s),m.removeEventListener("close",a),m.removeEventListener("message",d),m.close())}i.addTransitions("@connecting.backoff",{NAVIGATOR_ONLINE:{target:"@connecting.busy",effect:Pe({backoffDelay:Ee})}}).addTimedTransition("@connecting.backoff",m=>m.backoffDelay,"@connecting.busy").onEnterAsync("@connecting.busy",m=>j(this,null,function*(){let h=null,L=new Promise((te,ne)=>{if(m.token===null)throw new Error("No auth token");let w=t.createSocket(m.token);function Y(ce){h=ce,w.removeEventListener("message",d),ne(ce)}w.addEventListener("message",d),w.addEventListener("error",Y),w.addEventListener("close",Y),w.addEventListener("open",()=>{w.addEventListener("error",s),w.addEventListener("close",a),te([w,()=>{w.removeEventListener("error",Y),w.removeEventListener("close",Y)}])})});return xe(L,mo).then(([te,ne])=>{if(ne(),h)throw h;return te})}),m=>({target:"@ok.connected",effect:Pe({socket:m.data,backoffDelay:Ee})}),m=>{let h=m.reason;return h instanceof q?{target:"@idle.failed",effect:ue(2,h.message)}:st(h)&&h.code===4999?{target:"@idle.failed",effect:ue(2,h.reason)}:tn(h)&&h.code!==4001?{target:"@connecting.backoff",effect:[Zt,en(h)]}:{target:"@auth.backoff",effect:[pe,en(h)]}});let f={target:"@ok.awaiting-pong",effect:m=>{var h;(h=m.socket)==null||h.send("ping")}};if(i.addTimedTransition("@ok.connected",fo,f).addTransitions("@ok.connected",{NAVIGATOR_OFFLINE:f,WINDOW_GOT_FOCUS:f}),i.onEnter("@ok.*",m=>{m.patch({successCount:m.successCount+1});let h=setTimeout(e.unpause,0);return L=>{c(L.socket),L.patch({socket:null}),clearTimeout(h),e.pause()}}).addTransitions("@ok.awaiting-pong",{PONG:"@ok.connected"}).addTimedTransition("@ok.awaiting-pong",ho,{target:"@connecting.busy",effect:ue(1,"Received no pong from server, assume implicit connection loss.")}).addTransitions("@ok.*",{EXPLICIT_SOCKET_ERROR:(m,h)=>{var L;return((L=h.socket)==null?void 0:L.readyState)===1?null:{target:"@connecting.backoff",effect:pe}},EXPLICIT_SOCKET_CLOSE:m=>m.event.code===4999?{target:"@idle.failed",effect:To}:m.event.code===4001?{target:"@auth.backoff",effect:[pe,nt(m.event)]}:tn(m.event)?{target:"@connecting.backoff",effect:[Zt,nt(m.event),()=>{let h=new ot(m.event.reason,m.event.code);n.notify(h)}]}:{target:"@connecting.backoff",effect:[pe,nt(m.event)]}}),typeof document!="undefined"){let m=typeof document!="undefined"?document:void 0,h=typeof window!="undefined"?window:void 0,L=h!=null?h:m;i.onEnter("*",te=>{function ne(){i.send({type:"NAVIGATOR_OFFLINE"})}function w(){i.send({type:"NAVIGATOR_ONLINE"})}function Y(){(m==null?void 0:m.visibilityState)==="visible"&&i.send({type:"WINDOW_GOT_FOCUS"})}return h==null||h.addEventListener("online",w),h==null||h.addEventListener("offline",ne),L==null||L.addEventListener("visibilitychange",Y),()=>{L==null||L.removeEventListener("visibilitychange",Y),h==null||h.removeEventListener("online",w),h==null||h.removeEventListener("offline",ne),c(te.socket)}})}let y=[],{statusDidChange:b,didConnect:E,didDisconnect:G,unsubscribe:K}=vo(i);return y.push(K),o&&y.push(bo(i)),i.start(),{machine:i,cleanups:y,events:{statusDidChange:b,didConnect:E,didDisconnect:G,onMessage:e.observable,onLiveblocksError:n.observable}}}var Re=class{constructor(o,e=!1){let{machine:n,events:r,cleanups:i}=go(o,e);this.machine=n,this.events=r,this.cleanups=i}getLegacyStatus(){return rt(this.getStatus())}getStatus(){try{return nn(this.machine)}catch(o){return"initial"}}get token(){return this.machine.context.token}connect(){this.machine.send({type:"CONNECT"})}reconnect(){this.machine.send({type:"RECONNECT"})}disconnect(){this.machine.send({type:"DISCONNECT"})}destroy(){this.machine.stop();let o;for(;o=this.cleanups.pop();)o()}send(o){var n;let e=(n=this.machine.context)==null?void 0:n.socket;e===null?F("Cannot send: not connected yet",o):e.readyState!==1?F("Cannot send: WebSocket no longer open",o):e.send(o)}_privateSendMachineEvent(o){this.machine.send(o)}};var sn=at(0),we=at(1),_o=sn+at(-1);function at(t){let o=32+(t<0?95+t:t);if(o<32||o>126)throw new Error(`Invalid n value: ${t}`);return String.fromCharCode(o)}function z(t,o){return t!==void 0&&o!==void 0?So(t,o):t!==void 0?Eo(t):o!==void 0?Oo(o):we}function Oo(t){let o=t.length-1;for(let e=0;e<=o;e++){let n=t.charCodeAt(e);if(!(n<=32))return e===o?n===32+1?t.substring(0,e)+_o:t.substring(0,e)+String.fromCharCode(n-1):t.substring(0,e+1)}return we}function Eo(t){for(let o=0;o<=t.length-1;o++){let e=t.charCodeAt(o);if(!(e>=126))return t.substring(0,o)+String.fromCharCode(e+1)}return t+we}function So(t,o){if(t<o)return it(t,o);if(t>o)return it(o,t);throw new Error("Cannot compute value between two equal positions")}function it(t,o){let e=0,n=t.length,r=o.length;for(;;){let i=e<n?t.charCodeAt(e):32,s=e<r?o.charCodeAt(e):126;if(i===s){e++;continue}if(s-i===1){let a=t.substring(0,e+1),d=t.substring(e+1);return a+it(d,"")}else return Co(t,e)+String.fromCharCode(s+i>>1)}}function Co(t,o){return o<t.length?t.substring(0,o):t+sn.repeat(o-t.length)}var Io=32+1;function Lo(t){if(t==="")return!1;let o=t.length-1,e=t.charCodeAt(o);if(e<Io||e>126)return!1;for(let n=0;n<o;n++){let r=t.charCodeAt(n);if(r<32||r>126)return!1}return!0}function ko(t){let o=[];for(let e=0;e<t.length;e++){let n=t.charCodeAt(e);o.push(n<32?32:n>126?126:n)}for(;o.length>0&&o[o.length-1]===32;)o.length--;return o.length>0?String.fromCharCode(...o):we}function Z(t){return Lo(t)?t:ko(t)}var dt=(c=>(c[c.INIT=0]="INIT",c[c.SET_PARENT_KEY=1]="SET_PARENT_KEY",c[c.CREATE_LIST=2]="CREATE_LIST",c[c.UPDATE_OBJECT=3]="UPDATE_OBJECT",c[c.CREATE_OBJECT=4]="CREATE_OBJECT",c[c.DELETE_CRDT=5]="DELETE_CRDT",c[c.DELETE_OBJECT_KEY=6]="DELETE_OBJECT_KEY",c[c.CREATE_MAP=7]="CREATE_MAP",c[c.CREATE_REGISTER=8]="CREATE_REGISTER",c))(dt||{});function an(t){return t.type===5&&t.id==="ACK"}function dn(t,o,e=Z(o)){return Object.freeze({type:"HasParent",node:t,key:o,pos:e})}var cn=Object.freeze({type:"NoParent"});function xo(t,o=Z(t)){return Object.freeze({type:"Orphaned",oldKey:t,oldPos:o})}var H=class{constructor(){this._parent=cn}_getParentKeyOrThrow(){switch(this.parent.type){case"HasParent":return this.parent.key;case"NoParent":throw new Error("Parent key is missing");case"Orphaned":return this.parent.oldKey;default:return U(this.parent,"Unknown state")}}get _parentPos(){switch(this.parent.type){case"HasParent":return this.parent.pos;case"NoParent":throw new Error("Parent key is missing");case"Orphaned":return this.parent.oldPos;default:return U(this.parent,"Unknown state")}}get _pool(){return this.__pool}get roomId(){return this.__pool?this.__pool.roomId:null}get _id(){return this.__id}get parent(){return this._parent}get _parentKey(){switch(this.parent.type){case"HasParent":return this.parent.key;case"NoParent":return null;case"Orphaned":return this.parent.oldKey;default:return U(this.parent,"Unknown state")}}_apply(o,e){switch(o.type){case 5:return this.parent.type==="HasParent"?this.parent.node._detachChild(this):{modified:!1}}return{modified:!1}}_setParentLink(o,e){switch(this.parent.type){case"HasParent":if(this.parent.node!==o)throw new Error("Cannot set parent: node already has a parent");this._parent=dn(o,e);return;case"Orphaned":case"NoParent":{this._parent=dn(o,e);return}default:return U(this.parent,"Unknown state")}}_attach(o,e){if(this.__id||this.__pool)throw new Error("Cannot attach node: already attached");e.addNode(o,this),this.__id=o,this.__pool=e}_detach(){switch(this.__pool&&this.__id&&this.__pool.deleteNode(this.__id),this.parent.type){case"HasParent":{this._parent=xo(this.parent.key,this.parent.pos);break}case"NoParent":{this._parent=cn;break}case"Orphaned":break;default:U(this.parent,"Unknown state")}this.__pool=void 0}invalidate(){(this._cachedImmutable!==void 0||this._cachedTreeNode!==void 0)&&(this._cachedImmutable=void 0,this._cachedTreeNode=void 0,this.parent.type==="HasParent"&&this.parent.node.invalidate())}toTreeNode(o){return(this._cachedTreeNode===void 0||this._cachedTreeNodeKey!==o)&&(this._cachedTreeNodeKey=o,this._cachedTreeNode=this._toTreeNode(o)),this._cachedTreeNode}toImmutable(){return this._cachedImmutable===void 0&&(this._cachedImmutable=this._toImmutable()),this._cachedImmutable}};var ct=(r=>(r[r.OBJECT=0]="OBJECT",r[r.LIST=1]="LIST",r[r.MAP=2]="MAP",r[r.REGISTER=3]="REGISTER",r))(ct||{});function lt(t){return t.type===0&&!ln(t)}function ln(t){return t.parentId!==void 0&&t.parentKey!==void 0}function oe(t=7){let o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789,./;[]~!@#$%&*()_+=-",e=o.length;return Array.from({length:t},()=>o.charAt(Math.floor(Math.random()*e))).join("")}var J=class t extends H{constructor(e){super();this._data=e}get data(){return this._data}static _deserialize([e,n],r,i){let s=new t(n.data);return s._attach(e,i),s}_toOps(e,n,r){if(this._id===void 0)throw new Error("Cannot serialize register if parentId or parentKey is undefined");return[{type:8,opId:r==null?void 0:r.generateOpId(),id:this._id,parentId:e,parentKey:n,data:this.data}]}_serialize(){if(this.parent.type!=="HasParent")throw new Error("Cannot serialize LiveRegister if parent is missing");return{type:3,parentId:T(this.parent.node._id,"Parent node expected to have ID"),parentKey:this.parent.key,data:this.data}}_attachChild(e){throw new Error("Method not implemented.")}_detachChild(e){throw new Error("Method not implemented.")}_apply(e,n){return super._apply(e,n)}_toTreeNode(e){var n;return{type:"Json",id:(n=this._id)!=null?n:oe(),key:e,payload:this._data}}_toImmutable(){return this._data}};function Po(t,o){let e=t._parentPos,n=o._parentPos;return e===n?0:e<n?-1:1}var M=class t extends H{constructor(e=[]){super();this._items=[],this._implicitlyDeletedItems=new WeakSet,this._unacknowledgedSets=new Map;let n;for(let r of e){let i=z(n),s=re(r);s._setParentLink(this,i),this._items.push(s),n=i}}static _deserialize([e],n,r){let i=new t;i._attach(e,r);let s=n.get(e);if(s===void 0)return i;for(let[a,d]of s){let c=Ue([a,d],n,r);c._setParentLink(i,d.parentKey),i._insertAndSort(c)}return i}_toOps(e,n,r){if(this._id===void 0)throw new Error("Cannot serialize item is not attached");let i=[],s={id:this._id,opId:r==null?void 0:r.generateOpId(),type:2,parentId:e,parentKey:n};i.push(s);for(let a of this._items)i.push(...a._toOps(this._id,a._getParentKeyOrThrow(),r));return i}_insertAndSort(e){this._items.push(e),this._sortItems()}_sortItems(){this._items.sort(Po),this.invalidate()}_indexOfPosition(e){return this._items.findIndex(n=>n._getParentKeyOrThrow()===e)}_attach(e,n){super._attach(e,n);for(let r of this._items)r._attach(n.generateId(),n)}_detach(){super._detach();for(let e of this._items)e._detach()}_applySetRemote(e){if(this._pool===void 0)throw new Error("Can't attach child if managed pool is not present");let{id:n,parentKey:r}=e,i=ie(e);i._attach(n,this._pool),i._setParentLink(this,r);let s=e.deletedId,a=this._indexOfPosition(r);if(a!==-1){let d=this._items[a];if(d._id===s)return d._detach(),this._items[a]=i,{modified:S(this,[fe(a,i)]),reverse:[]};{this._implicitlyDeletedItems.add(d),this._items[a]=i;let c=[fe(a,i)],f=this._detachItemAssociatedToSetOperation(e.deletedId);return f&&c.push(f),{modified:S(this,c),reverse:[]}}}else{let d=[],c=this._detachItemAssociatedToSetOperation(e.deletedId);return c&&d.push(c),this._insertAndSort(i),d.push($(this._indexOfPosition(r),i)),{reverse:[],modified:S(this,d)}}}_applySetAck(e){if(this._pool===void 0)throw new Error("Can't attach child if managed pool is not present");let n=[],r=this._detachItemAssociatedToSetOperation(e.deletedId);r&&n.push(r);let i=this._unacknowledgedSets.get(e.parentKey);if(i!==void 0){if(i!==e.opId)return n.length===0?{modified:!1}:{modified:S(this,n),reverse:[]};this._unacknowledgedSets.delete(e.parentKey)}let s=this._indexOfPosition(e.parentKey),a=this._items.find(d=>d._id===e.id);if(a!==void 0){if(a._parentKey===e.parentKey)return{modified:n.length>0?S(this,n):!1,reverse:[]};s!==-1&&(this._implicitlyDeletedItems.add(this._items[s]),this._items.splice(s,1),n.push(Me(s)));let d=this._items.indexOf(a);a._setParentLink(this,e.parentKey),this._sortItems();let c=this._items.indexOf(a);return c!==d&&n.push(se(d,c,a)),{modified:n.length>0?S(this,n):!1,reverse:[]}}else{let d=this._pool.getNode(e.id);if(d&&this._implicitlyDeletedItems.has(d)){d._setParentLink(this,e.parentKey),this._implicitlyDeletedItems.delete(d),this._insertAndSort(d);let c=this._items.indexOf(d);return{modified:S(this,[s===-1?$(c,d):fe(c,d),...n]),reverse:[]}}else{s!==-1&&this._items.splice(s,1);let{newItem:c,newIndex:f}=this._createAttachItemAndSort(e,e.parentKey);return{modified:S(this,[s===-1?$(f,c):fe(f,c),...n]),reverse:[]}}}}_detachItemAssociatedToSetOperation(e){if(e===void 0||this._pool===void 0)return null;let n=this._pool.getNode(e);if(n===void 0)return null;let r=this._detachChild(n);return r.modified===!1?null:r.modified.updates[0]}_applyRemoteInsert(e){if(this._pool===void 0)throw new Error("Can't attach child if managed pool is not present");let n=Z(e.parentKey),r=this._indexOfPosition(n);r!==-1&&this._shiftItemPosition(r,n);let{newItem:i,newIndex:s}=this._createAttachItemAndSort(e,n);return{modified:S(this,[$(s,i)]),reverse:[]}}_applyInsertAck(e){let n=this._items.find(s=>s._id===e.id),r=Z(e.parentKey),i=this._indexOfPosition(r);if(n){if(n._parentKey===r)return{modified:!1};{let s=this._items.indexOf(n);i!==-1&&this._shiftItemPosition(i,r),n._setParentLink(this,r),this._sortItems();let a=this._indexOfPosition(r);return a===s?{modified:!1}:{modified:S(this,[se(s,a,n)]),reverse:[]}}}else{let s=T(this._pool).getNode(e.id);if(s&&this._implicitlyDeletedItems.has(s)){s._setParentLink(this,r),this._implicitlyDeletedItems.delete(s),this._insertAndSort(s);let a=this._indexOfPosition(r);return{modified:S(this,[$(a,s)]),reverse:[]}}else{i!==-1&&this._shiftItemPosition(i,r);let{newItem:a,newIndex:d}=this._createAttachItemAndSort(e,r);return{modified:S(this,[$(d,a)]),reverse:[]}}}}_applyInsertUndoRedo(e){var c,f,y;let{id:n,parentKey:r}=e,i=ie(e);if(((c=this._pool)==null?void 0:c.getNode(n))!==void 0)return{modified:!1};i._attach(n,T(this._pool)),i._setParentLink(this,r);let s=this._indexOfPosition(r),a=r;if(s!==-1){let b=(f=this._items[s])==null?void 0:f._parentPos,E=(y=this._items[s+1])==null?void 0:y._parentPos;a=z(b,E),i._setParentLink(this,a)}this._insertAndSort(i);let d=this._indexOfPosition(a);return{modified:S(this,[$(d,i)]),reverse:[{type:5,id:n}]}}_applySetUndoRedo(e){var d;let{id:n,parentKey:r}=e,i=ie(e);if(((d=this._pool)==null?void 0:d.getNode(n))!==void 0)return{modified:!1};this._unacknowledgedSets.set(r,T(e.opId));let s=this._indexOfPosition(r);i._attach(n,T(this._pool)),i._setParentLink(this,r);let a=r;if(s!==-1){let c=this._items[s];c._detach(),this._items[s]=i;let f=pt(c._toOps(T(this._id),r,this._pool),e.id),y=[fe(s,i)],b=this._detachItemAssociatedToSetOperation(e.deletedId);return b&&y.push(b),{modified:S(this,y),reverse:f}}else{this._insertAndSort(i),this._detachItemAssociatedToSetOperation(e.deletedId);let c=this._indexOfPosition(a);return{reverse:[{type:5,id:n}],modified:S(this,[$(c,i)])}}}_attachChild(e,n){if(this._pool===void 0)throw new Error("Can't attach child if managed pool is not present");let r;return e.intent==="set"?n===1?r=this._applySetRemote(e):n===2?r=this._applySetAck(e):r=this._applySetUndoRedo(e):n===1?r=this._applyRemoteInsert(e):n===2?r=this._applyInsertAck(e):r=this._applyInsertUndoRedo(e),r.modified!==!1&&this.invalidate(),r}_detachChild(e){if(e){let n=T(e._parentKey),r=e._toOps(T(this._id),n,this._pool),i=this._items.indexOf(e);return i===-1?{modified:!1}:(this._items.splice(i,1),this.invalidate(),e._detach(),{modified:S(this,[Me(i)]),reverse:r})}return{modified:!1}}_applySetChildKeyRemote(e,n){var s;if(this._implicitlyDeletedItems.has(n)){this._implicitlyDeletedItems.delete(n),n._setParentLink(this,e),this._insertAndSort(n);let a=this._items.indexOf(n);return{modified:S(this,[$(a,n)]),reverse:[]}}let r=n._parentKey;if(e===r)return{modified:!1};let i=this._indexOfPosition(e);if(i===-1){let a=this._items.indexOf(n);n._setParentLink(this,e),this._sortItems();let d=this._items.indexOf(n);return d===a?{modified:!1}:{modified:S(this,[se(a,d,n)]),reverse:[]}}else{this._items[i]._setParentLink(this,z(e,(s=this._items[i+1])==null?void 0:s._parentPos));let a=this._items.indexOf(n);n._setParentLink(this,e),this._sortItems();let d=this._items.indexOf(n);return d===a?{modified:!1}:{modified:S(this,[se(a,d,n)]),reverse:[]}}}_applySetChildKeyAck(e,n){var i,s;let r=T(n._parentKey);if(this._implicitlyDeletedItems.has(n)){let a=this._indexOfPosition(e);return this._implicitlyDeletedItems.delete(n),a!==-1&&this._items[a]._setParentLink(this,z(e,(i=this._items[a+1])==null?void 0:i._parentPos)),n._setParentLink(this,e),this._insertAndSort(n),{modified:!1}}else{if(e===r)return{modified:!1};let a=this._items.indexOf(n),d=this._indexOfPosition(e);d!==-1&&this._items[d]._setParentLink(this,z(e,(s=this._items[d+1])==null?void 0:s._parentPos)),n._setParentLink(this,e),this._sortItems();let c=this._items.indexOf(n);return a===c?{modified:!1}:{modified:S(this,[se(a,c,n)]),reverse:[]}}}_applySetChildKeyUndoRedo(e,n){var d;let r=T(n._parentKey),i=this._items.indexOf(n),s=this._indexOfPosition(e);s!==-1&&this._items[s]._setParentLink(this,z(e,(d=this._items[s+1])==null?void 0:d._parentPos)),n._setParentLink(this,e),this._sortItems();let a=this._items.indexOf(n);return i===a?{modified:!1}:{modified:S(this,[se(i,a,n)]),reverse:[{type:1,id:T(n._id),parentKey:r}]}}_setChildKey(e,n,r){return r===1?this._applySetChildKeyRemote(e,n):r===2?this._applySetChildKeyAck(e,n):this._applySetChildKeyUndoRedo(e,n)}_apply(e,n){return super._apply(e,n)}_serialize(){if(this.parent.type!=="HasParent")throw new Error("Cannot serialize LiveList if parent is missing");return{type:1,parentId:T(this.parent.node._id,"Parent node expected to have ID"),parentKey:this.parent.key}}get length(){return this._items.length}push(e){var n;return(n=this._pool)==null||n.assertStorageIsWritable(),this.insert(e,this.length)}insert(e,n){var d;if((d=this._pool)==null||d.assertStorageIsWritable(),n<0||n>this._items.length)throw new Error(`Cannot insert list item at index "${n}". index should be between 0 and ${this._items.length}`);let r=this._items[n-1]?this._items[n-1]._parentPos:void 0,i=this._items[n]?this._items[n]._parentPos:void 0,s=z(r,i),a=re(e);if(a._setParentLink(this,s),this._insertAndSort(a),this._pool&&this._id){let c=this._pool.generateId();a._attach(c,this._pool),this._pool.dispatch(a._toOps(this._id,s,this._pool),[{type:5,id:c}],new Map([[this._id,S(this,[$(n,a)])]]))}}move(e,n){var c;if((c=this._pool)==null||c.assertStorageIsWritable(),n<0)throw new Error("targetIndex cannot be less than 0");if(n>=this._items.length)throw new Error("targetIndex cannot be greater or equal than the list length");if(e<0)throw new Error("index cannot be less than 0");if(e>=this._items.length)throw new Error("index cannot be greater or equal than the list length");let r=null,i=null;e<n?(i=n===this._items.length-1?void 0:this._items[n+1]._parentPos,r=this._items[n]._parentPos):(i=this._items[n]._parentPos,r=n===0?void 0:this._items[n-1]._parentPos);let s=z(r,i),a=this._items[e],d=a._getParentKeyOrThrow();if(a._setParentLink(this,s),this._sortItems(),this._pool&&this._id){let f=new Map([[this._id,S(this,[se(e,n,a)])]]);this._pool.dispatch([{type:1,id:T(a._id),opId:this._pool.generateOpId(),parentKey:s}],[{type:1,id:T(a._id),parentKey:d}],f)}}delete(e){var r;if((r=this._pool)==null||r.assertStorageIsWritable(),e<0||e>=this._items.length)throw new Error(`Cannot delete list item at index "${e}". index should be between 0 and ${this._items.length-1}`);let n=this._items[e];if(n._detach(),this._items.splice(e,1),this.invalidate(),this._pool){let i=n._id;if(i){let s=new Map;s.set(T(this._id),S(this,[Me(e)])),this._pool.dispatch([{id:i,opId:this._pool.generateOpId(),type:5}],n._toOps(T(this._id),n._getParentKeyOrThrow()),s)}}}clear(){var e;if((e=this._pool)==null||e.assertStorageIsWritable(),this._pool){let n=[],r=[],i=[];for(let a of this._items){a._detach();let d=a._id;d&&(n.push({type:5,id:d,opId:this._pool.generateOpId()}),r.push(...a._toOps(T(this._id),a._getParentKeyOrThrow())),i.push(Me(0)))}this._items=[],this.invalidate();let s=new Map;s.set(T(this._id),S(this,i)),this._pool.dispatch(n,r,s)}else{for(let n of this._items)n._detach();this._items=[],this.invalidate()}}set(e,n){var d;if((d=this._pool)==null||d.assertStorageIsWritable(),e<0||e>=this._items.length)throw new Error(`Cannot set list item at index "${e}". index should be between 0 and ${this._items.length-1}`);let r=this._items[e],i=r._getParentKeyOrThrow(),s=r._id;r._detach();let a=re(n);if(a._setParentLink(this,i),this._items[e]=a,this.invalidate(),this._pool&&this._id){let c=this._pool.generateId();a._attach(c,this._pool);let f=new Map;f.set(this._id,S(this,[fe(e,a)]));let y=pt(a._toOps(this._id,i,this._pool),s);this._unacknowledgedSets.set(i,T(y[0].opId));let b=pt(r._toOps(this._id,i,void 0),c);this._pool.dispatch(y,b,f)}}toArray(){return this._items.map(e=>Q(e))}every(e){return this.toArray().every(e)}filter(e){return this.toArray().filter(e)}find(e){return this.toArray().find(e)}findIndex(e){return this.toArray().findIndex(e)}forEach(e){return this.toArray().forEach(e)}get(e){if(!(e<0||e>=this._items.length))return Q(this._items[e])}indexOf(e,n){return this.toArray().indexOf(e,n)}lastIndexOf(e,n){return this.toArray().lastIndexOf(e,n)}map(e){return this._items.map((n,r)=>e(Q(n),r))}some(e){return this.toArray().some(e)}[Symbol.iterator](){return new ut(this._items)}_createAttachItemAndSort(e,n){let r=ie(e);r._attach(e.id,T(this._pool)),r._setParentLink(this,n),this._insertAndSort(r);let i=this._indexOfPosition(n);return{newItem:r,newIndex:i}}_shiftItemPosition(e,n){var i;let r=z(n,this._items.length>e+1?(i=this._items[e+1])==null?void 0:i._parentPos:void 0);this._items[e]._setParentLink(this,r)}_toTreeNode(e){var n;return{type:"LiveList",id:(n=this._id)!=null?n:oe(),key:e,payload:this._items.map((r,i)=>r.toTreeNode(i.toString()))}}toImmutable(){return super.toImmutable()}_toImmutable(){let e=this._items.map(n=>n.toImmutable());return process.env.NODE_ENV==="production"?e:Object.freeze(e)}},ut=class{constructor(o){this._innerIterator=o[Symbol.iterator]()}[Symbol.iterator](){return this}next(){let o=this._innerIterator.next();return o.done?{done:!0,value:void 0}:{value:Q(o.value)}}};function S(t,o){return{node:t,type:"LiveList",updates:o}}function fe(t,o){return{index:t,type:"set",item:o instanceof J?o.data:o}}function Me(t){return{index:t,type:"delete"}}function $(t,o){return{index:t,type:"insert",item:o instanceof J?o.data:o}}function se(t,o,e){return{index:o,type:"move",previousIndex:t,item:e instanceof J?e.data:e}}function pt(t,o){return t.map((e,n)=>n===0?P(C({},e),{intent:"set",deletedId:o}):e)}var R=process.env.NODE_ENV==="production"?t=>t:Object.freeze;var N=class t extends H{constructor(e){super();if(this.unacknowledgedSet=new Map,e){let n=[];for(let r of e){let i=re(r[1]);i._setParentLink(this,r[0]),n.push([r[0],i])}this._map=new Map(n)}else this._map=new Map}_toOps(e,n,r){if(this._id===void 0)throw new Error("Cannot serialize item is not attached");let i=[],s={id:this._id,opId:r==null?void 0:r.generateOpId(),type:7,parentId:e,parentKey:n};i.push(s);for(let[a,d]of this._map)i.push(...d._toOps(this._id,a,r));return i}static _deserialize([e,n],r,i){let s=new t;s._attach(e,i);let a=r.get(e);if(a===void 0)return s;for(let[d,c]of a){let f=Ue([d,c],r,i);f._setParentLink(s,c.parentKey),s._map.set(c.parentKey,f),s.invalidate()}return s}_attach(e,n){super._attach(e,n);for(let[r,i]of this._map)I(i)&&i._attach(n.generateId(),n)}_attachChild(e,n){if(this._pool===void 0)throw new Error("Can't attach child if managed pool is not present");let{id:r,parentKey:i,opId:s}=e,a=i,d=ie(e);if(this._pool.getNode(r)!==void 0)return{modified:!1};if(n===2){let y=this.unacknowledgedSet.get(a);if(y===s)return this.unacknowledgedSet.delete(a),{modified:!1};if(y!==void 0)return{modified:!1}}else n===1&&this.unacknowledgedSet.delete(a);let c=this._map.get(a),f;if(c){let y=T(this._id);f=c._toOps(y,a),c._detach()}else f=[{type:5,id:r}];return d._setParentLink(this,a),d._attach(r,this._pool),this._map.set(a,d),this.invalidate(),{modified:{node:this,type:"LiveMap",updates:{[a]:{type:"update"}}},reverse:f}}_detach(){super._detach();for(let e of this._map.values())e._detach()}_detachChild(e){let n=T(this._id),r=T(e._parentKey),i=e._toOps(n,r,this._pool);for(let[a,d]of this._map)d===e&&(this._map.delete(a),this.invalidate());return e._detach(),{modified:{node:this,type:"LiveMap",updates:{[r]:{type:"delete"}}},reverse:i}}_serialize(){if(this.parent.type!=="HasParent")throw new Error("Cannot serialize LiveMap if parent is missing");return{type:2,parentId:T(this.parent.node._id,"Parent node expected to have ID"),parentKey:this.parent.key}}get(e){let n=this._map.get(e);if(n!==void 0)return Q(n)}set(e,n){var s;(s=this._pool)==null||s.assertStorageIsWritable();let r=this._map.get(e);r&&r._detach();let i=re(n);if(i._setParentLink(this,e),this._map.set(e,i),this.invalidate(),this._pool&&this._id){let a=this._pool.generateId();i._attach(a,this._pool);let d=new Map;d.set(this._id,{node:this,type:"LiveMap",updates:{[e]:{type:"update"}}});let c=i._toOps(this._id,e,this._pool);this.unacknowledgedSet.set(e,T(c[0].opId)),this._pool.dispatch(i._toOps(this._id,e,this._pool),r?r._toOps(this._id,e):[{type:5,id:a}],d)}}get size(){return this._map.size}has(e){return this._map.has(e)}delete(e){var r;(r=this._pool)==null||r.assertStorageIsWritable();let n=this._map.get(e);if(n===void 0)return!1;if(n._detach(),this._map.delete(e),this.invalidate(),this._pool&&n._id){let i=T(this._id),s=new Map;s.set(i,{node:this,type:"LiveMap",updates:{[e]:{type:"delete"}}}),this._pool.dispatch([{type:5,id:n._id,opId:this._pool.generateOpId()}],n._toOps(i,e),s)}return!0}entries(){let e=this._map.entries();return{[Symbol.iterator](){return this},next(){let n=e.next();if(n.done)return{done:!0,value:void 0};let i=n.value[0],s=Q(n.value[1]);return{value:[i,s]}}}}[Symbol.iterator](){return this.entries()}keys(){return this._map.keys()}values(){let e=this._map.values();return{[Symbol.iterator](){return this},next(){let n=e.next();return n.done?{done:!0,value:void 0}:{value:Q(n.value)}}}}forEach(e){for(let n of this)e(n[1],n[0],this)}_toTreeNode(e){var n;return{type:"LiveMap",id:(n=this._id)!=null?n:oe(),key:e,payload:Array.from(this._map.entries()).map(([r,i])=>i.toTreeNode(r))}}toImmutable(){return super.toImmutable()}_toImmutable(){let e=new Map;for(let[n,r]of this._map)e.set(n,r.toImmutable());return R(e)}};var x=class t extends H{constructor(e={}){super();this._propToLastUpdate=new Map;for(let n in e){let r=e[n];r!==void 0&&I(r)&&r._setParentLink(this,n)}this._map=new Map(Object.entries(e))}static _buildRootAndParentToChildren(e){let n=new Map,r=null;for(let[i,s]of e)if(lt(s))r=[i,s];else{let a=[i,s],d=n.get(s.parentId);d!==void 0?d.push(a):n.set(s.parentId,[a])}if(r===null)throw new Error("Root can't be null");return[r,n]}static _fromItems(e,n){let[r,i]=t._buildRootAndParentToChildren(e);return t._deserialize(r,i,n)}_toOps(e,n,r){if(this._id===void 0)throw new Error("Cannot serialize item is not attached");let i=r==null?void 0:r.generateOpId(),s=[],a=e!==void 0&&n!==void 0?{type:4,id:this._id,opId:i,parentId:e,parentKey:n,data:{}}:{type:4,id:this._id,opId:i,data:{}};s.push(a);for(let[d,c]of this._map)I(c)?s.push(...c._toOps(this._id,d,r)):a.data[d]=c;return s}static _deserialize([e,n],r,i){let s=new t(n.data);return s._attach(e,i),this._deserializeChildren(s,r,i)}static _deserializeChildren(e,n,r){let i=n.get(T(e._id));if(i===void 0)return e;for(let[s,a]of i){let d=un([s,a],n,r);Se(d)&&d._setParentLink(e,a.parentKey),e._map.set(a.parentKey,d),e.invalidate()}return e}_attach(e,n){super._attach(e,n);for(let[r,i]of this._map)I(i)&&i._attach(n.generateId(),n)}_attachChild(e,n){if(this._pool===void 0)throw new Error("Can't attach child if managed pool is not present");let{id:r,opId:i,parentKey:s}=e,a=ft(e);if(this._pool.getNode(r)!==void 0)return this._propToLastUpdate.get(s)===i&&this._propToLastUpdate.delete(s),{modified:!1};if(n===0)this._propToLastUpdate.set(s,T(i));else if(this._propToLastUpdate.get(s)!==void 0)return this._propToLastUpdate.get(s)===i?(this._propToLastUpdate.delete(s),{modified:!1}):{modified:!1};let d=T(this._id),c=this._map.get(s),f;return I(c)?(f=c._toOps(d,s),c._detach()):c===void 0?f=[{type:6,id:d,key:s}]:f=[{type:3,id:d,data:{[s]:c}}],this._map.set(s,a),this.invalidate(),Se(a)&&(a._setParentLink(this,s),a._attach(r,this._pool)),{reverse:f,modified:{node:this,type:"LiveObject",updates:{[s]:{type:"update"}}}}}_detachChild(e){if(e){let n=T(this._id),r=T(e._parentKey),i=e._toOps(n,r,this._pool);for(let[a,d]of this._map)d===e&&(this._map.delete(a),this.invalidate());return e._detach(),{modified:{node:this,type:"LiveObject",updates:{[r]:{type:"delete"}}},reverse:i}}return{modified:!1}}_detach(){super._detach();for(let e of this._map.values())I(e)&&e._detach()}_apply(e,n){return e.type===3?this._applyUpdate(e,n):e.type===6?this._applyDeleteObjectKey(e,n):super._apply(e,n)}_serialize(){let e={};for(let[n,r]of this._map)I(r)||(e[n]=r);return this.parent.type==="HasParent"&&this.parent.node._id?{type:0,parentId:this.parent.node._id,parentKey:this.parent.key,data:e}:{type:0,data:e}}_applyUpdate(e,n){let r=!1,i=T(this._id),s=[],a={type:3,id:i,data:{}};for(let c in e.data){let f=this._map.get(c);I(f)?(s.push(...f._toOps(i,c)),f._detach()):f!==void 0?a.data[c]=f:f===void 0&&s.push({type:6,id:i,key:c})}let d={};for(let c in e.data){let f=e.data[c];if(f===void 0)continue;if(n)this._propToLastUpdate.set(c,T(e.opId));else if(this._propToLastUpdate.get(c)===void 0)r=!0;else if(this._propToLastUpdate.get(c)===e.opId){this._propToLastUpdate.delete(c);continue}else continue;let y=this._map.get(c);I(y)&&y._detach(),r=!0,d[c]={type:"update"},this._map.set(c,f),this.invalidate()}return Object.keys(a.data).length!==0&&s.unshift(a),r?{modified:{node:this,type:"LiveObject",updates:d},reverse:s}:{modified:!1}}_applyDeleteObjectKey(e,n){let r=e.key;if(this._map.has(r)===!1)return{modified:!1};if(!n&&this._propToLastUpdate.get(r)!==void 0)return{modified:!1};let i=this._map.get(r),s=T(this._id),a=[];return I(i)?(a=i._toOps(s,e.key),i._detach()):i!==void 0&&(a=[{type:3,id:s,data:{[r]:i}}]),this._map.delete(r),this.invalidate(),{modified:{node:this,type:"LiveObject",updates:{[e.key]:{type:"delete"}}},reverse:a}}toObject(){return qt(this._map)}set(e,n){var r;(r=this._pool)==null||r.assertStorageIsWritable(),this.update({[e]:n})}get(e){return this._map.get(e)}delete(e){var a;(a=this._pool)==null||a.assertStorageIsWritable();let n=e,r=this._map.get(n);if(r===void 0)return;if(this._pool===void 0||this._id===void 0){I(r)&&r._detach(),this._map.delete(n),this.invalidate();return}let i;I(r)?(r._detach(),i=r._toOps(this._id,n)):i=[{type:3,data:{[n]:r},id:this._id}],this._map.delete(n),this.invalidate();let s=new Map;s.set(this._id,{node:this,type:"LiveObject",updates:{[e]:{type:"delete"}}}),this._pool.dispatch([{type:6,key:n,id:this._id,opId:this._pool.generateOpId()}],i,s)}update(e){var f;if((f=this._pool)==null||f.assertStorageIsWritable(),this._pool===void 0||this._id===void 0){for(let y in e){let b=e[y];if(b===void 0)continue;let E=this._map.get(y);I(E)&&E._detach(),I(b)&&b._setParentLink(this,y),this._map.set(y,b),this.invalidate()}return}let n=[],r=[],i=this._pool.generateOpId(),s={},a={id:this._id,type:3,data:{}},d={};for(let y in e){let b=e[y];if(b===void 0)continue;let E=this._map.get(y);if(I(E)?(r.push(...E._toOps(this._id,y)),E._detach()):E===void 0?r.push({type:6,id:this._id,key:y}):a.data[y]=E,I(b)){b._setParentLink(this,y),b._attach(this._pool.generateId(),this._pool);let G=b._toOps(this._id,y,this._pool),K=G.find(m=>m.parentId===this._id);K&&this._propToLastUpdate.set(y,T(K.opId)),n.push(...G)}else s[y]=b,this._propToLastUpdate.set(y,i);this._map.set(y,b),this.invalidate(),d[y]={type:"update"}}Object.keys(a.data).length!==0&&r.unshift(a),Object.keys(s).length!==0&&n.unshift({opId:i,id:this._id,type:3,data:s});let c=new Map;c.set(this._id,{node:this,type:"LiveObject",updates:d}),this._pool.dispatch(n,r,c)}toImmutable(){return super.toImmutable()}toTreeNode(e){return super.toTreeNode(e)}_toTreeNode(e){var r;let n=(r=this._id)!=null?r:oe();return{type:"LiveObject",id:n,key:e,payload:Array.from(this._map.entries()).map(([i,s])=>I(s)?s.toTreeNode(i):{type:"Json",id:`${n}:${i}`,key:i,payload:s})}}_toImmutable(){let e={};for(let[n,r]of this._map)e[n]=Se(r)?r.toImmutable():r;return process.env.NODE_ENV==="production"?e:Object.freeze(e)}};function ie(t){return re(ft(t))}function ft(t){switch(t.type){case 8:return t.data;case 4:return new x(t.data);case 7:return new N;case 2:return new M;default:return U(t,"Unknown creation Op")}}function ht(t,o){return t===o?!0:t.parent.type==="HasParent"?ht(t.parent.node,o):!1}function Ue([t,o],e,n){switch(o.type){case 0:return x._deserialize([t,o],e,n);case 1:return M._deserialize([t,o],e,n);case 2:return N._deserialize([t,o],e,n);case 3:return J._deserialize([t,o],e,n);default:throw new Error("Unexpected CRDT type")}}function un([t,o],e,n){switch(o.type){case 0:return x._deserialize([t,o],e,n);case 1:return M._deserialize([t,o],e,n);case 2:return N._deserialize([t,o],e,n);case 3:return o.data;default:throw new Error("Unexpected CRDT type")}}function Se(t){return he(t)||Ro(t)||Ae(t)}function I(t){return Se(t)||wo(t)}function he(t){return t instanceof M}function Ro(t){return t instanceof N}function Ae(t){return t instanceof x}function wo(t){return t instanceof J}function Q(t){return t instanceof J?t.data:t instanceof M||t instanceof N||t instanceof x?t:U(t,"Unknown AbstractCrdt")}function re(t){return t instanceof x||t instanceof N||t instanceof M?t:new J(t)}function hn(t,o){let e=[];return t.forEach((n,r)=>{o.get(r)||e.push({type:5,id:r})}),o.forEach((n,r)=>{let i=t.get(r);if(i)n.type===0&&(i.type!==0||JSON.stringify(n.data)!==JSON.stringify(i.data))&&e.push({type:3,id:r,data:n.data}),n.parentKey!==i.parentKey&&e.push({type:1,id:r,parentKey:T(n.parentKey,"Parent key must not be missing")});else switch(n.type){case 3:e.push({type:8,id:r,parentId:n.parentId,parentKey:n.parentKey,data:n.data});break;case 1:e.push({type:2,id:r,parentId:n.parentId,parentKey:n.parentKey});break;case 0:e.push(n.parentId?{type:4,id:r,parentId:n.parentId,parentKey:n.parentKey,data:n.data}:{type:4,id:r,data:n.data});break;case 2:e.push({type:7,id:r,parentId:n.parentId,parentKey:n.parentKey});break}}),e}function Mo(t,o){let e=t.updates;for(let[n,r]of et(o.updates))e[n]=r;return P(C({},o),{updates:e})}function Uo(t,o){let e=t.updates;for(let[n,r]of et(o.updates))e[n]=r;return P(C({},o),{updates:e})}function Ao(t,o){let e=t.updates;return P(C({},o),{updates:e.concat(o.updates)})}function Ne(t,o){return t===void 0?o:t.type==="LiveObject"&&o.type==="LiveObject"?Mo(t,o):t.type==="LiveMap"&&o.type==="LiveMap"?Uo(t,o):t.type==="LiveList"&&o.type==="LiveList"?Ao(t,o):o}function fn(t){let o=typeof t;return t==null||o==="string"||o==="boolean"||o==="number"||Array.isArray(t)||A(t)}function yt(t,o=""){if(!fn)return{path:o||"root",value:t};if(typeof t!="object"||t===null)return!1;for(let[e,n]of Object.entries(t)){let r=o?o+"."+e:e;if(!fn(n))return{path:r,value:n};if(typeof n=="object"){let i=yt(n,r);if(i)return i}}return!1}function yn(t,o){let e={name:t};if(typeof Error.captureStackTrace=="function")return Error.captureStackTrace(e,o),e.stack}function mn(t){return t===null||typeof t=="string"||typeof t=="number"||typeof t=="boolean"}function De(t){return Array.isArray(t)}function ae(t){return!mn(t)&&!De(t)}function Tn(t){let o=Date.now()/1e3;return!(o<=t.exp-300&&o>=t.iat-300)}function No(t){return Array.isArray(t)&&t.every(o=>typeof o=="string")}function Do(t){return A(t)&&typeof t.iat=="number"&&typeof t.exp=="number"&&typeof t.actor=="number"&&(t.id===void 0||typeof t.id=="string")&&No(t.scopes)}function je(t){let o=t.split(".");if(o.length!==3)throw new Error("Authentication error: invalid JWT token");let e=ge(tt(o[1]));if(!(e&&Do(e)))throw new Error("Authentication error: we expected a room token but did not get one. Hint: if you are using a callback, ensure the room is passed when creating the token. For more information: https://liveblocks.io/docs/api-reference/liveblocks-client#createClientCallback");return{raw:t,parsed:e}}var bn=(s=>(s[s.UPDATE_PRESENCE=100]="UPDATE_PRESENCE",s[s.BROADCAST_EVENT=103]="BROADCAST_EVENT",s[s.FETCH_STORAGE=200]="FETCH_STORAGE",s[s.UPDATE_STORAGE=201]="UPDATE_STORAGE",s[s.FETCH_YDOC=300]="FETCH_YDOC",s[s.UPDATE_YDOC=301]="UPDATE_YDOC",s))(bn||{});var vn=(c=>(c[c.UPDATE_PRESENCE=100]="UPDATE_PRESENCE",c[c.USER_JOINED=101]="USER_JOINED",c[c.USER_LEFT=102]="USER_LEFT",c[c.BROADCASTED_EVENT=103]="BROADCASTED_EVENT",c[c.ROOM_STATE=104]="ROOM_STATE",c[c.INITIAL_STORAGE_STATE=200]="INITIAL_STORAGE_STATE",c[c.UPDATE_STORAGE=201]="UPDATE_STORAGE",c[c.REJECT_STORAGE_OP=299]="REJECT_STORAGE_OP",c[c.UPDATE_YDOC=300]="UPDATE_YDOC",c))(vn||{});function mt(t){return Object.defineProperty(t,"count",{value:t.length,enumerable:!1}),Object.defineProperty(t,"toArray",{value:()=>t,enumerable:!1}),R(t)}function Je(t,o){let e=!1,n=C({},t);return Object.keys(o).forEach(r=>{let i=r,s=o[i];n[i]!==s&&(s===void 0?delete n[i]:n[i]=s,e=!0)}),e?n:t}var ee=class{constructor(){this._ev=O()}get didInvalidate(){return this._ev.observable}invalidate(){this._cache!==void 0&&(this._cache=void 0,this._ev.notify())}get current(){var o;return(o=this._cache)!=null?o:this._cache=this._toImmutable()}};function jo(t,o){return R(Oe(P(C({},t),{presence:o})))}var Ke=class extends ee{constructor(){super();this._connections={},this._presences={},this._users={}}_toImmutable(){let e=_e(Object.keys(this._presences).map(n=>this.getUser(Number(n))));return mt(e)}clearOthers(){this._connections={},this._presences={},this._users={},this.invalidate()}_getUser(e){let n=this._connections[e],r=this._presences[e];if(n!==void 0&&r!==void 0)return jo(n,r)}getUser(e){let n=this._users[e];if(n)return n;let r=this._getUser(e);if(r)return this._users[e]=r,r}_invalidateUser(e){this._users[e]!==void 0&&delete this._users[e],this.invalidate()}setConnection(e,n,r,i){this._connections[e]=R({connectionId:e,id:n,info:r,isReadOnly:i}),this._presences[e]!==void 0&&this._invalidateUser(e)}removeConnection(e){delete this._connections[e],delete this._presences[e],this._invalidateUser(e)}setOther(e,n){this._presences[e]=R(Oe(n)),this._connections[e]!==void 0&&this._invalidateUser(e)}patchOther(e,n){let r=this._presences[e];if(r===void 0)return;let i=Je(r,n);r!==i&&(this._presences[e]=R(i),this._invalidateUser(e))}};var Be=class extends ee{constructor(e){super();this._data=R(Oe(e))}_toImmutable(){return this._data}patch(e){let n=this._data,r=Je(n,e);n!==r&&(this._data=R(r),this.invalidate())}};var ze=class extends ee{constructor(e){super();this._value=R(e)}_toImmutable(){return this._value}set(e){this._value=R(e),this.invalidate()}},ye=class extends ee{constructor(...e){super();let n=e.pop(),r=e;this._refs=r,this._refs.forEach(i=>{i.didInvalidate.subscribe(()=>this.invalidate())}),this._transform=n}_toImmutable(){return this._transform(...this._refs.map(e=>e.current))}};var Jo=1024*1024-128;function Ko(t){let o=0;return()=>`${t}:${o++}`}function gn(t,o){return{type:"User",id:`${o.connectionId}`,key:t,payload:o}}function On(t,o){var Lt,kt,xt,Pt;let e=typeof t.initialPresence=="function"?t.initialPresence(o.roomId):t.initialPresence,n=typeof t.initialStorage=="function"?t.initialStorage(o.roomId):t.initialStorage,r=(xt=o.delegates)!=null?xt:{authenticate:Fo(o.roomId,o.authentication,(Lt=o.polyfills)==null?void 0:Lt.fetch),createSocket:Vo(o.liveblocksServer,(kt=o.polyfills)==null?void 0:kt.WebSocket)},i=new Re(r,o.enableDebugLogging),s={buffer:{flushTimerID:void 0,lastFlushedAt:0,me:{type:"full",data:e},messages:[],storageOperations:[]},sessionInfo:new ze(null),me:new Be(e),others:new Ke,initialStorage:n,idFactory:null,clock:0,opClock:0,nodes:new Map,root:void 0,undoStack:[],redoStack:[],pausedHistory:null,activeBatch:null,unacknowledgedOps:new Map,opStackTraces:process.env.NODE_ENV!=="production"?new Map:void 0},a=l=>l(),d=(Pt=o.unstable_batchedUpdates)!=null?Pt:a,c;function f(l){var u;let p=(u=i.token)==null?void 0:u.parsed;p!==void 0&&p!==c&&(s.sessionInfo.set({userInfo:p.info,userId:p.id,actor:p.actor,isReadOnly:Fe(p.scopes)}),c=p),d(()=>{h.status.notify(l),h.connection.notify(rt(l))})}let y,b=!1;function E(l){l==="reconnecting"?y=setTimeout(()=>{d(()=>{h.lostConnection.notify("lost"),b=!0,s.others.clearOthers(),X({others:[{type:"reset"}]},a)})},o.lostConnectionTimeout):(clearTimeout(y),b&&(d(l==="disconnected"?()=>{h.lostConnection.notify("failed")}:()=>{h.lostConnection.notify("restored")}),b=!1))}function G(){let l=s.sessionInfo.current;if(l===null)throw new Error("Unexpected missing session info");s.buffer.me={type:"full",data:C({},s.me.current)},s.idFactory=Ko(l.actor),Te!==null&&Et({flush:!1}),B()}function K(){clearTimeout(s.buffer.flushTimerID)}i.events.onMessage.subscribe(Dn),i.events.statusDidChange.subscribe(f),i.events.statusDidChange.subscribe(E),i.events.didConnect.subscribe(G),i.events.didDisconnect.subscribe(K),i.events.onLiveblocksError.subscribe(l=>{d(()=>{process.env.NODE_ENV!=="production"&&le(`Connection to websocket server closed. Reason: ${l.message} (code: ${l.code}).`),h.error.notify(l)})});let m={roomId:o.roomId,getNode:l=>s.nodes.get(l),addNode:(l,p)=>void s.nodes.set(l,p),deleteNode:l=>void s.nodes.delete(l),generateId:()=>`${bt()}:${s.clock++}`,generateOpId:()=>`${bt()}:${s.opClock++}`,dispatch(l,p,u){let g=s.activeBatch;if(process.env.NODE_ENV!=="production"){let _=yn("Storage mutation",this.dispatch);if(_)for(let v of l)v.opId&&T(s.opStackTraces).set(v.opId,_)}if(g){g.ops.push(...l);for(let[_,v]of u)g.updates.storageUpdates.set(_,Ne(g.updates.storageUpdates.get(_),v));g.reverseOps.unshift(...p)}else d(()=>{We(p,a),s.redoStack=[],Ot(l),X({storageUpdates:u},a)})},assertStorageIsWritable:()=>{var l;if((l=s.sessionInfo.current)!=null&&l.isReadOnly)throw new Error("Cannot write to storage with a read only user, please ensure the user has write permissions")}},h={connection:O(),status:O(),lostConnection:O(),customEvent:O(),me:O(),others:O(),error:O(),storage:O(),history:O(),storageDidLoad:O(),storageStatus:O(),ydoc:O()};function L(l){var u,g;let p=JSON.stringify(l);if(o.unstable_fallbackToHTTP&&new TextEncoder().encode(p).length>Jo&&(u=i.token)!=null&&u.raw&&o.httpSendEndpoint){if(Tn(i.token.parsed))return i.reconnect();Wo(p,i.token.raw,o.httpSendEndpoint,(g=o.polyfills)==null?void 0:g.fetch),F("Message was too large for websockets and sent over HTTP instead");return}i.send(p)}let te=new ye(s.sessionInfo,s.me,(l,p)=>l!==null?{connectionId:l.actor,id:l.userId,info:l.userInfo,presence:p,isReadOnly:l.isReadOnly}:null),ne=new ye(te,l=>l!==null?gn("Me",l):null);function w(l,p){if(l.items.length===0)throw new Error("Internal error: cannot load storage without items");s.root!==void 0?Y(l.items,p):s.root=x._fromItems(l.items,m);for(let u in s.initialStorage)s.root.get(u)===void 0&&s.root.set(u,s.initialStorage[u])}function Y(l,p){if(s.root===void 0)return;let u=new Map;for(let[v,D]of s.nodes)u.set(v,D._serialize());let g=hn(u,new Map(l)),_=me(g,!1);X(_.updates,p)}function ce(l,p){s.undoStack.length>=50&&s.undoStack.shift(),s.undoStack.push(l),He(p)}function We(l,p){s.pausedHistory!==null?s.pausedHistory.unshift(...l):ce(l,p)}function X({storageUpdates:l=new Map,presence:p=!1,others:u=[]},g){g(()=>{if(u.length>0){let _=s.others.current;for(let v of u)h.others.notify({others:_,event:v})}if(p&&h.me.notify(s.me.current),l.size>0){let _=Array.from(l.values());h.storage.notify(_)}})}function bt(){let l=s.sessionInfo.current;if(l)return l.actor;throw new Error("Internal. Tried to get connection id but connection was never open")}function me(l,p){let u={reverse:[],storageUpdates:new Map,presence:!1},g=new Set,_=l.map(v=>v.type!=="presence"&&!v.opId?P(C({},v),{opId:m.generateOpId()}):v);for(let v of _)if(v.type==="presence"){let D={type:"presence",data:{}};for(let k in v.data)D.data[k]=s.me.current[k];if(s.me.patch(v.data),s.buffer.me===null)s.buffer.me={type:"partial",data:v.data};else for(let k in v.data)s.buffer.me.data[k]=v.data[k];u.reverse.unshift(D),u.presence=!0}else{let D;if(p)D=0;else{let be=T(v.opId);process.env.NODE_ENV!=="production"&&T(s.opStackTraces).delete(be),D=s.unacknowledgedOps.delete(be)?2:1}let k=xn(v,D);if(k.modified){let be=k.modified.node._id;be&&g.has(be)||(u.storageUpdates.set(T(k.modified.node._id),Ne(u.storageUpdates.get(T(k.modified.node._id)),k.modified)),u.reverse.unshift(...k.reverse)),(v.type===2||v.type===7||v.type===4)&&g.add(T(v.id))}}return Ie(),{ops:_,reverse:u.reverse,updates:{storageUpdates:u.storageUpdates,presence:u.presence}}}function xn(l,p){if(an(l))return{modified:!1};switch(l.type){case 6:case 3:case 5:{let u=s.nodes.get(l.id);return u===void 0?{modified:!1}:u._apply(l,p===0)}case 1:{let u=s.nodes.get(l.id);return u===void 0?{modified:!1}:u.parent.type==="HasParent"&&he(u.parent.node)?u.parent.node._setChildKey(Z(l.parentKey),u,p):{modified:!1}}case 4:case 2:case 7:case 8:{if(l.parentId===void 0)return{modified:!1};let u=s.nodes.get(l.parentId);return u===void 0?{modified:!1}:u._attachChild(l,p)}}}function Pn(l,p){let u={};s.buffer.me===null&&(s.buffer.me={type:"partial",data:{}});for(let g in l){let _=l[g];_!==void 0&&(s.buffer.me.data[g]=_,u[g]=s.me.current[g])}s.me.patch(l),s.activeBatch?(p!=null&&p.addToHistory&&s.activeBatch.reverseOps.unshift({type:"presence",data:u}),s.activeBatch.updates.presence=!0):(B(),d(()=>{p!=null&&p.addToHistory&&We([{type:"presence",data:u}],a),X({presence:!0},a)}))}function Fe(l){return l.includes("room:read")&&l.includes("room:presence:write")&&!l.includes("room:write")}function Rn(l){if(l.targetActor!==void 0){let u=s.others.getUser(l.actor);s.others.setOther(l.actor,l.data);let g=s.others.getUser(l.actor);if(u===void 0&&g!==void 0)return{type:"enter",user:g}}else s.others.patchOther(l.actor,l.data);let p=s.others.getUser(l.actor);if(p)return{type:"update",updates:l.data,user:p}}function wn(l){let p=s.others.getUser(l.actor);return p?(s.others.removeConnection(l.actor),{type:"leave",user:p}):null}function Mn(l){for(let p in s.others._connections)l.users[p]===void 0&&s.others.removeConnection(Number(p));for(let p in l.users){let u=l.users[p],g=Number(p);s.others.setConnection(g,u.id,u.info,Fe(u.scopes))}return{type:"reset"}}function vt(){return s.undoStack.length>0}function gt(){return s.redoStack.length>0}function He(l){l(()=>{h.history.notify({canUndo:vt(),canRedo:gt()})})}function Un(l){s.others.setConnection(l.actor,l.id,l.info,Fe(l.scopes)),s.buffer.messages.push({type:100,data:s.me.current,targetActor:l.actor}),B();let p=s.others.getUser(l.actor);return p?{type:"enter",user:p}:void 0}function _t(l){return ae(l)?l:null}function An(l){let p=ge(l);return p===void 0?null:De(p)?_e(p.map(u=>_t(u))):_e([_t(p)])}function Nn(l,p){if(l.size===0)return;let u=[],g=Array.from(l.values()),_=me(g,!0);u.push({type:201,ops:_.ops}),X(_.updates,p),L(u)}function Dn(l){if(typeof l.data!="string")return;let p=An(l.data);if(p===null||p.length===0)return;let u={storageUpdates:new Map,others:[]};d(()=>{var g;for(let _ of p)switch(_.type){case 101:{let v=Un(_);v&&u.others.push(v);break}case 100:{let v=Rn(_);v&&u.others.push(v);break}case 103:{h.customEvent.notify({connectionId:_.actor,event:_.event});break}case 102:{let v=wn(_);v&&u.others.push(v);break}case 300:{h.ydoc.notify(_.update);break}case 104:{u.others.push(Mn(_));break}case 200:{let v=new Map(s.unacknowledgedOps);w(_,a),Nn(v,a),Ce==null||Ce(),Ie(),h.storageDidLoad.notify();break}case 201:{let v=me(_.ops,!1);for(let[D,k]of v.updates.storageUpdates)u.storageUpdates.set(D,Ne(u.storageUpdates.get(D),k));break}case 299:{if(ve("Storage mutation rejection error",_.reason),process.env.NODE_ENV!=="production"){let v=new Set;for(let D of _.opIds){let k=(g=s.opStackTraces)==null?void 0:g.get(D);k&&v.add(k)}throw v.size>0&&Ht("The following function calls caused the rejected storage mutations:",`
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var Xn=Object.defineProperty,qn=Object.defineProperties;var Zn=Object.getOwnPropertyDescriptors;var Rt=Object.getOwnPropertySymbols;var Qn=Object.prototype.hasOwnProperty,eo=Object.prototype.propertyIsEnumerable;var wt=(t,o,e)=>o in t?Xn(t,o,{enumerable:!0,configurable:!0,writable:!0,value:e}):t[o]=e,C=(t,o)=>{for(var e in o||(o={}))Qn.call(o,e)&&wt(t,e,o[e]);if(Rt)for(var e of Rt(o))eo.call(o,e)&&wt(t,e,o[e]);return t},P=(t,o)=>qn(t,Zn(o));var j=(t,o,e)=>new Promise((n,r)=>{var i=d=>{try{a(e.next(d))}catch(c){r(c)}},s=d=>{try{a(e.throw(d))}catch(c){r(c)}},a=d=>d.done?n(d.value):Promise.resolve(d.value).then(i,s);a((e=e.apply(t,o)).next())});function O(){let t=new Set,o=new Set,e=null;function n(){e=[]}function r(){if(e!==null){for(let b of e)c(b);e=null}}function i(b){return o.add(b),()=>o.delete(b)}function s(b){return t.add(b),()=>t.delete(b)}function a(b){return j(this,null,function*(){let E;return new Promise(G=>{E=i(K=>{(b===void 0||b(K))&&G(K)})}).finally(()=>E==null?void 0:E())})}function d(b){e!==null?e.push(b):c(b)}function c(b){t.forEach(E=>E(b)),t.clear(),o.forEach(E=>E(b))}function f(){t.clear(),o.clear()}function y(){return t.size+o.size}return{notify:d,subscribe:i,subscribeOnce:s,clear:f,count:y,waitUntil:a,pause:n,unpause:r,observable:{subscribe:i,subscribeOnce:s,waitUntil:a}}}var Mt=!1;function Ut(t){Mt=t}function W(t,o){if(process.env.NODE_ENV==="production"||typeof window=="undefined")return;let e=P(C({},t),{source:"liveblocks-devtools-client"});(o!=null&&o.force||Mt)&&window.postMessage(e,"*")}var At=O();process.env.NODE_ENV!=="production"&&typeof window!="undefined"&&window.addEventListener("message",t=>{var o;t.source===window&&((o=t.data)==null?void 0:o.source)==="liveblocks-devtools-panel"&&At.notify(t.data)});var Ge=At.observable;var jt="1.1.1-dual5",Nt=!1;function Jt(t){process.env.NODE_ENV==="production"||typeof window=="undefined"||Nt||(Nt=!0,Ge.subscribe(o=>{switch(o.msg){case"connect":{Ut(!0);for(let e of t())W({msg:"room::available",roomId:e,clientVersion:jt});break}}}),W({msg:"wake-up-devtools"},{force:!0}))}var Ye=new Map;function qe(t){var e;let o=(e=Ye.get(t))!=null?e:[];Ye.delete(t);for(let n of o)n()}function to(t){qe(t.id),so(t),Ye.set(t.id,[t.events.status.subscribe(()=>no(t)),t.events.storageDidLoad.subscribeOnce(()=>Dt(t)),t.events.storage.subscribe(()=>Dt(t)),t.events.me.subscribe(()=>oo(t)),t.events.others.subscribe(()=>ro(t))])}function no(t){W({msg:"room::sync::partial",roomId:t.id,status:t.getStatus()})}function Dt(t){let o=t.getStorageSnapshot();o&&W({msg:"room::sync::partial",roomId:t.id,storage:o.toTreeNode("root").payload})}function oo(t){let o=t.__internal.getSelf_forDevTools();o&&W({msg:"room::sync::partial",roomId:t.id,me:o})}function ro(t){let o=t.__internal.getOthers_forDevTools();o&&W({msg:"room::sync::partial",roomId:t.id,others:o})}function so(t){var r;let o=t.getStorageSnapshot(),e=t.__internal.getSelf_forDevTools(),n=t.__internal.getOthers_forDevTools();W({msg:"room::sync::full",roomId:t.id,status:t.getStatus(),storage:(r=o==null?void 0:o.toTreeNode("root").payload)!=null?r:null,me:e,others:n})}var Xe=new Map;function Kt(t){let o=Xe.get(t);Xe.delete(t),o&&o()}function Bt(t,o){process.env.NODE_ENV==="production"||typeof window=="undefined"||(W({msg:"room::available",roomId:t,clientVersion:jt}),Kt(t),Xe.set(t,Ge.subscribe(e=>{switch(e.msg){case"room::subscribe":{e.roomId===t&&to(o);break}case"room::unsubscribe":{e.roomId===t&&qe(t);break}}})))}function zt(t){process.env.NODE_ENV==="production"||typeof window=="undefined"||(qe(t),Kt(t),W({msg:"room::unavailable",roomId:t}))}var Vt="background:#0e0d12;border-radius:9999px;color:#fff;padding:3px 7px;font-family:sans-serif;font-weight:600;",io="font-weight:600";function Wt(t){return typeof window=="undefined"||process.env.NODE_ENV==="test"?console[t]:(o,...e)=>console[t]("%cLiveblocks",Vt,o,...e)}var F=Wt("warn"),le=Wt("error");function Ft(t){return typeof window=="undefined"||process.env.NODE_ENV==="test"?console[t]:(o,e,...n)=>console[t](`%cLiveblocks%c ${o}`,Vt,io,e,...n)}var Ht=Ft("warn"),ve=Ft("error");var $t=new Set;function Gt(t,o=t){process.env.NODE_ENV!=="production"&&($t.has(o)||($t.add(o),ve("Deprecation warning",t)))}function Ze(t,o,e=o){process.env.NODE_ENV!=="production"&&t&&Gt(o,e)}function Yt(t){if(process.env.NODE_ENV!=="production"){let o=new Error(t);throw o.name="Usage error",ve("Usage error",t),o}}function ao(t,o){process.env.NODE_ENV!=="production"&&t&&Yt(o)}function U(t,o){throw new Error(o)}function Xt(t,o){if(process.env.NODE_ENV!=="production"&&!t){let e=new Error(o);throw e.name="Assertion failure",e}}function T(t,o="Expected value to be non-nullable"){return Xt(t!=null,o),t}function co(t,o){if(t===o)return[0,0];let e=t.split("."),n=o.split("."),r=Math.min(e.length,n.length),i=0;for(;i<r&&e[i]===n[i];i++);let s=e.length-i,a=n.length-i;return[s,a]}function lo(t,o){let e=t.split(".");if(o<1||o>e.length+1)throw new Error("Invalid number of levels");let n=[];o>e.length&&n.push("*");for(let r=e.length-o+1;r<e.length;r++){let i=e.slice(0,r);i.length>0&&n.push(i.join(".")+".*")}return n.push(t),n}var Qe=class{constructor(o){this.curr=o}get current(){return this.curr}allowPatching(o){let e=this,n=!0,r=P(C({},this.curr),{patch(i){if(n){e.curr=Object.assign({},e.curr,i);for(let s of Object.entries(i)){let[a,d]=s;a!=="patch"&&(this[a]=d)}}else throw new Error("Can no longer patch stale context")}});o(r),n=!1}};var po=1,ke=class{get initialState(){let o=this.states.values()[Symbol.iterator]().next();if(o.done)throw new Error("No states defined yet");return o.value}get currentState(){if(this.currentStateOrNull===null)throw this.runningState===0?new Error("Not started yet"):new Error("Already stopped");return this.currentStateOrNull}start(){if(this.runningState!==0)throw new Error("State machine has already started");return this.runningState=1,this.currentStateOrNull=this.initialState,this.enter(null),this}stop(){if(this.runningState!==1)throw new Error("Cannot stop a state machine that hasn't started yet");this.exit(null),this.runningState=2,this.currentStateOrNull=null}constructor(o){this.id=po++,this.runningState=0,this.currentStateOrNull=null,this.states=new Set,this.enterFns=new Map,this.cleanupStack=[],this.knownEventTypes=new Set,this.allowedTransitions=new Map,this.currentContext=new Qe(o),this.eventHub={didReceiveEvent:O(),willTransition:O(),didIgnoreEvent:O(),willExitState:O(),didEnterState:O()},this.events={didReceiveEvent:this.eventHub.didReceiveEvent.observable,willTransition:this.eventHub.willTransition.observable,didIgnoreEvent:this.eventHub.didIgnoreEvent.observable,willExitState:this.eventHub.willExitState.observable,didEnterState:this.eventHub.didEnterState.observable}}get context(){return this.currentContext.current}addState(o){if(this.runningState!==0)throw new Error("Already started");return this.states.add(o),this}onEnter(o,e){if(this.runningState!==0)throw new Error("Already started");if(this.enterFns.has(o))throw new Error(`enter/exit function for ${o} already exists`);return this.enterFns.set(o,e),this}onEnterAsync(o,e,n,r){return this.onEnter(o,()=>{let i=!1;return e(this.currentContext.current).then(s=>{i||this.transition({type:"ASYNC_OK",data:s},n)},s=>{i||this.transition({type:"ASYNC_ERROR",reason:s},r)}),()=>{i=!0}})}getStatesMatching(o){let e=[];if(o==="*")for(let n of this.states)e.push(n);else if(o.endsWith(".*")){let n=o.slice(0,-1);for(let r of this.states)r.startsWith(n)&&e.push(r)}else{let n=o;this.states.has(n)&&e.push(n)}if(e.length===0)throw new Error(`No states match ${JSON.stringify(o)}`);return e}addTransitions(o,e){if(this.runningState!==0)throw new Error("Already started");for(let n of this.getStatesMatching(o)){let r=this.allowedTransitions.get(n);r===void 0&&(r=new Map,this.allowedTransitions.set(n,r));for(let[i,s]of Object.entries(e)){if(r.has(i))throw new Error(`Trying to set transition "${i}" on "${n}" (via "${o}"), but a transition already exists there.`);let a=s;if(this.knownEventTypes.add(i),a!==void 0){let d=typeof a=="function"?a:()=>a;r.set(i,d)}}}return this}addTimedTransition(o,e,n){return this.onEnter(o,()=>{let r=typeof e=="function"?e(this.currentContext.current):e,i=setTimeout(()=>{this.transition({type:"TIMER"},n)},r);return()=>{clearTimeout(i)}})}getTargetFn(o){var e;return(e=this.allowedTransitions.get(this.currentState))==null?void 0:e.get(o)}exit(o){this.eventHub.willExitState.notify(this.currentState),this.currentContext.allowPatching(e=>{var n;o=o!=null?o:this.cleanupStack.length;for(let r=0;r<o;r++)(n=this.cleanupStack.pop())==null||n(e)})}enter(o){let e=lo(this.currentState,o!=null?o:this.currentState.split(".").length+1);this.currentContext.allowPatching(n=>{for(let r of e){let i=this.enterFns.get(r),s=i==null?void 0:i(n);typeof s=="function"?this.cleanupStack.push(s):this.cleanupStack.push(null)}}),this.eventHub.didEnterState.notify(this.currentState)}send(o){if(!this.knownEventTypes.has(o.type))throw new Error(`Invalid event ${JSON.stringify(o.type)}`);if(this.runningState===2)return;let e=this.getTargetFn(o.type);if(e!==void 0)return this.transition(o,e);this.eventHub.didIgnoreEvent.notify(o)}transition(o,e){this.eventHub.didReceiveEvent.notify(o);let n=this.currentState,i=(typeof e=="function"?e:()=>e)(o,this.currentContext.current),s,a;if(i===null){this.eventHub.didIgnoreEvent.notify(o);return}if(typeof i=="string"?s=i:(s=i.target,a=Array.isArray(i.effect)?i.effect:[i.effect]),!this.states.has(s))throw new Error(`Invalid next state name: ${JSON.stringify(s)}`);this.eventHub.willTransition.notify({from:n,to:s});let[d,c]=co(this.currentState,s);if(d>0&&this.exit(d),this.currentStateOrNull=s,a!==void 0){let f=a;this.currentContext.allowPatching(y=>{for(let b of f)typeof b=="function"?b(y,o):y.patch(b)})}c>0&&this.enter(c)}};function A(t){return t!==null&&typeof t=="object"&&Object.prototype.toString.call(t)==="[object Object]"}function qt(t){let o={};for(let[e,n]of t)o[e]=n;return o}function et(t){return Object.entries(t)}function ge(t){try{return JSON.parse(t)}catch(o){return}}function tt(t){try{let o=t.replace(/-/g,"+").replace(/_/g,"/");return decodeURIComponent(atob(o).split("").map(function(n){return"%"+("00"+n.charCodeAt(0).toString(16)).slice(-2)}).join(""))}catch(o){return atob(t)}}function _e(t){return t.filter(o=>o!=null)}function Oe(t){let o=C({},t);return Object.keys(t).forEach(e=>{let n=e;o[n]===void 0&&delete o[n]}),o}function xe(t,o,e="Timed out"){return j(this,null,function*(){let n,r=new Promise((i,s)=>{n=setTimeout(()=>{s(new Error(e))},o)});return Promise.race([t,r]).finally(()=>clearTimeout(n))})}function rt(t){switch(t){case"connecting":return"connecting";case"connected":return"open";case"reconnecting":return"unavailable";case"disconnected":return"failed";case"initial":return"closed";default:return"closed"}}function nn(t){let o=t.currentState;switch(o){case"@ok.connected":case"@ok.awaiting-pong":return"connected";case"@idle.initial":return"initial";case"@auth.busy":case"@auth.backoff":case"@connecting.busy":case"@connecting.backoff":return t.context.successCount>0?"reconnecting":"connecting";case"@idle.failed":return"disconnected";default:return U(o,"Unknown state")}}var on=[250,500,1e3,2e3,4e3,8e3,1e4],Ee=on[0]-1,uo=[2e3,3e4,6e4,3e5],fo=3e4,ho=2e3,yo=1e4,mo=1e4,q=class extends Error{constructor(o){super(o)}},ot=class extends Error{constructor(e,n){super(e);this.code=n}};function rn(t,o=on){var e;return(e=o.find(n=>n>t))!=null?e:o[o.length-1]}function pe(t){t.patch({backoffDelay:rn(t.backoffDelay)})}function Zt(t){t.patch({backoffDelay:rn(t.backoffDelay,uo)})}function Qt(t){t.patch({successCount:0})}function ue(t,o){let e=t===2?le:t===1?F:()=>{};return()=>{e(o)}}function en(t){let o="Connection to Liveblocks websocket server";return e=>{t instanceof Error?F(`${o} could not be established. ${String(t)}`):F(st(t)?`${o} closed prematurely (code: ${t.code}). Retrying in ${e.backoffDelay}ms.`:`${o} could not be established.`)}}function nt(t){return o=>{F(`Connection to Liveblocks websocket server closed (code: ${t.code}). Retrying in ${o.backoffDelay}ms.`)}}var To=ue(1,"Connection to WebSocket closed permanently. Won't retry.");function st(t){return!(t instanceof Error)&&t.type==="close"}function tn(t){return st(t)&&t.code>=4e3&&t.code<4100}function bo(t){let o=new Date().getTime();function e(...r){F(`${((new Date().getTime()-o)/1e3).toFixed(2)} [FSM #${t.id}]`,...r)}let n=[t.events.didReceiveEvent.subscribe(r=>e(`Event ${r.type}`)),t.events.willTransition.subscribe(({from:r,to:i})=>e("Transitioning",r,"\u2192",i)),t.events.didIgnoreEvent.subscribe(r=>e("Ignored event",r.type,r,"(current state won't handle it)"))];return()=>{for(let r of n)r()}}function vo(t){let o=O(),e=O(),n=O(),r=null,i=t.events.didEnterState.subscribe(()=>{let s=nn(t);s!==r&&o.notify(s),r==="connected"&&s!=="connected"?n.notify():r!=="connected"&&s==="connected"&&e.notify(),r=s});return{statusDidChange:o.observable,didConnect:e.observable,didDisconnect:n.observable,unsubscribe:i}}var Pe=t=>o=>o.patch(t);function go(t,o){let e=O();e.pause();let n=O(),r={successCount:0,token:null,socket:null,backoffDelay:Ee},i=new ke(r).addState("@idle.initial").addState("@idle.failed").addState("@auth.busy").addState("@auth.backoff").addState("@connecting.busy").addState("@connecting.backoff").addState("@ok.connected").addState("@ok.awaiting-pong");i.addTransitions("*",{RECONNECT:{target:"@auth.backoff",effect:[pe,Qt]},DISCONNECT:"@idle.initial"}),i.onEnter("@idle.*",Qt).addTransitions("@idle.*",{CONNECT:(m,h)=>h.token!==null?"@connecting.busy":"@auth.busy"}),i.addTransitions("@auth.backoff",{NAVIGATOR_ONLINE:{target:"@auth.busy",effect:Pe({backoffDelay:Ee})}}).addTimedTransition("@auth.backoff",m=>m.backoffDelay,"@auth.busy").onEnterAsync("@auth.busy",()=>xe(t.authenticate(),yo),m=>({target:"@connecting.busy",effect:Pe({token:m.data,backoffDelay:Ee})}),m=>m.reason instanceof q?{target:"@idle.failed",effect:ue(2,m.reason.message)}:{target:"@auth.backoff",effect:[pe,ue(2,`Authentication failed: ${m.reason instanceof Error?m.reason.message:String(m.reason)}`)]});let s=m=>i.send({type:"EXPLICIT_SOCKET_ERROR",event:m}),a=m=>i.send({type:"EXPLICIT_SOCKET_CLOSE",event:m}),d=m=>m.data==="pong"?i.send({type:"PONG"}):e.notify(m);function c(m){m&&(m.removeEventListener("error",s),m.removeEventListener("close",a),m.removeEventListener("message",d),m.close())}i.addTransitions("@connecting.backoff",{NAVIGATOR_ONLINE:{target:"@connecting.busy",effect:Pe({backoffDelay:Ee})}}).addTimedTransition("@connecting.backoff",m=>m.backoffDelay,"@connecting.busy").onEnterAsync("@connecting.busy",m=>j(this,null,function*(){let h=null,L=new Promise((te,ne)=>{if(m.token===null)throw new Error("No auth token");let w=t.createSocket(m.token);function Y(ce){h=ce,w.removeEventListener("message",d),ne(ce)}w.addEventListener("message",d),w.addEventListener("error",Y),w.addEventListener("close",Y),w.addEventListener("open",()=>{w.addEventListener("error",s),w.addEventListener("close",a),te([w,()=>{w.removeEventListener("error",Y),w.removeEventListener("close",Y)}])})});return xe(L,mo).then(([te,ne])=>{if(ne(),h)throw h;return te})}),m=>({target:"@ok.connected",effect:Pe({socket:m.data,backoffDelay:Ee})}),m=>{let h=m.reason;return h instanceof q?{target:"@idle.failed",effect:ue(2,h.message)}:st(h)&&h.code===4999?{target:"@idle.failed",effect:ue(2,h.reason)}:tn(h)&&h.code!==4001?{target:"@connecting.backoff",effect:[Zt,en(h)]}:{target:"@auth.backoff",effect:[pe,en(h)]}});let f={target:"@ok.awaiting-pong",effect:m=>{var h;(h=m.socket)==null||h.send("ping")}};if(i.addTimedTransition("@ok.connected",fo,f).addTransitions("@ok.connected",{NAVIGATOR_OFFLINE:f,WINDOW_GOT_FOCUS:f}),i.onEnter("@ok.*",m=>{m.patch({successCount:m.successCount+1});let h=setTimeout(e.unpause,0);return L=>{c(L.socket),L.patch({socket:null}),clearTimeout(h),e.pause()}}).addTransitions("@ok.awaiting-pong",{PONG:"@ok.connected"}).addTimedTransition("@ok.awaiting-pong",ho,{target:"@connecting.busy",effect:ue(1,"Received no pong from server, assume implicit connection loss.")}).addTransitions("@ok.*",{EXPLICIT_SOCKET_ERROR:(m,h)=>{var L;return((L=h.socket)==null?void 0:L.readyState)===1?null:{target:"@connecting.backoff",effect:pe}},EXPLICIT_SOCKET_CLOSE:m=>m.event.code===4999?{target:"@idle.failed",effect:To}:m.event.code===4001?{target:"@auth.backoff",effect:[pe,nt(m.event)]}:tn(m.event)?{target:"@connecting.backoff",effect:[Zt,nt(m.event),()=>{let h=new ot(m.event.reason,m.event.code);n.notify(h)}]}:{target:"@connecting.backoff",effect:[pe,nt(m.event)]}}),typeof document!="undefined"){let m=typeof document!="undefined"?document:void 0,h=typeof window!="undefined"?window:void 0,L=h!=null?h:m;i.onEnter("*",te=>{function ne(){i.send({type:"NAVIGATOR_OFFLINE"})}function w(){i.send({type:"NAVIGATOR_ONLINE"})}function Y(){(m==null?void 0:m.visibilityState)==="visible"&&i.send({type:"WINDOW_GOT_FOCUS"})}return h==null||h.addEventListener("online",w),h==null||h.addEventListener("offline",ne),L==null||L.addEventListener("visibilitychange",Y),()=>{L==null||L.removeEventListener("visibilitychange",Y),h==null||h.removeEventListener("online",w),h==null||h.removeEventListener("offline",ne),c(te.socket)}})}let y=[],{statusDidChange:b,didConnect:E,didDisconnect:G,unsubscribe:K}=vo(i);return y.push(K),o&&y.push(bo(i)),i.start(),{machine:i,cleanups:y,events:{statusDidChange:b,didConnect:E,didDisconnect:G,onMessage:e.observable,onLiveblocksError:n.observable}}}var Re=class{constructor(o,e=!1){let{machine:n,events:r,cleanups:i}=go(o,e);this.machine=n,this.events=r,this.cleanups=i}getLegacyStatus(){return rt(this.getStatus())}getStatus(){try{return nn(this.machine)}catch(o){return"initial"}}get token(){return this.machine.context.token}connect(){this.machine.send({type:"CONNECT"})}reconnect(){this.machine.send({type:"RECONNECT"})}disconnect(){this.machine.send({type:"DISCONNECT"})}destroy(){this.machine.stop();let o;for(;o=this.cleanups.pop();)o()}send(o){var n;let e=(n=this.machine.context)==null?void 0:n.socket;e===null?F("Cannot send: not connected yet",o):e.readyState!==1?F("Cannot send: WebSocket no longer open",o):e.send(o)}_privateSendMachineEvent(o){this.machine.send(o)}};var sn=at(0),we=at(1),_o=sn+at(-1);function at(t){let o=32+(t<0?95+t:t);if(o<32||o>126)throw new Error(`Invalid n value: ${t}`);return String.fromCharCode(o)}function z(t,o){return t!==void 0&&o!==void 0?So(t,o):t!==void 0?Eo(t):o!==void 0?Oo(o):we}function Oo(t){let o=t.length-1;for(let e=0;e<=o;e++){let n=t.charCodeAt(e);if(!(n<=32))return e===o?n===32+1?t.substring(0,e)+_o:t.substring(0,e)+String.fromCharCode(n-1):t.substring(0,e+1)}return we}function Eo(t){for(let o=0;o<=t.length-1;o++){let e=t.charCodeAt(o);if(!(e>=126))return t.substring(0,o)+String.fromCharCode(e+1)}return t+we}function So(t,o){if(t<o)return it(t,o);if(t>o)return it(o,t);throw new Error("Cannot compute value between two equal positions")}function it(t,o){let e=0,n=t.length,r=o.length;for(;;){let i=e<n?t.charCodeAt(e):32,s=e<r?o.charCodeAt(e):126;if(i===s){e++;continue}if(s-i===1){let a=t.substring(0,e+1),d=t.substring(e+1);return a+it(d,"")}else return Co(t,e)+String.fromCharCode(s+i>>1)}}function Co(t,o){return o<t.length?t.substring(0,o):t+sn.repeat(o-t.length)}var Io=32+1;function Lo(t){if(t==="")return!1;let o=t.length-1,e=t.charCodeAt(o);if(e<Io||e>126)return!1;for(let n=0;n<o;n++){let r=t.charCodeAt(n);if(r<32||r>126)return!1}return!0}function ko(t){let o=[];for(let e=0;e<t.length;e++){let n=t.charCodeAt(e);o.push(n<32?32:n>126?126:n)}for(;o.length>0&&o[o.length-1]===32;)o.length--;return o.length>0?String.fromCharCode(...o):we}function Z(t){return Lo(t)?t:ko(t)}var dt=(c=>(c[c.INIT=0]="INIT",c[c.SET_PARENT_KEY=1]="SET_PARENT_KEY",c[c.CREATE_LIST=2]="CREATE_LIST",c[c.UPDATE_OBJECT=3]="UPDATE_OBJECT",c[c.CREATE_OBJECT=4]="CREATE_OBJECT",c[c.DELETE_CRDT=5]="DELETE_CRDT",c[c.DELETE_OBJECT_KEY=6]="DELETE_OBJECT_KEY",c[c.CREATE_MAP=7]="CREATE_MAP",c[c.CREATE_REGISTER=8]="CREATE_REGISTER",c))(dt||{});function an(t){return t.type===5&&t.id==="ACK"}function dn(t,o,e=Z(o)){return Object.freeze({type:"HasParent",node:t,key:o,pos:e})}var cn=Object.freeze({type:"NoParent"});function xo(t,o=Z(t)){return Object.freeze({type:"Orphaned",oldKey:t,oldPos:o})}var H=class{constructor(){this._parent=cn}_getParentKeyOrThrow(){switch(this.parent.type){case"HasParent":return this.parent.key;case"NoParent":throw new Error("Parent key is missing");case"Orphaned":return this.parent.oldKey;default:return U(this.parent,"Unknown state")}}get _parentPos(){switch(this.parent.type){case"HasParent":return this.parent.pos;case"NoParent":throw new Error("Parent key is missing");case"Orphaned":return this.parent.oldPos;default:return U(this.parent,"Unknown state")}}get _pool(){return this.__pool}get roomId(){return this.__pool?this.__pool.roomId:null}get _id(){return this.__id}get parent(){return this._parent}get _parentKey(){switch(this.parent.type){case"HasParent":return this.parent.key;case"NoParent":return null;case"Orphaned":return this.parent.oldKey;default:return U(this.parent,"Unknown state")}}_apply(o,e){switch(o.type){case 5:return this.parent.type==="HasParent"?this.parent.node._detachChild(this):{modified:!1}}return{modified:!1}}_setParentLink(o,e){switch(this.parent.type){case"HasParent":if(this.parent.node!==o)throw new Error("Cannot set parent: node already has a parent");this._parent=dn(o,e);return;case"Orphaned":case"NoParent":{this._parent=dn(o,e);return}default:return U(this.parent,"Unknown state")}}_attach(o,e){if(this.__id||this.__pool)throw new Error("Cannot attach node: already attached");e.addNode(o,this),this.__id=o,this.__pool=e}_detach(){switch(this.__pool&&this.__id&&this.__pool.deleteNode(this.__id),this.parent.type){case"HasParent":{this._parent=xo(this.parent.key,this.parent.pos);break}case"NoParent":{this._parent=cn;break}case"Orphaned":break;default:U(this.parent,"Unknown state")}this.__pool=void 0}invalidate(){(this._cachedImmutable!==void 0||this._cachedTreeNode!==void 0)&&(this._cachedImmutable=void 0,this._cachedTreeNode=void 0,this.parent.type==="HasParent"&&this.parent.node.invalidate())}toTreeNode(o){return(this._cachedTreeNode===void 0||this._cachedTreeNodeKey!==o)&&(this._cachedTreeNodeKey=o,this._cachedTreeNode=this._toTreeNode(o)),this._cachedTreeNode}toImmutable(){return this._cachedImmutable===void 0&&(this._cachedImmutable=this._toImmutable()),this._cachedImmutable}};var ct=(r=>(r[r.OBJECT=0]="OBJECT",r[r.LIST=1]="LIST",r[r.MAP=2]="MAP",r[r.REGISTER=3]="REGISTER",r))(ct||{});function lt(t){return t.type===0&&!ln(t)}function ln(t){return t.parentId!==void 0&&t.parentKey!==void 0}function oe(t=7){let o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789,./;[]~!@#$%&*()_+=-",e=o.length;return Array.from({length:t},()=>o.charAt(Math.floor(Math.random()*e))).join("")}var J=class t extends H{constructor(e){super();this._data=e}get data(){return this._data}static _deserialize([e,n],r,i){let s=new t(n.data);return s._attach(e,i),s}_toOps(e,n,r){if(this._id===void 0)throw new Error("Cannot serialize register if parentId or parentKey is undefined");return[{type:8,opId:r==null?void 0:r.generateOpId(),id:this._id,parentId:e,parentKey:n,data:this.data}]}_serialize(){if(this.parent.type!=="HasParent")throw new Error("Cannot serialize LiveRegister if parent is missing");return{type:3,parentId:T(this.parent.node._id,"Parent node expected to have ID"),parentKey:this.parent.key,data:this.data}}_attachChild(e){throw new Error("Method not implemented.")}_detachChild(e){throw new Error("Method not implemented.")}_apply(e,n){return super._apply(e,n)}_toTreeNode(e){var n;return{type:"Json",id:(n=this._id)!=null?n:oe(),key:e,payload:this._data}}_toImmutable(){return this._data}};function Po(t,o){let e=t._parentPos,n=o._parentPos;return e===n?0:e<n?-1:1}var M=class t extends H{constructor(e=[]){super();this._items=[],this._implicitlyDeletedItems=new WeakSet,this._unacknowledgedSets=new Map;let n;for(let r of e){let i=z(n),s=re(r);s._setParentLink(this,i),this._items.push(s),n=i}}static _deserialize([e],n,r){let i=new t;i._attach(e,r);let s=n.get(e);if(s===void 0)return i;for(let[a,d]of s){let c=Ue([a,d],n,r);c._setParentLink(i,d.parentKey),i._insertAndSort(c)}return i}_toOps(e,n,r){if(this._id===void 0)throw new Error("Cannot serialize item is not attached");let i=[],s={id:this._id,opId:r==null?void 0:r.generateOpId(),type:2,parentId:e,parentKey:n};i.push(s);for(let a of this._items)i.push(...a._toOps(this._id,a._getParentKeyOrThrow(),r));return i}_insertAndSort(e){this._items.push(e),this._sortItems()}_sortItems(){this._items.sort(Po),this.invalidate()}_indexOfPosition(e){return this._items.findIndex(n=>n._getParentKeyOrThrow()===e)}_attach(e,n){super._attach(e,n);for(let r of this._items)r._attach(n.generateId(),n)}_detach(){super._detach();for(let e of this._items)e._detach()}_applySetRemote(e){if(this._pool===void 0)throw new Error("Can't attach child if managed pool is not present");let{id:n,parentKey:r}=e,i=ie(e);i._attach(n,this._pool),i._setParentLink(this,r);let s=e.deletedId,a=this._indexOfPosition(r);if(a!==-1){let d=this._items[a];if(d._id===s)return d._detach(),this._items[a]=i,{modified:S(this,[fe(a,i)]),reverse:[]};{this._implicitlyDeletedItems.add(d),this._items[a]=i;let c=[fe(a,i)],f=this._detachItemAssociatedToSetOperation(e.deletedId);return f&&c.push(f),{modified:S(this,c),reverse:[]}}}else{let d=[],c=this._detachItemAssociatedToSetOperation(e.deletedId);return c&&d.push(c),this._insertAndSort(i),d.push($(this._indexOfPosition(r),i)),{reverse:[],modified:S(this,d)}}}_applySetAck(e){if(this._pool===void 0)throw new Error("Can't attach child if managed pool is not present");let n=[],r=this._detachItemAssociatedToSetOperation(e.deletedId);r&&n.push(r);let i=this._unacknowledgedSets.get(e.parentKey);if(i!==void 0){if(i!==e.opId)return n.length===0?{modified:!1}:{modified:S(this,n),reverse:[]};this._unacknowledgedSets.delete(e.parentKey)}let s=this._indexOfPosition(e.parentKey),a=this._items.find(d=>d._id===e.id);if(a!==void 0){if(a._parentKey===e.parentKey)return{modified:n.length>0?S(this,n):!1,reverse:[]};s!==-1&&(this._implicitlyDeletedItems.add(this._items[s]),this._items.splice(s,1),n.push(Me(s)));let d=this._items.indexOf(a);a._setParentLink(this,e.parentKey),this._sortItems();let c=this._items.indexOf(a);return c!==d&&n.push(se(d,c,a)),{modified:n.length>0?S(this,n):!1,reverse:[]}}else{let d=this._pool.getNode(e.id);if(d&&this._implicitlyDeletedItems.has(d)){d._setParentLink(this,e.parentKey),this._implicitlyDeletedItems.delete(d),this._insertAndSort(d);let c=this._items.indexOf(d);return{modified:S(this,[s===-1?$(c,d):fe(c,d),...n]),reverse:[]}}else{s!==-1&&this._items.splice(s,1);let{newItem:c,newIndex:f}=this._createAttachItemAndSort(e,e.parentKey);return{modified:S(this,[s===-1?$(f,c):fe(f,c),...n]),reverse:[]}}}}_detachItemAssociatedToSetOperation(e){if(e===void 0||this._pool===void 0)return null;let n=this._pool.getNode(e);if(n===void 0)return null;let r=this._detachChild(n);return r.modified===!1?null:r.modified.updates[0]}_applyRemoteInsert(e){if(this._pool===void 0)throw new Error("Can't attach child if managed pool is not present");let n=Z(e.parentKey),r=this._indexOfPosition(n);r!==-1&&this._shiftItemPosition(r,n);let{newItem:i,newIndex:s}=this._createAttachItemAndSort(e,n);return{modified:S(this,[$(s,i)]),reverse:[]}}_applyInsertAck(e){let n=this._items.find(s=>s._id===e.id),r=Z(e.parentKey),i=this._indexOfPosition(r);if(n){if(n._parentKey===r)return{modified:!1};{let s=this._items.indexOf(n);i!==-1&&this._shiftItemPosition(i,r),n._setParentLink(this,r),this._sortItems();let a=this._indexOfPosition(r);return a===s?{modified:!1}:{modified:S(this,[se(s,a,n)]),reverse:[]}}}else{let s=T(this._pool).getNode(e.id);if(s&&this._implicitlyDeletedItems.has(s)){s._setParentLink(this,r),this._implicitlyDeletedItems.delete(s),this._insertAndSort(s);let a=this._indexOfPosition(r);return{modified:S(this,[$(a,s)]),reverse:[]}}else{i!==-1&&this._shiftItemPosition(i,r);let{newItem:a,newIndex:d}=this._createAttachItemAndSort(e,r);return{modified:S(this,[$(d,a)]),reverse:[]}}}}_applyInsertUndoRedo(e){var c,f,y;let{id:n,parentKey:r}=e,i=ie(e);if(((c=this._pool)==null?void 0:c.getNode(n))!==void 0)return{modified:!1};i._attach(n,T(this._pool)),i._setParentLink(this,r);let s=this._indexOfPosition(r),a=r;if(s!==-1){let b=(f=this._items[s])==null?void 0:f._parentPos,E=(y=this._items[s+1])==null?void 0:y._parentPos;a=z(b,E),i._setParentLink(this,a)}this._insertAndSort(i);let d=this._indexOfPosition(a);return{modified:S(this,[$(d,i)]),reverse:[{type:5,id:n}]}}_applySetUndoRedo(e){var d;let{id:n,parentKey:r}=e,i=ie(e);if(((d=this._pool)==null?void 0:d.getNode(n))!==void 0)return{modified:!1};this._unacknowledgedSets.set(r,T(e.opId));let s=this._indexOfPosition(r);i._attach(n,T(this._pool)),i._setParentLink(this,r);let a=r;if(s!==-1){let c=this._items[s];c._detach(),this._items[s]=i;let f=pt(c._toOps(T(this._id),r,this._pool),e.id),y=[fe(s,i)],b=this._detachItemAssociatedToSetOperation(e.deletedId);return b&&y.push(b),{modified:S(this,y),reverse:f}}else{this._insertAndSort(i),this._detachItemAssociatedToSetOperation(e.deletedId);let c=this._indexOfPosition(a);return{reverse:[{type:5,id:n}],modified:S(this,[$(c,i)])}}}_attachChild(e,n){if(this._pool===void 0)throw new Error("Can't attach child if managed pool is not present");let r;return e.intent==="set"?n===1?r=this._applySetRemote(e):n===2?r=this._applySetAck(e):r=this._applySetUndoRedo(e):n===1?r=this._applyRemoteInsert(e):n===2?r=this._applyInsertAck(e):r=this._applyInsertUndoRedo(e),r.modified!==!1&&this.invalidate(),r}_detachChild(e){if(e){let n=T(e._parentKey),r=e._toOps(T(this._id),n,this._pool),i=this._items.indexOf(e);return i===-1?{modified:!1}:(this._items.splice(i,1),this.invalidate(),e._detach(),{modified:S(this,[Me(i)]),reverse:r})}return{modified:!1}}_applySetChildKeyRemote(e,n){var s;if(this._implicitlyDeletedItems.has(n)){this._implicitlyDeletedItems.delete(n),n._setParentLink(this,e),this._insertAndSort(n);let a=this._items.indexOf(n);return{modified:S(this,[$(a,n)]),reverse:[]}}let r=n._parentKey;if(e===r)return{modified:!1};let i=this._indexOfPosition(e);if(i===-1){let a=this._items.indexOf(n);n._setParentLink(this,e),this._sortItems();let d=this._items.indexOf(n);return d===a?{modified:!1}:{modified:S(this,[se(a,d,n)]),reverse:[]}}else{this._items[i]._setParentLink(this,z(e,(s=this._items[i+1])==null?void 0:s._parentPos));let a=this._items.indexOf(n);n._setParentLink(this,e),this._sortItems();let d=this._items.indexOf(n);return d===a?{modified:!1}:{modified:S(this,[se(a,d,n)]),reverse:[]}}}_applySetChildKeyAck(e,n){var i,s;let r=T(n._parentKey);if(this._implicitlyDeletedItems.has(n)){let a=this._indexOfPosition(e);return this._implicitlyDeletedItems.delete(n),a!==-1&&this._items[a]._setParentLink(this,z(e,(i=this._items[a+1])==null?void 0:i._parentPos)),n._setParentLink(this,e),this._insertAndSort(n),{modified:!1}}else{if(e===r)return{modified:!1};let a=this._items.indexOf(n),d=this._indexOfPosition(e);d!==-1&&this._items[d]._setParentLink(this,z(e,(s=this._items[d+1])==null?void 0:s._parentPos)),n._setParentLink(this,e),this._sortItems();let c=this._items.indexOf(n);return a===c?{modified:!1}:{modified:S(this,[se(a,c,n)]),reverse:[]}}}_applySetChildKeyUndoRedo(e,n){var d;let r=T(n._parentKey),i=this._items.indexOf(n),s=this._indexOfPosition(e);s!==-1&&this._items[s]._setParentLink(this,z(e,(d=this._items[s+1])==null?void 0:d._parentPos)),n._setParentLink(this,e),this._sortItems();let a=this._items.indexOf(n);return i===a?{modified:!1}:{modified:S(this,[se(i,a,n)]),reverse:[{type:1,id:T(n._id),parentKey:r}]}}_setChildKey(e,n,r){return r===1?this._applySetChildKeyRemote(e,n):r===2?this._applySetChildKeyAck(e,n):this._applySetChildKeyUndoRedo(e,n)}_apply(e,n){return super._apply(e,n)}_serialize(){if(this.parent.type!=="HasParent")throw new Error("Cannot serialize LiveList if parent is missing");return{type:1,parentId:T(this.parent.node._id,"Parent node expected to have ID"),parentKey:this.parent.key}}get length(){return this._items.length}push(e){var n;return(n=this._pool)==null||n.assertStorageIsWritable(),this.insert(e,this.length)}insert(e,n){var d;if((d=this._pool)==null||d.assertStorageIsWritable(),n<0||n>this._items.length)throw new Error(`Cannot insert list item at index "${n}". index should be between 0 and ${this._items.length}`);let r=this._items[n-1]?this._items[n-1]._parentPos:void 0,i=this._items[n]?this._items[n]._parentPos:void 0,s=z(r,i),a=re(e);if(a._setParentLink(this,s),this._insertAndSort(a),this._pool&&this._id){let c=this._pool.generateId();a._attach(c,this._pool),this._pool.dispatch(a._toOps(this._id,s,this._pool),[{type:5,id:c}],new Map([[this._id,S(this,[$(n,a)])]]))}}move(e,n){var c;if((c=this._pool)==null||c.assertStorageIsWritable(),n<0)throw new Error("targetIndex cannot be less than 0");if(n>=this._items.length)throw new Error("targetIndex cannot be greater or equal than the list length");if(e<0)throw new Error("index cannot be less than 0");if(e>=this._items.length)throw new Error("index cannot be greater or equal than the list length");let r=null,i=null;e<n?(i=n===this._items.length-1?void 0:this._items[n+1]._parentPos,r=this._items[n]._parentPos):(i=this._items[n]._parentPos,r=n===0?void 0:this._items[n-1]._parentPos);let s=z(r,i),a=this._items[e],d=a._getParentKeyOrThrow();if(a._setParentLink(this,s),this._sortItems(),this._pool&&this._id){let f=new Map([[this._id,S(this,[se(e,n,a)])]]);this._pool.dispatch([{type:1,id:T(a._id),opId:this._pool.generateOpId(),parentKey:s}],[{type:1,id:T(a._id),parentKey:d}],f)}}delete(e){var r;if((r=this._pool)==null||r.assertStorageIsWritable(),e<0||e>=this._items.length)throw new Error(`Cannot delete list item at index "${e}". index should be between 0 and ${this._items.length-1}`);let n=this._items[e];if(n._detach(),this._items.splice(e,1),this.invalidate(),this._pool){let i=n._id;if(i){let s=new Map;s.set(T(this._id),S(this,[Me(e)])),this._pool.dispatch([{id:i,opId:this._pool.generateOpId(),type:5}],n._toOps(T(this._id),n._getParentKeyOrThrow()),s)}}}clear(){var e;if((e=this._pool)==null||e.assertStorageIsWritable(),this._pool){let n=[],r=[],i=[];for(let a of this._items){a._detach();let d=a._id;d&&(n.push({type:5,id:d,opId:this._pool.generateOpId()}),r.push(...a._toOps(T(this._id),a._getParentKeyOrThrow())),i.push(Me(0)))}this._items=[],this.invalidate();let s=new Map;s.set(T(this._id),S(this,i)),this._pool.dispatch(n,r,s)}else{for(let n of this._items)n._detach();this._items=[],this.invalidate()}}set(e,n){var d;if((d=this._pool)==null||d.assertStorageIsWritable(),e<0||e>=this._items.length)throw new Error(`Cannot set list item at index "${e}". index should be between 0 and ${this._items.length-1}`);let r=this._items[e],i=r._getParentKeyOrThrow(),s=r._id;r._detach();let a=re(n);if(a._setParentLink(this,i),this._items[e]=a,this.invalidate(),this._pool&&this._id){let c=this._pool.generateId();a._attach(c,this._pool);let f=new Map;f.set(this._id,S(this,[fe(e,a)]));let y=pt(a._toOps(this._id,i,this._pool),s);this._unacknowledgedSets.set(i,T(y[0].opId));let b=pt(r._toOps(this._id,i,void 0),c);this._pool.dispatch(y,b,f)}}toArray(){return this._items.map(e=>Q(e))}every(e){return this.toArray().every(e)}filter(e){return this.toArray().filter(e)}find(e){return this.toArray().find(e)}findIndex(e){return this.toArray().findIndex(e)}forEach(e){return this.toArray().forEach(e)}get(e){if(!(e<0||e>=this._items.length))return Q(this._items[e])}indexOf(e,n){return this.toArray().indexOf(e,n)}lastIndexOf(e,n){return this.toArray().lastIndexOf(e,n)}map(e){return this._items.map((n,r)=>e(Q(n),r))}some(e){return this.toArray().some(e)}[Symbol.iterator](){return new ut(this._items)}_createAttachItemAndSort(e,n){let r=ie(e);r._attach(e.id,T(this._pool)),r._setParentLink(this,n),this._insertAndSort(r);let i=this._indexOfPosition(n);return{newItem:r,newIndex:i}}_shiftItemPosition(e,n){var i;let r=z(n,this._items.length>e+1?(i=this._items[e+1])==null?void 0:i._parentPos:void 0);this._items[e]._setParentLink(this,r)}_toTreeNode(e){var n;return{type:"LiveList",id:(n=this._id)!=null?n:oe(),key:e,payload:this._items.map((r,i)=>r.toTreeNode(i.toString()))}}toImmutable(){return super.toImmutable()}_toImmutable(){let e=this._items.map(n=>n.toImmutable());return process.env.NODE_ENV==="production"?e:Object.freeze(e)}},ut=class{constructor(o){this._innerIterator=o[Symbol.iterator]()}[Symbol.iterator](){return this}next(){let o=this._innerIterator.next();return o.done?{done:!0,value:void 0}:{value:Q(o.value)}}};function S(t,o){return{node:t,type:"LiveList",updates:o}}function fe(t,o){return{index:t,type:"set",item:o instanceof J?o.data:o}}function Me(t){return{index:t,type:"delete"}}function $(t,o){return{index:t,type:"insert",item:o instanceof J?o.data:o}}function se(t,o,e){return{index:o,type:"move",previousIndex:t,item:e instanceof J?e.data:e}}function pt(t,o){return t.map((e,n)=>n===0?P(C({},e),{intent:"set",deletedId:o}):e)}var R=process.env.NODE_ENV==="production"?t=>t:Object.freeze;var N=class t extends H{constructor(e){super();if(this.unacknowledgedSet=new Map,e){let n=[];for(let r of e){let i=re(r[1]);i._setParentLink(this,r[0]),n.push([r[0],i])}this._map=new Map(n)}else this._map=new Map}_toOps(e,n,r){if(this._id===void 0)throw new Error("Cannot serialize item is not attached");let i=[],s={id:this._id,opId:r==null?void 0:r.generateOpId(),type:7,parentId:e,parentKey:n};i.push(s);for(let[a,d]of this._map)i.push(...d._toOps(this._id,a,r));return i}static _deserialize([e,n],r,i){let s=new t;s._attach(e,i);let a=r.get(e);if(a===void 0)return s;for(let[d,c]of a){let f=Ue([d,c],r,i);f._setParentLink(s,c.parentKey),s._map.set(c.parentKey,f),s.invalidate()}return s}_attach(e,n){super._attach(e,n);for(let[r,i]of this._map)I(i)&&i._attach(n.generateId(),n)}_attachChild(e,n){if(this._pool===void 0)throw new Error("Can't attach child if managed pool is not present");let{id:r,parentKey:i,opId:s}=e,a=i,d=ie(e);if(this._pool.getNode(r)!==void 0)return{modified:!1};if(n===2){let y=this.unacknowledgedSet.get(a);if(y===s)return this.unacknowledgedSet.delete(a),{modified:!1};if(y!==void 0)return{modified:!1}}else n===1&&this.unacknowledgedSet.delete(a);let c=this._map.get(a),f;if(c){let y=T(this._id);f=c._toOps(y,a),c._detach()}else f=[{type:5,id:r}];return d._setParentLink(this,a),d._attach(r,this._pool),this._map.set(a,d),this.invalidate(),{modified:{node:this,type:"LiveMap",updates:{[a]:{type:"update"}}},reverse:f}}_detach(){super._detach();for(let e of this._map.values())e._detach()}_detachChild(e){let n=T(this._id),r=T(e._parentKey),i=e._toOps(n,r,this._pool);for(let[a,d]of this._map)d===e&&(this._map.delete(a),this.invalidate());return e._detach(),{modified:{node:this,type:"LiveMap",updates:{[r]:{type:"delete"}}},reverse:i}}_serialize(){if(this.parent.type!=="HasParent")throw new Error("Cannot serialize LiveMap if parent is missing");return{type:2,parentId:T(this.parent.node._id,"Parent node expected to have ID"),parentKey:this.parent.key}}get(e){let n=this._map.get(e);if(n!==void 0)return Q(n)}set(e,n){var s;(s=this._pool)==null||s.assertStorageIsWritable();let r=this._map.get(e);r&&r._detach();let i=re(n);if(i._setParentLink(this,e),this._map.set(e,i),this.invalidate(),this._pool&&this._id){let a=this._pool.generateId();i._attach(a,this._pool);let d=new Map;d.set(this._id,{node:this,type:"LiveMap",updates:{[e]:{type:"update"}}});let c=i._toOps(this._id,e,this._pool);this.unacknowledgedSet.set(e,T(c[0].opId)),this._pool.dispatch(i._toOps(this._id,e,this._pool),r?r._toOps(this._id,e):[{type:5,id:a}],d)}}get size(){return this._map.size}has(e){return this._map.has(e)}delete(e){var r;(r=this._pool)==null||r.assertStorageIsWritable();let n=this._map.get(e);if(n===void 0)return!1;if(n._detach(),this._map.delete(e),this.invalidate(),this._pool&&n._id){let i=T(this._id),s=new Map;s.set(i,{node:this,type:"LiveMap",updates:{[e]:{type:"delete"}}}),this._pool.dispatch([{type:5,id:n._id,opId:this._pool.generateOpId()}],n._toOps(i,e),s)}return!0}entries(){let e=this._map.entries();return{[Symbol.iterator](){return this},next(){let n=e.next();if(n.done)return{done:!0,value:void 0};let i=n.value[0],s=Q(n.value[1]);return{value:[i,s]}}}}[Symbol.iterator](){return this.entries()}keys(){return this._map.keys()}values(){let e=this._map.values();return{[Symbol.iterator](){return this},next(){let n=e.next();return n.done?{done:!0,value:void 0}:{value:Q(n.value)}}}}forEach(e){for(let n of this)e(n[1],n[0],this)}_toTreeNode(e){var n;return{type:"LiveMap",id:(n=this._id)!=null?n:oe(),key:e,payload:Array.from(this._map.entries()).map(([r,i])=>i.toTreeNode(r))}}toImmutable(){return super.toImmutable()}_toImmutable(){let e=new Map;for(let[n,r]of this._map)e.set(n,r.toImmutable());return R(e)}};var x=class t extends H{constructor(e={}){super();this._propToLastUpdate=new Map;for(let n in e){let r=e[n];r!==void 0&&I(r)&&r._setParentLink(this,n)}this._map=new Map(Object.entries(e))}static _buildRootAndParentToChildren(e){let n=new Map,r=null;for(let[i,s]of e)if(lt(s))r=[i,s];else{let a=[i,s],d=n.get(s.parentId);d!==void 0?d.push(a):n.set(s.parentId,[a])}if(r===null)throw new Error("Root can't be null");return[r,n]}static _fromItems(e,n){let[r,i]=t._buildRootAndParentToChildren(e);return t._deserialize(r,i,n)}_toOps(e,n,r){if(this._id===void 0)throw new Error("Cannot serialize item is not attached");let i=r==null?void 0:r.generateOpId(),s=[],a=e!==void 0&&n!==void 0?{type:4,id:this._id,opId:i,parentId:e,parentKey:n,data:{}}:{type:4,id:this._id,opId:i,data:{}};s.push(a);for(let[d,c]of this._map)I(c)?s.push(...c._toOps(this._id,d,r)):a.data[d]=c;return s}static _deserialize([e,n],r,i){let s=new t(n.data);return s._attach(e,i),this._deserializeChildren(s,r,i)}static _deserializeChildren(e,n,r){let i=n.get(T(e._id));if(i===void 0)return e;for(let[s,a]of i){let d=un([s,a],n,r);Se(d)&&d._setParentLink(e,a.parentKey),e._map.set(a.parentKey,d),e.invalidate()}return e}_attach(e,n){super._attach(e,n);for(let[r,i]of this._map)I(i)&&i._attach(n.generateId(),n)}_attachChild(e,n){if(this._pool===void 0)throw new Error("Can't attach child if managed pool is not present");let{id:r,opId:i,parentKey:s}=e,a=ft(e);if(this._pool.getNode(r)!==void 0)return this._propToLastUpdate.get(s)===i&&this._propToLastUpdate.delete(s),{modified:!1};if(n===0)this._propToLastUpdate.set(s,T(i));else if(this._propToLastUpdate.get(s)!==void 0)return this._propToLastUpdate.get(s)===i?(this._propToLastUpdate.delete(s),{modified:!1}):{modified:!1};let d=T(this._id),c=this._map.get(s),f;return I(c)?(f=c._toOps(d,s),c._detach()):c===void 0?f=[{type:6,id:d,key:s}]:f=[{type:3,id:d,data:{[s]:c}}],this._map.set(s,a),this.invalidate(),Se(a)&&(a._setParentLink(this,s),a._attach(r,this._pool)),{reverse:f,modified:{node:this,type:"LiveObject",updates:{[s]:{type:"update"}}}}}_detachChild(e){if(e){let n=T(this._id),r=T(e._parentKey),i=e._toOps(n,r,this._pool);for(let[a,d]of this._map)d===e&&(this._map.delete(a),this.invalidate());return e._detach(),{modified:{node:this,type:"LiveObject",updates:{[r]:{type:"delete"}}},reverse:i}}return{modified:!1}}_detach(){super._detach();for(let e of this._map.values())I(e)&&e._detach()}_apply(e,n){return e.type===3?this._applyUpdate(e,n):e.type===6?this._applyDeleteObjectKey(e,n):super._apply(e,n)}_serialize(){let e={};for(let[n,r]of this._map)I(r)||(e[n]=r);return this.parent.type==="HasParent"&&this.parent.node._id?{type:0,parentId:this.parent.node._id,parentKey:this.parent.key,data:e}:{type:0,data:e}}_applyUpdate(e,n){let r=!1,i=T(this._id),s=[],a={type:3,id:i,data:{}};for(let c in e.data){let f=this._map.get(c);I(f)?(s.push(...f._toOps(i,c)),f._detach()):f!==void 0?a.data[c]=f:f===void 0&&s.push({type:6,id:i,key:c})}let d={};for(let c in e.data){let f=e.data[c];if(f===void 0)continue;if(n)this._propToLastUpdate.set(c,T(e.opId));else if(this._propToLastUpdate.get(c)===void 0)r=!0;else if(this._propToLastUpdate.get(c)===e.opId){this._propToLastUpdate.delete(c);continue}else continue;let y=this._map.get(c);I(y)&&y._detach(),r=!0,d[c]={type:"update"},this._map.set(c,f),this.invalidate()}return Object.keys(a.data).length!==0&&s.unshift(a),r?{modified:{node:this,type:"LiveObject",updates:d},reverse:s}:{modified:!1}}_applyDeleteObjectKey(e,n){let r=e.key;if(this._map.has(r)===!1)return{modified:!1};if(!n&&this._propToLastUpdate.get(r)!==void 0)return{modified:!1};let i=this._map.get(r),s=T(this._id),a=[];return I(i)?(a=i._toOps(s,e.key),i._detach()):i!==void 0&&(a=[{type:3,id:s,data:{[r]:i}}]),this._map.delete(r),this.invalidate(),{modified:{node:this,type:"LiveObject",updates:{[e.key]:{type:"delete"}}},reverse:a}}toObject(){return qt(this._map)}set(e,n){var r;(r=this._pool)==null||r.assertStorageIsWritable(),this.update({[e]:n})}get(e){return this._map.get(e)}delete(e){var a;(a=this._pool)==null||a.assertStorageIsWritable();let n=e,r=this._map.get(n);if(r===void 0)return;if(this._pool===void 0||this._id===void 0){I(r)&&r._detach(),this._map.delete(n),this.invalidate();return}let i;I(r)?(r._detach(),i=r._toOps(this._id,n)):i=[{type:3,data:{[n]:r},id:this._id}],this._map.delete(n),this.invalidate();let s=new Map;s.set(this._id,{node:this,type:"LiveObject",updates:{[e]:{type:"delete"}}}),this._pool.dispatch([{type:6,key:n,id:this._id,opId:this._pool.generateOpId()}],i,s)}update(e){var f;if((f=this._pool)==null||f.assertStorageIsWritable(),this._pool===void 0||this._id===void 0){for(let y in e){let b=e[y];if(b===void 0)continue;let E=this._map.get(y);I(E)&&E._detach(),I(b)&&b._setParentLink(this,y),this._map.set(y,b),this.invalidate()}return}let n=[],r=[],i=this._pool.generateOpId(),s={},a={id:this._id,type:3,data:{}},d={};for(let y in e){let b=e[y];if(b===void 0)continue;let E=this._map.get(y);if(I(E)?(r.push(...E._toOps(this._id,y)),E._detach()):E===void 0?r.push({type:6,id:this._id,key:y}):a.data[y]=E,I(b)){b._setParentLink(this,y),b._attach(this._pool.generateId(),this._pool);let G=b._toOps(this._id,y,this._pool),K=G.find(m=>m.parentId===this._id);K&&this._propToLastUpdate.set(y,T(K.opId)),n.push(...G)}else s[y]=b,this._propToLastUpdate.set(y,i);this._map.set(y,b),this.invalidate(),d[y]={type:"update"}}Object.keys(a.data).length!==0&&r.unshift(a),Object.keys(s).length!==0&&n.unshift({opId:i,id:this._id,type:3,data:s});let c=new Map;c.set(this._id,{node:this,type:"LiveObject",updates:d}),this._pool.dispatch(n,r,c)}toImmutable(){return super.toImmutable()}toTreeNode(e){return super.toTreeNode(e)}_toTreeNode(e){var r;let n=(r=this._id)!=null?r:oe();return{type:"LiveObject",id:n,key:e,payload:Array.from(this._map.entries()).map(([i,s])=>I(s)?s.toTreeNode(i):{type:"Json",id:`${n}:${i}`,key:i,payload:s})}}_toImmutable(){let e={};for(let[n,r]of this._map)e[n]=Se(r)?r.toImmutable():r;return process.env.NODE_ENV==="production"?e:Object.freeze(e)}};function ie(t){return re(ft(t))}function ft(t){switch(t.type){case 8:return t.data;case 4:return new x(t.data);case 7:return new N;case 2:return new M;default:return U(t,"Unknown creation Op")}}function ht(t,o){return t===o?!0:t.parent.type==="HasParent"?ht(t.parent.node,o):!1}function Ue([t,o],e,n){switch(o.type){case 0:return x._deserialize([t,o],e,n);case 1:return M._deserialize([t,o],e,n);case 2:return N._deserialize([t,o],e,n);case 3:return J._deserialize([t,o],e,n);default:throw new Error("Unexpected CRDT type")}}function un([t,o],e,n){switch(o.type){case 0:return x._deserialize([t,o],e,n);case 1:return M._deserialize([t,o],e,n);case 2:return N._deserialize([t,o],e,n);case 3:return o.data;default:throw new Error("Unexpected CRDT type")}}function Se(t){return he(t)||Ro(t)||Ae(t)}function I(t){return Se(t)||wo(t)}function he(t){return t instanceof M}function Ro(t){return t instanceof N}function Ae(t){return t instanceof x}function wo(t){return t instanceof J}function Q(t){return t instanceof J?t.data:t instanceof M||t instanceof N||t instanceof x?t:U(t,"Unknown AbstractCrdt")}function re(t){return t instanceof x||t instanceof N||t instanceof M?t:new J(t)}function hn(t,o){let e=[];return t.forEach((n,r)=>{o.get(r)||e.push({type:5,id:r})}),o.forEach((n,r)=>{let i=t.get(r);if(i)n.type===0&&(i.type!==0||JSON.stringify(n.data)!==JSON.stringify(i.data))&&e.push({type:3,id:r,data:n.data}),n.parentKey!==i.parentKey&&e.push({type:1,id:r,parentKey:T(n.parentKey,"Parent key must not be missing")});else switch(n.type){case 3:e.push({type:8,id:r,parentId:n.parentId,parentKey:n.parentKey,data:n.data});break;case 1:e.push({type:2,id:r,parentId:n.parentId,parentKey:n.parentKey});break;case 0:e.push(n.parentId?{type:4,id:r,parentId:n.parentId,parentKey:n.parentKey,data:n.data}:{type:4,id:r,data:n.data});break;case 2:e.push({type:7,id:r,parentId:n.parentId,parentKey:n.parentKey});break}}),e}function Mo(t,o){let e=t.updates;for(let[n,r]of et(o.updates))e[n]=r;return P(C({},o),{updates:e})}function Uo(t,o){let e=t.updates;for(let[n,r]of et(o.updates))e[n]=r;return P(C({},o),{updates:e})}function Ao(t,o){let e=t.updates;return P(C({},o),{updates:e.concat(o.updates)})}function Ne(t,o){return t===void 0?o:t.type==="LiveObject"&&o.type==="LiveObject"?Mo(t,o):t.type==="LiveMap"&&o.type==="LiveMap"?Uo(t,o):t.type==="LiveList"&&o.type==="LiveList"?Ao(t,o):o}function fn(t){let o=typeof t;return t==null||o==="string"||o==="boolean"||o==="number"||Array.isArray(t)||A(t)}function yt(t,o=""){if(!fn)return{path:o||"root",value:t};if(typeof t!="object"||t===null)return!1;for(let[e,n]of Object.entries(t)){let r=o?o+"."+e:e;if(!fn(n))return{path:r,value:n};if(typeof n=="object"){let i=yt(n,r);if(i)return i}}return!1}function yn(t,o){let e={name:t};if(typeof Error.captureStackTrace=="function")return Error.captureStackTrace(e,o),e.stack}function mn(t){return t===null||typeof t=="string"||typeof t=="number"||typeof t=="boolean"}function De(t){return Array.isArray(t)}function ae(t){return!mn(t)&&!De(t)}function Tn(t){let o=Date.now()/1e3;return!(o<=t.exp-300&&o>=t.iat-300)}function No(t){return Array.isArray(t)&&t.every(o=>typeof o=="string")}function Do(t){return A(t)&&typeof t.iat=="number"&&typeof t.exp=="number"&&typeof t.actor=="number"&&(t.id===void 0||typeof t.id=="string")&&No(t.scopes)}function je(t){let o=t.split(".");if(o.length!==3)throw new Error("Authentication error: invalid JWT token");let e=ge(tt(o[1]));if(!(e&&Do(e)))throw new Error("Authentication error: we expected a room token but did not get one. Hint: if you are using a callback, ensure the room is passed when creating the token. For more information: https://liveblocks.io/docs/api-reference/liveblocks-client#createClientCallback");return{raw:t,parsed:e}}var bn=(s=>(s[s.UPDATE_PRESENCE=100]="UPDATE_PRESENCE",s[s.BROADCAST_EVENT=103]="BROADCAST_EVENT",s[s.FETCH_STORAGE=200]="FETCH_STORAGE",s[s.UPDATE_STORAGE=201]="UPDATE_STORAGE",s[s.FETCH_YDOC=300]="FETCH_YDOC",s[s.UPDATE_YDOC=301]="UPDATE_YDOC",s))(bn||{});var vn=(c=>(c[c.UPDATE_PRESENCE=100]="UPDATE_PRESENCE",c[c.USER_JOINED=101]="USER_JOINED",c[c.USER_LEFT=102]="USER_LEFT",c[c.BROADCASTED_EVENT=103]="BROADCASTED_EVENT",c[c.ROOM_STATE=104]="ROOM_STATE",c[c.INITIAL_STORAGE_STATE=200]="INITIAL_STORAGE_STATE",c[c.UPDATE_STORAGE=201]="UPDATE_STORAGE",c[c.REJECT_STORAGE_OP=299]="REJECT_STORAGE_OP",c[c.UPDATE_YDOC=300]="UPDATE_YDOC",c))(vn||{});function mt(t){return Object.defineProperty(t,"count",{value:t.length,enumerable:!1}),Object.defineProperty(t,"toArray",{value:()=>t,enumerable:!1}),R(t)}function Je(t,o){let e=!1,n=C({},t);return Object.keys(o).forEach(r=>{let i=r,s=o[i];n[i]!==s&&(s===void 0?delete n[i]:n[i]=s,e=!0)}),e?n:t}var ee=class{constructor(){this._ev=O()}get didInvalidate(){return this._ev.observable}invalidate(){this._cache!==void 0&&(this._cache=void 0,this._ev.notify())}get current(){var o;return(o=this._cache)!=null?o:this._cache=this._toImmutable()}};function jo(t,o){return R(Oe(P(C({},t),{presence:o})))}var Ke=class extends ee{constructor(){super();this._connections={},this._presences={},this._users={}}_toImmutable(){let e=_e(Object.keys(this._presences).map(n=>this.getUser(Number(n))));return mt(e)}clearOthers(){this._connections={},this._presences={},this._users={},this.invalidate()}_getUser(e){let n=this._connections[e],r=this._presences[e];if(n!==void 0&&r!==void 0)return jo(n,r)}getUser(e){let n=this._users[e];if(n)return n;let r=this._getUser(e);if(r)return this._users[e]=r,r}_invalidateUser(e){this._users[e]!==void 0&&delete this._users[e],this.invalidate()}setConnection(e,n,r,i){this._connections[e]=R({connectionId:e,id:n,info:r,isReadOnly:i}),this._presences[e]!==void 0&&this._invalidateUser(e)}removeConnection(e){delete this._connections[e],delete this._presences[e],this._invalidateUser(e)}setOther(e,n){this._presences[e]=R(Oe(n)),this._connections[e]!==void 0&&this._invalidateUser(e)}patchOther(e,n){let r=this._presences[e];if(r===void 0)return;let i=Je(r,n);r!==i&&(this._presences[e]=R(i),this._invalidateUser(e))}};var Be=class extends ee{constructor(e){super();this._data=R(Oe(e))}_toImmutable(){return this._data}patch(e){let n=this._data,r=Je(n,e);n!==r&&(this._data=R(r),this.invalidate())}};var ze=class extends ee{constructor(e){super();this._value=R(e)}_toImmutable(){return this._value}set(e){this._value=R(e),this.invalidate()}},ye=class extends ee{constructor(...e){super();let n=e.pop(),r=e;this._refs=r,this._refs.forEach(i=>{i.didInvalidate.subscribe(()=>this.invalidate())}),this._transform=n}_toImmutable(){return this._transform(...this._refs.map(e=>e.current))}};var Jo=1024*1024-128;function Ko(t){let o=0;return()=>`${t}:${o++}`}function gn(t,o){return{type:"User",id:`${o.connectionId}`,key:t,payload:o}}function On(t,o){var Lt,kt,xt,Pt;let e=typeof t.initialPresence=="function"?t.initialPresence(o.roomId):t.initialPresence,n=typeof t.initialStorage=="function"?t.initialStorage(o.roomId):t.initialStorage,r=(xt=o.delegates)!=null?xt:{authenticate:Fo(o.roomId,o.authentication,(Lt=o.polyfills)==null?void 0:Lt.fetch),createSocket:Vo(o.liveblocksServer,(kt=o.polyfills)==null?void 0:kt.WebSocket)},i=new Re(r,o.enableDebugLogging),s={buffer:{flushTimerID:void 0,lastFlushedAt:0,me:{type:"full",data:e},messages:[],storageOperations:[]},sessionInfo:new ze(null),me:new Be(e),others:new Ke,initialStorage:n,idFactory:null,clock:0,opClock:0,nodes:new Map,root:void 0,undoStack:[],redoStack:[],pausedHistory:null,activeBatch:null,unacknowledgedOps:new Map,opStackTraces:process.env.NODE_ENV!=="production"?new Map:void 0},a=l=>l(),d=(Pt=o.unstable_batchedUpdates)!=null?Pt:a,c;function f(l){var u;let p=(u=i.token)==null?void 0:u.parsed;p!==void 0&&p!==c&&(s.sessionInfo.set({userInfo:p.info,userId:p.id,actor:p.actor,isReadOnly:Fe(p.scopes)}),c=p),d(()=>{h.status.notify(l),h.connection.notify(rt(l))})}let y,b=!1;function E(l){l==="reconnecting"?y=setTimeout(()=>{d(()=>{h.lostConnection.notify("lost"),b=!0,s.others.clearOthers(),X({others:[{type:"reset"}]},a)})},o.lostConnectionTimeout):(clearTimeout(y),b&&(d(l==="disconnected"?()=>{h.lostConnection.notify("failed")}:()=>{h.lostConnection.notify("restored")}),b=!1))}function G(){let l=s.sessionInfo.current;if(l===null)throw new Error("Unexpected missing session info");s.buffer.me={type:"full",data:C({},s.me.current)},s.idFactory=Ko(l.actor),Te!==null&&Et({flush:!1}),B()}function K(){clearTimeout(s.buffer.flushTimerID)}i.events.onMessage.subscribe(Dn),i.events.statusDidChange.subscribe(f),i.events.statusDidChange.subscribe(E),i.events.didConnect.subscribe(G),i.events.didDisconnect.subscribe(K),i.events.onLiveblocksError.subscribe(l=>{d(()=>{process.env.NODE_ENV!=="production"&&le(`Connection to websocket server closed. Reason: ${l.message} (code: ${l.code}).`),h.error.notify(l)})});let m={roomId:o.roomId,getNode:l=>s.nodes.get(l),addNode:(l,p)=>void s.nodes.set(l,p),deleteNode:l=>void s.nodes.delete(l),generateId:()=>`${bt()}:${s.clock++}`,generateOpId:()=>`${bt()}:${s.opClock++}`,dispatch(l,p,u){let g=s.activeBatch;if(process.env.NODE_ENV!=="production"){let _=yn("Storage mutation",this.dispatch);if(_)for(let v of l)v.opId&&T(s.opStackTraces).set(v.opId,_)}if(g){g.ops.push(...l);for(let[_,v]of u)g.updates.storageUpdates.set(_,Ne(g.updates.storageUpdates.get(_),v));g.reverseOps.unshift(...p)}else d(()=>{We(p,a),s.redoStack=[],Ot(l),X({storageUpdates:u},a)})},assertStorageIsWritable:()=>{var l;if((l=s.sessionInfo.current)!=null&&l.isReadOnly)throw new Error("Cannot write to storage with a read only user, please ensure the user has write permissions")}},h={connection:O(),status:O(),lostConnection:O(),customEvent:O(),me:O(),others:O(),error:O(),storage:O(),history:O(),storageDidLoad:O(),storageStatus:O(),ydoc:O()};function L(l){var u,g;let p=JSON.stringify(l);if(o.unstable_fallbackToHTTP&&new TextEncoder().encode(p).length>Jo&&(u=i.token)!=null&&u.raw&&o.httpSendEndpoint){if(Tn(i.token.parsed))return i.reconnect();Wo(p,i.token.raw,o.httpSendEndpoint,(g=o.polyfills)==null?void 0:g.fetch),F("Message was too large for websockets and sent over HTTP instead");return}i.send(p)}let te=new ye(s.sessionInfo,s.me,(l,p)=>l!==null?{connectionId:l.actor,id:l.userId,info:l.userInfo,presence:p,isReadOnly:l.isReadOnly}:null),ne=new ye(te,l=>l!==null?gn("Me",l):null);function w(l,p){if(l.items.length===0)throw new Error("Internal error: cannot load storage without items");s.root!==void 0?Y(l.items,p):s.root=x._fromItems(l.items,m);for(let u in s.initialStorage)s.root.get(u)===void 0&&s.root.set(u,s.initialStorage[u])}function Y(l,p){if(s.root===void 0)return;let u=new Map;for(let[v,D]of s.nodes)u.set(v,D._serialize());let g=hn(u,new Map(l)),_=me(g,!1);X(_.updates,p)}function ce(l,p){s.undoStack.length>=50&&s.undoStack.shift(),s.undoStack.push(l),He(p)}function We(l,p){s.pausedHistory!==null?s.pausedHistory.unshift(...l):ce(l,p)}function X({storageUpdates:l=new Map,presence:p=!1,others:u=[]},g){g(()=>{if(u.length>0){let _=s.others.current;for(let v of u)h.others.notify({others:_,event:v})}if(p&&h.me.notify(s.me.current),l.size>0){let _=Array.from(l.values());h.storage.notify(_)}})}function bt(){let l=s.sessionInfo.current;if(l)return l.actor;throw new Error("Internal. Tried to get connection id but connection was never open")}function me(l,p){let u={reverse:[],storageUpdates:new Map,presence:!1},g=new Set,_=l.map(v=>v.type!=="presence"&&!v.opId?P(C({},v),{opId:m.generateOpId()}):v);for(let v of _)if(v.type==="presence"){let D={type:"presence",data:{}};for(let k in v.data)D.data[k]=s.me.current[k];if(s.me.patch(v.data),s.buffer.me===null)s.buffer.me={type:"partial",data:v.data};else for(let k in v.data)s.buffer.me.data[k]=v.data[k];u.reverse.unshift(D),u.presence=!0}else{let D;if(p)D=0;else{let be=T(v.opId);process.env.NODE_ENV!=="production"&&T(s.opStackTraces).delete(be),D=s.unacknowledgedOps.delete(be)?2:1}let k=xn(v,D);if(k.modified){let be=k.modified.node._id;be&&g.has(be)||(u.storageUpdates.set(T(k.modified.node._id),Ne(u.storageUpdates.get(T(k.modified.node._id)),k.modified)),u.reverse.unshift(...k.reverse)),(v.type===2||v.type===7||v.type===4)&&g.add(T(v.id))}}return Ie(),{ops:_,reverse:u.reverse,updates:{storageUpdates:u.storageUpdates,presence:u.presence}}}function xn(l,p){if(an(l))return{modified:!1};switch(l.type){case 6:case 3:case 5:{let u=s.nodes.get(l.id);return u===void 0?{modified:!1}:u._apply(l,p===0)}case 1:{let u=s.nodes.get(l.id);return u===void 0?{modified:!1}:u.parent.type==="HasParent"&&he(u.parent.node)?u.parent.node._setChildKey(Z(l.parentKey),u,p):{modified:!1}}case 4:case 2:case 7:case 8:{if(l.parentId===void 0)return{modified:!1};let u=s.nodes.get(l.parentId);return u===void 0?{modified:!1}:u._attachChild(l,p)}}}function Pn(l,p){let u={};s.buffer.me===null&&(s.buffer.me={type:"partial",data:{}});for(let g in l){let _=l[g];_!==void 0&&(s.buffer.me.data[g]=_,u[g]=s.me.current[g])}s.me.patch(l),s.activeBatch?(p!=null&&p.addToHistory&&s.activeBatch.reverseOps.unshift({type:"presence",data:u}),s.activeBatch.updates.presence=!0):(B(),d(()=>{p!=null&&p.addToHistory&&We([{type:"presence",data:u}],a),X({presence:!0},a)}))}function Fe(l){return l.includes("room:read")&&l.includes("room:presence:write")&&!l.includes("room:write")}function Rn(l){if(l.targetActor!==void 0){let u=s.others.getUser(l.actor);s.others.setOther(l.actor,l.data);let g=s.others.getUser(l.actor);if(u===void 0&&g!==void 0)return{type:"enter",user:g}}else s.others.patchOther(l.actor,l.data);let p=s.others.getUser(l.actor);if(p)return{type:"update",updates:l.data,user:p}}function wn(l){let p=s.others.getUser(l.actor);return p?(s.others.removeConnection(l.actor),{type:"leave",user:p}):null}function Mn(l){for(let p in s.others._connections)l.users[p]===void 0&&s.others.removeConnection(Number(p));for(let p in l.users){let u=l.users[p],g=Number(p);s.others.setConnection(g,u.id,u.info,Fe(u.scopes))}return{type:"reset"}}function vt(){return s.undoStack.length>0}function gt(){return s.redoStack.length>0}function He(l){l(()=>{h.history.notify({canUndo:vt(),canRedo:gt()})})}function Un(l){s.others.setConnection(l.actor,l.id,l.info,Fe(l.scopes)),s.buffer.messages.push({type:100,data:s.me.current,targetActor:l.actor}),B();let p=s.others.getUser(l.actor);return p?{type:"enter",user:p}:void 0}function _t(l){return ae(l)?l:null}function An(l){let p=ge(l);return p===void 0?null:De(p)?_e(p.map(u=>_t(u))):_e([_t(p)])}function Nn(l,p){if(l.size===0)return;let u=[],g=Array.from(l.values()),_=me(g,!0);u.push({type:201,ops:_.ops}),X(_.updates,p),L(u)}function Dn(l){if(typeof l.data!="string")return;let p=An(l.data);if(p===null||p.length===0)return;let u={storageUpdates:new Map,others:[]};d(()=>{var g;for(let _ of p)switch(_.type){case 101:{let v=Un(_);v&&u.others.push(v);break}case 100:{let v=Rn(_);v&&u.others.push(v);break}case 103:{h.customEvent.notify({connectionId:_.actor,event:_.event});break}case 102:{let v=wn(_);v&&u.others.push(v);break}case 300:{h.ydoc.notify(_.update);break}case 104:{u.others.push(Mn(_));break}case 200:{let v=new Map(s.unacknowledgedOps);w(_,a),Nn(v,a),Ce==null||Ce(),Ie(),h.storageDidLoad.notify();break}case 201:{let v=me(_.ops,!1);for(let[D,k]of v.updates.storageUpdates)u.storageUpdates.set(D,Ne(u.storageUpdates.get(D),k));break}case 299:{if(ve("Storage mutation rejection error",_.reason),process.env.NODE_ENV!=="production"){let v=new Set;for(let D of _.opIds){let k=(g=s.opStackTraces)==null?void 0:g.get(D);k&&v.add(k)}throw v.size>0&&Ht("The following function calls caused the rejected storage mutations:",`
|
|
2
2
|
|
|
3
3
|
${Array.from(v).join(`
|
|
4
4
|
|
|
5
|
-
`)}`),new Error(`Storage mutations rejected by server: ${_.reason}`)}break}}X(u,a)})}function B(){let l=s.buffer.storageOperations;if(l.length>0){for(let g of l)s.unacknowledgedOps.set(T(g.opId),g);Ie()}if(i.getStatus()!=="connected"){s.buffer.storageOperations=[];return}let p=Date.now(),u=p-s.buffer.lastFlushedAt;if(u>o.throttleDelay){let g=jn();if(g.length===0)return;L(g),s.buffer={flushTimerID:void 0,lastFlushedAt:p,messages:[],storageOperations:[],me:null}}else clearTimeout(s.buffer.flushTimerID),s.buffer.flushTimerID=setTimeout(B,o.throttleDelay-u)}function jn(){let l=[];s.buffer.me&&l.push(s.buffer.me.type==="full"?{type:100,targetActor:-1,data:s.buffer.me.data}:{type:100,data:s.buffer.me.data});for(let p of s.buffer.messages)l.push(p);return s.buffer.storageOperations.length>0&&l.push({type:201,ops:s.buffer.storageOperations}),l}function Jn(l){s.buffer.messages.push({type:301,update:l}),B()}function Kn(l,p={shouldQueueEventIfNotReady:!1}){i.getStatus()!=="connected"&&!p.shouldQueueEventIfNotReady||(s.buffer.messages.push({type:103,event:l}),B())}function Ot(l){s.buffer.storageOperations.push(...l),B()}let Te=null,Ce=null;function Et(l){let p=s.buffer.messages;p.some(u=>u.type===200)||p.push({type:200}),l.flush&&B()}function St(){return Te===null&&(Et({flush:!0}),Te=new Promise(l=>{Ce=l}),Ie()),Te}function Bn(){let l=s.root;return l!==void 0?l:(St(),null)}function zn(){return j(this,null,function*(){return s.root!==void 0?Promise.resolve({root:s.root}):(yield St(),{root:T(s.root)})})}function Vn(l){s.buffer.messages.push({type:300,vector:l}),B()}function Wn(){if(s.activeBatch)throw new Error("undo is not allowed during a batch");let l=s.undoStack.pop();if(l===void 0)return;s.pausedHistory=null;let p=me(l,!0);d(()=>{X(p.updates,a),s.redoStack.push(p.reverse),He(a)});for(let u of p.ops)u.type!=="presence"&&s.buffer.storageOperations.push(u);B()}function Fn(){if(s.activeBatch)throw new Error("redo is not allowed during a batch");let l=s.redoStack.pop();if(l===void 0)return;s.pausedHistory=null;let p=me(l,!0);d(()=>{X(p.updates,a),s.undoStack.push(p.reverse),He(a)});for(let u of p.ops)u.type!=="presence"&&s.buffer.storageOperations.push(u);B()}function Hn(l){if(s.activeBatch)return l();let p;return d(()=>{s.activeBatch={ops:[],updates:{storageUpdates:new Map,presence:!1,others:[]},reverseOps:[]};try{p=l()}finally{let u=s.activeBatch;s.activeBatch=null,u.reverseOps.length>0&&We(u.reverseOps,a),u.ops.length>0&&(s.redoStack=[]),u.ops.length>0&&Ot(u.ops),X(u.updates,a),B()}}),p}function $n(){s.pausedHistory=[]}function Gn(){let l=s.pausedHistory;s.pausedHistory=null,l!==null&&l.length>0&&ce(l,d)}function $e(){return s.root===void 0?Te===null?"not-loaded":"loading":s.unacknowledgedOps.size===0?"synchronized":"synchronizing"}let Ct=$e();function Ie(){let l=$e();Ct!==l&&(Ct=l,h.storageStatus.notify(l))}let Yn=new ye(s.others,l=>l.map((p,u)=>gn(`Other ${u}`,p))),It={connection:h.connection.observable,status:h.status.observable,lostConnection:h.lostConnection.observable,customEvent:h.customEvent.observable,others:h.others.observable,me:h.me.observable,error:h.error.observable,storage:h.storage.observable,history:h.history.observable,storageDidLoad:h.storageDidLoad.observable,storageStatus:h.storageStatus.observable,ydoc:h.ydoc.observable};return{__internal:{get buffer(){return s.buffer},get undoStack(){return s.undoStack},get nodeCount(){return s.nodes.size},getSelf_forDevTools:()=>ne.current,getOthers_forDevTools:()=>Yn.current,send:{explicitClose:l=>i._privateSendMachineEvent({type:"EXPLICIT_SOCKET_CLOSE",event:l}),implicitClose:()=>i._privateSendMachineEvent({type:"NAVIGATOR_OFFLINE"})}},id:o.roomId,subscribe:Bo(It),connect:()=>i.connect(),reconnect:()=>i.reconnect(),disconnect:()=>i.disconnect(),destroy:()=>i.destroy(),updatePresence:Pn,updateYDoc:Jn,broadcastEvent:Kn,batch:Hn,history:{undo:Wn,redo:Fn,canUndo:vt,canRedo:gt,pause:$n,resume:Gn},fetchYDoc:Vn,getStorage:zn,getStorageSnapshot:Bn,getStorageStatus:$e,events:It,getStatus:()=>i.getStatus(),getConnectionState:()=>i.getLegacyStatus(),isSelfAware:()=>s.sessionInfo.current!==null,getSelf:()=>te.current,getPresence:()=>s.me.current,getOthers:()=>s.others.current}}function Bo(t){function o(r,i){return t.storage.subscribe(s=>{let a=s.filter(d=>ht(d.node,r));a.length>0&&i(a)})}function e(r,i){return t.storage.subscribe(s=>{for(let a of s)a.node._id===r._id&&i(a.node)})}function n(r,i,s){if(typeof r=="string"&&zo(r)){if(typeof i!="function")throw new Error("Second argument must be a callback function");let a=i;switch(r){case"event":return t.customEvent.subscribe(a);case"my-presence":return t.me.subscribe(a);case"others":{let d=a;return t.others.subscribe(({others:c,event:f})=>d(c,f))}case"error":return t.error.subscribe(a);case"connection":return t.connection.subscribe(a);case"status":return t.status.subscribe(a);case"lost-connection":return t.lostConnection.subscribe(a);case"history":return t.history.subscribe(a);case"storage-status":return t.storageStatus.subscribe(a);default:return U(r,"Unknown event")}}if(i===void 0||typeof r=="function")if(typeof r=="function"){let a=r;return t.storage.subscribe(a)}else throw new Error("Please specify a listener callback");if(I(r)){let a=r;return s!=null&&s.isDeep?o(a,i):e(a,i)}throw new Error(`"${String(r)}" is not a valid event name`)}return n}function zo(t){return t==="my-presence"||t==="others"||t==="event"||t==="error"||t==="history"||t==="status"||t==="storage-status"||t==="lost-connection"||t==="connection"}function Vo(t,o){return e=>{let n=o!=null?o:typeof WebSocket=="undefined"?void 0:WebSocket;if(n===void 0)throw new q("To use Liveblocks client in a non-dom environment, you need to provide a WebSocket polyfill.");let r=e.raw;return new n(`${t}/?token=${r}&version=1.1.1-dual4`)}}function Wo(t,o,e,n){return j(this,null,function*(){return(n||fetch)(e,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`},body:t})})}function Fo(t,o,e){let n=e!=null?e:typeof window=="undefined"?void 0:window.fetch;if(o.type==="public")return()=>j(this,null,function*(){if(n===void 0)throw new q("To use Liveblocks client in a non-dom environment with a publicApiKey, you need to provide a fetch polyfill.");return _n(n,o.url,{room:t,publicApiKey:o.publicApiKey}).then(({token:r})=>je(r))});if(o.type==="private")return()=>j(this,null,function*(){if(n===void 0)throw new q("To use Liveblocks client in a non-dom environment with a url as auth endpoint, you need to provide a fetch polyfill.");return _n(n,o.url,{room:t}).then(({token:r})=>je(r))});if(o.type==="custom")return()=>j(this,null,function*(){let r=yield o.callback(t);if(!r||!r.token)throw new Error('We expect the authentication callback to return a token, but it does not. Hint: the return value should look like: { token: "..." }');return je(r.token)});throw new Error("Internal error. Unexpected authentication type")}function _n(t,o,e){return j(this,null,function*(){let n=yield t(o,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify(e)});if(!n.ok){let s=`${(yield n.text()).trim()||"reason not provided in auth response"} (${n.status} returned by POST ${o})`;throw n.status===401||n.status===403?new q(`Unauthorized: ${s}`):new Error(`Failed to authenticate: ${s}`)}let r;try{r=yield n.json()}catch(s){throw new Error(`Expected a JSON response when doing a POST request on "${o}". ${String(s)}`)}if(!A(r)||typeof r.token!="string")throw new Error(`Expected a JSON response of the form \`{ token: "..." }\` when doing a POST request on "${o}", but got ${JSON.stringify(r)}`);let{token:i}=r;return{token:i}})}var Ho=16,$o=1e3,Go=100,Yo=200,Xo=1e3,qo=3e4,Zo=5e3;function Qo(t){let o=t;return typeof o.liveblocksServer=="string"?o.liveblocksServer:"wss://api.liveblocks.io/v6"}function er(t){var d,c;let o=t,e=tr((d=o.throttle)!=null?d:Go),n=nr((c=o.lostConnectionTimeout)!=null?c:Zo),r=new Map;function i(f){let y=r.get(f);return y||null}function s(f,y){var K,m,h;let b=r.get(f);if(b!==void 0)return b;Ze(y.initialPresence===null||y.initialPresence===void 0,"Please provide an initial presence value for the current user when entering the room.");let E=On({initialPresence:(K=y.initialPresence)!=null?K:{},initialStorage:y.initialStorage},{roomId:f,throttleDelay:e,lostConnectionTimeout:n,polyfills:o.polyfills,delegates:o.mockedDelegates,enableDebugLogging:o.enableDebugLogging,unstable_batchedUpdates:y==null?void 0:y.unstable_batchedUpdates,liveblocksServer:Qo(o),authentication:or(o,f),httpSendEndpoint:rr(o,f),unstable_fallbackToHTTP:!!o.unstable_fallbackToHTTP});if(r.set(f,E),Jt(()=>Array.from(r.keys())),Bt(f,E),(m=y.shouldInitiallyConnect)!=null?m:!0){if(typeof atob=="undefined"){if(((h=o.polyfills)==null?void 0:h.atob)===void 0)throw new Error("You need to polyfill atob to use the client in your environment. Please follow the instructions at https://liveblocks.io/docs/errors/liveblocks-client/atob-polyfill");global.atob=o.polyfills.atob}E.connect()}return E}function a(f){zt(f);let y=r.get(f);y!==void 0&&(y.destroy(),r.delete(f))}return{getRoom:i,enter:s,leave:a}}function En(t,o,e,n,r){if(typeof o!="number"||o<e||o>n)throw new Error(`${t} should be a number between ${r!=null?r:e} and ${n}.`);return o}function tr(t){return En("throttle",t,Ho,$o)}function nr(t){return En("lostConnectionTimeout",t,Yo,qo,Xo)}function or(t,o){let{publicApiKey:e,authEndpoint:n}=t;if(n!==void 0&&e!==void 0)throw new Error("You cannot use both publicApiKey and authEndpoint. Please use either publicApiKey or authEndpoint, but not both. For more information: https://liveblocks.io/docs/api-reference/liveblocks-client#createClient");if(typeof e=="string"){if(e.startsWith("sk_"))throw new Error("Invalid publicApiKey. You are using the secret key which is not supported. Please use the public key instead. For more information: https://liveblocks.io/docs/api-reference/liveblocks-client#createClientPublicKey");if(!e.startsWith("pk_"))throw new Error("Invalid key. Please use the public key format: pk_<public key>. For more information: https://liveblocks.io/docs/api-reference/liveblocks-client#createClientPublicKey");return{type:"public",publicApiKey:e,url:sr(t,o)}}if(typeof n=="string")return{type:"private",url:n};if(typeof n=="function")return{type:"custom",callback:n};throw n!==void 0?new Error("authEndpoint must be a string or a function. For more information: https://liveblocks.io/docs/api-reference/liveblocks-client#createClientAuthEndpoint"):new Error("Invalid Liveblocks client options. For more information: https://liveblocks.io/docs/api-reference/liveblocks-client#createClient")}function rr(t,o){return t.httpSendEndpoint?t.httpSendEndpoint.replace("{roomId}",o):`https://api.liveblocks.io/v2/rooms/${encodeURIComponent(o)}/send-message`}function sr(t,o){return t.publicAuthorizeEndpoint?t.publicAuthorizeEndpoint.replace("{roomId}",o):`https://api.liveblocks.io/v2/rooms/${encodeURIComponent(o)}/public/authorize`}function Ve(t){return t instanceof x?{liveblocksType:"LiveObject",data:Object.fromEntries(Object.entries(t.toObject()).map(([o,e])=>[o,e?Ve(e):""]))}:t instanceof N?{liveblocksType:"LiveMap",data:Object.fromEntries([...t].map(([o,e])=>[o,Ve(e)]))}:t instanceof M?{liveblocksType:"LiveList",data:[...t].map(o=>Ve(o))}:t}function Sn(t){let o={};for(let e in t){let n=t[e];n!==void 0&&(o[e]=V(n))}return o}function ir(t){return Sn(t.toObject())}function ar(t){let o={};for(let[e,n]of t.entries())o[e]=V(n);return o}function Cn(t){return t.map(V)}function dr(t){return Cn(t.toArray())}function V(t){return t instanceof x?ir(t):t instanceof M?dr(t):t instanceof N?ar(t):t instanceof J?t.data:Array.isArray(t)?Cn(t):A(t)?Sn(t):t}function de(t){if(Array.isArray(t))return new M(t.map(de));if(A(t)){let o={};for(let e in t){let n=t[e];n!==void 0&&(o[e]=de(n))}return new x(o)}else return t}function cr(t,o,e){let n=0,r=o.length-1,i=e.length-1,s=o[0],a=e[0];e:{for(;s===a;){if(++n,n>r||n>i)break e;s=o[n],a=e[n]}for(s=o[r],a=e[i];s===a;){if(r--,i--,n>r||n>i)break e;s=o[r],a=e[i]}}if(n>r){if(n<=i)for(;n<=i;)t.insert(de(e[n]),n),n++}else if(n>i){let d=n;for(;d<=r;)t.delete(n),d++}else{for(;n<=r&&n<=i;){s=o[n],a=e[n];let c=t.get(n);Ae(c)&&A(s)&&A(a)?Ln(c,s,a):t.set(n,de(a)),n++}for(;n<=i;)t.insert(de(e[n]),n),n++;let d=n;for(;d<=r;)t.delete(n),d++}}function In(t,o,e,n){if(process.env.NODE_ENV!=="production"){let i=yt(n);if(i){le(`New state path: '${i.path}' value: '${String(i.value)}' is not serializable.
|
|
5
|
+
`)}`),new Error(`Storage mutations rejected by server: ${_.reason}`)}break}}X(u,a)})}function B(){let l=s.buffer.storageOperations;if(l.length>0){for(let g of l)s.unacknowledgedOps.set(T(g.opId),g);Ie()}if(i.getStatus()!=="connected"){s.buffer.storageOperations=[];return}let p=Date.now(),u=p-s.buffer.lastFlushedAt;if(u>o.throttleDelay){let g=jn();if(g.length===0)return;L(g),s.buffer={flushTimerID:void 0,lastFlushedAt:p,messages:[],storageOperations:[],me:null}}else clearTimeout(s.buffer.flushTimerID),s.buffer.flushTimerID=setTimeout(B,o.throttleDelay-u)}function jn(){let l=[];s.buffer.me&&l.push(s.buffer.me.type==="full"?{type:100,targetActor:-1,data:s.buffer.me.data}:{type:100,data:s.buffer.me.data});for(let p of s.buffer.messages)l.push(p);return s.buffer.storageOperations.length>0&&l.push({type:201,ops:s.buffer.storageOperations}),l}function Jn(l){s.buffer.messages.push({type:301,update:l}),B()}function Kn(l,p={shouldQueueEventIfNotReady:!1}){i.getStatus()!=="connected"&&!p.shouldQueueEventIfNotReady||(s.buffer.messages.push({type:103,event:l}),B())}function Ot(l){s.buffer.storageOperations.push(...l),B()}let Te=null,Ce=null;function Et(l){let p=s.buffer.messages;p.some(u=>u.type===200)||p.push({type:200}),l.flush&&B()}function St(){return Te===null&&(Et({flush:!0}),Te=new Promise(l=>{Ce=l}),Ie()),Te}function Bn(){let l=s.root;return l!==void 0?l:(St(),null)}function zn(){return j(this,null,function*(){return s.root!==void 0?Promise.resolve({root:s.root}):(yield St(),{root:T(s.root)})})}function Vn(l){s.buffer.messages.push({type:300,vector:l}),B()}function Wn(){if(s.activeBatch)throw new Error("undo is not allowed during a batch");let l=s.undoStack.pop();if(l===void 0)return;s.pausedHistory=null;let p=me(l,!0);d(()=>{X(p.updates,a),s.redoStack.push(p.reverse),He(a)});for(let u of p.ops)u.type!=="presence"&&s.buffer.storageOperations.push(u);B()}function Fn(){if(s.activeBatch)throw new Error("redo is not allowed during a batch");let l=s.redoStack.pop();if(l===void 0)return;s.pausedHistory=null;let p=me(l,!0);d(()=>{X(p.updates,a),s.undoStack.push(p.reverse),He(a)});for(let u of p.ops)u.type!=="presence"&&s.buffer.storageOperations.push(u);B()}function Hn(l){if(s.activeBatch)return l();let p;return d(()=>{s.activeBatch={ops:[],updates:{storageUpdates:new Map,presence:!1,others:[]},reverseOps:[]};try{p=l()}finally{let u=s.activeBatch;s.activeBatch=null,u.reverseOps.length>0&&We(u.reverseOps,a),u.ops.length>0&&(s.redoStack=[]),u.ops.length>0&&Ot(u.ops),X(u.updates,a),B()}}),p}function $n(){s.pausedHistory=[]}function Gn(){let l=s.pausedHistory;s.pausedHistory=null,l!==null&&l.length>0&&ce(l,d)}function $e(){return s.root===void 0?Te===null?"not-loaded":"loading":s.unacknowledgedOps.size===0?"synchronized":"synchronizing"}let Ct=$e();function Ie(){let l=$e();Ct!==l&&(Ct=l,h.storageStatus.notify(l))}let Yn=new ye(s.others,l=>l.map((p,u)=>gn(`Other ${u}`,p))),It={connection:h.connection.observable,status:h.status.observable,lostConnection:h.lostConnection.observable,customEvent:h.customEvent.observable,others:h.others.observable,me:h.me.observable,error:h.error.observable,storage:h.storage.observable,history:h.history.observable,storageDidLoad:h.storageDidLoad.observable,storageStatus:h.storageStatus.observable,ydoc:h.ydoc.observable};return{__internal:{get buffer(){return s.buffer},get undoStack(){return s.undoStack},get nodeCount(){return s.nodes.size},getSelf_forDevTools:()=>ne.current,getOthers_forDevTools:()=>Yn.current,send:{explicitClose:l=>i._privateSendMachineEvent({type:"EXPLICIT_SOCKET_CLOSE",event:l}),implicitClose:()=>i._privateSendMachineEvent({type:"NAVIGATOR_OFFLINE"})}},id:o.roomId,subscribe:Bo(It),connect:()=>i.connect(),reconnect:()=>i.reconnect(),disconnect:()=>i.disconnect(),destroy:()=>i.destroy(),updatePresence:Pn,updateYDoc:Jn,broadcastEvent:Kn,batch:Hn,history:{undo:Wn,redo:Fn,canUndo:vt,canRedo:gt,pause:$n,resume:Gn},fetchYDoc:Vn,getStorage:zn,getStorageSnapshot:Bn,getStorageStatus:$e,events:It,getStatus:()=>i.getStatus(),getConnectionState:()=>i.getLegacyStatus(),isSelfAware:()=>s.sessionInfo.current!==null,getSelf:()=>te.current,getPresence:()=>s.me.current,getOthers:()=>s.others.current}}function Bo(t){function o(r,i){return t.storage.subscribe(s=>{let a=s.filter(d=>ht(d.node,r));a.length>0&&i(a)})}function e(r,i){return t.storage.subscribe(s=>{for(let a of s)a.node._id===r._id&&i(a.node)})}function n(r,i,s){if(typeof r=="string"&&zo(r)){if(typeof i!="function")throw new Error("Second argument must be a callback function");let a=i;switch(r){case"event":return t.customEvent.subscribe(a);case"my-presence":return t.me.subscribe(a);case"others":{let d=a;return t.others.subscribe(({others:c,event:f})=>d(c,f))}case"error":return t.error.subscribe(a);case"connection":return t.connection.subscribe(a);case"status":return t.status.subscribe(a);case"lost-connection":return t.lostConnection.subscribe(a);case"history":return t.history.subscribe(a);case"storage-status":return t.storageStatus.subscribe(a);default:return U(r,"Unknown event")}}if(i===void 0||typeof r=="function")if(typeof r=="function"){let a=r;return t.storage.subscribe(a)}else throw new Error("Please specify a listener callback");if(I(r)){let a=r;return s!=null&&s.isDeep?o(a,i):e(a,i)}throw new Error(`"${String(r)}" is not a valid event name`)}return n}function zo(t){return t==="my-presence"||t==="others"||t==="event"||t==="error"||t==="history"||t==="status"||t==="storage-status"||t==="lost-connection"||t==="connection"}function Vo(t,o){return e=>{let n=o!=null?o:typeof WebSocket=="undefined"?void 0:WebSocket;if(n===void 0)throw new q("To use Liveblocks client in a non-dom environment, you need to provide a WebSocket polyfill.");let r=e.raw;return new n(`${t}/?token=${r}&version=1.1.1-dual5`)}}function Wo(t,o,e,n){return j(this,null,function*(){return(n||fetch)(e,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`},body:t})})}function Fo(t,o,e){let n=e!=null?e:typeof window=="undefined"?void 0:window.fetch;if(o.type==="public")return()=>j(this,null,function*(){if(n===void 0)throw new q("To use Liveblocks client in a non-dom environment with a publicApiKey, you need to provide a fetch polyfill.");return _n(n,o.url,{room:t,publicApiKey:o.publicApiKey}).then(({token:r})=>je(r))});if(o.type==="private")return()=>j(this,null,function*(){if(n===void 0)throw new q("To use Liveblocks client in a non-dom environment with a url as auth endpoint, you need to provide a fetch polyfill.");return _n(n,o.url,{room:t}).then(({token:r})=>je(r))});if(o.type==="custom")return()=>j(this,null,function*(){let r=yield o.callback(t);if(!r||!r.token)throw new Error('We expect the authentication callback to return a token, but it does not. Hint: the return value should look like: { token: "..." }');return je(r.token)});throw new Error("Internal error. Unexpected authentication type")}function _n(t,o,e){return j(this,null,function*(){let n=yield t(o,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify(e)});if(!n.ok){let s=`${(yield n.text()).trim()||"reason not provided in auth response"} (${n.status} returned by POST ${o})`;throw n.status===401||n.status===403?new q(`Unauthorized: ${s}`):new Error(`Failed to authenticate: ${s}`)}let r;try{r=yield n.json()}catch(s){throw new Error(`Expected a JSON response when doing a POST request on "${o}". ${String(s)}`)}if(!A(r)||typeof r.token!="string")throw new Error(`Expected a JSON response of the form \`{ token: "..." }\` when doing a POST request on "${o}", but got ${JSON.stringify(r)}`);let{token:i}=r;return{token:i}})}var Ho=16,$o=1e3,Go=100,Yo=200,Xo=1e3,qo=3e4,Zo=5e3;function Qo(t){let o=t;return typeof o.liveblocksServer=="string"?o.liveblocksServer:"wss://api.liveblocks.io/v6"}function er(t){var d,c;let o=t,e=tr((d=o.throttle)!=null?d:Go),n=nr((c=o.lostConnectionTimeout)!=null?c:Zo),r=new Map;function i(f){let y=r.get(f);return y||null}function s(f,y){var K,m,h;let b=r.get(f);if(b!==void 0)return b;Ze(y.initialPresence===null||y.initialPresence===void 0,"Please provide an initial presence value for the current user when entering the room.");let E=On({initialPresence:(K=y.initialPresence)!=null?K:{},initialStorage:y.initialStorage},{roomId:f,throttleDelay:e,lostConnectionTimeout:n,polyfills:o.polyfills,delegates:o.mockedDelegates,enableDebugLogging:o.enableDebugLogging,unstable_batchedUpdates:y==null?void 0:y.unstable_batchedUpdates,liveblocksServer:Qo(o),authentication:or(o,f),httpSendEndpoint:rr(o,f),unstable_fallbackToHTTP:!!o.unstable_fallbackToHTTP});if(r.set(f,E),Jt(()=>Array.from(r.keys())),Bt(f,E),(m=y.shouldInitiallyConnect)!=null?m:!0){if(typeof atob=="undefined"){if(((h=o.polyfills)==null?void 0:h.atob)===void 0)throw new Error("You need to polyfill atob to use the client in your environment. Please follow the instructions at https://liveblocks.io/docs/errors/liveblocks-client/atob-polyfill");global.atob=o.polyfills.atob}E.connect()}return E}function a(f){zt(f);let y=r.get(f);y!==void 0&&(y.destroy(),r.delete(f))}return{getRoom:i,enter:s,leave:a}}function En(t,o,e,n,r){if(typeof o!="number"||o<e||o>n)throw new Error(`${t} should be a number between ${r!=null?r:e} and ${n}.`);return o}function tr(t){return En("throttle",t,Ho,$o)}function nr(t){return En("lostConnectionTimeout",t,Yo,qo,Xo)}function or(t,o){let{publicApiKey:e,authEndpoint:n}=t;if(n!==void 0&&e!==void 0)throw new Error("You cannot use both publicApiKey and authEndpoint. Please use either publicApiKey or authEndpoint, but not both. For more information: https://liveblocks.io/docs/api-reference/liveblocks-client#createClient");if(typeof e=="string"){if(e.startsWith("sk_"))throw new Error("Invalid publicApiKey. You are using the secret key which is not supported. Please use the public key instead. For more information: https://liveblocks.io/docs/api-reference/liveblocks-client#createClientPublicKey");if(!e.startsWith("pk_"))throw new Error("Invalid key. Please use the public key format: pk_<public key>. For more information: https://liveblocks.io/docs/api-reference/liveblocks-client#createClientPublicKey");return{type:"public",publicApiKey:e,url:sr(t,o)}}if(typeof n=="string")return{type:"private",url:n};if(typeof n=="function")return{type:"custom",callback:n};throw n!==void 0?new Error("authEndpoint must be a string or a function. For more information: https://liveblocks.io/docs/api-reference/liveblocks-client#createClientAuthEndpoint"):new Error("Invalid Liveblocks client options. For more information: https://liveblocks.io/docs/api-reference/liveblocks-client#createClient")}function rr(t,o){return t.httpSendEndpoint?t.httpSendEndpoint.replace("{roomId}",o):`https://api.liveblocks.io/v2/rooms/${encodeURIComponent(o)}/send-message`}function sr(t,o){return t.publicAuthorizeEndpoint?t.publicAuthorizeEndpoint.replace("{roomId}",o):`https://api.liveblocks.io/v2/rooms/${encodeURIComponent(o)}/public/authorize`}function Ve(t){return t instanceof x?{liveblocksType:"LiveObject",data:Object.fromEntries(Object.entries(t.toObject()).map(([o,e])=>[o,e?Ve(e):""]))}:t instanceof N?{liveblocksType:"LiveMap",data:Object.fromEntries([...t].map(([o,e])=>[o,Ve(e)]))}:t instanceof M?{liveblocksType:"LiveList",data:[...t].map(o=>Ve(o))}:t}function Sn(t){let o={};for(let e in t){let n=t[e];n!==void 0&&(o[e]=V(n))}return o}function ir(t){return Sn(t.toObject())}function ar(t){let o={};for(let[e,n]of t.entries())o[e]=V(n);return o}function Cn(t){return t.map(V)}function dr(t){return Cn(t.toArray())}function V(t){return t instanceof x?ir(t):t instanceof M?dr(t):t instanceof N?ar(t):t instanceof J?t.data:Array.isArray(t)?Cn(t):A(t)?Sn(t):t}function de(t){if(Array.isArray(t))return new M(t.map(de));if(A(t)){let o={};for(let e in t){let n=t[e];n!==void 0&&(o[e]=de(n))}return new x(o)}else return t}function cr(t,o,e){let n=0,r=o.length-1,i=e.length-1,s=o[0],a=e[0];e:{for(;s===a;){if(++n,n>r||n>i)break e;s=o[n],a=e[n]}for(s=o[r],a=e[i];s===a;){if(r--,i--,n>r||n>i)break e;s=o[r],a=e[i]}}if(n>r){if(n<=i)for(;n<=i;)t.insert(de(e[n]),n),n++}else if(n>i){let d=n;for(;d<=r;)t.delete(n),d++}else{for(;n<=r&&n<=i;){s=o[n],a=e[n];let c=t.get(n);Ae(c)&&A(s)&&A(a)?Ln(c,s,a):t.set(n,de(a)),n++}for(;n<=i;)t.insert(de(e[n]),n),n++;let d=n;for(;d<=r;)t.delete(n),d++}}function In(t,o,e,n){if(process.env.NODE_ENV!=="production"){let i=yt(n);if(i){le(`New state path: '${i.path}' value: '${String(i.value)}' is not serializable.
|
|
6
6
|
Only serializable value can be synced with Liveblocks.`);return}}let r=t.get(o);if(n===void 0)t.delete(o);else if(r===void 0)t.set(o,de(n));else{if(e===n)return;he(r)&&Array.isArray(e)&&Array.isArray(n)?cr(r,e,n):Ae(r)&&A(e)&&A(n)?Ln(r,e,n):t.set(o,de(n))}}function Ln(t,o,e){let n={};for(let r in e)In(t,r,o[r],e[r]);for(let r in o)e[r]===void 0&&t.delete(r);Object.keys(n).length>0&&t.update(n)}function lr(t){let o=[];for(;t.parent.type==="HasParent";)he(t.parent.node)?o.push(t.parent.node._indexOfPosition(t.parent.key)):o.push(t.parent.key),t=t.parent.node;return o}function pr(t,o){return o.reduce((e,n)=>ur(e,n),t)}function ur(t,o){let e=lr(o.node);return Tt(t,e,o)}function Tt(t,o,e){var r,i,s,a;let n=o.pop();if(n===void 0)switch(e.type){case"LiveObject":{if(!ae(t))throw new Error("Internal: received update on LiveObject but state was not an object");let d=Object.assign({},t);for(let c in e.updates)if(((r=e.updates[c])==null?void 0:r.type)==="update"){let f=e.node.get(c);f!==void 0&&(d[c]=V(f))}else((i=e.updates[c])==null?void 0:i.type)==="delete"&&delete d[c];return d}case"LiveList":{if(!Array.isArray(t))throw new Error("Internal: received update on LiveList but state was not an array");let d=t.map(c=>c);for(let c of e.updates)c.type==="set"?d=d.map((f,y)=>y===c.index?V(c.item):f):c.type==="insert"?c.index===d.length?d.push(V(c.item)):d=[...d.slice(0,c.index),V(c.item),...d.slice(c.index)]:c.type==="delete"?d.splice(c.index,1):c.type==="move"&&(c.previousIndex>c.index?d=[...d.slice(0,c.index),V(c.item),...d.slice(c.index,c.previousIndex),...d.slice(c.previousIndex+1)]:d=[...d.slice(0,c.previousIndex),...d.slice(c.previousIndex+1,c.index+1),V(c.item),...d.slice(c.index+1)]);return d}case"LiveMap":{if(!ae(t))throw new Error("Internal: received update on LiveMap but state was not an object");let d=Object.assign({},t);for(let c in e.updates)if(((s=e.updates[c])==null?void 0:s.type)==="update"){let f=e.node.get(c);f!==void 0&&(d[c]=V(f))}else((a=e.updates[c])==null?void 0:a.type)==="delete"&&delete d[c];return d}}if(Array.isArray(t)){let d=[...t];return d[n]=Tt(t[n],o,e),d}else if(ae(t)){let d=t[n];return d===void 0?t:P(C({},t),{[n]:Tt(d,o,e)})}else return t}function fr(t,o){if(t.length!==o.length)return!1;for(let e=0;e<t.length;e++)if(!Object.is(t[e],o[e]))return!1;return!0}function hr(t,o){if(typeof t!="object"||t===null||typeof o!="object"||o===null||Object.prototype.toString.call(t)!=="[object Object]"||Object.prototype.toString.call(o)!=="[object Object]")return!1;let e=Object.keys(t);return e.length!==Object.keys(o).length?!1:e.every(n=>Object.prototype.hasOwnProperty.call(o,n)&&Object.is(t[n],o[n]))}function yr(t,o){if(Object.is(t,o))return!0;let e=Array.isArray(t),n=Array.isArray(o);return e||n?!e||!n?!1:fr(t,o):hr(t,o)}var kn=(d=>(d[d.CLOSE_ABNORMAL=1006]="CLOSE_ABNORMAL",d[d.INVALID_MESSAGE_FORMAT=4e3]="INVALID_MESSAGE_FORMAT",d[d.NOT_ALLOWED=4001]="NOT_ALLOWED",d[d.MAX_NUMBER_OF_MESSAGES_PER_SECONDS=4002]="MAX_NUMBER_OF_MESSAGES_PER_SECONDS",d[d.MAX_NUMBER_OF_CONCURRENT_CONNECTIONS=4003]="MAX_NUMBER_OF_CONCURRENT_CONNECTIONS",d[d.MAX_NUMBER_OF_MESSAGES_PER_DAY_PER_APP=4004]="MAX_NUMBER_OF_MESSAGES_PER_DAY_PER_APP",d[d.MAX_NUMBER_OF_CONCURRENT_CONNECTIONS_PER_ROOM=4005]="MAX_NUMBER_OF_CONCURRENT_CONNECTIONS_PER_ROOM",d[d.CLOSE_WITHOUT_RETRY=4999]="CLOSE_WITHOUT_RETRY",d))(kn||{});exports.ClientMsgCode = bn; exports.CrdtType = ct; exports.LiveList = M; exports.LiveMap = N; exports.LiveObject = x; exports.OpCode = dt; exports.ServerMsgCode = vn; exports.WebsocketCloseCodes = kn; exports.asArrayWithLegacyMethods = mt; exports.asPos = Z; exports.assert = Xt; exports.assertNever = U; exports.b64decode = tt; exports.createClient = er; exports.deprecate = Gt; exports.deprecateIf = Ze; exports.errorIf = ao; exports.freeze = R; exports.isChildCrdt = ln; exports.isJsonArray = De; exports.isJsonObject = ae; exports.isJsonScalar = mn; exports.isPlainObject = A; exports.isRootCrdt = lt; exports.legacy_patchImmutableObject = pr; exports.lsonToJson = V; exports.makePosition = z; exports.nn = T; exports.patchLiveObjectKey = In; exports.shallow = yr; exports.throwUsageError = Yt; exports.toPlainLson = Ve; exports.tryParseJson = ge; exports.withTimeout = xe;
|
|
7
7
|
//# sourceMappingURL=index.js.map
|
package/dist/index.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
var Xn=Object.defineProperty,qn=Object.defineProperties;var Zn=Object.getOwnPropertyDescriptors;var Rt=Object.getOwnPropertySymbols;var Qn=Object.prototype.hasOwnProperty,eo=Object.prototype.propertyIsEnumerable;var wt=(t,o,e)=>o in t?Xn(t,o,{enumerable:!0,configurable:!0,writable:!0,value:e}):t[o]=e,C=(t,o)=>{for(var e in o||(o={}))Qn.call(o,e)&&wt(t,e,o[e]);if(Rt)for(var e of Rt(o))eo.call(o,e)&&wt(t,e,o[e]);return t},P=(t,o)=>qn(t,Zn(o));var j=(t,o,e)=>new Promise((n,r)=>{var i=d=>{try{a(e.next(d))}catch(c){r(c)}},s=d=>{try{a(e.throw(d))}catch(c){r(c)}},a=d=>d.done?n(d.value):Promise.resolve(d.value).then(i,s);a((e=e.apply(t,o)).next())});function O(){let t=new Set,o=new Set,e=null;function n(){e=[]}function r(){if(e!==null){for(let b of e)c(b);e=null}}function i(b){return o.add(b),()=>o.delete(b)}function s(b){return t.add(b),()=>t.delete(b)}function a(b){return j(this,null,function*(){let E;return new Promise(G=>{E=i(K=>{(b===void 0||b(K))&&G(K)})}).finally(()=>E==null?void 0:E())})}function d(b){e!==null?e.push(b):c(b)}function c(b){t.forEach(E=>E(b)),t.clear(),o.forEach(E=>E(b))}function f(){t.clear(),o.clear()}function y(){return t.size+o.size}return{notify:d,subscribe:i,subscribeOnce:s,clear:f,count:y,waitUntil:a,pause:n,unpause:r,observable:{subscribe:i,subscribeOnce:s,waitUntil:a}}}var Mt=!1;function Ut(t){Mt=t}function W(t,o){if(process.env.NODE_ENV==="production"||typeof window=="undefined")return;let e=P(C({},t),{source:"liveblocks-devtools-client"});(o!=null&&o.force||Mt)&&window.postMessage(e,"*")}var At=O();process.env.NODE_ENV!=="production"&&typeof window!="undefined"&&window.addEventListener("message",t=>{var o;t.source===window&&((o=t.data)==null?void 0:o.source)==="liveblocks-devtools-panel"&&At.notify(t.data)});var Ge=At.observable;var jt="1.1.1-dual4",Nt=!1;function Jt(t){process.env.NODE_ENV==="production"||typeof window=="undefined"||Nt||(Nt=!0,Ge.subscribe(o=>{switch(o.msg){case"connect":{Ut(!0);for(let e of t())W({msg:"room::available",roomId:e,clientVersion:jt});break}}}),W({msg:"wake-up-devtools"},{force:!0}))}var Ye=new Map;function qe(t){var e;let o=(e=Ye.get(t))!=null?e:[];Ye.delete(t);for(let n of o)n()}function to(t){qe(t.id),so(t),Ye.set(t.id,[t.events.status.subscribe(()=>no(t)),t.events.storageDidLoad.subscribeOnce(()=>Dt(t)),t.events.storage.subscribe(()=>Dt(t)),t.events.me.subscribe(()=>oo(t)),t.events.others.subscribe(()=>ro(t))])}function no(t){W({msg:"room::sync::partial",roomId:t.id,status:t.getStatus()})}function Dt(t){let o=t.getStorageSnapshot();o&&W({msg:"room::sync::partial",roomId:t.id,storage:o.toTreeNode("root").payload})}function oo(t){let o=t.__internal.getSelf_forDevTools();o&&W({msg:"room::sync::partial",roomId:t.id,me:o})}function ro(t){let o=t.__internal.getOthers_forDevTools();o&&W({msg:"room::sync::partial",roomId:t.id,others:o})}function so(t){var r;let o=t.getStorageSnapshot(),e=t.__internal.getSelf_forDevTools(),n=t.__internal.getOthers_forDevTools();W({msg:"room::sync::full",roomId:t.id,status:t.getStatus(),storage:(r=o==null?void 0:o.toTreeNode("root").payload)!=null?r:null,me:e,others:n})}var Xe=new Map;function Kt(t){let o=Xe.get(t);Xe.delete(t),o&&o()}function Bt(t,o){process.env.NODE_ENV==="production"||typeof window=="undefined"||(W({msg:"room::available",roomId:t,clientVersion:jt}),Kt(t),Xe.set(t,Ge.subscribe(e=>{switch(e.msg){case"room::subscribe":{e.roomId===t&&to(o);break}case"room::unsubscribe":{e.roomId===t&&qe(t);break}}})))}function zt(t){process.env.NODE_ENV==="production"||typeof window=="undefined"||(qe(t),Kt(t),W({msg:"room::unavailable",roomId:t}))}var Vt="background:#0e0d12;border-radius:9999px;color:#fff;padding:3px 7px;font-family:sans-serif;font-weight:600;",io="font-weight:600";function Wt(t){return typeof window=="undefined"||process.env.NODE_ENV==="test"?console[t]:(o,...e)=>console[t]("%cLiveblocks",Vt,o,...e)}var F=Wt("warn"),le=Wt("error");function Ft(t){return typeof window=="undefined"||process.env.NODE_ENV==="test"?console[t]:(o,e,...n)=>console[t](`%cLiveblocks%c ${o}`,Vt,io,e,...n)}var Ht=Ft("warn"),ve=Ft("error");var $t=new Set;function Gt(t,o=t){process.env.NODE_ENV!=="production"&&($t.has(o)||($t.add(o),ve("Deprecation warning",t)))}function Ze(t,o,e=o){process.env.NODE_ENV!=="production"&&t&&Gt(o,e)}function Yt(t){if(process.env.NODE_ENV!=="production"){let o=new Error(t);throw o.name="Usage error",ve("Usage error",t),o}}function ao(t,o){process.env.NODE_ENV!=="production"&&t&&Yt(o)}function U(t,o){throw new Error(o)}function Xt(t,o){if(process.env.NODE_ENV!=="production"&&!t){let e=new Error(o);throw e.name="Assertion failure",e}}function T(t,o="Expected value to be non-nullable"){return Xt(t!=null,o),t}function co(t,o){if(t===o)return[0,0];let e=t.split("."),n=o.split("."),r=Math.min(e.length,n.length),i=0;for(;i<r&&e[i]===n[i];i++);let s=e.length-i,a=n.length-i;return[s,a]}function lo(t,o){let e=t.split(".");if(o<1||o>e.length+1)throw new Error("Invalid number of levels");let n=[];o>e.length&&n.push("*");for(let r=e.length-o+1;r<e.length;r++){let i=e.slice(0,r);i.length>0&&n.push(i.join(".")+".*")}return n.push(t),n}var Qe=class{constructor(o){this.curr=o}get current(){return this.curr}allowPatching(o){let e=this,n=!0,r=P(C({},this.curr),{patch(i){if(n){e.curr=Object.assign({},e.curr,i);for(let s of Object.entries(i)){let[a,d]=s;a!=="patch"&&(this[a]=d)}}else throw new Error("Can no longer patch stale context")}});o(r),n=!1}};var po=1,ke=class{get initialState(){let o=this.states.values()[Symbol.iterator]().next();if(o.done)throw new Error("No states defined yet");return o.value}get currentState(){if(this.currentStateOrNull===null)throw this.runningState===0?new Error("Not started yet"):new Error("Already stopped");return this.currentStateOrNull}start(){if(this.runningState!==0)throw new Error("State machine has already started");return this.runningState=1,this.currentStateOrNull=this.initialState,this.enter(null),this}stop(){if(this.runningState!==1)throw new Error("Cannot stop a state machine that hasn't started yet");this.exit(null),this.runningState=2,this.currentStateOrNull=null}constructor(o){this.id=po++,this.runningState=0,this.currentStateOrNull=null,this.states=new Set,this.enterFns=new Map,this.cleanupStack=[],this.knownEventTypes=new Set,this.allowedTransitions=new Map,this.currentContext=new Qe(o),this.eventHub={didReceiveEvent:O(),willTransition:O(),didIgnoreEvent:O(),willExitState:O(),didEnterState:O()},this.events={didReceiveEvent:this.eventHub.didReceiveEvent.observable,willTransition:this.eventHub.willTransition.observable,didIgnoreEvent:this.eventHub.didIgnoreEvent.observable,willExitState:this.eventHub.willExitState.observable,didEnterState:this.eventHub.didEnterState.observable}}get context(){return this.currentContext.current}addState(o){if(this.runningState!==0)throw new Error("Already started");return this.states.add(o),this}onEnter(o,e){if(this.runningState!==0)throw new Error("Already started");if(this.enterFns.has(o))throw new Error(`enter/exit function for ${o} already exists`);return this.enterFns.set(o,e),this}onEnterAsync(o,e,n,r){return this.onEnter(o,()=>{let i=!1;return e(this.currentContext.current).then(s=>{i||this.transition({type:"ASYNC_OK",data:s},n)},s=>{i||this.transition({type:"ASYNC_ERROR",reason:s},r)}),()=>{i=!0}})}getStatesMatching(o){let e=[];if(o==="*")for(let n of this.states)e.push(n);else if(o.endsWith(".*")){let n=o.slice(0,-1);for(let r of this.states)r.startsWith(n)&&e.push(r)}else{let n=o;this.states.has(n)&&e.push(n)}if(e.length===0)throw new Error(`No states match ${JSON.stringify(o)}`);return e}addTransitions(o,e){if(this.runningState!==0)throw new Error("Already started");for(let n of this.getStatesMatching(o)){let r=this.allowedTransitions.get(n);r===void 0&&(r=new Map,this.allowedTransitions.set(n,r));for(let[i,s]of Object.entries(e)){if(r.has(i))throw new Error(`Trying to set transition "${i}" on "${n}" (via "${o}"), but a transition already exists there.`);let a=s;if(this.knownEventTypes.add(i),a!==void 0){let d=typeof a=="function"?a:()=>a;r.set(i,d)}}}return this}addTimedTransition(o,e,n){return this.onEnter(o,()=>{let r=typeof e=="function"?e(this.currentContext.current):e,i=setTimeout(()=>{this.transition({type:"TIMER"},n)},r);return()=>{clearTimeout(i)}})}getTargetFn(o){var e;return(e=this.allowedTransitions.get(this.currentState))==null?void 0:e.get(o)}exit(o){this.eventHub.willExitState.notify(this.currentState),this.currentContext.allowPatching(e=>{var n;o=o!=null?o:this.cleanupStack.length;for(let r=0;r<o;r++)(n=this.cleanupStack.pop())==null||n(e)})}enter(o){let e=lo(this.currentState,o!=null?o:this.currentState.split(".").length+1);this.currentContext.allowPatching(n=>{for(let r of e){let i=this.enterFns.get(r),s=i==null?void 0:i(n);typeof s=="function"?this.cleanupStack.push(s):this.cleanupStack.push(null)}}),this.eventHub.didEnterState.notify(this.currentState)}send(o){if(!this.knownEventTypes.has(o.type))throw new Error(`Invalid event ${JSON.stringify(o.type)}`);if(this.runningState===2)return;let e=this.getTargetFn(o.type);if(e!==void 0)return this.transition(o,e);this.eventHub.didIgnoreEvent.notify(o)}transition(o,e){this.eventHub.didReceiveEvent.notify(o);let n=this.currentState,i=(typeof e=="function"?e:()=>e)(o,this.currentContext.current),s,a;if(i===null){this.eventHub.didIgnoreEvent.notify(o);return}if(typeof i=="string"?s=i:(s=i.target,a=Array.isArray(i.effect)?i.effect:[i.effect]),!this.states.has(s))throw new Error(`Invalid next state name: ${JSON.stringify(s)}`);this.eventHub.willTransition.notify({from:n,to:s});let[d,c]=co(this.currentState,s);if(d>0&&this.exit(d),this.currentStateOrNull=s,a!==void 0){let f=a;this.currentContext.allowPatching(y=>{for(let b of f)typeof b=="function"?b(y,o):y.patch(b)})}c>0&&this.enter(c)}};function A(t){return t!==null&&typeof t=="object"&&Object.prototype.toString.call(t)==="[object Object]"}function qt(t){let o={};for(let[e,n]of t)o[e]=n;return o}function et(t){return Object.entries(t)}function ge(t){try{return JSON.parse(t)}catch(o){return}}function tt(t){try{let o=t.replace(/-/g,"+").replace(/_/g,"/");return decodeURIComponent(atob(o).split("").map(function(n){return"%"+("00"+n.charCodeAt(0).toString(16)).slice(-2)}).join(""))}catch(o){return atob(t)}}function _e(t){return t.filter(o=>o!=null)}function Oe(t){let o=C({},t);return Object.keys(t).forEach(e=>{let n=e;o[n]===void 0&&delete o[n]}),o}function xe(t,o,e="Timed out"){return j(this,null,function*(){let n,r=new Promise((i,s)=>{n=setTimeout(()=>{s(new Error(e))},o)});return Promise.race([t,r]).finally(()=>clearTimeout(n))})}function rt(t){switch(t){case"connecting":return"connecting";case"connected":return"open";case"reconnecting":return"unavailable";case"disconnected":return"failed";case"initial":return"closed";default:return"closed"}}function nn(t){let o=t.currentState;switch(o){case"@ok.connected":case"@ok.awaiting-pong":return"connected";case"@idle.initial":return"initial";case"@auth.busy":case"@auth.backoff":case"@connecting.busy":case"@connecting.backoff":return t.context.successCount>0?"reconnecting":"connecting";case"@idle.failed":return"disconnected";default:return U(o,"Unknown state")}}var on=[250,500,1e3,2e3,4e3,8e3,1e4],Ee=on[0]-1,uo=[2e3,3e4,6e4,3e5],fo=3e4,ho=2e3,yo=1e4,mo=1e4,q=class extends Error{constructor(o){super(o)}},ot=class extends Error{constructor(e,n){super(e);this.code=n}};function rn(t,o=on){var e;return(e=o.find(n=>n>t))!=null?e:o[o.length-1]}function pe(t){t.patch({backoffDelay:rn(t.backoffDelay)})}function Zt(t){t.patch({backoffDelay:rn(t.backoffDelay,uo)})}function Qt(t){t.patch({successCount:0})}function ue(t,o){let e=t===2?le:t===1?F:()=>{};return()=>{e(o)}}function en(t){let o="Connection to Liveblocks websocket server";return e=>{t instanceof Error?F(`${o} could not be established. ${String(t)}`):F(st(t)?`${o} closed prematurely (code: ${t.code}). Retrying in ${e.backoffDelay}ms.`:`${o} could not be established.`)}}function nt(t){return o=>{F(`Connection to Liveblocks websocket server closed (code: ${t.code}). Retrying in ${o.backoffDelay}ms.`)}}var To=ue(1,"Connection to WebSocket closed permanently. Won't retry.");function st(t){return!(t instanceof Error)&&t.type==="close"}function tn(t){return st(t)&&t.code>=4e3&&t.code<4100}function bo(t){let o=new Date().getTime();function e(...r){F(`${((new Date().getTime()-o)/1e3).toFixed(2)} [FSM #${t.id}]`,...r)}let n=[t.events.didReceiveEvent.subscribe(r=>e(`Event ${r.type}`)),t.events.willTransition.subscribe(({from:r,to:i})=>e("Transitioning",r,"\u2192",i)),t.events.didIgnoreEvent.subscribe(r=>e("Ignored event",r.type,r,"(current state won't handle it)"))];return()=>{for(let r of n)r()}}function vo(t){let o=O(),e=O(),n=O(),r=null,i=t.events.didEnterState.subscribe(()=>{let s=nn(t);s!==r&&o.notify(s),r==="connected"&&s!=="connected"?n.notify():r!=="connected"&&s==="connected"&&e.notify(),r=s});return{statusDidChange:o.observable,didConnect:e.observable,didDisconnect:n.observable,unsubscribe:i}}var Pe=t=>o=>o.patch(t);function go(t,o){let e=O();e.pause();let n=O(),r={successCount:0,token:null,socket:null,backoffDelay:Ee},i=new ke(r).addState("@idle.initial").addState("@idle.failed").addState("@auth.busy").addState("@auth.backoff").addState("@connecting.busy").addState("@connecting.backoff").addState("@ok.connected").addState("@ok.awaiting-pong");i.addTransitions("*",{RECONNECT:{target:"@auth.backoff",effect:[pe,Qt]},DISCONNECT:"@idle.initial"}),i.onEnter("@idle.*",Qt).addTransitions("@idle.*",{CONNECT:(m,h)=>h.token!==null?"@connecting.busy":"@auth.busy"}),i.addTransitions("@auth.backoff",{NAVIGATOR_ONLINE:{target:"@auth.busy",effect:Pe({backoffDelay:Ee})}}).addTimedTransition("@auth.backoff",m=>m.backoffDelay,"@auth.busy").onEnterAsync("@auth.busy",()=>xe(t.authenticate(),yo),m=>({target:"@connecting.busy",effect:Pe({token:m.data,backoffDelay:Ee})}),m=>m.reason instanceof q?{target:"@idle.failed",effect:ue(2,m.reason.message)}:{target:"@auth.backoff",effect:[pe,ue(2,`Authentication failed: ${m.reason instanceof Error?m.reason.message:String(m.reason)}`)]});let s=m=>i.send({type:"EXPLICIT_SOCKET_ERROR",event:m}),a=m=>i.send({type:"EXPLICIT_SOCKET_CLOSE",event:m}),d=m=>m.data==="pong"?i.send({type:"PONG"}):e.notify(m);function c(m){m&&(m.removeEventListener("error",s),m.removeEventListener("close",a),m.removeEventListener("message",d),m.close())}i.addTransitions("@connecting.backoff",{NAVIGATOR_ONLINE:{target:"@connecting.busy",effect:Pe({backoffDelay:Ee})}}).addTimedTransition("@connecting.backoff",m=>m.backoffDelay,"@connecting.busy").onEnterAsync("@connecting.busy",m=>j(this,null,function*(){let h=null,L=new Promise((te,ne)=>{if(m.token===null)throw new Error("No auth token");let w=t.createSocket(m.token);function Y(ce){h=ce,w.removeEventListener("message",d),ne(ce)}w.addEventListener("message",d),w.addEventListener("error",Y),w.addEventListener("close",Y),w.addEventListener("open",()=>{w.addEventListener("error",s),w.addEventListener("close",a),te([w,()=>{w.removeEventListener("error",Y),w.removeEventListener("close",Y)}])})});return xe(L,mo).then(([te,ne])=>{if(ne(),h)throw h;return te})}),m=>({target:"@ok.connected",effect:Pe({socket:m.data,backoffDelay:Ee})}),m=>{let h=m.reason;return h instanceof q?{target:"@idle.failed",effect:ue(2,h.message)}:st(h)&&h.code===4999?{target:"@idle.failed",effect:ue(2,h.reason)}:tn(h)&&h.code!==4001?{target:"@connecting.backoff",effect:[Zt,en(h)]}:{target:"@auth.backoff",effect:[pe,en(h)]}});let f={target:"@ok.awaiting-pong",effect:m=>{var h;(h=m.socket)==null||h.send("ping")}};if(i.addTimedTransition("@ok.connected",fo,f).addTransitions("@ok.connected",{NAVIGATOR_OFFLINE:f,WINDOW_GOT_FOCUS:f}),i.onEnter("@ok.*",m=>{m.patch({successCount:m.successCount+1});let h=setTimeout(e.unpause,0);return L=>{c(L.socket),L.patch({socket:null}),clearTimeout(h),e.pause()}}).addTransitions("@ok.awaiting-pong",{PONG:"@ok.connected"}).addTimedTransition("@ok.awaiting-pong",ho,{target:"@connecting.busy",effect:ue(1,"Received no pong from server, assume implicit connection loss.")}).addTransitions("@ok.*",{EXPLICIT_SOCKET_ERROR:(m,h)=>{var L;return((L=h.socket)==null?void 0:L.readyState)===1?null:{target:"@connecting.backoff",effect:pe}},EXPLICIT_SOCKET_CLOSE:m=>m.event.code===4999?{target:"@idle.failed",effect:To}:m.event.code===4001?{target:"@auth.backoff",effect:[pe,nt(m.event)]}:tn(m.event)?{target:"@connecting.backoff",effect:[Zt,nt(m.event),()=>{let h=new ot(m.event.reason,m.event.code);n.notify(h)}]}:{target:"@connecting.backoff",effect:[pe,nt(m.event)]}}),typeof document!="undefined"){let m=typeof document!="undefined"?document:void 0,h=typeof window!="undefined"?window:void 0,L=h!=null?h:m;i.onEnter("*",te=>{function ne(){i.send({type:"NAVIGATOR_OFFLINE"})}function w(){i.send({type:"NAVIGATOR_ONLINE"})}function Y(){(m==null?void 0:m.visibilityState)==="visible"&&i.send({type:"WINDOW_GOT_FOCUS"})}return h==null||h.addEventListener("online",w),h==null||h.addEventListener("offline",ne),L==null||L.addEventListener("visibilitychange",Y),()=>{L==null||L.removeEventListener("visibilitychange",Y),h==null||h.removeEventListener("online",w),h==null||h.removeEventListener("offline",ne),c(te.socket)}})}let y=[],{statusDidChange:b,didConnect:E,didDisconnect:G,unsubscribe:K}=vo(i);return y.push(K),o&&y.push(bo(i)),i.start(),{machine:i,cleanups:y,events:{statusDidChange:b,didConnect:E,didDisconnect:G,onMessage:e.observable,onLiveblocksError:n.observable}}}var Re=class{constructor(o,e=!1){let{machine:n,events:r,cleanups:i}=go(o,e);this.machine=n,this.events=r,this.cleanups=i}getLegacyStatus(){return rt(this.getStatus())}getStatus(){try{return nn(this.machine)}catch(o){return"initial"}}get token(){return this.machine.context.token}connect(){this.machine.send({type:"CONNECT"})}reconnect(){this.machine.send({type:"RECONNECT"})}disconnect(){this.machine.send({type:"DISCONNECT"})}destroy(){this.machine.stop();let o;for(;o=this.cleanups.pop();)o()}send(o){var n;let e=(n=this.machine.context)==null?void 0:n.socket;e===null?F("Cannot send: not connected yet",o):e.readyState!==1?F("Cannot send: WebSocket no longer open",o):e.send(o)}_privateSendMachineEvent(o){this.machine.send(o)}};var sn=at(0),we=at(1),_o=sn+at(-1);function at(t){let o=32+(t<0?95+t:t);if(o<32||o>126)throw new Error(`Invalid n value: ${t}`);return String.fromCharCode(o)}function z(t,o){return t!==void 0&&o!==void 0?So(t,o):t!==void 0?Eo(t):o!==void 0?Oo(o):we}function Oo(t){let o=t.length-1;for(let e=0;e<=o;e++){let n=t.charCodeAt(e);if(!(n<=32))return e===o?n===32+1?t.substring(0,e)+_o:t.substring(0,e)+String.fromCharCode(n-1):t.substring(0,e+1)}return we}function Eo(t){for(let o=0;o<=t.length-1;o++){let e=t.charCodeAt(o);if(!(e>=126))return t.substring(0,o)+String.fromCharCode(e+1)}return t+we}function So(t,o){if(t<o)return it(t,o);if(t>o)return it(o,t);throw new Error("Cannot compute value between two equal positions")}function it(t,o){let e=0,n=t.length,r=o.length;for(;;){let i=e<n?t.charCodeAt(e):32,s=e<r?o.charCodeAt(e):126;if(i===s){e++;continue}if(s-i===1){let a=t.substring(0,e+1),d=t.substring(e+1);return a+it(d,"")}else return Co(t,e)+String.fromCharCode(s+i>>1)}}function Co(t,o){return o<t.length?t.substring(0,o):t+sn.repeat(o-t.length)}var Io=32+1;function Lo(t){if(t==="")return!1;let o=t.length-1,e=t.charCodeAt(o);if(e<Io||e>126)return!1;for(let n=0;n<o;n++){let r=t.charCodeAt(n);if(r<32||r>126)return!1}return!0}function ko(t){let o=[];for(let e=0;e<t.length;e++){let n=t.charCodeAt(e);o.push(n<32?32:n>126?126:n)}for(;o.length>0&&o[o.length-1]===32;)o.length--;return o.length>0?String.fromCharCode(...o):we}function Z(t){return Lo(t)?t:ko(t)}var dt=(c=>(c[c.INIT=0]="INIT",c[c.SET_PARENT_KEY=1]="SET_PARENT_KEY",c[c.CREATE_LIST=2]="CREATE_LIST",c[c.UPDATE_OBJECT=3]="UPDATE_OBJECT",c[c.CREATE_OBJECT=4]="CREATE_OBJECT",c[c.DELETE_CRDT=5]="DELETE_CRDT",c[c.DELETE_OBJECT_KEY=6]="DELETE_OBJECT_KEY",c[c.CREATE_MAP=7]="CREATE_MAP",c[c.CREATE_REGISTER=8]="CREATE_REGISTER",c))(dt||{});function an(t){return t.type===5&&t.id==="ACK"}function dn(t,o,e=Z(o)){return Object.freeze({type:"HasParent",node:t,key:o,pos:e})}var cn=Object.freeze({type:"NoParent"});function xo(t,o=Z(t)){return Object.freeze({type:"Orphaned",oldKey:t,oldPos:o})}var H=class{constructor(){this._parent=cn}_getParentKeyOrThrow(){switch(this.parent.type){case"HasParent":return this.parent.key;case"NoParent":throw new Error("Parent key is missing");case"Orphaned":return this.parent.oldKey;default:return U(this.parent,"Unknown state")}}get _parentPos(){switch(this.parent.type){case"HasParent":return this.parent.pos;case"NoParent":throw new Error("Parent key is missing");case"Orphaned":return this.parent.oldPos;default:return U(this.parent,"Unknown state")}}get _pool(){return this.__pool}get roomId(){return this.__pool?this.__pool.roomId:null}get _id(){return this.__id}get parent(){return this._parent}get _parentKey(){switch(this.parent.type){case"HasParent":return this.parent.key;case"NoParent":return null;case"Orphaned":return this.parent.oldKey;default:return U(this.parent,"Unknown state")}}_apply(o,e){switch(o.type){case 5:return this.parent.type==="HasParent"?this.parent.node._detachChild(this):{modified:!1}}return{modified:!1}}_setParentLink(o,e){switch(this.parent.type){case"HasParent":if(this.parent.node!==o)throw new Error("Cannot set parent: node already has a parent");this._parent=dn(o,e);return;case"Orphaned":case"NoParent":{this._parent=dn(o,e);return}default:return U(this.parent,"Unknown state")}}_attach(o,e){if(this.__id||this.__pool)throw new Error("Cannot attach node: already attached");e.addNode(o,this),this.__id=o,this.__pool=e}_detach(){switch(this.__pool&&this.__id&&this.__pool.deleteNode(this.__id),this.parent.type){case"HasParent":{this._parent=xo(this.parent.key,this.parent.pos);break}case"NoParent":{this._parent=cn;break}case"Orphaned":break;default:U(this.parent,"Unknown state")}this.__pool=void 0}invalidate(){(this._cachedImmutable!==void 0||this._cachedTreeNode!==void 0)&&(this._cachedImmutable=void 0,this._cachedTreeNode=void 0,this.parent.type==="HasParent"&&this.parent.node.invalidate())}toTreeNode(o){return(this._cachedTreeNode===void 0||this._cachedTreeNodeKey!==o)&&(this._cachedTreeNodeKey=o,this._cachedTreeNode=this._toTreeNode(o)),this._cachedTreeNode}toImmutable(){return this._cachedImmutable===void 0&&(this._cachedImmutable=this._toImmutable()),this._cachedImmutable}};var ct=(r=>(r[r.OBJECT=0]="OBJECT",r[r.LIST=1]="LIST",r[r.MAP=2]="MAP",r[r.REGISTER=3]="REGISTER",r))(ct||{});function lt(t){return t.type===0&&!ln(t)}function ln(t){return t.parentId!==void 0&&t.parentKey!==void 0}function oe(t=7){let o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789,./;[]~!@#$%&*()_+=-",e=o.length;return Array.from({length:t},()=>o.charAt(Math.floor(Math.random()*e))).join("")}var J=class t extends H{constructor(e){super();this._data=e}get data(){return this._data}static _deserialize([e,n],r,i){let s=new t(n.data);return s._attach(e,i),s}_toOps(e,n,r){if(this._id===void 0)throw new Error("Cannot serialize register if parentId or parentKey is undefined");return[{type:8,opId:r==null?void 0:r.generateOpId(),id:this._id,parentId:e,parentKey:n,data:this.data}]}_serialize(){if(this.parent.type!=="HasParent")throw new Error("Cannot serialize LiveRegister if parent is missing");return{type:3,parentId:T(this.parent.node._id,"Parent node expected to have ID"),parentKey:this.parent.key,data:this.data}}_attachChild(e){throw new Error("Method not implemented.")}_detachChild(e){throw new Error("Method not implemented.")}_apply(e,n){return super._apply(e,n)}_toTreeNode(e){var n;return{type:"Json",id:(n=this._id)!=null?n:oe(),key:e,payload:this._data}}_toImmutable(){return this._data}};function Po(t,o){let e=t._parentPos,n=o._parentPos;return e===n?0:e<n?-1:1}var M=class t extends H{constructor(e=[]){super();this._items=[],this._implicitlyDeletedItems=new WeakSet,this._unacknowledgedSets=new Map;let n;for(let r of e){let i=z(n),s=re(r);s._setParentLink(this,i),this._items.push(s),n=i}}static _deserialize([e],n,r){let i=new t;i._attach(e,r);let s=n.get(e);if(s===void 0)return i;for(let[a,d]of s){let c=Ue([a,d],n,r);c._setParentLink(i,d.parentKey),i._insertAndSort(c)}return i}_toOps(e,n,r){if(this._id===void 0)throw new Error("Cannot serialize item is not attached");let i=[],s={id:this._id,opId:r==null?void 0:r.generateOpId(),type:2,parentId:e,parentKey:n};i.push(s);for(let a of this._items)i.push(...a._toOps(this._id,a._getParentKeyOrThrow(),r));return i}_insertAndSort(e){this._items.push(e),this._sortItems()}_sortItems(){this._items.sort(Po),this.invalidate()}_indexOfPosition(e){return this._items.findIndex(n=>n._getParentKeyOrThrow()===e)}_attach(e,n){super._attach(e,n);for(let r of this._items)r._attach(n.generateId(),n)}_detach(){super._detach();for(let e of this._items)e._detach()}_applySetRemote(e){if(this._pool===void 0)throw new Error("Can't attach child if managed pool is not present");let{id:n,parentKey:r}=e,i=ie(e);i._attach(n,this._pool),i._setParentLink(this,r);let s=e.deletedId,a=this._indexOfPosition(r);if(a!==-1){let d=this._items[a];if(d._id===s)return d._detach(),this._items[a]=i,{modified:S(this,[fe(a,i)]),reverse:[]};{this._implicitlyDeletedItems.add(d),this._items[a]=i;let c=[fe(a,i)],f=this._detachItemAssociatedToSetOperation(e.deletedId);return f&&c.push(f),{modified:S(this,c),reverse:[]}}}else{let d=[],c=this._detachItemAssociatedToSetOperation(e.deletedId);return c&&d.push(c),this._insertAndSort(i),d.push($(this._indexOfPosition(r),i)),{reverse:[],modified:S(this,d)}}}_applySetAck(e){if(this._pool===void 0)throw new Error("Can't attach child if managed pool is not present");let n=[],r=this._detachItemAssociatedToSetOperation(e.deletedId);r&&n.push(r);let i=this._unacknowledgedSets.get(e.parentKey);if(i!==void 0){if(i!==e.opId)return n.length===0?{modified:!1}:{modified:S(this,n),reverse:[]};this._unacknowledgedSets.delete(e.parentKey)}let s=this._indexOfPosition(e.parentKey),a=this._items.find(d=>d._id===e.id);if(a!==void 0){if(a._parentKey===e.parentKey)return{modified:n.length>0?S(this,n):!1,reverse:[]};s!==-1&&(this._implicitlyDeletedItems.add(this._items[s]),this._items.splice(s,1),n.push(Me(s)));let d=this._items.indexOf(a);a._setParentLink(this,e.parentKey),this._sortItems();let c=this._items.indexOf(a);return c!==d&&n.push(se(d,c,a)),{modified:n.length>0?S(this,n):!1,reverse:[]}}else{let d=this._pool.getNode(e.id);if(d&&this._implicitlyDeletedItems.has(d)){d._setParentLink(this,e.parentKey),this._implicitlyDeletedItems.delete(d),this._insertAndSort(d);let c=this._items.indexOf(d);return{modified:S(this,[s===-1?$(c,d):fe(c,d),...n]),reverse:[]}}else{s!==-1&&this._items.splice(s,1);let{newItem:c,newIndex:f}=this._createAttachItemAndSort(e,e.parentKey);return{modified:S(this,[s===-1?$(f,c):fe(f,c),...n]),reverse:[]}}}}_detachItemAssociatedToSetOperation(e){if(e===void 0||this._pool===void 0)return null;let n=this._pool.getNode(e);if(n===void 0)return null;let r=this._detachChild(n);return r.modified===!1?null:r.modified.updates[0]}_applyRemoteInsert(e){if(this._pool===void 0)throw new Error("Can't attach child if managed pool is not present");let n=Z(e.parentKey),r=this._indexOfPosition(n);r!==-1&&this._shiftItemPosition(r,n);let{newItem:i,newIndex:s}=this._createAttachItemAndSort(e,n);return{modified:S(this,[$(s,i)]),reverse:[]}}_applyInsertAck(e){let n=this._items.find(s=>s._id===e.id),r=Z(e.parentKey),i=this._indexOfPosition(r);if(n){if(n._parentKey===r)return{modified:!1};{let s=this._items.indexOf(n);i!==-1&&this._shiftItemPosition(i,r),n._setParentLink(this,r),this._sortItems();let a=this._indexOfPosition(r);return a===s?{modified:!1}:{modified:S(this,[se(s,a,n)]),reverse:[]}}}else{let s=T(this._pool).getNode(e.id);if(s&&this._implicitlyDeletedItems.has(s)){s._setParentLink(this,r),this._implicitlyDeletedItems.delete(s),this._insertAndSort(s);let a=this._indexOfPosition(r);return{modified:S(this,[$(a,s)]),reverse:[]}}else{i!==-1&&this._shiftItemPosition(i,r);let{newItem:a,newIndex:d}=this._createAttachItemAndSort(e,r);return{modified:S(this,[$(d,a)]),reverse:[]}}}}_applyInsertUndoRedo(e){var c,f,y;let{id:n,parentKey:r}=e,i=ie(e);if(((c=this._pool)==null?void 0:c.getNode(n))!==void 0)return{modified:!1};i._attach(n,T(this._pool)),i._setParentLink(this,r);let s=this._indexOfPosition(r),a=r;if(s!==-1){let b=(f=this._items[s])==null?void 0:f._parentPos,E=(y=this._items[s+1])==null?void 0:y._parentPos;a=z(b,E),i._setParentLink(this,a)}this._insertAndSort(i);let d=this._indexOfPosition(a);return{modified:S(this,[$(d,i)]),reverse:[{type:5,id:n}]}}_applySetUndoRedo(e){var d;let{id:n,parentKey:r}=e,i=ie(e);if(((d=this._pool)==null?void 0:d.getNode(n))!==void 0)return{modified:!1};this._unacknowledgedSets.set(r,T(e.opId));let s=this._indexOfPosition(r);i._attach(n,T(this._pool)),i._setParentLink(this,r);let a=r;if(s!==-1){let c=this._items[s];c._detach(),this._items[s]=i;let f=pt(c._toOps(T(this._id),r,this._pool),e.id),y=[fe(s,i)],b=this._detachItemAssociatedToSetOperation(e.deletedId);return b&&y.push(b),{modified:S(this,y),reverse:f}}else{this._insertAndSort(i),this._detachItemAssociatedToSetOperation(e.deletedId);let c=this._indexOfPosition(a);return{reverse:[{type:5,id:n}],modified:S(this,[$(c,i)])}}}_attachChild(e,n){if(this._pool===void 0)throw new Error("Can't attach child if managed pool is not present");let r;return e.intent==="set"?n===1?r=this._applySetRemote(e):n===2?r=this._applySetAck(e):r=this._applySetUndoRedo(e):n===1?r=this._applyRemoteInsert(e):n===2?r=this._applyInsertAck(e):r=this._applyInsertUndoRedo(e),r.modified!==!1&&this.invalidate(),r}_detachChild(e){if(e){let n=T(e._parentKey),r=e._toOps(T(this._id),n,this._pool),i=this._items.indexOf(e);return i===-1?{modified:!1}:(this._items.splice(i,1),this.invalidate(),e._detach(),{modified:S(this,[Me(i)]),reverse:r})}return{modified:!1}}_applySetChildKeyRemote(e,n){var s;if(this._implicitlyDeletedItems.has(n)){this._implicitlyDeletedItems.delete(n),n._setParentLink(this,e),this._insertAndSort(n);let a=this._items.indexOf(n);return{modified:S(this,[$(a,n)]),reverse:[]}}let r=n._parentKey;if(e===r)return{modified:!1};let i=this._indexOfPosition(e);if(i===-1){let a=this._items.indexOf(n);n._setParentLink(this,e),this._sortItems();let d=this._items.indexOf(n);return d===a?{modified:!1}:{modified:S(this,[se(a,d,n)]),reverse:[]}}else{this._items[i]._setParentLink(this,z(e,(s=this._items[i+1])==null?void 0:s._parentPos));let a=this._items.indexOf(n);n._setParentLink(this,e),this._sortItems();let d=this._items.indexOf(n);return d===a?{modified:!1}:{modified:S(this,[se(a,d,n)]),reverse:[]}}}_applySetChildKeyAck(e,n){var i,s;let r=T(n._parentKey);if(this._implicitlyDeletedItems.has(n)){let a=this._indexOfPosition(e);return this._implicitlyDeletedItems.delete(n),a!==-1&&this._items[a]._setParentLink(this,z(e,(i=this._items[a+1])==null?void 0:i._parentPos)),n._setParentLink(this,e),this._insertAndSort(n),{modified:!1}}else{if(e===r)return{modified:!1};let a=this._items.indexOf(n),d=this._indexOfPosition(e);d!==-1&&this._items[d]._setParentLink(this,z(e,(s=this._items[d+1])==null?void 0:s._parentPos)),n._setParentLink(this,e),this._sortItems();let c=this._items.indexOf(n);return a===c?{modified:!1}:{modified:S(this,[se(a,c,n)]),reverse:[]}}}_applySetChildKeyUndoRedo(e,n){var d;let r=T(n._parentKey),i=this._items.indexOf(n),s=this._indexOfPosition(e);s!==-1&&this._items[s]._setParentLink(this,z(e,(d=this._items[s+1])==null?void 0:d._parentPos)),n._setParentLink(this,e),this._sortItems();let a=this._items.indexOf(n);return i===a?{modified:!1}:{modified:S(this,[se(i,a,n)]),reverse:[{type:1,id:T(n._id),parentKey:r}]}}_setChildKey(e,n,r){return r===1?this._applySetChildKeyRemote(e,n):r===2?this._applySetChildKeyAck(e,n):this._applySetChildKeyUndoRedo(e,n)}_apply(e,n){return super._apply(e,n)}_serialize(){if(this.parent.type!=="HasParent")throw new Error("Cannot serialize LiveList if parent is missing");return{type:1,parentId:T(this.parent.node._id,"Parent node expected to have ID"),parentKey:this.parent.key}}get length(){return this._items.length}push(e){var n;return(n=this._pool)==null||n.assertStorageIsWritable(),this.insert(e,this.length)}insert(e,n){var d;if((d=this._pool)==null||d.assertStorageIsWritable(),n<0||n>this._items.length)throw new Error(`Cannot insert list item at index "${n}". index should be between 0 and ${this._items.length}`);let r=this._items[n-1]?this._items[n-1]._parentPos:void 0,i=this._items[n]?this._items[n]._parentPos:void 0,s=z(r,i),a=re(e);if(a._setParentLink(this,s),this._insertAndSort(a),this._pool&&this._id){let c=this._pool.generateId();a._attach(c,this._pool),this._pool.dispatch(a._toOps(this._id,s,this._pool),[{type:5,id:c}],new Map([[this._id,S(this,[$(n,a)])]]))}}move(e,n){var c;if((c=this._pool)==null||c.assertStorageIsWritable(),n<0)throw new Error("targetIndex cannot be less than 0");if(n>=this._items.length)throw new Error("targetIndex cannot be greater or equal than the list length");if(e<0)throw new Error("index cannot be less than 0");if(e>=this._items.length)throw new Error("index cannot be greater or equal than the list length");let r=null,i=null;e<n?(i=n===this._items.length-1?void 0:this._items[n+1]._parentPos,r=this._items[n]._parentPos):(i=this._items[n]._parentPos,r=n===0?void 0:this._items[n-1]._parentPos);let s=z(r,i),a=this._items[e],d=a._getParentKeyOrThrow();if(a._setParentLink(this,s),this._sortItems(),this._pool&&this._id){let f=new Map([[this._id,S(this,[se(e,n,a)])]]);this._pool.dispatch([{type:1,id:T(a._id),opId:this._pool.generateOpId(),parentKey:s}],[{type:1,id:T(a._id),parentKey:d}],f)}}delete(e){var r;if((r=this._pool)==null||r.assertStorageIsWritable(),e<0||e>=this._items.length)throw new Error(`Cannot delete list item at index "${e}". index should be between 0 and ${this._items.length-1}`);let n=this._items[e];if(n._detach(),this._items.splice(e,1),this.invalidate(),this._pool){let i=n._id;if(i){let s=new Map;s.set(T(this._id),S(this,[Me(e)])),this._pool.dispatch([{id:i,opId:this._pool.generateOpId(),type:5}],n._toOps(T(this._id),n._getParentKeyOrThrow()),s)}}}clear(){var e;if((e=this._pool)==null||e.assertStorageIsWritable(),this._pool){let n=[],r=[],i=[];for(let a of this._items){a._detach();let d=a._id;d&&(n.push({type:5,id:d,opId:this._pool.generateOpId()}),r.push(...a._toOps(T(this._id),a._getParentKeyOrThrow())),i.push(Me(0)))}this._items=[],this.invalidate();let s=new Map;s.set(T(this._id),S(this,i)),this._pool.dispatch(n,r,s)}else{for(let n of this._items)n._detach();this._items=[],this.invalidate()}}set(e,n){var d;if((d=this._pool)==null||d.assertStorageIsWritable(),e<0||e>=this._items.length)throw new Error(`Cannot set list item at index "${e}". index should be between 0 and ${this._items.length-1}`);let r=this._items[e],i=r._getParentKeyOrThrow(),s=r._id;r._detach();let a=re(n);if(a._setParentLink(this,i),this._items[e]=a,this.invalidate(),this._pool&&this._id){let c=this._pool.generateId();a._attach(c,this._pool);let f=new Map;f.set(this._id,S(this,[fe(e,a)]));let y=pt(a._toOps(this._id,i,this._pool),s);this._unacknowledgedSets.set(i,T(y[0].opId));let b=pt(r._toOps(this._id,i,void 0),c);this._pool.dispatch(y,b,f)}}toArray(){return this._items.map(e=>Q(e))}every(e){return this.toArray().every(e)}filter(e){return this.toArray().filter(e)}find(e){return this.toArray().find(e)}findIndex(e){return this.toArray().findIndex(e)}forEach(e){return this.toArray().forEach(e)}get(e){if(!(e<0||e>=this._items.length))return Q(this._items[e])}indexOf(e,n){return this.toArray().indexOf(e,n)}lastIndexOf(e,n){return this.toArray().lastIndexOf(e,n)}map(e){return this._items.map((n,r)=>e(Q(n),r))}some(e){return this.toArray().some(e)}[Symbol.iterator](){return new ut(this._items)}_createAttachItemAndSort(e,n){let r=ie(e);r._attach(e.id,T(this._pool)),r._setParentLink(this,n),this._insertAndSort(r);let i=this._indexOfPosition(n);return{newItem:r,newIndex:i}}_shiftItemPosition(e,n){var i;let r=z(n,this._items.length>e+1?(i=this._items[e+1])==null?void 0:i._parentPos:void 0);this._items[e]._setParentLink(this,r)}_toTreeNode(e){var n;return{type:"LiveList",id:(n=this._id)!=null?n:oe(),key:e,payload:this._items.map((r,i)=>r.toTreeNode(i.toString()))}}toImmutable(){return super.toImmutable()}_toImmutable(){let e=this._items.map(n=>n.toImmutable());return process.env.NODE_ENV==="production"?e:Object.freeze(e)}},ut=class{constructor(o){this._innerIterator=o[Symbol.iterator]()}[Symbol.iterator](){return this}next(){let o=this._innerIterator.next();return o.done?{done:!0,value:void 0}:{value:Q(o.value)}}};function S(t,o){return{node:t,type:"LiveList",updates:o}}function fe(t,o){return{index:t,type:"set",item:o instanceof J?o.data:o}}function Me(t){return{index:t,type:"delete"}}function $(t,o){return{index:t,type:"insert",item:o instanceof J?o.data:o}}function se(t,o,e){return{index:o,type:"move",previousIndex:t,item:e instanceof J?e.data:e}}function pt(t,o){return t.map((e,n)=>n===0?P(C({},e),{intent:"set",deletedId:o}):e)}var R=process.env.NODE_ENV==="production"?t=>t:Object.freeze;var N=class t extends H{constructor(e){super();if(this.unacknowledgedSet=new Map,e){let n=[];for(let r of e){let i=re(r[1]);i._setParentLink(this,r[0]),n.push([r[0],i])}this._map=new Map(n)}else this._map=new Map}_toOps(e,n,r){if(this._id===void 0)throw new Error("Cannot serialize item is not attached");let i=[],s={id:this._id,opId:r==null?void 0:r.generateOpId(),type:7,parentId:e,parentKey:n};i.push(s);for(let[a,d]of this._map)i.push(...d._toOps(this._id,a,r));return i}static _deserialize([e,n],r,i){let s=new t;s._attach(e,i);let a=r.get(e);if(a===void 0)return s;for(let[d,c]of a){let f=Ue([d,c],r,i);f._setParentLink(s,c.parentKey),s._map.set(c.parentKey,f),s.invalidate()}return s}_attach(e,n){super._attach(e,n);for(let[r,i]of this._map)I(i)&&i._attach(n.generateId(),n)}_attachChild(e,n){if(this._pool===void 0)throw new Error("Can't attach child if managed pool is not present");let{id:r,parentKey:i,opId:s}=e,a=i,d=ie(e);if(this._pool.getNode(r)!==void 0)return{modified:!1};if(n===2){let y=this.unacknowledgedSet.get(a);if(y===s)return this.unacknowledgedSet.delete(a),{modified:!1};if(y!==void 0)return{modified:!1}}else n===1&&this.unacknowledgedSet.delete(a);let c=this._map.get(a),f;if(c){let y=T(this._id);f=c._toOps(y,a),c._detach()}else f=[{type:5,id:r}];return d._setParentLink(this,a),d._attach(r,this._pool),this._map.set(a,d),this.invalidate(),{modified:{node:this,type:"LiveMap",updates:{[a]:{type:"update"}}},reverse:f}}_detach(){super._detach();for(let e of this._map.values())e._detach()}_detachChild(e){let n=T(this._id),r=T(e._parentKey),i=e._toOps(n,r,this._pool);for(let[a,d]of this._map)d===e&&(this._map.delete(a),this.invalidate());return e._detach(),{modified:{node:this,type:"LiveMap",updates:{[r]:{type:"delete"}}},reverse:i}}_serialize(){if(this.parent.type!=="HasParent")throw new Error("Cannot serialize LiveMap if parent is missing");return{type:2,parentId:T(this.parent.node._id,"Parent node expected to have ID"),parentKey:this.parent.key}}get(e){let n=this._map.get(e);if(n!==void 0)return Q(n)}set(e,n){var s;(s=this._pool)==null||s.assertStorageIsWritable();let r=this._map.get(e);r&&r._detach();let i=re(n);if(i._setParentLink(this,e),this._map.set(e,i),this.invalidate(),this._pool&&this._id){let a=this._pool.generateId();i._attach(a,this._pool);let d=new Map;d.set(this._id,{node:this,type:"LiveMap",updates:{[e]:{type:"update"}}});let c=i._toOps(this._id,e,this._pool);this.unacknowledgedSet.set(e,T(c[0].opId)),this._pool.dispatch(i._toOps(this._id,e,this._pool),r?r._toOps(this._id,e):[{type:5,id:a}],d)}}get size(){return this._map.size}has(e){return this._map.has(e)}delete(e){var r;(r=this._pool)==null||r.assertStorageIsWritable();let n=this._map.get(e);if(n===void 0)return!1;if(n._detach(),this._map.delete(e),this.invalidate(),this._pool&&n._id){let i=T(this._id),s=new Map;s.set(i,{node:this,type:"LiveMap",updates:{[e]:{type:"delete"}}}),this._pool.dispatch([{type:5,id:n._id,opId:this._pool.generateOpId()}],n._toOps(i,e),s)}return!0}entries(){let e=this._map.entries();return{[Symbol.iterator](){return this},next(){let n=e.next();if(n.done)return{done:!0,value:void 0};let i=n.value[0],s=Q(n.value[1]);return{value:[i,s]}}}}[Symbol.iterator](){return this.entries()}keys(){return this._map.keys()}values(){let e=this._map.values();return{[Symbol.iterator](){return this},next(){let n=e.next();return n.done?{done:!0,value:void 0}:{value:Q(n.value)}}}}forEach(e){for(let n of this)e(n[1],n[0],this)}_toTreeNode(e){var n;return{type:"LiveMap",id:(n=this._id)!=null?n:oe(),key:e,payload:Array.from(this._map.entries()).map(([r,i])=>i.toTreeNode(r))}}toImmutable(){return super.toImmutable()}_toImmutable(){let e=new Map;for(let[n,r]of this._map)e.set(n,r.toImmutable());return R(e)}};var x=class t extends H{constructor(e={}){super();this._propToLastUpdate=new Map;for(let n in e){let r=e[n];r!==void 0&&I(r)&&r._setParentLink(this,n)}this._map=new Map(Object.entries(e))}static _buildRootAndParentToChildren(e){let n=new Map,r=null;for(let[i,s]of e)if(lt(s))r=[i,s];else{let a=[i,s],d=n.get(s.parentId);d!==void 0?d.push(a):n.set(s.parentId,[a])}if(r===null)throw new Error("Root can't be null");return[r,n]}static _fromItems(e,n){let[r,i]=t._buildRootAndParentToChildren(e);return t._deserialize(r,i,n)}_toOps(e,n,r){if(this._id===void 0)throw new Error("Cannot serialize item is not attached");let i=r==null?void 0:r.generateOpId(),s=[],a=e!==void 0&&n!==void 0?{type:4,id:this._id,opId:i,parentId:e,parentKey:n,data:{}}:{type:4,id:this._id,opId:i,data:{}};s.push(a);for(let[d,c]of this._map)I(c)?s.push(...c._toOps(this._id,d,r)):a.data[d]=c;return s}static _deserialize([e,n],r,i){let s=new t(n.data);return s._attach(e,i),this._deserializeChildren(s,r,i)}static _deserializeChildren(e,n,r){let i=n.get(T(e._id));if(i===void 0)return e;for(let[s,a]of i){let d=un([s,a],n,r);Se(d)&&d._setParentLink(e,a.parentKey),e._map.set(a.parentKey,d),e.invalidate()}return e}_attach(e,n){super._attach(e,n);for(let[r,i]of this._map)I(i)&&i._attach(n.generateId(),n)}_attachChild(e,n){if(this._pool===void 0)throw new Error("Can't attach child if managed pool is not present");let{id:r,opId:i,parentKey:s}=e,a=ft(e);if(this._pool.getNode(r)!==void 0)return this._propToLastUpdate.get(s)===i&&this._propToLastUpdate.delete(s),{modified:!1};if(n===0)this._propToLastUpdate.set(s,T(i));else if(this._propToLastUpdate.get(s)!==void 0)return this._propToLastUpdate.get(s)===i?(this._propToLastUpdate.delete(s),{modified:!1}):{modified:!1};let d=T(this._id),c=this._map.get(s),f;return I(c)?(f=c._toOps(d,s),c._detach()):c===void 0?f=[{type:6,id:d,key:s}]:f=[{type:3,id:d,data:{[s]:c}}],this._map.set(s,a),this.invalidate(),Se(a)&&(a._setParentLink(this,s),a._attach(r,this._pool)),{reverse:f,modified:{node:this,type:"LiveObject",updates:{[s]:{type:"update"}}}}}_detachChild(e){if(e){let n=T(this._id),r=T(e._parentKey),i=e._toOps(n,r,this._pool);for(let[a,d]of this._map)d===e&&(this._map.delete(a),this.invalidate());return e._detach(),{modified:{node:this,type:"LiveObject",updates:{[r]:{type:"delete"}}},reverse:i}}return{modified:!1}}_detach(){super._detach();for(let e of this._map.values())I(e)&&e._detach()}_apply(e,n){return e.type===3?this._applyUpdate(e,n):e.type===6?this._applyDeleteObjectKey(e,n):super._apply(e,n)}_serialize(){let e={};for(let[n,r]of this._map)I(r)||(e[n]=r);return this.parent.type==="HasParent"&&this.parent.node._id?{type:0,parentId:this.parent.node._id,parentKey:this.parent.key,data:e}:{type:0,data:e}}_applyUpdate(e,n){let r=!1,i=T(this._id),s=[],a={type:3,id:i,data:{}};for(let c in e.data){let f=this._map.get(c);I(f)?(s.push(...f._toOps(i,c)),f._detach()):f!==void 0?a.data[c]=f:f===void 0&&s.push({type:6,id:i,key:c})}let d={};for(let c in e.data){let f=e.data[c];if(f===void 0)continue;if(n)this._propToLastUpdate.set(c,T(e.opId));else if(this._propToLastUpdate.get(c)===void 0)r=!0;else if(this._propToLastUpdate.get(c)===e.opId){this._propToLastUpdate.delete(c);continue}else continue;let y=this._map.get(c);I(y)&&y._detach(),r=!0,d[c]={type:"update"},this._map.set(c,f),this.invalidate()}return Object.keys(a.data).length!==0&&s.unshift(a),r?{modified:{node:this,type:"LiveObject",updates:d},reverse:s}:{modified:!1}}_applyDeleteObjectKey(e,n){let r=e.key;if(this._map.has(r)===!1)return{modified:!1};if(!n&&this._propToLastUpdate.get(r)!==void 0)return{modified:!1};let i=this._map.get(r),s=T(this._id),a=[];return I(i)?(a=i._toOps(s,e.key),i._detach()):i!==void 0&&(a=[{type:3,id:s,data:{[r]:i}}]),this._map.delete(r),this.invalidate(),{modified:{node:this,type:"LiveObject",updates:{[e.key]:{type:"delete"}}},reverse:a}}toObject(){return qt(this._map)}set(e,n){var r;(r=this._pool)==null||r.assertStorageIsWritable(),this.update({[e]:n})}get(e){return this._map.get(e)}delete(e){var a;(a=this._pool)==null||a.assertStorageIsWritable();let n=e,r=this._map.get(n);if(r===void 0)return;if(this._pool===void 0||this._id===void 0){I(r)&&r._detach(),this._map.delete(n),this.invalidate();return}let i;I(r)?(r._detach(),i=r._toOps(this._id,n)):i=[{type:3,data:{[n]:r},id:this._id}],this._map.delete(n),this.invalidate();let s=new Map;s.set(this._id,{node:this,type:"LiveObject",updates:{[e]:{type:"delete"}}}),this._pool.dispatch([{type:6,key:n,id:this._id,opId:this._pool.generateOpId()}],i,s)}update(e){var f;if((f=this._pool)==null||f.assertStorageIsWritable(),this._pool===void 0||this._id===void 0){for(let y in e){let b=e[y];if(b===void 0)continue;let E=this._map.get(y);I(E)&&E._detach(),I(b)&&b._setParentLink(this,y),this._map.set(y,b),this.invalidate()}return}let n=[],r=[],i=this._pool.generateOpId(),s={},a={id:this._id,type:3,data:{}},d={};for(let y in e){let b=e[y];if(b===void 0)continue;let E=this._map.get(y);if(I(E)?(r.push(...E._toOps(this._id,y)),E._detach()):E===void 0?r.push({type:6,id:this._id,key:y}):a.data[y]=E,I(b)){b._setParentLink(this,y),b._attach(this._pool.generateId(),this._pool);let G=b._toOps(this._id,y,this._pool),K=G.find(m=>m.parentId===this._id);K&&this._propToLastUpdate.set(y,T(K.opId)),n.push(...G)}else s[y]=b,this._propToLastUpdate.set(y,i);this._map.set(y,b),this.invalidate(),d[y]={type:"update"}}Object.keys(a.data).length!==0&&r.unshift(a),Object.keys(s).length!==0&&n.unshift({opId:i,id:this._id,type:3,data:s});let c=new Map;c.set(this._id,{node:this,type:"LiveObject",updates:d}),this._pool.dispatch(n,r,c)}toImmutable(){return super.toImmutable()}toTreeNode(e){return super.toTreeNode(e)}_toTreeNode(e){var r;let n=(r=this._id)!=null?r:oe();return{type:"LiveObject",id:n,key:e,payload:Array.from(this._map.entries()).map(([i,s])=>I(s)?s.toTreeNode(i):{type:"Json",id:`${n}:${i}`,key:i,payload:s})}}_toImmutable(){let e={};for(let[n,r]of this._map)e[n]=Se(r)?r.toImmutable():r;return process.env.NODE_ENV==="production"?e:Object.freeze(e)}};function ie(t){return re(ft(t))}function ft(t){switch(t.type){case 8:return t.data;case 4:return new x(t.data);case 7:return new N;case 2:return new M;default:return U(t,"Unknown creation Op")}}function ht(t,o){return t===o?!0:t.parent.type==="HasParent"?ht(t.parent.node,o):!1}function Ue([t,o],e,n){switch(o.type){case 0:return x._deserialize([t,o],e,n);case 1:return M._deserialize([t,o],e,n);case 2:return N._deserialize([t,o],e,n);case 3:return J._deserialize([t,o],e,n);default:throw new Error("Unexpected CRDT type")}}function un([t,o],e,n){switch(o.type){case 0:return x._deserialize([t,o],e,n);case 1:return M._deserialize([t,o],e,n);case 2:return N._deserialize([t,o],e,n);case 3:return o.data;default:throw new Error("Unexpected CRDT type")}}function Se(t){return he(t)||Ro(t)||Ae(t)}function I(t){return Se(t)||wo(t)}function he(t){return t instanceof M}function Ro(t){return t instanceof N}function Ae(t){return t instanceof x}function wo(t){return t instanceof J}function Q(t){return t instanceof J?t.data:t instanceof M||t instanceof N||t instanceof x?t:U(t,"Unknown AbstractCrdt")}function re(t){return t instanceof x||t instanceof N||t instanceof M?t:new J(t)}function hn(t,o){let e=[];return t.forEach((n,r)=>{o.get(r)||e.push({type:5,id:r})}),o.forEach((n,r)=>{let i=t.get(r);if(i)n.type===0&&(i.type!==0||JSON.stringify(n.data)!==JSON.stringify(i.data))&&e.push({type:3,id:r,data:n.data}),n.parentKey!==i.parentKey&&e.push({type:1,id:r,parentKey:T(n.parentKey,"Parent key must not be missing")});else switch(n.type){case 3:e.push({type:8,id:r,parentId:n.parentId,parentKey:n.parentKey,data:n.data});break;case 1:e.push({type:2,id:r,parentId:n.parentId,parentKey:n.parentKey});break;case 0:e.push(n.parentId?{type:4,id:r,parentId:n.parentId,parentKey:n.parentKey,data:n.data}:{type:4,id:r,data:n.data});break;case 2:e.push({type:7,id:r,parentId:n.parentId,parentKey:n.parentKey});break}}),e}function Mo(t,o){let e=t.updates;for(let[n,r]of et(o.updates))e[n]=r;return P(C({},o),{updates:e})}function Uo(t,o){let e=t.updates;for(let[n,r]of et(o.updates))e[n]=r;return P(C({},o),{updates:e})}function Ao(t,o){let e=t.updates;return P(C({},o),{updates:e.concat(o.updates)})}function Ne(t,o){return t===void 0?o:t.type==="LiveObject"&&o.type==="LiveObject"?Mo(t,o):t.type==="LiveMap"&&o.type==="LiveMap"?Uo(t,o):t.type==="LiveList"&&o.type==="LiveList"?Ao(t,o):o}function fn(t){let o=typeof t;return t==null||o==="string"||o==="boolean"||o==="number"||Array.isArray(t)||A(t)}function yt(t,o=""){if(!fn)return{path:o||"root",value:t};if(typeof t!="object"||t===null)return!1;for(let[e,n]of Object.entries(t)){let r=o?o+"."+e:e;if(!fn(n))return{path:r,value:n};if(typeof n=="object"){let i=yt(n,r);if(i)return i}}return!1}function yn(t,o){let e={name:t};if(typeof Error.captureStackTrace=="function")return Error.captureStackTrace(e,o),e.stack}function mn(t){return t===null||typeof t=="string"||typeof t=="number"||typeof t=="boolean"}function De(t){return Array.isArray(t)}function ae(t){return!mn(t)&&!De(t)}function Tn(t){let o=Date.now()/1e3;return!(o<=t.exp-300&&o>=t.iat-300)}function No(t){return Array.isArray(t)&&t.every(o=>typeof o=="string")}function Do(t){return A(t)&&typeof t.iat=="number"&&typeof t.exp=="number"&&typeof t.actor=="number"&&(t.id===void 0||typeof t.id=="string")&&No(t.scopes)}function je(t){let o=t.split(".");if(o.length!==3)throw new Error("Authentication error: invalid JWT token");let e=ge(tt(o[1]));if(!(e&&Do(e)))throw new Error("Authentication error: we expected a room token but did not get one. Hint: if you are using a callback, ensure the room is passed when creating the token. For more information: https://liveblocks.io/docs/api-reference/liveblocks-client#createClientCallback");return{raw:t,parsed:e}}var bn=(s=>(s[s.UPDATE_PRESENCE=100]="UPDATE_PRESENCE",s[s.BROADCAST_EVENT=103]="BROADCAST_EVENT",s[s.FETCH_STORAGE=200]="FETCH_STORAGE",s[s.UPDATE_STORAGE=201]="UPDATE_STORAGE",s[s.FETCH_YDOC=300]="FETCH_YDOC",s[s.UPDATE_YDOC=301]="UPDATE_YDOC",s))(bn||{});var vn=(c=>(c[c.UPDATE_PRESENCE=100]="UPDATE_PRESENCE",c[c.USER_JOINED=101]="USER_JOINED",c[c.USER_LEFT=102]="USER_LEFT",c[c.BROADCASTED_EVENT=103]="BROADCASTED_EVENT",c[c.ROOM_STATE=104]="ROOM_STATE",c[c.INITIAL_STORAGE_STATE=200]="INITIAL_STORAGE_STATE",c[c.UPDATE_STORAGE=201]="UPDATE_STORAGE",c[c.REJECT_STORAGE_OP=299]="REJECT_STORAGE_OP",c[c.UPDATE_YDOC=300]="UPDATE_YDOC",c))(vn||{});function mt(t){return Object.defineProperty(t,"count",{value:t.length,enumerable:!1}),Object.defineProperty(t,"toArray",{value:()=>t,enumerable:!1}),R(t)}function Je(t,o){let e=!1,n=C({},t);return Object.keys(o).forEach(r=>{let i=r,s=o[i];n[i]!==s&&(s===void 0?delete n[i]:n[i]=s,e=!0)}),e?n:t}var ee=class{constructor(){this._ev=O()}get didInvalidate(){return this._ev.observable}invalidate(){this._cache!==void 0&&(this._cache=void 0,this._ev.notify())}get current(){var o;return(o=this._cache)!=null?o:this._cache=this._toImmutable()}};function jo(t,o){return R(Oe(P(C({},t),{presence:o})))}var Ke=class extends ee{constructor(){super();this._connections={},this._presences={},this._users={}}_toImmutable(){let e=_e(Object.keys(this._presences).map(n=>this.getUser(Number(n))));return mt(e)}clearOthers(){this._connections={},this._presences={},this._users={},this.invalidate()}_getUser(e){let n=this._connections[e],r=this._presences[e];if(n!==void 0&&r!==void 0)return jo(n,r)}getUser(e){let n=this._users[e];if(n)return n;let r=this._getUser(e);if(r)return this._users[e]=r,r}_invalidateUser(e){this._users[e]!==void 0&&delete this._users[e],this.invalidate()}setConnection(e,n,r,i){this._connections[e]=R({connectionId:e,id:n,info:r,isReadOnly:i}),this._presences[e]!==void 0&&this._invalidateUser(e)}removeConnection(e){delete this._connections[e],delete this._presences[e],this._invalidateUser(e)}setOther(e,n){this._presences[e]=R(Oe(n)),this._connections[e]!==void 0&&this._invalidateUser(e)}patchOther(e,n){let r=this._presences[e];if(r===void 0)return;let i=Je(r,n);r!==i&&(this._presences[e]=R(i),this._invalidateUser(e))}};var Be=class extends ee{constructor(e){super();this._data=R(Oe(e))}_toImmutable(){return this._data}patch(e){let n=this._data,r=Je(n,e);n!==r&&(this._data=R(r),this.invalidate())}};var ze=class extends ee{constructor(e){super();this._value=R(e)}_toImmutable(){return this._value}set(e){this._value=R(e),this.invalidate()}},ye=class extends ee{constructor(...e){super();let n=e.pop(),r=e;this._refs=r,this._refs.forEach(i=>{i.didInvalidate.subscribe(()=>this.invalidate())}),this._transform=n}_toImmutable(){return this._transform(...this._refs.map(e=>e.current))}};var Jo=1024*1024-128;function Ko(t){let o=0;return()=>`${t}:${o++}`}function gn(t,o){return{type:"User",id:`${o.connectionId}`,key:t,payload:o}}function On(t,o){var Lt,kt,xt,Pt;let e=typeof t.initialPresence=="function"?t.initialPresence(o.roomId):t.initialPresence,n=typeof t.initialStorage=="function"?t.initialStorage(o.roomId):t.initialStorage,r=(xt=o.delegates)!=null?xt:{authenticate:Fo(o.roomId,o.authentication,(Lt=o.polyfills)==null?void 0:Lt.fetch),createSocket:Vo(o.liveblocksServer,(kt=o.polyfills)==null?void 0:kt.WebSocket)},i=new Re(r,o.enableDebugLogging),s={buffer:{flushTimerID:void 0,lastFlushedAt:0,me:{type:"full",data:e},messages:[],storageOperations:[]},sessionInfo:new ze(null),me:new Be(e),others:new Ke,initialStorage:n,idFactory:null,clock:0,opClock:0,nodes:new Map,root:void 0,undoStack:[],redoStack:[],pausedHistory:null,activeBatch:null,unacknowledgedOps:new Map,opStackTraces:process.env.NODE_ENV!=="production"?new Map:void 0},a=l=>l(),d=(Pt=o.unstable_batchedUpdates)!=null?Pt:a,c;function f(l){var u;let p=(u=i.token)==null?void 0:u.parsed;p!==void 0&&p!==c&&(s.sessionInfo.set({userInfo:p.info,userId:p.id,actor:p.actor,isReadOnly:Fe(p.scopes)}),c=p),d(()=>{h.status.notify(l),h.connection.notify(rt(l))})}let y,b=!1;function E(l){l==="reconnecting"?y=setTimeout(()=>{d(()=>{h.lostConnection.notify("lost"),b=!0,s.others.clearOthers(),X({others:[{type:"reset"}]},a)})},o.lostConnectionTimeout):(clearTimeout(y),b&&(d(l==="disconnected"?()=>{h.lostConnection.notify("failed")}:()=>{h.lostConnection.notify("restored")}),b=!1))}function G(){let l=s.sessionInfo.current;if(l===null)throw new Error("Unexpected missing session info");s.buffer.me={type:"full",data:C({},s.me.current)},s.idFactory=Ko(l.actor),Te!==null&&Et({flush:!1}),B()}function K(){clearTimeout(s.buffer.flushTimerID)}i.events.onMessage.subscribe(Dn),i.events.statusDidChange.subscribe(f),i.events.statusDidChange.subscribe(E),i.events.didConnect.subscribe(G),i.events.didDisconnect.subscribe(K),i.events.onLiveblocksError.subscribe(l=>{d(()=>{process.env.NODE_ENV!=="production"&&le(`Connection to websocket server closed. Reason: ${l.message} (code: ${l.code}).`),h.error.notify(l)})});let m={roomId:o.roomId,getNode:l=>s.nodes.get(l),addNode:(l,p)=>void s.nodes.set(l,p),deleteNode:l=>void s.nodes.delete(l),generateId:()=>`${bt()}:${s.clock++}`,generateOpId:()=>`${bt()}:${s.opClock++}`,dispatch(l,p,u){let g=s.activeBatch;if(process.env.NODE_ENV!=="production"){let _=yn("Storage mutation",this.dispatch);if(_)for(let v of l)v.opId&&T(s.opStackTraces).set(v.opId,_)}if(g){g.ops.push(...l);for(let[_,v]of u)g.updates.storageUpdates.set(_,Ne(g.updates.storageUpdates.get(_),v));g.reverseOps.unshift(...p)}else d(()=>{We(p,a),s.redoStack=[],Ot(l),X({storageUpdates:u},a)})},assertStorageIsWritable:()=>{var l;if((l=s.sessionInfo.current)!=null&&l.isReadOnly)throw new Error("Cannot write to storage with a read only user, please ensure the user has write permissions")}},h={connection:O(),status:O(),lostConnection:O(),customEvent:O(),me:O(),others:O(),error:O(),storage:O(),history:O(),storageDidLoad:O(),storageStatus:O(),ydoc:O()};function L(l){var u,g;let p=JSON.stringify(l);if(o.unstable_fallbackToHTTP&&new TextEncoder().encode(p).length>Jo&&(u=i.token)!=null&&u.raw&&o.httpSendEndpoint){if(Tn(i.token.parsed))return i.reconnect();Wo(p,i.token.raw,o.httpSendEndpoint,(g=o.polyfills)==null?void 0:g.fetch),F("Message was too large for websockets and sent over HTTP instead");return}i.send(p)}let te=new ye(s.sessionInfo,s.me,(l,p)=>l!==null?{connectionId:l.actor,id:l.userId,info:l.userInfo,presence:p,isReadOnly:l.isReadOnly}:null),ne=new ye(te,l=>l!==null?gn("Me",l):null);function w(l,p){if(l.items.length===0)throw new Error("Internal error: cannot load storage without items");s.root!==void 0?Y(l.items,p):s.root=x._fromItems(l.items,m);for(let u in s.initialStorage)s.root.get(u)===void 0&&s.root.set(u,s.initialStorage[u])}function Y(l,p){if(s.root===void 0)return;let u=new Map;for(let[v,D]of s.nodes)u.set(v,D._serialize());let g=hn(u,new Map(l)),_=me(g,!1);X(_.updates,p)}function ce(l,p){s.undoStack.length>=50&&s.undoStack.shift(),s.undoStack.push(l),He(p)}function We(l,p){s.pausedHistory!==null?s.pausedHistory.unshift(...l):ce(l,p)}function X({storageUpdates:l=new Map,presence:p=!1,others:u=[]},g){g(()=>{if(u.length>0){let _=s.others.current;for(let v of u)h.others.notify({others:_,event:v})}if(p&&h.me.notify(s.me.current),l.size>0){let _=Array.from(l.values());h.storage.notify(_)}})}function bt(){let l=s.sessionInfo.current;if(l)return l.actor;throw new Error("Internal. Tried to get connection id but connection was never open")}function me(l,p){let u={reverse:[],storageUpdates:new Map,presence:!1},g=new Set,_=l.map(v=>v.type!=="presence"&&!v.opId?P(C({},v),{opId:m.generateOpId()}):v);for(let v of _)if(v.type==="presence"){let D={type:"presence",data:{}};for(let k in v.data)D.data[k]=s.me.current[k];if(s.me.patch(v.data),s.buffer.me===null)s.buffer.me={type:"partial",data:v.data};else for(let k in v.data)s.buffer.me.data[k]=v.data[k];u.reverse.unshift(D),u.presence=!0}else{let D;if(p)D=0;else{let be=T(v.opId);process.env.NODE_ENV!=="production"&&T(s.opStackTraces).delete(be),D=s.unacknowledgedOps.delete(be)?2:1}let k=xn(v,D);if(k.modified){let be=k.modified.node._id;be&&g.has(be)||(u.storageUpdates.set(T(k.modified.node._id),Ne(u.storageUpdates.get(T(k.modified.node._id)),k.modified)),u.reverse.unshift(...k.reverse)),(v.type===2||v.type===7||v.type===4)&&g.add(T(v.id))}}return Ie(),{ops:_,reverse:u.reverse,updates:{storageUpdates:u.storageUpdates,presence:u.presence}}}function xn(l,p){if(an(l))return{modified:!1};switch(l.type){case 6:case 3:case 5:{let u=s.nodes.get(l.id);return u===void 0?{modified:!1}:u._apply(l,p===0)}case 1:{let u=s.nodes.get(l.id);return u===void 0?{modified:!1}:u.parent.type==="HasParent"&&he(u.parent.node)?u.parent.node._setChildKey(Z(l.parentKey),u,p):{modified:!1}}case 4:case 2:case 7:case 8:{if(l.parentId===void 0)return{modified:!1};let u=s.nodes.get(l.parentId);return u===void 0?{modified:!1}:u._attachChild(l,p)}}}function Pn(l,p){let u={};s.buffer.me===null&&(s.buffer.me={type:"partial",data:{}});for(let g in l){let _=l[g];_!==void 0&&(s.buffer.me.data[g]=_,u[g]=s.me.current[g])}s.me.patch(l),s.activeBatch?(p!=null&&p.addToHistory&&s.activeBatch.reverseOps.unshift({type:"presence",data:u}),s.activeBatch.updates.presence=!0):(B(),d(()=>{p!=null&&p.addToHistory&&We([{type:"presence",data:u}],a),X({presence:!0},a)}))}function Fe(l){return l.includes("room:read")&&l.includes("room:presence:write")&&!l.includes("room:write")}function Rn(l){if(l.targetActor!==void 0){let u=s.others.getUser(l.actor);s.others.setOther(l.actor,l.data);let g=s.others.getUser(l.actor);if(u===void 0&&g!==void 0)return{type:"enter",user:g}}else s.others.patchOther(l.actor,l.data);let p=s.others.getUser(l.actor);if(p)return{type:"update",updates:l.data,user:p}}function wn(l){let p=s.others.getUser(l.actor);return p?(s.others.removeConnection(l.actor),{type:"leave",user:p}):null}function Mn(l){for(let p in s.others._connections)l.users[p]===void 0&&s.others.removeConnection(Number(p));for(let p in l.users){let u=l.users[p],g=Number(p);s.others.setConnection(g,u.id,u.info,Fe(u.scopes))}return{type:"reset"}}function vt(){return s.undoStack.length>0}function gt(){return s.redoStack.length>0}function He(l){l(()=>{h.history.notify({canUndo:vt(),canRedo:gt()})})}function Un(l){s.others.setConnection(l.actor,l.id,l.info,Fe(l.scopes)),s.buffer.messages.push({type:100,data:s.me.current,targetActor:l.actor}),B();let p=s.others.getUser(l.actor);return p?{type:"enter",user:p}:void 0}function _t(l){return ae(l)?l:null}function An(l){let p=ge(l);return p===void 0?null:De(p)?_e(p.map(u=>_t(u))):_e([_t(p)])}function Nn(l,p){if(l.size===0)return;let u=[],g=Array.from(l.values()),_=me(g,!0);u.push({type:201,ops:_.ops}),X(_.updates,p),L(u)}function Dn(l){if(typeof l.data!="string")return;let p=An(l.data);if(p===null||p.length===0)return;let u={storageUpdates:new Map,others:[]};d(()=>{var g;for(let _ of p)switch(_.type){case 101:{let v=Un(_);v&&u.others.push(v);break}case 100:{let v=Rn(_);v&&u.others.push(v);break}case 103:{h.customEvent.notify({connectionId:_.actor,event:_.event});break}case 102:{let v=wn(_);v&&u.others.push(v);break}case 300:{h.ydoc.notify(_.update);break}case 104:{u.others.push(Mn(_));break}case 200:{let v=new Map(s.unacknowledgedOps);w(_,a),Nn(v,a),Ce==null||Ce(),Ie(),h.storageDidLoad.notify();break}case 201:{let v=me(_.ops,!1);for(let[D,k]of v.updates.storageUpdates)u.storageUpdates.set(D,Ne(u.storageUpdates.get(D),k));break}case 299:{if(ve("Storage mutation rejection error",_.reason),process.env.NODE_ENV!=="production"){let v=new Set;for(let D of _.opIds){let k=(g=s.opStackTraces)==null?void 0:g.get(D);k&&v.add(k)}throw v.size>0&&Ht("The following function calls caused the rejected storage mutations:",`
|
|
1
|
+
var Xn=Object.defineProperty,qn=Object.defineProperties;var Zn=Object.getOwnPropertyDescriptors;var Rt=Object.getOwnPropertySymbols;var Qn=Object.prototype.hasOwnProperty,eo=Object.prototype.propertyIsEnumerable;var wt=(t,o,e)=>o in t?Xn(t,o,{enumerable:!0,configurable:!0,writable:!0,value:e}):t[o]=e,C=(t,o)=>{for(var e in o||(o={}))Qn.call(o,e)&&wt(t,e,o[e]);if(Rt)for(var e of Rt(o))eo.call(o,e)&&wt(t,e,o[e]);return t},P=(t,o)=>qn(t,Zn(o));var j=(t,o,e)=>new Promise((n,r)=>{var i=d=>{try{a(e.next(d))}catch(c){r(c)}},s=d=>{try{a(e.throw(d))}catch(c){r(c)}},a=d=>d.done?n(d.value):Promise.resolve(d.value).then(i,s);a((e=e.apply(t,o)).next())});function O(){let t=new Set,o=new Set,e=null;function n(){e=[]}function r(){if(e!==null){for(let b of e)c(b);e=null}}function i(b){return o.add(b),()=>o.delete(b)}function s(b){return t.add(b),()=>t.delete(b)}function a(b){return j(this,null,function*(){let E;return new Promise(G=>{E=i(K=>{(b===void 0||b(K))&&G(K)})}).finally(()=>E==null?void 0:E())})}function d(b){e!==null?e.push(b):c(b)}function c(b){t.forEach(E=>E(b)),t.clear(),o.forEach(E=>E(b))}function f(){t.clear(),o.clear()}function y(){return t.size+o.size}return{notify:d,subscribe:i,subscribeOnce:s,clear:f,count:y,waitUntil:a,pause:n,unpause:r,observable:{subscribe:i,subscribeOnce:s,waitUntil:a}}}var Mt=!1;function Ut(t){Mt=t}function W(t,o){if(process.env.NODE_ENV==="production"||typeof window=="undefined")return;let e=P(C({},t),{source:"liveblocks-devtools-client"});(o!=null&&o.force||Mt)&&window.postMessage(e,"*")}var At=O();process.env.NODE_ENV!=="production"&&typeof window!="undefined"&&window.addEventListener("message",t=>{var o;t.source===window&&((o=t.data)==null?void 0:o.source)==="liveblocks-devtools-panel"&&At.notify(t.data)});var Ge=At.observable;var jt="1.1.1-dual5",Nt=!1;function Jt(t){process.env.NODE_ENV==="production"||typeof window=="undefined"||Nt||(Nt=!0,Ge.subscribe(o=>{switch(o.msg){case"connect":{Ut(!0);for(let e of t())W({msg:"room::available",roomId:e,clientVersion:jt});break}}}),W({msg:"wake-up-devtools"},{force:!0}))}var Ye=new Map;function qe(t){var e;let o=(e=Ye.get(t))!=null?e:[];Ye.delete(t);for(let n of o)n()}function to(t){qe(t.id),so(t),Ye.set(t.id,[t.events.status.subscribe(()=>no(t)),t.events.storageDidLoad.subscribeOnce(()=>Dt(t)),t.events.storage.subscribe(()=>Dt(t)),t.events.me.subscribe(()=>oo(t)),t.events.others.subscribe(()=>ro(t))])}function no(t){W({msg:"room::sync::partial",roomId:t.id,status:t.getStatus()})}function Dt(t){let o=t.getStorageSnapshot();o&&W({msg:"room::sync::partial",roomId:t.id,storage:o.toTreeNode("root").payload})}function oo(t){let o=t.__internal.getSelf_forDevTools();o&&W({msg:"room::sync::partial",roomId:t.id,me:o})}function ro(t){let o=t.__internal.getOthers_forDevTools();o&&W({msg:"room::sync::partial",roomId:t.id,others:o})}function so(t){var r;let o=t.getStorageSnapshot(),e=t.__internal.getSelf_forDevTools(),n=t.__internal.getOthers_forDevTools();W({msg:"room::sync::full",roomId:t.id,status:t.getStatus(),storage:(r=o==null?void 0:o.toTreeNode("root").payload)!=null?r:null,me:e,others:n})}var Xe=new Map;function Kt(t){let o=Xe.get(t);Xe.delete(t),o&&o()}function Bt(t,o){process.env.NODE_ENV==="production"||typeof window=="undefined"||(W({msg:"room::available",roomId:t,clientVersion:jt}),Kt(t),Xe.set(t,Ge.subscribe(e=>{switch(e.msg){case"room::subscribe":{e.roomId===t&&to(o);break}case"room::unsubscribe":{e.roomId===t&&qe(t);break}}})))}function zt(t){process.env.NODE_ENV==="production"||typeof window=="undefined"||(qe(t),Kt(t),W({msg:"room::unavailable",roomId:t}))}var Vt="background:#0e0d12;border-radius:9999px;color:#fff;padding:3px 7px;font-family:sans-serif;font-weight:600;",io="font-weight:600";function Wt(t){return typeof window=="undefined"||process.env.NODE_ENV==="test"?console[t]:(o,...e)=>console[t]("%cLiveblocks",Vt,o,...e)}var F=Wt("warn"),le=Wt("error");function Ft(t){return typeof window=="undefined"||process.env.NODE_ENV==="test"?console[t]:(o,e,...n)=>console[t](`%cLiveblocks%c ${o}`,Vt,io,e,...n)}var Ht=Ft("warn"),ve=Ft("error");var $t=new Set;function Gt(t,o=t){process.env.NODE_ENV!=="production"&&($t.has(o)||($t.add(o),ve("Deprecation warning",t)))}function Ze(t,o,e=o){process.env.NODE_ENV!=="production"&&t&&Gt(o,e)}function Yt(t){if(process.env.NODE_ENV!=="production"){let o=new Error(t);throw o.name="Usage error",ve("Usage error",t),o}}function ao(t,o){process.env.NODE_ENV!=="production"&&t&&Yt(o)}function U(t,o){throw new Error(o)}function Xt(t,o){if(process.env.NODE_ENV!=="production"&&!t){let e=new Error(o);throw e.name="Assertion failure",e}}function T(t,o="Expected value to be non-nullable"){return Xt(t!=null,o),t}function co(t,o){if(t===o)return[0,0];let e=t.split("."),n=o.split("."),r=Math.min(e.length,n.length),i=0;for(;i<r&&e[i]===n[i];i++);let s=e.length-i,a=n.length-i;return[s,a]}function lo(t,o){let e=t.split(".");if(o<1||o>e.length+1)throw new Error("Invalid number of levels");let n=[];o>e.length&&n.push("*");for(let r=e.length-o+1;r<e.length;r++){let i=e.slice(0,r);i.length>0&&n.push(i.join(".")+".*")}return n.push(t),n}var Qe=class{constructor(o){this.curr=o}get current(){return this.curr}allowPatching(o){let e=this,n=!0,r=P(C({},this.curr),{patch(i){if(n){e.curr=Object.assign({},e.curr,i);for(let s of Object.entries(i)){let[a,d]=s;a!=="patch"&&(this[a]=d)}}else throw new Error("Can no longer patch stale context")}});o(r),n=!1}};var po=1,ke=class{get initialState(){let o=this.states.values()[Symbol.iterator]().next();if(o.done)throw new Error("No states defined yet");return o.value}get currentState(){if(this.currentStateOrNull===null)throw this.runningState===0?new Error("Not started yet"):new Error("Already stopped");return this.currentStateOrNull}start(){if(this.runningState!==0)throw new Error("State machine has already started");return this.runningState=1,this.currentStateOrNull=this.initialState,this.enter(null),this}stop(){if(this.runningState!==1)throw new Error("Cannot stop a state machine that hasn't started yet");this.exit(null),this.runningState=2,this.currentStateOrNull=null}constructor(o){this.id=po++,this.runningState=0,this.currentStateOrNull=null,this.states=new Set,this.enterFns=new Map,this.cleanupStack=[],this.knownEventTypes=new Set,this.allowedTransitions=new Map,this.currentContext=new Qe(o),this.eventHub={didReceiveEvent:O(),willTransition:O(),didIgnoreEvent:O(),willExitState:O(),didEnterState:O()},this.events={didReceiveEvent:this.eventHub.didReceiveEvent.observable,willTransition:this.eventHub.willTransition.observable,didIgnoreEvent:this.eventHub.didIgnoreEvent.observable,willExitState:this.eventHub.willExitState.observable,didEnterState:this.eventHub.didEnterState.observable}}get context(){return this.currentContext.current}addState(o){if(this.runningState!==0)throw new Error("Already started");return this.states.add(o),this}onEnter(o,e){if(this.runningState!==0)throw new Error("Already started");if(this.enterFns.has(o))throw new Error(`enter/exit function for ${o} already exists`);return this.enterFns.set(o,e),this}onEnterAsync(o,e,n,r){return this.onEnter(o,()=>{let i=!1;return e(this.currentContext.current).then(s=>{i||this.transition({type:"ASYNC_OK",data:s},n)},s=>{i||this.transition({type:"ASYNC_ERROR",reason:s},r)}),()=>{i=!0}})}getStatesMatching(o){let e=[];if(o==="*")for(let n of this.states)e.push(n);else if(o.endsWith(".*")){let n=o.slice(0,-1);for(let r of this.states)r.startsWith(n)&&e.push(r)}else{let n=o;this.states.has(n)&&e.push(n)}if(e.length===0)throw new Error(`No states match ${JSON.stringify(o)}`);return e}addTransitions(o,e){if(this.runningState!==0)throw new Error("Already started");for(let n of this.getStatesMatching(o)){let r=this.allowedTransitions.get(n);r===void 0&&(r=new Map,this.allowedTransitions.set(n,r));for(let[i,s]of Object.entries(e)){if(r.has(i))throw new Error(`Trying to set transition "${i}" on "${n}" (via "${o}"), but a transition already exists there.`);let a=s;if(this.knownEventTypes.add(i),a!==void 0){let d=typeof a=="function"?a:()=>a;r.set(i,d)}}}return this}addTimedTransition(o,e,n){return this.onEnter(o,()=>{let r=typeof e=="function"?e(this.currentContext.current):e,i=setTimeout(()=>{this.transition({type:"TIMER"},n)},r);return()=>{clearTimeout(i)}})}getTargetFn(o){var e;return(e=this.allowedTransitions.get(this.currentState))==null?void 0:e.get(o)}exit(o){this.eventHub.willExitState.notify(this.currentState),this.currentContext.allowPatching(e=>{var n;o=o!=null?o:this.cleanupStack.length;for(let r=0;r<o;r++)(n=this.cleanupStack.pop())==null||n(e)})}enter(o){let e=lo(this.currentState,o!=null?o:this.currentState.split(".").length+1);this.currentContext.allowPatching(n=>{for(let r of e){let i=this.enterFns.get(r),s=i==null?void 0:i(n);typeof s=="function"?this.cleanupStack.push(s):this.cleanupStack.push(null)}}),this.eventHub.didEnterState.notify(this.currentState)}send(o){if(!this.knownEventTypes.has(o.type))throw new Error(`Invalid event ${JSON.stringify(o.type)}`);if(this.runningState===2)return;let e=this.getTargetFn(o.type);if(e!==void 0)return this.transition(o,e);this.eventHub.didIgnoreEvent.notify(o)}transition(o,e){this.eventHub.didReceiveEvent.notify(o);let n=this.currentState,i=(typeof e=="function"?e:()=>e)(o,this.currentContext.current),s,a;if(i===null){this.eventHub.didIgnoreEvent.notify(o);return}if(typeof i=="string"?s=i:(s=i.target,a=Array.isArray(i.effect)?i.effect:[i.effect]),!this.states.has(s))throw new Error(`Invalid next state name: ${JSON.stringify(s)}`);this.eventHub.willTransition.notify({from:n,to:s});let[d,c]=co(this.currentState,s);if(d>0&&this.exit(d),this.currentStateOrNull=s,a!==void 0){let f=a;this.currentContext.allowPatching(y=>{for(let b of f)typeof b=="function"?b(y,o):y.patch(b)})}c>0&&this.enter(c)}};function A(t){return t!==null&&typeof t=="object"&&Object.prototype.toString.call(t)==="[object Object]"}function qt(t){let o={};for(let[e,n]of t)o[e]=n;return o}function et(t){return Object.entries(t)}function ge(t){try{return JSON.parse(t)}catch(o){return}}function tt(t){try{let o=t.replace(/-/g,"+").replace(/_/g,"/");return decodeURIComponent(atob(o).split("").map(function(n){return"%"+("00"+n.charCodeAt(0).toString(16)).slice(-2)}).join(""))}catch(o){return atob(t)}}function _e(t){return t.filter(o=>o!=null)}function Oe(t){let o=C({},t);return Object.keys(t).forEach(e=>{let n=e;o[n]===void 0&&delete o[n]}),o}function xe(t,o,e="Timed out"){return j(this,null,function*(){let n,r=new Promise((i,s)=>{n=setTimeout(()=>{s(new Error(e))},o)});return Promise.race([t,r]).finally(()=>clearTimeout(n))})}function rt(t){switch(t){case"connecting":return"connecting";case"connected":return"open";case"reconnecting":return"unavailable";case"disconnected":return"failed";case"initial":return"closed";default:return"closed"}}function nn(t){let o=t.currentState;switch(o){case"@ok.connected":case"@ok.awaiting-pong":return"connected";case"@idle.initial":return"initial";case"@auth.busy":case"@auth.backoff":case"@connecting.busy":case"@connecting.backoff":return t.context.successCount>0?"reconnecting":"connecting";case"@idle.failed":return"disconnected";default:return U(o,"Unknown state")}}var on=[250,500,1e3,2e3,4e3,8e3,1e4],Ee=on[0]-1,uo=[2e3,3e4,6e4,3e5],fo=3e4,ho=2e3,yo=1e4,mo=1e4,q=class extends Error{constructor(o){super(o)}},ot=class extends Error{constructor(e,n){super(e);this.code=n}};function rn(t,o=on){var e;return(e=o.find(n=>n>t))!=null?e:o[o.length-1]}function pe(t){t.patch({backoffDelay:rn(t.backoffDelay)})}function Zt(t){t.patch({backoffDelay:rn(t.backoffDelay,uo)})}function Qt(t){t.patch({successCount:0})}function ue(t,o){let e=t===2?le:t===1?F:()=>{};return()=>{e(o)}}function en(t){let o="Connection to Liveblocks websocket server";return e=>{t instanceof Error?F(`${o} could not be established. ${String(t)}`):F(st(t)?`${o} closed prematurely (code: ${t.code}). Retrying in ${e.backoffDelay}ms.`:`${o} could not be established.`)}}function nt(t){return o=>{F(`Connection to Liveblocks websocket server closed (code: ${t.code}). Retrying in ${o.backoffDelay}ms.`)}}var To=ue(1,"Connection to WebSocket closed permanently. Won't retry.");function st(t){return!(t instanceof Error)&&t.type==="close"}function tn(t){return st(t)&&t.code>=4e3&&t.code<4100}function bo(t){let o=new Date().getTime();function e(...r){F(`${((new Date().getTime()-o)/1e3).toFixed(2)} [FSM #${t.id}]`,...r)}let n=[t.events.didReceiveEvent.subscribe(r=>e(`Event ${r.type}`)),t.events.willTransition.subscribe(({from:r,to:i})=>e("Transitioning",r,"\u2192",i)),t.events.didIgnoreEvent.subscribe(r=>e("Ignored event",r.type,r,"(current state won't handle it)"))];return()=>{for(let r of n)r()}}function vo(t){let o=O(),e=O(),n=O(),r=null,i=t.events.didEnterState.subscribe(()=>{let s=nn(t);s!==r&&o.notify(s),r==="connected"&&s!=="connected"?n.notify():r!=="connected"&&s==="connected"&&e.notify(),r=s});return{statusDidChange:o.observable,didConnect:e.observable,didDisconnect:n.observable,unsubscribe:i}}var Pe=t=>o=>o.patch(t);function go(t,o){let e=O();e.pause();let n=O(),r={successCount:0,token:null,socket:null,backoffDelay:Ee},i=new ke(r).addState("@idle.initial").addState("@idle.failed").addState("@auth.busy").addState("@auth.backoff").addState("@connecting.busy").addState("@connecting.backoff").addState("@ok.connected").addState("@ok.awaiting-pong");i.addTransitions("*",{RECONNECT:{target:"@auth.backoff",effect:[pe,Qt]},DISCONNECT:"@idle.initial"}),i.onEnter("@idle.*",Qt).addTransitions("@idle.*",{CONNECT:(m,h)=>h.token!==null?"@connecting.busy":"@auth.busy"}),i.addTransitions("@auth.backoff",{NAVIGATOR_ONLINE:{target:"@auth.busy",effect:Pe({backoffDelay:Ee})}}).addTimedTransition("@auth.backoff",m=>m.backoffDelay,"@auth.busy").onEnterAsync("@auth.busy",()=>xe(t.authenticate(),yo),m=>({target:"@connecting.busy",effect:Pe({token:m.data,backoffDelay:Ee})}),m=>m.reason instanceof q?{target:"@idle.failed",effect:ue(2,m.reason.message)}:{target:"@auth.backoff",effect:[pe,ue(2,`Authentication failed: ${m.reason instanceof Error?m.reason.message:String(m.reason)}`)]});let s=m=>i.send({type:"EXPLICIT_SOCKET_ERROR",event:m}),a=m=>i.send({type:"EXPLICIT_SOCKET_CLOSE",event:m}),d=m=>m.data==="pong"?i.send({type:"PONG"}):e.notify(m);function c(m){m&&(m.removeEventListener("error",s),m.removeEventListener("close",a),m.removeEventListener("message",d),m.close())}i.addTransitions("@connecting.backoff",{NAVIGATOR_ONLINE:{target:"@connecting.busy",effect:Pe({backoffDelay:Ee})}}).addTimedTransition("@connecting.backoff",m=>m.backoffDelay,"@connecting.busy").onEnterAsync("@connecting.busy",m=>j(this,null,function*(){let h=null,L=new Promise((te,ne)=>{if(m.token===null)throw new Error("No auth token");let w=t.createSocket(m.token);function Y(ce){h=ce,w.removeEventListener("message",d),ne(ce)}w.addEventListener("message",d),w.addEventListener("error",Y),w.addEventListener("close",Y),w.addEventListener("open",()=>{w.addEventListener("error",s),w.addEventListener("close",a),te([w,()=>{w.removeEventListener("error",Y),w.removeEventListener("close",Y)}])})});return xe(L,mo).then(([te,ne])=>{if(ne(),h)throw h;return te})}),m=>({target:"@ok.connected",effect:Pe({socket:m.data,backoffDelay:Ee})}),m=>{let h=m.reason;return h instanceof q?{target:"@idle.failed",effect:ue(2,h.message)}:st(h)&&h.code===4999?{target:"@idle.failed",effect:ue(2,h.reason)}:tn(h)&&h.code!==4001?{target:"@connecting.backoff",effect:[Zt,en(h)]}:{target:"@auth.backoff",effect:[pe,en(h)]}});let f={target:"@ok.awaiting-pong",effect:m=>{var h;(h=m.socket)==null||h.send("ping")}};if(i.addTimedTransition("@ok.connected",fo,f).addTransitions("@ok.connected",{NAVIGATOR_OFFLINE:f,WINDOW_GOT_FOCUS:f}),i.onEnter("@ok.*",m=>{m.patch({successCount:m.successCount+1});let h=setTimeout(e.unpause,0);return L=>{c(L.socket),L.patch({socket:null}),clearTimeout(h),e.pause()}}).addTransitions("@ok.awaiting-pong",{PONG:"@ok.connected"}).addTimedTransition("@ok.awaiting-pong",ho,{target:"@connecting.busy",effect:ue(1,"Received no pong from server, assume implicit connection loss.")}).addTransitions("@ok.*",{EXPLICIT_SOCKET_ERROR:(m,h)=>{var L;return((L=h.socket)==null?void 0:L.readyState)===1?null:{target:"@connecting.backoff",effect:pe}},EXPLICIT_SOCKET_CLOSE:m=>m.event.code===4999?{target:"@idle.failed",effect:To}:m.event.code===4001?{target:"@auth.backoff",effect:[pe,nt(m.event)]}:tn(m.event)?{target:"@connecting.backoff",effect:[Zt,nt(m.event),()=>{let h=new ot(m.event.reason,m.event.code);n.notify(h)}]}:{target:"@connecting.backoff",effect:[pe,nt(m.event)]}}),typeof document!="undefined"){let m=typeof document!="undefined"?document:void 0,h=typeof window!="undefined"?window:void 0,L=h!=null?h:m;i.onEnter("*",te=>{function ne(){i.send({type:"NAVIGATOR_OFFLINE"})}function w(){i.send({type:"NAVIGATOR_ONLINE"})}function Y(){(m==null?void 0:m.visibilityState)==="visible"&&i.send({type:"WINDOW_GOT_FOCUS"})}return h==null||h.addEventListener("online",w),h==null||h.addEventListener("offline",ne),L==null||L.addEventListener("visibilitychange",Y),()=>{L==null||L.removeEventListener("visibilitychange",Y),h==null||h.removeEventListener("online",w),h==null||h.removeEventListener("offline",ne),c(te.socket)}})}let y=[],{statusDidChange:b,didConnect:E,didDisconnect:G,unsubscribe:K}=vo(i);return y.push(K),o&&y.push(bo(i)),i.start(),{machine:i,cleanups:y,events:{statusDidChange:b,didConnect:E,didDisconnect:G,onMessage:e.observable,onLiveblocksError:n.observable}}}var Re=class{constructor(o,e=!1){let{machine:n,events:r,cleanups:i}=go(o,e);this.machine=n,this.events=r,this.cleanups=i}getLegacyStatus(){return rt(this.getStatus())}getStatus(){try{return nn(this.machine)}catch(o){return"initial"}}get token(){return this.machine.context.token}connect(){this.machine.send({type:"CONNECT"})}reconnect(){this.machine.send({type:"RECONNECT"})}disconnect(){this.machine.send({type:"DISCONNECT"})}destroy(){this.machine.stop();let o;for(;o=this.cleanups.pop();)o()}send(o){var n;let e=(n=this.machine.context)==null?void 0:n.socket;e===null?F("Cannot send: not connected yet",o):e.readyState!==1?F("Cannot send: WebSocket no longer open",o):e.send(o)}_privateSendMachineEvent(o){this.machine.send(o)}};var sn=at(0),we=at(1),_o=sn+at(-1);function at(t){let o=32+(t<0?95+t:t);if(o<32||o>126)throw new Error(`Invalid n value: ${t}`);return String.fromCharCode(o)}function z(t,o){return t!==void 0&&o!==void 0?So(t,o):t!==void 0?Eo(t):o!==void 0?Oo(o):we}function Oo(t){let o=t.length-1;for(let e=0;e<=o;e++){let n=t.charCodeAt(e);if(!(n<=32))return e===o?n===32+1?t.substring(0,e)+_o:t.substring(0,e)+String.fromCharCode(n-1):t.substring(0,e+1)}return we}function Eo(t){for(let o=0;o<=t.length-1;o++){let e=t.charCodeAt(o);if(!(e>=126))return t.substring(0,o)+String.fromCharCode(e+1)}return t+we}function So(t,o){if(t<o)return it(t,o);if(t>o)return it(o,t);throw new Error("Cannot compute value between two equal positions")}function it(t,o){let e=0,n=t.length,r=o.length;for(;;){let i=e<n?t.charCodeAt(e):32,s=e<r?o.charCodeAt(e):126;if(i===s){e++;continue}if(s-i===1){let a=t.substring(0,e+1),d=t.substring(e+1);return a+it(d,"")}else return Co(t,e)+String.fromCharCode(s+i>>1)}}function Co(t,o){return o<t.length?t.substring(0,o):t+sn.repeat(o-t.length)}var Io=32+1;function Lo(t){if(t==="")return!1;let o=t.length-1,e=t.charCodeAt(o);if(e<Io||e>126)return!1;for(let n=0;n<o;n++){let r=t.charCodeAt(n);if(r<32||r>126)return!1}return!0}function ko(t){let o=[];for(let e=0;e<t.length;e++){let n=t.charCodeAt(e);o.push(n<32?32:n>126?126:n)}for(;o.length>0&&o[o.length-1]===32;)o.length--;return o.length>0?String.fromCharCode(...o):we}function Z(t){return Lo(t)?t:ko(t)}var dt=(c=>(c[c.INIT=0]="INIT",c[c.SET_PARENT_KEY=1]="SET_PARENT_KEY",c[c.CREATE_LIST=2]="CREATE_LIST",c[c.UPDATE_OBJECT=3]="UPDATE_OBJECT",c[c.CREATE_OBJECT=4]="CREATE_OBJECT",c[c.DELETE_CRDT=5]="DELETE_CRDT",c[c.DELETE_OBJECT_KEY=6]="DELETE_OBJECT_KEY",c[c.CREATE_MAP=7]="CREATE_MAP",c[c.CREATE_REGISTER=8]="CREATE_REGISTER",c))(dt||{});function an(t){return t.type===5&&t.id==="ACK"}function dn(t,o,e=Z(o)){return Object.freeze({type:"HasParent",node:t,key:o,pos:e})}var cn=Object.freeze({type:"NoParent"});function xo(t,o=Z(t)){return Object.freeze({type:"Orphaned",oldKey:t,oldPos:o})}var H=class{constructor(){this._parent=cn}_getParentKeyOrThrow(){switch(this.parent.type){case"HasParent":return this.parent.key;case"NoParent":throw new Error("Parent key is missing");case"Orphaned":return this.parent.oldKey;default:return U(this.parent,"Unknown state")}}get _parentPos(){switch(this.parent.type){case"HasParent":return this.parent.pos;case"NoParent":throw new Error("Parent key is missing");case"Orphaned":return this.parent.oldPos;default:return U(this.parent,"Unknown state")}}get _pool(){return this.__pool}get roomId(){return this.__pool?this.__pool.roomId:null}get _id(){return this.__id}get parent(){return this._parent}get _parentKey(){switch(this.parent.type){case"HasParent":return this.parent.key;case"NoParent":return null;case"Orphaned":return this.parent.oldKey;default:return U(this.parent,"Unknown state")}}_apply(o,e){switch(o.type){case 5:return this.parent.type==="HasParent"?this.parent.node._detachChild(this):{modified:!1}}return{modified:!1}}_setParentLink(o,e){switch(this.parent.type){case"HasParent":if(this.parent.node!==o)throw new Error("Cannot set parent: node already has a parent");this._parent=dn(o,e);return;case"Orphaned":case"NoParent":{this._parent=dn(o,e);return}default:return U(this.parent,"Unknown state")}}_attach(o,e){if(this.__id||this.__pool)throw new Error("Cannot attach node: already attached");e.addNode(o,this),this.__id=o,this.__pool=e}_detach(){switch(this.__pool&&this.__id&&this.__pool.deleteNode(this.__id),this.parent.type){case"HasParent":{this._parent=xo(this.parent.key,this.parent.pos);break}case"NoParent":{this._parent=cn;break}case"Orphaned":break;default:U(this.parent,"Unknown state")}this.__pool=void 0}invalidate(){(this._cachedImmutable!==void 0||this._cachedTreeNode!==void 0)&&(this._cachedImmutable=void 0,this._cachedTreeNode=void 0,this.parent.type==="HasParent"&&this.parent.node.invalidate())}toTreeNode(o){return(this._cachedTreeNode===void 0||this._cachedTreeNodeKey!==o)&&(this._cachedTreeNodeKey=o,this._cachedTreeNode=this._toTreeNode(o)),this._cachedTreeNode}toImmutable(){return this._cachedImmutable===void 0&&(this._cachedImmutable=this._toImmutable()),this._cachedImmutable}};var ct=(r=>(r[r.OBJECT=0]="OBJECT",r[r.LIST=1]="LIST",r[r.MAP=2]="MAP",r[r.REGISTER=3]="REGISTER",r))(ct||{});function lt(t){return t.type===0&&!ln(t)}function ln(t){return t.parentId!==void 0&&t.parentKey!==void 0}function oe(t=7){let o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789,./;[]~!@#$%&*()_+=-",e=o.length;return Array.from({length:t},()=>o.charAt(Math.floor(Math.random()*e))).join("")}var J=class t extends H{constructor(e){super();this._data=e}get data(){return this._data}static _deserialize([e,n],r,i){let s=new t(n.data);return s._attach(e,i),s}_toOps(e,n,r){if(this._id===void 0)throw new Error("Cannot serialize register if parentId or parentKey is undefined");return[{type:8,opId:r==null?void 0:r.generateOpId(),id:this._id,parentId:e,parentKey:n,data:this.data}]}_serialize(){if(this.parent.type!=="HasParent")throw new Error("Cannot serialize LiveRegister if parent is missing");return{type:3,parentId:T(this.parent.node._id,"Parent node expected to have ID"),parentKey:this.parent.key,data:this.data}}_attachChild(e){throw new Error("Method not implemented.")}_detachChild(e){throw new Error("Method not implemented.")}_apply(e,n){return super._apply(e,n)}_toTreeNode(e){var n;return{type:"Json",id:(n=this._id)!=null?n:oe(),key:e,payload:this._data}}_toImmutable(){return this._data}};function Po(t,o){let e=t._parentPos,n=o._parentPos;return e===n?0:e<n?-1:1}var M=class t extends H{constructor(e=[]){super();this._items=[],this._implicitlyDeletedItems=new WeakSet,this._unacknowledgedSets=new Map;let n;for(let r of e){let i=z(n),s=re(r);s._setParentLink(this,i),this._items.push(s),n=i}}static _deserialize([e],n,r){let i=new t;i._attach(e,r);let s=n.get(e);if(s===void 0)return i;for(let[a,d]of s){let c=Ue([a,d],n,r);c._setParentLink(i,d.parentKey),i._insertAndSort(c)}return i}_toOps(e,n,r){if(this._id===void 0)throw new Error("Cannot serialize item is not attached");let i=[],s={id:this._id,opId:r==null?void 0:r.generateOpId(),type:2,parentId:e,parentKey:n};i.push(s);for(let a of this._items)i.push(...a._toOps(this._id,a._getParentKeyOrThrow(),r));return i}_insertAndSort(e){this._items.push(e),this._sortItems()}_sortItems(){this._items.sort(Po),this.invalidate()}_indexOfPosition(e){return this._items.findIndex(n=>n._getParentKeyOrThrow()===e)}_attach(e,n){super._attach(e,n);for(let r of this._items)r._attach(n.generateId(),n)}_detach(){super._detach();for(let e of this._items)e._detach()}_applySetRemote(e){if(this._pool===void 0)throw new Error("Can't attach child if managed pool is not present");let{id:n,parentKey:r}=e,i=ie(e);i._attach(n,this._pool),i._setParentLink(this,r);let s=e.deletedId,a=this._indexOfPosition(r);if(a!==-1){let d=this._items[a];if(d._id===s)return d._detach(),this._items[a]=i,{modified:S(this,[fe(a,i)]),reverse:[]};{this._implicitlyDeletedItems.add(d),this._items[a]=i;let c=[fe(a,i)],f=this._detachItemAssociatedToSetOperation(e.deletedId);return f&&c.push(f),{modified:S(this,c),reverse:[]}}}else{let d=[],c=this._detachItemAssociatedToSetOperation(e.deletedId);return c&&d.push(c),this._insertAndSort(i),d.push($(this._indexOfPosition(r),i)),{reverse:[],modified:S(this,d)}}}_applySetAck(e){if(this._pool===void 0)throw new Error("Can't attach child if managed pool is not present");let n=[],r=this._detachItemAssociatedToSetOperation(e.deletedId);r&&n.push(r);let i=this._unacknowledgedSets.get(e.parentKey);if(i!==void 0){if(i!==e.opId)return n.length===0?{modified:!1}:{modified:S(this,n),reverse:[]};this._unacknowledgedSets.delete(e.parentKey)}let s=this._indexOfPosition(e.parentKey),a=this._items.find(d=>d._id===e.id);if(a!==void 0){if(a._parentKey===e.parentKey)return{modified:n.length>0?S(this,n):!1,reverse:[]};s!==-1&&(this._implicitlyDeletedItems.add(this._items[s]),this._items.splice(s,1),n.push(Me(s)));let d=this._items.indexOf(a);a._setParentLink(this,e.parentKey),this._sortItems();let c=this._items.indexOf(a);return c!==d&&n.push(se(d,c,a)),{modified:n.length>0?S(this,n):!1,reverse:[]}}else{let d=this._pool.getNode(e.id);if(d&&this._implicitlyDeletedItems.has(d)){d._setParentLink(this,e.parentKey),this._implicitlyDeletedItems.delete(d),this._insertAndSort(d);let c=this._items.indexOf(d);return{modified:S(this,[s===-1?$(c,d):fe(c,d),...n]),reverse:[]}}else{s!==-1&&this._items.splice(s,1);let{newItem:c,newIndex:f}=this._createAttachItemAndSort(e,e.parentKey);return{modified:S(this,[s===-1?$(f,c):fe(f,c),...n]),reverse:[]}}}}_detachItemAssociatedToSetOperation(e){if(e===void 0||this._pool===void 0)return null;let n=this._pool.getNode(e);if(n===void 0)return null;let r=this._detachChild(n);return r.modified===!1?null:r.modified.updates[0]}_applyRemoteInsert(e){if(this._pool===void 0)throw new Error("Can't attach child if managed pool is not present");let n=Z(e.parentKey),r=this._indexOfPosition(n);r!==-1&&this._shiftItemPosition(r,n);let{newItem:i,newIndex:s}=this._createAttachItemAndSort(e,n);return{modified:S(this,[$(s,i)]),reverse:[]}}_applyInsertAck(e){let n=this._items.find(s=>s._id===e.id),r=Z(e.parentKey),i=this._indexOfPosition(r);if(n){if(n._parentKey===r)return{modified:!1};{let s=this._items.indexOf(n);i!==-1&&this._shiftItemPosition(i,r),n._setParentLink(this,r),this._sortItems();let a=this._indexOfPosition(r);return a===s?{modified:!1}:{modified:S(this,[se(s,a,n)]),reverse:[]}}}else{let s=T(this._pool).getNode(e.id);if(s&&this._implicitlyDeletedItems.has(s)){s._setParentLink(this,r),this._implicitlyDeletedItems.delete(s),this._insertAndSort(s);let a=this._indexOfPosition(r);return{modified:S(this,[$(a,s)]),reverse:[]}}else{i!==-1&&this._shiftItemPosition(i,r);let{newItem:a,newIndex:d}=this._createAttachItemAndSort(e,r);return{modified:S(this,[$(d,a)]),reverse:[]}}}}_applyInsertUndoRedo(e){var c,f,y;let{id:n,parentKey:r}=e,i=ie(e);if(((c=this._pool)==null?void 0:c.getNode(n))!==void 0)return{modified:!1};i._attach(n,T(this._pool)),i._setParentLink(this,r);let s=this._indexOfPosition(r),a=r;if(s!==-1){let b=(f=this._items[s])==null?void 0:f._parentPos,E=(y=this._items[s+1])==null?void 0:y._parentPos;a=z(b,E),i._setParentLink(this,a)}this._insertAndSort(i);let d=this._indexOfPosition(a);return{modified:S(this,[$(d,i)]),reverse:[{type:5,id:n}]}}_applySetUndoRedo(e){var d;let{id:n,parentKey:r}=e,i=ie(e);if(((d=this._pool)==null?void 0:d.getNode(n))!==void 0)return{modified:!1};this._unacknowledgedSets.set(r,T(e.opId));let s=this._indexOfPosition(r);i._attach(n,T(this._pool)),i._setParentLink(this,r);let a=r;if(s!==-1){let c=this._items[s];c._detach(),this._items[s]=i;let f=pt(c._toOps(T(this._id),r,this._pool),e.id),y=[fe(s,i)],b=this._detachItemAssociatedToSetOperation(e.deletedId);return b&&y.push(b),{modified:S(this,y),reverse:f}}else{this._insertAndSort(i),this._detachItemAssociatedToSetOperation(e.deletedId);let c=this._indexOfPosition(a);return{reverse:[{type:5,id:n}],modified:S(this,[$(c,i)])}}}_attachChild(e,n){if(this._pool===void 0)throw new Error("Can't attach child if managed pool is not present");let r;return e.intent==="set"?n===1?r=this._applySetRemote(e):n===2?r=this._applySetAck(e):r=this._applySetUndoRedo(e):n===1?r=this._applyRemoteInsert(e):n===2?r=this._applyInsertAck(e):r=this._applyInsertUndoRedo(e),r.modified!==!1&&this.invalidate(),r}_detachChild(e){if(e){let n=T(e._parentKey),r=e._toOps(T(this._id),n,this._pool),i=this._items.indexOf(e);return i===-1?{modified:!1}:(this._items.splice(i,1),this.invalidate(),e._detach(),{modified:S(this,[Me(i)]),reverse:r})}return{modified:!1}}_applySetChildKeyRemote(e,n){var s;if(this._implicitlyDeletedItems.has(n)){this._implicitlyDeletedItems.delete(n),n._setParentLink(this,e),this._insertAndSort(n);let a=this._items.indexOf(n);return{modified:S(this,[$(a,n)]),reverse:[]}}let r=n._parentKey;if(e===r)return{modified:!1};let i=this._indexOfPosition(e);if(i===-1){let a=this._items.indexOf(n);n._setParentLink(this,e),this._sortItems();let d=this._items.indexOf(n);return d===a?{modified:!1}:{modified:S(this,[se(a,d,n)]),reverse:[]}}else{this._items[i]._setParentLink(this,z(e,(s=this._items[i+1])==null?void 0:s._parentPos));let a=this._items.indexOf(n);n._setParentLink(this,e),this._sortItems();let d=this._items.indexOf(n);return d===a?{modified:!1}:{modified:S(this,[se(a,d,n)]),reverse:[]}}}_applySetChildKeyAck(e,n){var i,s;let r=T(n._parentKey);if(this._implicitlyDeletedItems.has(n)){let a=this._indexOfPosition(e);return this._implicitlyDeletedItems.delete(n),a!==-1&&this._items[a]._setParentLink(this,z(e,(i=this._items[a+1])==null?void 0:i._parentPos)),n._setParentLink(this,e),this._insertAndSort(n),{modified:!1}}else{if(e===r)return{modified:!1};let a=this._items.indexOf(n),d=this._indexOfPosition(e);d!==-1&&this._items[d]._setParentLink(this,z(e,(s=this._items[d+1])==null?void 0:s._parentPos)),n._setParentLink(this,e),this._sortItems();let c=this._items.indexOf(n);return a===c?{modified:!1}:{modified:S(this,[se(a,c,n)]),reverse:[]}}}_applySetChildKeyUndoRedo(e,n){var d;let r=T(n._parentKey),i=this._items.indexOf(n),s=this._indexOfPosition(e);s!==-1&&this._items[s]._setParentLink(this,z(e,(d=this._items[s+1])==null?void 0:d._parentPos)),n._setParentLink(this,e),this._sortItems();let a=this._items.indexOf(n);return i===a?{modified:!1}:{modified:S(this,[se(i,a,n)]),reverse:[{type:1,id:T(n._id),parentKey:r}]}}_setChildKey(e,n,r){return r===1?this._applySetChildKeyRemote(e,n):r===2?this._applySetChildKeyAck(e,n):this._applySetChildKeyUndoRedo(e,n)}_apply(e,n){return super._apply(e,n)}_serialize(){if(this.parent.type!=="HasParent")throw new Error("Cannot serialize LiveList if parent is missing");return{type:1,parentId:T(this.parent.node._id,"Parent node expected to have ID"),parentKey:this.parent.key}}get length(){return this._items.length}push(e){var n;return(n=this._pool)==null||n.assertStorageIsWritable(),this.insert(e,this.length)}insert(e,n){var d;if((d=this._pool)==null||d.assertStorageIsWritable(),n<0||n>this._items.length)throw new Error(`Cannot insert list item at index "${n}". index should be between 0 and ${this._items.length}`);let r=this._items[n-1]?this._items[n-1]._parentPos:void 0,i=this._items[n]?this._items[n]._parentPos:void 0,s=z(r,i),a=re(e);if(a._setParentLink(this,s),this._insertAndSort(a),this._pool&&this._id){let c=this._pool.generateId();a._attach(c,this._pool),this._pool.dispatch(a._toOps(this._id,s,this._pool),[{type:5,id:c}],new Map([[this._id,S(this,[$(n,a)])]]))}}move(e,n){var c;if((c=this._pool)==null||c.assertStorageIsWritable(),n<0)throw new Error("targetIndex cannot be less than 0");if(n>=this._items.length)throw new Error("targetIndex cannot be greater or equal than the list length");if(e<0)throw new Error("index cannot be less than 0");if(e>=this._items.length)throw new Error("index cannot be greater or equal than the list length");let r=null,i=null;e<n?(i=n===this._items.length-1?void 0:this._items[n+1]._parentPos,r=this._items[n]._parentPos):(i=this._items[n]._parentPos,r=n===0?void 0:this._items[n-1]._parentPos);let s=z(r,i),a=this._items[e],d=a._getParentKeyOrThrow();if(a._setParentLink(this,s),this._sortItems(),this._pool&&this._id){let f=new Map([[this._id,S(this,[se(e,n,a)])]]);this._pool.dispatch([{type:1,id:T(a._id),opId:this._pool.generateOpId(),parentKey:s}],[{type:1,id:T(a._id),parentKey:d}],f)}}delete(e){var r;if((r=this._pool)==null||r.assertStorageIsWritable(),e<0||e>=this._items.length)throw new Error(`Cannot delete list item at index "${e}". index should be between 0 and ${this._items.length-1}`);let n=this._items[e];if(n._detach(),this._items.splice(e,1),this.invalidate(),this._pool){let i=n._id;if(i){let s=new Map;s.set(T(this._id),S(this,[Me(e)])),this._pool.dispatch([{id:i,opId:this._pool.generateOpId(),type:5}],n._toOps(T(this._id),n._getParentKeyOrThrow()),s)}}}clear(){var e;if((e=this._pool)==null||e.assertStorageIsWritable(),this._pool){let n=[],r=[],i=[];for(let a of this._items){a._detach();let d=a._id;d&&(n.push({type:5,id:d,opId:this._pool.generateOpId()}),r.push(...a._toOps(T(this._id),a._getParentKeyOrThrow())),i.push(Me(0)))}this._items=[],this.invalidate();let s=new Map;s.set(T(this._id),S(this,i)),this._pool.dispatch(n,r,s)}else{for(let n of this._items)n._detach();this._items=[],this.invalidate()}}set(e,n){var d;if((d=this._pool)==null||d.assertStorageIsWritable(),e<0||e>=this._items.length)throw new Error(`Cannot set list item at index "${e}". index should be between 0 and ${this._items.length-1}`);let r=this._items[e],i=r._getParentKeyOrThrow(),s=r._id;r._detach();let a=re(n);if(a._setParentLink(this,i),this._items[e]=a,this.invalidate(),this._pool&&this._id){let c=this._pool.generateId();a._attach(c,this._pool);let f=new Map;f.set(this._id,S(this,[fe(e,a)]));let y=pt(a._toOps(this._id,i,this._pool),s);this._unacknowledgedSets.set(i,T(y[0].opId));let b=pt(r._toOps(this._id,i,void 0),c);this._pool.dispatch(y,b,f)}}toArray(){return this._items.map(e=>Q(e))}every(e){return this.toArray().every(e)}filter(e){return this.toArray().filter(e)}find(e){return this.toArray().find(e)}findIndex(e){return this.toArray().findIndex(e)}forEach(e){return this.toArray().forEach(e)}get(e){if(!(e<0||e>=this._items.length))return Q(this._items[e])}indexOf(e,n){return this.toArray().indexOf(e,n)}lastIndexOf(e,n){return this.toArray().lastIndexOf(e,n)}map(e){return this._items.map((n,r)=>e(Q(n),r))}some(e){return this.toArray().some(e)}[Symbol.iterator](){return new ut(this._items)}_createAttachItemAndSort(e,n){let r=ie(e);r._attach(e.id,T(this._pool)),r._setParentLink(this,n),this._insertAndSort(r);let i=this._indexOfPosition(n);return{newItem:r,newIndex:i}}_shiftItemPosition(e,n){var i;let r=z(n,this._items.length>e+1?(i=this._items[e+1])==null?void 0:i._parentPos:void 0);this._items[e]._setParentLink(this,r)}_toTreeNode(e){var n;return{type:"LiveList",id:(n=this._id)!=null?n:oe(),key:e,payload:this._items.map((r,i)=>r.toTreeNode(i.toString()))}}toImmutable(){return super.toImmutable()}_toImmutable(){let e=this._items.map(n=>n.toImmutable());return process.env.NODE_ENV==="production"?e:Object.freeze(e)}},ut=class{constructor(o){this._innerIterator=o[Symbol.iterator]()}[Symbol.iterator](){return this}next(){let o=this._innerIterator.next();return o.done?{done:!0,value:void 0}:{value:Q(o.value)}}};function S(t,o){return{node:t,type:"LiveList",updates:o}}function fe(t,o){return{index:t,type:"set",item:o instanceof J?o.data:o}}function Me(t){return{index:t,type:"delete"}}function $(t,o){return{index:t,type:"insert",item:o instanceof J?o.data:o}}function se(t,o,e){return{index:o,type:"move",previousIndex:t,item:e instanceof J?e.data:e}}function pt(t,o){return t.map((e,n)=>n===0?P(C({},e),{intent:"set",deletedId:o}):e)}var R=process.env.NODE_ENV==="production"?t=>t:Object.freeze;var N=class t extends H{constructor(e){super();if(this.unacknowledgedSet=new Map,e){let n=[];for(let r of e){let i=re(r[1]);i._setParentLink(this,r[0]),n.push([r[0],i])}this._map=new Map(n)}else this._map=new Map}_toOps(e,n,r){if(this._id===void 0)throw new Error("Cannot serialize item is not attached");let i=[],s={id:this._id,opId:r==null?void 0:r.generateOpId(),type:7,parentId:e,parentKey:n};i.push(s);for(let[a,d]of this._map)i.push(...d._toOps(this._id,a,r));return i}static _deserialize([e,n],r,i){let s=new t;s._attach(e,i);let a=r.get(e);if(a===void 0)return s;for(let[d,c]of a){let f=Ue([d,c],r,i);f._setParentLink(s,c.parentKey),s._map.set(c.parentKey,f),s.invalidate()}return s}_attach(e,n){super._attach(e,n);for(let[r,i]of this._map)I(i)&&i._attach(n.generateId(),n)}_attachChild(e,n){if(this._pool===void 0)throw new Error("Can't attach child if managed pool is not present");let{id:r,parentKey:i,opId:s}=e,a=i,d=ie(e);if(this._pool.getNode(r)!==void 0)return{modified:!1};if(n===2){let y=this.unacknowledgedSet.get(a);if(y===s)return this.unacknowledgedSet.delete(a),{modified:!1};if(y!==void 0)return{modified:!1}}else n===1&&this.unacknowledgedSet.delete(a);let c=this._map.get(a),f;if(c){let y=T(this._id);f=c._toOps(y,a),c._detach()}else f=[{type:5,id:r}];return d._setParentLink(this,a),d._attach(r,this._pool),this._map.set(a,d),this.invalidate(),{modified:{node:this,type:"LiveMap",updates:{[a]:{type:"update"}}},reverse:f}}_detach(){super._detach();for(let e of this._map.values())e._detach()}_detachChild(e){let n=T(this._id),r=T(e._parentKey),i=e._toOps(n,r,this._pool);for(let[a,d]of this._map)d===e&&(this._map.delete(a),this.invalidate());return e._detach(),{modified:{node:this,type:"LiveMap",updates:{[r]:{type:"delete"}}},reverse:i}}_serialize(){if(this.parent.type!=="HasParent")throw new Error("Cannot serialize LiveMap if parent is missing");return{type:2,parentId:T(this.parent.node._id,"Parent node expected to have ID"),parentKey:this.parent.key}}get(e){let n=this._map.get(e);if(n!==void 0)return Q(n)}set(e,n){var s;(s=this._pool)==null||s.assertStorageIsWritable();let r=this._map.get(e);r&&r._detach();let i=re(n);if(i._setParentLink(this,e),this._map.set(e,i),this.invalidate(),this._pool&&this._id){let a=this._pool.generateId();i._attach(a,this._pool);let d=new Map;d.set(this._id,{node:this,type:"LiveMap",updates:{[e]:{type:"update"}}});let c=i._toOps(this._id,e,this._pool);this.unacknowledgedSet.set(e,T(c[0].opId)),this._pool.dispatch(i._toOps(this._id,e,this._pool),r?r._toOps(this._id,e):[{type:5,id:a}],d)}}get size(){return this._map.size}has(e){return this._map.has(e)}delete(e){var r;(r=this._pool)==null||r.assertStorageIsWritable();let n=this._map.get(e);if(n===void 0)return!1;if(n._detach(),this._map.delete(e),this.invalidate(),this._pool&&n._id){let i=T(this._id),s=new Map;s.set(i,{node:this,type:"LiveMap",updates:{[e]:{type:"delete"}}}),this._pool.dispatch([{type:5,id:n._id,opId:this._pool.generateOpId()}],n._toOps(i,e),s)}return!0}entries(){let e=this._map.entries();return{[Symbol.iterator](){return this},next(){let n=e.next();if(n.done)return{done:!0,value:void 0};let i=n.value[0],s=Q(n.value[1]);return{value:[i,s]}}}}[Symbol.iterator](){return this.entries()}keys(){return this._map.keys()}values(){let e=this._map.values();return{[Symbol.iterator](){return this},next(){let n=e.next();return n.done?{done:!0,value:void 0}:{value:Q(n.value)}}}}forEach(e){for(let n of this)e(n[1],n[0],this)}_toTreeNode(e){var n;return{type:"LiveMap",id:(n=this._id)!=null?n:oe(),key:e,payload:Array.from(this._map.entries()).map(([r,i])=>i.toTreeNode(r))}}toImmutable(){return super.toImmutable()}_toImmutable(){let e=new Map;for(let[n,r]of this._map)e.set(n,r.toImmutable());return R(e)}};var x=class t extends H{constructor(e={}){super();this._propToLastUpdate=new Map;for(let n in e){let r=e[n];r!==void 0&&I(r)&&r._setParentLink(this,n)}this._map=new Map(Object.entries(e))}static _buildRootAndParentToChildren(e){let n=new Map,r=null;for(let[i,s]of e)if(lt(s))r=[i,s];else{let a=[i,s],d=n.get(s.parentId);d!==void 0?d.push(a):n.set(s.parentId,[a])}if(r===null)throw new Error("Root can't be null");return[r,n]}static _fromItems(e,n){let[r,i]=t._buildRootAndParentToChildren(e);return t._deserialize(r,i,n)}_toOps(e,n,r){if(this._id===void 0)throw new Error("Cannot serialize item is not attached");let i=r==null?void 0:r.generateOpId(),s=[],a=e!==void 0&&n!==void 0?{type:4,id:this._id,opId:i,parentId:e,parentKey:n,data:{}}:{type:4,id:this._id,opId:i,data:{}};s.push(a);for(let[d,c]of this._map)I(c)?s.push(...c._toOps(this._id,d,r)):a.data[d]=c;return s}static _deserialize([e,n],r,i){let s=new t(n.data);return s._attach(e,i),this._deserializeChildren(s,r,i)}static _deserializeChildren(e,n,r){let i=n.get(T(e._id));if(i===void 0)return e;for(let[s,a]of i){let d=un([s,a],n,r);Se(d)&&d._setParentLink(e,a.parentKey),e._map.set(a.parentKey,d),e.invalidate()}return e}_attach(e,n){super._attach(e,n);for(let[r,i]of this._map)I(i)&&i._attach(n.generateId(),n)}_attachChild(e,n){if(this._pool===void 0)throw new Error("Can't attach child if managed pool is not present");let{id:r,opId:i,parentKey:s}=e,a=ft(e);if(this._pool.getNode(r)!==void 0)return this._propToLastUpdate.get(s)===i&&this._propToLastUpdate.delete(s),{modified:!1};if(n===0)this._propToLastUpdate.set(s,T(i));else if(this._propToLastUpdate.get(s)!==void 0)return this._propToLastUpdate.get(s)===i?(this._propToLastUpdate.delete(s),{modified:!1}):{modified:!1};let d=T(this._id),c=this._map.get(s),f;return I(c)?(f=c._toOps(d,s),c._detach()):c===void 0?f=[{type:6,id:d,key:s}]:f=[{type:3,id:d,data:{[s]:c}}],this._map.set(s,a),this.invalidate(),Se(a)&&(a._setParentLink(this,s),a._attach(r,this._pool)),{reverse:f,modified:{node:this,type:"LiveObject",updates:{[s]:{type:"update"}}}}}_detachChild(e){if(e){let n=T(this._id),r=T(e._parentKey),i=e._toOps(n,r,this._pool);for(let[a,d]of this._map)d===e&&(this._map.delete(a),this.invalidate());return e._detach(),{modified:{node:this,type:"LiveObject",updates:{[r]:{type:"delete"}}},reverse:i}}return{modified:!1}}_detach(){super._detach();for(let e of this._map.values())I(e)&&e._detach()}_apply(e,n){return e.type===3?this._applyUpdate(e,n):e.type===6?this._applyDeleteObjectKey(e,n):super._apply(e,n)}_serialize(){let e={};for(let[n,r]of this._map)I(r)||(e[n]=r);return this.parent.type==="HasParent"&&this.parent.node._id?{type:0,parentId:this.parent.node._id,parentKey:this.parent.key,data:e}:{type:0,data:e}}_applyUpdate(e,n){let r=!1,i=T(this._id),s=[],a={type:3,id:i,data:{}};for(let c in e.data){let f=this._map.get(c);I(f)?(s.push(...f._toOps(i,c)),f._detach()):f!==void 0?a.data[c]=f:f===void 0&&s.push({type:6,id:i,key:c})}let d={};for(let c in e.data){let f=e.data[c];if(f===void 0)continue;if(n)this._propToLastUpdate.set(c,T(e.opId));else if(this._propToLastUpdate.get(c)===void 0)r=!0;else if(this._propToLastUpdate.get(c)===e.opId){this._propToLastUpdate.delete(c);continue}else continue;let y=this._map.get(c);I(y)&&y._detach(),r=!0,d[c]={type:"update"},this._map.set(c,f),this.invalidate()}return Object.keys(a.data).length!==0&&s.unshift(a),r?{modified:{node:this,type:"LiveObject",updates:d},reverse:s}:{modified:!1}}_applyDeleteObjectKey(e,n){let r=e.key;if(this._map.has(r)===!1)return{modified:!1};if(!n&&this._propToLastUpdate.get(r)!==void 0)return{modified:!1};let i=this._map.get(r),s=T(this._id),a=[];return I(i)?(a=i._toOps(s,e.key),i._detach()):i!==void 0&&(a=[{type:3,id:s,data:{[r]:i}}]),this._map.delete(r),this.invalidate(),{modified:{node:this,type:"LiveObject",updates:{[e.key]:{type:"delete"}}},reverse:a}}toObject(){return qt(this._map)}set(e,n){var r;(r=this._pool)==null||r.assertStorageIsWritable(),this.update({[e]:n})}get(e){return this._map.get(e)}delete(e){var a;(a=this._pool)==null||a.assertStorageIsWritable();let n=e,r=this._map.get(n);if(r===void 0)return;if(this._pool===void 0||this._id===void 0){I(r)&&r._detach(),this._map.delete(n),this.invalidate();return}let i;I(r)?(r._detach(),i=r._toOps(this._id,n)):i=[{type:3,data:{[n]:r},id:this._id}],this._map.delete(n),this.invalidate();let s=new Map;s.set(this._id,{node:this,type:"LiveObject",updates:{[e]:{type:"delete"}}}),this._pool.dispatch([{type:6,key:n,id:this._id,opId:this._pool.generateOpId()}],i,s)}update(e){var f;if((f=this._pool)==null||f.assertStorageIsWritable(),this._pool===void 0||this._id===void 0){for(let y in e){let b=e[y];if(b===void 0)continue;let E=this._map.get(y);I(E)&&E._detach(),I(b)&&b._setParentLink(this,y),this._map.set(y,b),this.invalidate()}return}let n=[],r=[],i=this._pool.generateOpId(),s={},a={id:this._id,type:3,data:{}},d={};for(let y in e){let b=e[y];if(b===void 0)continue;let E=this._map.get(y);if(I(E)?(r.push(...E._toOps(this._id,y)),E._detach()):E===void 0?r.push({type:6,id:this._id,key:y}):a.data[y]=E,I(b)){b._setParentLink(this,y),b._attach(this._pool.generateId(),this._pool);let G=b._toOps(this._id,y,this._pool),K=G.find(m=>m.parentId===this._id);K&&this._propToLastUpdate.set(y,T(K.opId)),n.push(...G)}else s[y]=b,this._propToLastUpdate.set(y,i);this._map.set(y,b),this.invalidate(),d[y]={type:"update"}}Object.keys(a.data).length!==0&&r.unshift(a),Object.keys(s).length!==0&&n.unshift({opId:i,id:this._id,type:3,data:s});let c=new Map;c.set(this._id,{node:this,type:"LiveObject",updates:d}),this._pool.dispatch(n,r,c)}toImmutable(){return super.toImmutable()}toTreeNode(e){return super.toTreeNode(e)}_toTreeNode(e){var r;let n=(r=this._id)!=null?r:oe();return{type:"LiveObject",id:n,key:e,payload:Array.from(this._map.entries()).map(([i,s])=>I(s)?s.toTreeNode(i):{type:"Json",id:`${n}:${i}`,key:i,payload:s})}}_toImmutable(){let e={};for(let[n,r]of this._map)e[n]=Se(r)?r.toImmutable():r;return process.env.NODE_ENV==="production"?e:Object.freeze(e)}};function ie(t){return re(ft(t))}function ft(t){switch(t.type){case 8:return t.data;case 4:return new x(t.data);case 7:return new N;case 2:return new M;default:return U(t,"Unknown creation Op")}}function ht(t,o){return t===o?!0:t.parent.type==="HasParent"?ht(t.parent.node,o):!1}function Ue([t,o],e,n){switch(o.type){case 0:return x._deserialize([t,o],e,n);case 1:return M._deserialize([t,o],e,n);case 2:return N._deserialize([t,o],e,n);case 3:return J._deserialize([t,o],e,n);default:throw new Error("Unexpected CRDT type")}}function un([t,o],e,n){switch(o.type){case 0:return x._deserialize([t,o],e,n);case 1:return M._deserialize([t,o],e,n);case 2:return N._deserialize([t,o],e,n);case 3:return o.data;default:throw new Error("Unexpected CRDT type")}}function Se(t){return he(t)||Ro(t)||Ae(t)}function I(t){return Se(t)||wo(t)}function he(t){return t instanceof M}function Ro(t){return t instanceof N}function Ae(t){return t instanceof x}function wo(t){return t instanceof J}function Q(t){return t instanceof J?t.data:t instanceof M||t instanceof N||t instanceof x?t:U(t,"Unknown AbstractCrdt")}function re(t){return t instanceof x||t instanceof N||t instanceof M?t:new J(t)}function hn(t,o){let e=[];return t.forEach((n,r)=>{o.get(r)||e.push({type:5,id:r})}),o.forEach((n,r)=>{let i=t.get(r);if(i)n.type===0&&(i.type!==0||JSON.stringify(n.data)!==JSON.stringify(i.data))&&e.push({type:3,id:r,data:n.data}),n.parentKey!==i.parentKey&&e.push({type:1,id:r,parentKey:T(n.parentKey,"Parent key must not be missing")});else switch(n.type){case 3:e.push({type:8,id:r,parentId:n.parentId,parentKey:n.parentKey,data:n.data});break;case 1:e.push({type:2,id:r,parentId:n.parentId,parentKey:n.parentKey});break;case 0:e.push(n.parentId?{type:4,id:r,parentId:n.parentId,parentKey:n.parentKey,data:n.data}:{type:4,id:r,data:n.data});break;case 2:e.push({type:7,id:r,parentId:n.parentId,parentKey:n.parentKey});break}}),e}function Mo(t,o){let e=t.updates;for(let[n,r]of et(o.updates))e[n]=r;return P(C({},o),{updates:e})}function Uo(t,o){let e=t.updates;for(let[n,r]of et(o.updates))e[n]=r;return P(C({},o),{updates:e})}function Ao(t,o){let e=t.updates;return P(C({},o),{updates:e.concat(o.updates)})}function Ne(t,o){return t===void 0?o:t.type==="LiveObject"&&o.type==="LiveObject"?Mo(t,o):t.type==="LiveMap"&&o.type==="LiveMap"?Uo(t,o):t.type==="LiveList"&&o.type==="LiveList"?Ao(t,o):o}function fn(t){let o=typeof t;return t==null||o==="string"||o==="boolean"||o==="number"||Array.isArray(t)||A(t)}function yt(t,o=""){if(!fn)return{path:o||"root",value:t};if(typeof t!="object"||t===null)return!1;for(let[e,n]of Object.entries(t)){let r=o?o+"."+e:e;if(!fn(n))return{path:r,value:n};if(typeof n=="object"){let i=yt(n,r);if(i)return i}}return!1}function yn(t,o){let e={name:t};if(typeof Error.captureStackTrace=="function")return Error.captureStackTrace(e,o),e.stack}function mn(t){return t===null||typeof t=="string"||typeof t=="number"||typeof t=="boolean"}function De(t){return Array.isArray(t)}function ae(t){return!mn(t)&&!De(t)}function Tn(t){let o=Date.now()/1e3;return!(o<=t.exp-300&&o>=t.iat-300)}function No(t){return Array.isArray(t)&&t.every(o=>typeof o=="string")}function Do(t){return A(t)&&typeof t.iat=="number"&&typeof t.exp=="number"&&typeof t.actor=="number"&&(t.id===void 0||typeof t.id=="string")&&No(t.scopes)}function je(t){let o=t.split(".");if(o.length!==3)throw new Error("Authentication error: invalid JWT token");let e=ge(tt(o[1]));if(!(e&&Do(e)))throw new Error("Authentication error: we expected a room token but did not get one. Hint: if you are using a callback, ensure the room is passed when creating the token. For more information: https://liveblocks.io/docs/api-reference/liveblocks-client#createClientCallback");return{raw:t,parsed:e}}var bn=(s=>(s[s.UPDATE_PRESENCE=100]="UPDATE_PRESENCE",s[s.BROADCAST_EVENT=103]="BROADCAST_EVENT",s[s.FETCH_STORAGE=200]="FETCH_STORAGE",s[s.UPDATE_STORAGE=201]="UPDATE_STORAGE",s[s.FETCH_YDOC=300]="FETCH_YDOC",s[s.UPDATE_YDOC=301]="UPDATE_YDOC",s))(bn||{});var vn=(c=>(c[c.UPDATE_PRESENCE=100]="UPDATE_PRESENCE",c[c.USER_JOINED=101]="USER_JOINED",c[c.USER_LEFT=102]="USER_LEFT",c[c.BROADCASTED_EVENT=103]="BROADCASTED_EVENT",c[c.ROOM_STATE=104]="ROOM_STATE",c[c.INITIAL_STORAGE_STATE=200]="INITIAL_STORAGE_STATE",c[c.UPDATE_STORAGE=201]="UPDATE_STORAGE",c[c.REJECT_STORAGE_OP=299]="REJECT_STORAGE_OP",c[c.UPDATE_YDOC=300]="UPDATE_YDOC",c))(vn||{});function mt(t){return Object.defineProperty(t,"count",{value:t.length,enumerable:!1}),Object.defineProperty(t,"toArray",{value:()=>t,enumerable:!1}),R(t)}function Je(t,o){let e=!1,n=C({},t);return Object.keys(o).forEach(r=>{let i=r,s=o[i];n[i]!==s&&(s===void 0?delete n[i]:n[i]=s,e=!0)}),e?n:t}var ee=class{constructor(){this._ev=O()}get didInvalidate(){return this._ev.observable}invalidate(){this._cache!==void 0&&(this._cache=void 0,this._ev.notify())}get current(){var o;return(o=this._cache)!=null?o:this._cache=this._toImmutable()}};function jo(t,o){return R(Oe(P(C({},t),{presence:o})))}var Ke=class extends ee{constructor(){super();this._connections={},this._presences={},this._users={}}_toImmutable(){let e=_e(Object.keys(this._presences).map(n=>this.getUser(Number(n))));return mt(e)}clearOthers(){this._connections={},this._presences={},this._users={},this.invalidate()}_getUser(e){let n=this._connections[e],r=this._presences[e];if(n!==void 0&&r!==void 0)return jo(n,r)}getUser(e){let n=this._users[e];if(n)return n;let r=this._getUser(e);if(r)return this._users[e]=r,r}_invalidateUser(e){this._users[e]!==void 0&&delete this._users[e],this.invalidate()}setConnection(e,n,r,i){this._connections[e]=R({connectionId:e,id:n,info:r,isReadOnly:i}),this._presences[e]!==void 0&&this._invalidateUser(e)}removeConnection(e){delete this._connections[e],delete this._presences[e],this._invalidateUser(e)}setOther(e,n){this._presences[e]=R(Oe(n)),this._connections[e]!==void 0&&this._invalidateUser(e)}patchOther(e,n){let r=this._presences[e];if(r===void 0)return;let i=Je(r,n);r!==i&&(this._presences[e]=R(i),this._invalidateUser(e))}};var Be=class extends ee{constructor(e){super();this._data=R(Oe(e))}_toImmutable(){return this._data}patch(e){let n=this._data,r=Je(n,e);n!==r&&(this._data=R(r),this.invalidate())}};var ze=class extends ee{constructor(e){super();this._value=R(e)}_toImmutable(){return this._value}set(e){this._value=R(e),this.invalidate()}},ye=class extends ee{constructor(...e){super();let n=e.pop(),r=e;this._refs=r,this._refs.forEach(i=>{i.didInvalidate.subscribe(()=>this.invalidate())}),this._transform=n}_toImmutable(){return this._transform(...this._refs.map(e=>e.current))}};var Jo=1024*1024-128;function Ko(t){let o=0;return()=>`${t}:${o++}`}function gn(t,o){return{type:"User",id:`${o.connectionId}`,key:t,payload:o}}function On(t,o){var Lt,kt,xt,Pt;let e=typeof t.initialPresence=="function"?t.initialPresence(o.roomId):t.initialPresence,n=typeof t.initialStorage=="function"?t.initialStorage(o.roomId):t.initialStorage,r=(xt=o.delegates)!=null?xt:{authenticate:Fo(o.roomId,o.authentication,(Lt=o.polyfills)==null?void 0:Lt.fetch),createSocket:Vo(o.liveblocksServer,(kt=o.polyfills)==null?void 0:kt.WebSocket)},i=new Re(r,o.enableDebugLogging),s={buffer:{flushTimerID:void 0,lastFlushedAt:0,me:{type:"full",data:e},messages:[],storageOperations:[]},sessionInfo:new ze(null),me:new Be(e),others:new Ke,initialStorage:n,idFactory:null,clock:0,opClock:0,nodes:new Map,root:void 0,undoStack:[],redoStack:[],pausedHistory:null,activeBatch:null,unacknowledgedOps:new Map,opStackTraces:process.env.NODE_ENV!=="production"?new Map:void 0},a=l=>l(),d=(Pt=o.unstable_batchedUpdates)!=null?Pt:a,c;function f(l){var u;let p=(u=i.token)==null?void 0:u.parsed;p!==void 0&&p!==c&&(s.sessionInfo.set({userInfo:p.info,userId:p.id,actor:p.actor,isReadOnly:Fe(p.scopes)}),c=p),d(()=>{h.status.notify(l),h.connection.notify(rt(l))})}let y,b=!1;function E(l){l==="reconnecting"?y=setTimeout(()=>{d(()=>{h.lostConnection.notify("lost"),b=!0,s.others.clearOthers(),X({others:[{type:"reset"}]},a)})},o.lostConnectionTimeout):(clearTimeout(y),b&&(d(l==="disconnected"?()=>{h.lostConnection.notify("failed")}:()=>{h.lostConnection.notify("restored")}),b=!1))}function G(){let l=s.sessionInfo.current;if(l===null)throw new Error("Unexpected missing session info");s.buffer.me={type:"full",data:C({},s.me.current)},s.idFactory=Ko(l.actor),Te!==null&&Et({flush:!1}),B()}function K(){clearTimeout(s.buffer.flushTimerID)}i.events.onMessage.subscribe(Dn),i.events.statusDidChange.subscribe(f),i.events.statusDidChange.subscribe(E),i.events.didConnect.subscribe(G),i.events.didDisconnect.subscribe(K),i.events.onLiveblocksError.subscribe(l=>{d(()=>{process.env.NODE_ENV!=="production"&&le(`Connection to websocket server closed. Reason: ${l.message} (code: ${l.code}).`),h.error.notify(l)})});let m={roomId:o.roomId,getNode:l=>s.nodes.get(l),addNode:(l,p)=>void s.nodes.set(l,p),deleteNode:l=>void s.nodes.delete(l),generateId:()=>`${bt()}:${s.clock++}`,generateOpId:()=>`${bt()}:${s.opClock++}`,dispatch(l,p,u){let g=s.activeBatch;if(process.env.NODE_ENV!=="production"){let _=yn("Storage mutation",this.dispatch);if(_)for(let v of l)v.opId&&T(s.opStackTraces).set(v.opId,_)}if(g){g.ops.push(...l);for(let[_,v]of u)g.updates.storageUpdates.set(_,Ne(g.updates.storageUpdates.get(_),v));g.reverseOps.unshift(...p)}else d(()=>{We(p,a),s.redoStack=[],Ot(l),X({storageUpdates:u},a)})},assertStorageIsWritable:()=>{var l;if((l=s.sessionInfo.current)!=null&&l.isReadOnly)throw new Error("Cannot write to storage with a read only user, please ensure the user has write permissions")}},h={connection:O(),status:O(),lostConnection:O(),customEvent:O(),me:O(),others:O(),error:O(),storage:O(),history:O(),storageDidLoad:O(),storageStatus:O(),ydoc:O()};function L(l){var u,g;let p=JSON.stringify(l);if(o.unstable_fallbackToHTTP&&new TextEncoder().encode(p).length>Jo&&(u=i.token)!=null&&u.raw&&o.httpSendEndpoint){if(Tn(i.token.parsed))return i.reconnect();Wo(p,i.token.raw,o.httpSendEndpoint,(g=o.polyfills)==null?void 0:g.fetch),F("Message was too large for websockets and sent over HTTP instead");return}i.send(p)}let te=new ye(s.sessionInfo,s.me,(l,p)=>l!==null?{connectionId:l.actor,id:l.userId,info:l.userInfo,presence:p,isReadOnly:l.isReadOnly}:null),ne=new ye(te,l=>l!==null?gn("Me",l):null);function w(l,p){if(l.items.length===0)throw new Error("Internal error: cannot load storage without items");s.root!==void 0?Y(l.items,p):s.root=x._fromItems(l.items,m);for(let u in s.initialStorage)s.root.get(u)===void 0&&s.root.set(u,s.initialStorage[u])}function Y(l,p){if(s.root===void 0)return;let u=new Map;for(let[v,D]of s.nodes)u.set(v,D._serialize());let g=hn(u,new Map(l)),_=me(g,!1);X(_.updates,p)}function ce(l,p){s.undoStack.length>=50&&s.undoStack.shift(),s.undoStack.push(l),He(p)}function We(l,p){s.pausedHistory!==null?s.pausedHistory.unshift(...l):ce(l,p)}function X({storageUpdates:l=new Map,presence:p=!1,others:u=[]},g){g(()=>{if(u.length>0){let _=s.others.current;for(let v of u)h.others.notify({others:_,event:v})}if(p&&h.me.notify(s.me.current),l.size>0){let _=Array.from(l.values());h.storage.notify(_)}})}function bt(){let l=s.sessionInfo.current;if(l)return l.actor;throw new Error("Internal. Tried to get connection id but connection was never open")}function me(l,p){let u={reverse:[],storageUpdates:new Map,presence:!1},g=new Set,_=l.map(v=>v.type!=="presence"&&!v.opId?P(C({},v),{opId:m.generateOpId()}):v);for(let v of _)if(v.type==="presence"){let D={type:"presence",data:{}};for(let k in v.data)D.data[k]=s.me.current[k];if(s.me.patch(v.data),s.buffer.me===null)s.buffer.me={type:"partial",data:v.data};else for(let k in v.data)s.buffer.me.data[k]=v.data[k];u.reverse.unshift(D),u.presence=!0}else{let D;if(p)D=0;else{let be=T(v.opId);process.env.NODE_ENV!=="production"&&T(s.opStackTraces).delete(be),D=s.unacknowledgedOps.delete(be)?2:1}let k=xn(v,D);if(k.modified){let be=k.modified.node._id;be&&g.has(be)||(u.storageUpdates.set(T(k.modified.node._id),Ne(u.storageUpdates.get(T(k.modified.node._id)),k.modified)),u.reverse.unshift(...k.reverse)),(v.type===2||v.type===7||v.type===4)&&g.add(T(v.id))}}return Ie(),{ops:_,reverse:u.reverse,updates:{storageUpdates:u.storageUpdates,presence:u.presence}}}function xn(l,p){if(an(l))return{modified:!1};switch(l.type){case 6:case 3:case 5:{let u=s.nodes.get(l.id);return u===void 0?{modified:!1}:u._apply(l,p===0)}case 1:{let u=s.nodes.get(l.id);return u===void 0?{modified:!1}:u.parent.type==="HasParent"&&he(u.parent.node)?u.parent.node._setChildKey(Z(l.parentKey),u,p):{modified:!1}}case 4:case 2:case 7:case 8:{if(l.parentId===void 0)return{modified:!1};let u=s.nodes.get(l.parentId);return u===void 0?{modified:!1}:u._attachChild(l,p)}}}function Pn(l,p){let u={};s.buffer.me===null&&(s.buffer.me={type:"partial",data:{}});for(let g in l){let _=l[g];_!==void 0&&(s.buffer.me.data[g]=_,u[g]=s.me.current[g])}s.me.patch(l),s.activeBatch?(p!=null&&p.addToHistory&&s.activeBatch.reverseOps.unshift({type:"presence",data:u}),s.activeBatch.updates.presence=!0):(B(),d(()=>{p!=null&&p.addToHistory&&We([{type:"presence",data:u}],a),X({presence:!0},a)}))}function Fe(l){return l.includes("room:read")&&l.includes("room:presence:write")&&!l.includes("room:write")}function Rn(l){if(l.targetActor!==void 0){let u=s.others.getUser(l.actor);s.others.setOther(l.actor,l.data);let g=s.others.getUser(l.actor);if(u===void 0&&g!==void 0)return{type:"enter",user:g}}else s.others.patchOther(l.actor,l.data);let p=s.others.getUser(l.actor);if(p)return{type:"update",updates:l.data,user:p}}function wn(l){let p=s.others.getUser(l.actor);return p?(s.others.removeConnection(l.actor),{type:"leave",user:p}):null}function Mn(l){for(let p in s.others._connections)l.users[p]===void 0&&s.others.removeConnection(Number(p));for(let p in l.users){let u=l.users[p],g=Number(p);s.others.setConnection(g,u.id,u.info,Fe(u.scopes))}return{type:"reset"}}function vt(){return s.undoStack.length>0}function gt(){return s.redoStack.length>0}function He(l){l(()=>{h.history.notify({canUndo:vt(),canRedo:gt()})})}function Un(l){s.others.setConnection(l.actor,l.id,l.info,Fe(l.scopes)),s.buffer.messages.push({type:100,data:s.me.current,targetActor:l.actor}),B();let p=s.others.getUser(l.actor);return p?{type:"enter",user:p}:void 0}function _t(l){return ae(l)?l:null}function An(l){let p=ge(l);return p===void 0?null:De(p)?_e(p.map(u=>_t(u))):_e([_t(p)])}function Nn(l,p){if(l.size===0)return;let u=[],g=Array.from(l.values()),_=me(g,!0);u.push({type:201,ops:_.ops}),X(_.updates,p),L(u)}function Dn(l){if(typeof l.data!="string")return;let p=An(l.data);if(p===null||p.length===0)return;let u={storageUpdates:new Map,others:[]};d(()=>{var g;for(let _ of p)switch(_.type){case 101:{let v=Un(_);v&&u.others.push(v);break}case 100:{let v=Rn(_);v&&u.others.push(v);break}case 103:{h.customEvent.notify({connectionId:_.actor,event:_.event});break}case 102:{let v=wn(_);v&&u.others.push(v);break}case 300:{h.ydoc.notify(_.update);break}case 104:{u.others.push(Mn(_));break}case 200:{let v=new Map(s.unacknowledgedOps);w(_,a),Nn(v,a),Ce==null||Ce(),Ie(),h.storageDidLoad.notify();break}case 201:{let v=me(_.ops,!1);for(let[D,k]of v.updates.storageUpdates)u.storageUpdates.set(D,Ne(u.storageUpdates.get(D),k));break}case 299:{if(ve("Storage mutation rejection error",_.reason),process.env.NODE_ENV!=="production"){let v=new Set;for(let D of _.opIds){let k=(g=s.opStackTraces)==null?void 0:g.get(D);k&&v.add(k)}throw v.size>0&&Ht("The following function calls caused the rejected storage mutations:",`
|
|
2
2
|
|
|
3
3
|
${Array.from(v).join(`
|
|
4
4
|
|
|
5
|
-
`)}`),new Error(`Storage mutations rejected by server: ${_.reason}`)}break}}X(u,a)})}function B(){let l=s.buffer.storageOperations;if(l.length>0){for(let g of l)s.unacknowledgedOps.set(T(g.opId),g);Ie()}if(i.getStatus()!=="connected"){s.buffer.storageOperations=[];return}let p=Date.now(),u=p-s.buffer.lastFlushedAt;if(u>o.throttleDelay){let g=jn();if(g.length===0)return;L(g),s.buffer={flushTimerID:void 0,lastFlushedAt:p,messages:[],storageOperations:[],me:null}}else clearTimeout(s.buffer.flushTimerID),s.buffer.flushTimerID=setTimeout(B,o.throttleDelay-u)}function jn(){let l=[];s.buffer.me&&l.push(s.buffer.me.type==="full"?{type:100,targetActor:-1,data:s.buffer.me.data}:{type:100,data:s.buffer.me.data});for(let p of s.buffer.messages)l.push(p);return s.buffer.storageOperations.length>0&&l.push({type:201,ops:s.buffer.storageOperations}),l}function Jn(l){s.buffer.messages.push({type:301,update:l}),B()}function Kn(l,p={shouldQueueEventIfNotReady:!1}){i.getStatus()!=="connected"&&!p.shouldQueueEventIfNotReady||(s.buffer.messages.push({type:103,event:l}),B())}function Ot(l){s.buffer.storageOperations.push(...l),B()}let Te=null,Ce=null;function Et(l){let p=s.buffer.messages;p.some(u=>u.type===200)||p.push({type:200}),l.flush&&B()}function St(){return Te===null&&(Et({flush:!0}),Te=new Promise(l=>{Ce=l}),Ie()),Te}function Bn(){let l=s.root;return l!==void 0?l:(St(),null)}function zn(){return j(this,null,function*(){return s.root!==void 0?Promise.resolve({root:s.root}):(yield St(),{root:T(s.root)})})}function Vn(l){s.buffer.messages.push({type:300,vector:l}),B()}function Wn(){if(s.activeBatch)throw new Error("undo is not allowed during a batch");let l=s.undoStack.pop();if(l===void 0)return;s.pausedHistory=null;let p=me(l,!0);d(()=>{X(p.updates,a),s.redoStack.push(p.reverse),He(a)});for(let u of p.ops)u.type!=="presence"&&s.buffer.storageOperations.push(u);B()}function Fn(){if(s.activeBatch)throw new Error("redo is not allowed during a batch");let l=s.redoStack.pop();if(l===void 0)return;s.pausedHistory=null;let p=me(l,!0);d(()=>{X(p.updates,a),s.undoStack.push(p.reverse),He(a)});for(let u of p.ops)u.type!=="presence"&&s.buffer.storageOperations.push(u);B()}function Hn(l){if(s.activeBatch)return l();let p;return d(()=>{s.activeBatch={ops:[],updates:{storageUpdates:new Map,presence:!1,others:[]},reverseOps:[]};try{p=l()}finally{let u=s.activeBatch;s.activeBatch=null,u.reverseOps.length>0&&We(u.reverseOps,a),u.ops.length>0&&(s.redoStack=[]),u.ops.length>0&&Ot(u.ops),X(u.updates,a),B()}}),p}function $n(){s.pausedHistory=[]}function Gn(){let l=s.pausedHistory;s.pausedHistory=null,l!==null&&l.length>0&&ce(l,d)}function $e(){return s.root===void 0?Te===null?"not-loaded":"loading":s.unacknowledgedOps.size===0?"synchronized":"synchronizing"}let Ct=$e();function Ie(){let l=$e();Ct!==l&&(Ct=l,h.storageStatus.notify(l))}let Yn=new ye(s.others,l=>l.map((p,u)=>gn(`Other ${u}`,p))),It={connection:h.connection.observable,status:h.status.observable,lostConnection:h.lostConnection.observable,customEvent:h.customEvent.observable,others:h.others.observable,me:h.me.observable,error:h.error.observable,storage:h.storage.observable,history:h.history.observable,storageDidLoad:h.storageDidLoad.observable,storageStatus:h.storageStatus.observable,ydoc:h.ydoc.observable};return{__internal:{get buffer(){return s.buffer},get undoStack(){return s.undoStack},get nodeCount(){return s.nodes.size},getSelf_forDevTools:()=>ne.current,getOthers_forDevTools:()=>Yn.current,send:{explicitClose:l=>i._privateSendMachineEvent({type:"EXPLICIT_SOCKET_CLOSE",event:l}),implicitClose:()=>i._privateSendMachineEvent({type:"NAVIGATOR_OFFLINE"})}},id:o.roomId,subscribe:Bo(It),connect:()=>i.connect(),reconnect:()=>i.reconnect(),disconnect:()=>i.disconnect(),destroy:()=>i.destroy(),updatePresence:Pn,updateYDoc:Jn,broadcastEvent:Kn,batch:Hn,history:{undo:Wn,redo:Fn,canUndo:vt,canRedo:gt,pause:$n,resume:Gn},fetchYDoc:Vn,getStorage:zn,getStorageSnapshot:Bn,getStorageStatus:$e,events:It,getStatus:()=>i.getStatus(),getConnectionState:()=>i.getLegacyStatus(),isSelfAware:()=>s.sessionInfo.current!==null,getSelf:()=>te.current,getPresence:()=>s.me.current,getOthers:()=>s.others.current}}function Bo(t){function o(r,i){return t.storage.subscribe(s=>{let a=s.filter(d=>ht(d.node,r));a.length>0&&i(a)})}function e(r,i){return t.storage.subscribe(s=>{for(let a of s)a.node._id===r._id&&i(a.node)})}function n(r,i,s){if(typeof r=="string"&&zo(r)){if(typeof i!="function")throw new Error("Second argument must be a callback function");let a=i;switch(r){case"event":return t.customEvent.subscribe(a);case"my-presence":return t.me.subscribe(a);case"others":{let d=a;return t.others.subscribe(({others:c,event:f})=>d(c,f))}case"error":return t.error.subscribe(a);case"connection":return t.connection.subscribe(a);case"status":return t.status.subscribe(a);case"lost-connection":return t.lostConnection.subscribe(a);case"history":return t.history.subscribe(a);case"storage-status":return t.storageStatus.subscribe(a);default:return U(r,"Unknown event")}}if(i===void 0||typeof r=="function")if(typeof r=="function"){let a=r;return t.storage.subscribe(a)}else throw new Error("Please specify a listener callback");if(I(r)){let a=r;return s!=null&&s.isDeep?o(a,i):e(a,i)}throw new Error(`"${String(r)}" is not a valid event name`)}return n}function zo(t){return t==="my-presence"||t==="others"||t==="event"||t==="error"||t==="history"||t==="status"||t==="storage-status"||t==="lost-connection"||t==="connection"}function Vo(t,o){return e=>{let n=o!=null?o:typeof WebSocket=="undefined"?void 0:WebSocket;if(n===void 0)throw new q("To use Liveblocks client in a non-dom environment, you need to provide a WebSocket polyfill.");let r=e.raw;return new n(`${t}/?token=${r}&version=1.1.1-dual4`)}}function Wo(t,o,e,n){return j(this,null,function*(){return(n||fetch)(e,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`},body:t})})}function Fo(t,o,e){let n=e!=null?e:typeof window=="undefined"?void 0:window.fetch;if(o.type==="public")return()=>j(this,null,function*(){if(n===void 0)throw new q("To use Liveblocks client in a non-dom environment with a publicApiKey, you need to provide a fetch polyfill.");return _n(n,o.url,{room:t,publicApiKey:o.publicApiKey}).then(({token:r})=>je(r))});if(o.type==="private")return()=>j(this,null,function*(){if(n===void 0)throw new q("To use Liveblocks client in a non-dom environment with a url as auth endpoint, you need to provide a fetch polyfill.");return _n(n,o.url,{room:t}).then(({token:r})=>je(r))});if(o.type==="custom")return()=>j(this,null,function*(){let r=yield o.callback(t);if(!r||!r.token)throw new Error('We expect the authentication callback to return a token, but it does not. Hint: the return value should look like: { token: "..." }');return je(r.token)});throw new Error("Internal error. Unexpected authentication type")}function _n(t,o,e){return j(this,null,function*(){let n=yield t(o,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify(e)});if(!n.ok){let s=`${(yield n.text()).trim()||"reason not provided in auth response"} (${n.status} returned by POST ${o})`;throw n.status===401||n.status===403?new q(`Unauthorized: ${s}`):new Error(`Failed to authenticate: ${s}`)}let r;try{r=yield n.json()}catch(s){throw new Error(`Expected a JSON response when doing a POST request on "${o}". ${String(s)}`)}if(!A(r)||typeof r.token!="string")throw new Error(`Expected a JSON response of the form \`{ token: "..." }\` when doing a POST request on "${o}", but got ${JSON.stringify(r)}`);let{token:i}=r;return{token:i}})}var Ho=16,$o=1e3,Go=100,Yo=200,Xo=1e3,qo=3e4,Zo=5e3;function Qo(t){let o=t;return typeof o.liveblocksServer=="string"?o.liveblocksServer:"wss://api.liveblocks.io/v6"}function er(t){var d,c;let o=t,e=tr((d=o.throttle)!=null?d:Go),n=nr((c=o.lostConnectionTimeout)!=null?c:Zo),r=new Map;function i(f){let y=r.get(f);return y||null}function s(f,y){var K,m,h;let b=r.get(f);if(b!==void 0)return b;Ze(y.initialPresence===null||y.initialPresence===void 0,"Please provide an initial presence value for the current user when entering the room.");let E=On({initialPresence:(K=y.initialPresence)!=null?K:{},initialStorage:y.initialStorage},{roomId:f,throttleDelay:e,lostConnectionTimeout:n,polyfills:o.polyfills,delegates:o.mockedDelegates,enableDebugLogging:o.enableDebugLogging,unstable_batchedUpdates:y==null?void 0:y.unstable_batchedUpdates,liveblocksServer:Qo(o),authentication:or(o,f),httpSendEndpoint:rr(o,f),unstable_fallbackToHTTP:!!o.unstable_fallbackToHTTP});if(r.set(f,E),Jt(()=>Array.from(r.keys())),Bt(f,E),(m=y.shouldInitiallyConnect)!=null?m:!0){if(typeof atob=="undefined"){if(((h=o.polyfills)==null?void 0:h.atob)===void 0)throw new Error("You need to polyfill atob to use the client in your environment. Please follow the instructions at https://liveblocks.io/docs/errors/liveblocks-client/atob-polyfill");global.atob=o.polyfills.atob}E.connect()}return E}function a(f){zt(f);let y=r.get(f);y!==void 0&&(y.destroy(),r.delete(f))}return{getRoom:i,enter:s,leave:a}}function En(t,o,e,n,r){if(typeof o!="number"||o<e||o>n)throw new Error(`${t} should be a number between ${r!=null?r:e} and ${n}.`);return o}function tr(t){return En("throttle",t,Ho,$o)}function nr(t){return En("lostConnectionTimeout",t,Yo,qo,Xo)}function or(t,o){let{publicApiKey:e,authEndpoint:n}=t;if(n!==void 0&&e!==void 0)throw new Error("You cannot use both publicApiKey and authEndpoint. Please use either publicApiKey or authEndpoint, but not both. For more information: https://liveblocks.io/docs/api-reference/liveblocks-client#createClient");if(typeof e=="string"){if(e.startsWith("sk_"))throw new Error("Invalid publicApiKey. You are using the secret key which is not supported. Please use the public key instead. For more information: https://liveblocks.io/docs/api-reference/liveblocks-client#createClientPublicKey");if(!e.startsWith("pk_"))throw new Error("Invalid key. Please use the public key format: pk_<public key>. For more information: https://liveblocks.io/docs/api-reference/liveblocks-client#createClientPublicKey");return{type:"public",publicApiKey:e,url:sr(t,o)}}if(typeof n=="string")return{type:"private",url:n};if(typeof n=="function")return{type:"custom",callback:n};throw n!==void 0?new Error("authEndpoint must be a string or a function. For more information: https://liveblocks.io/docs/api-reference/liveblocks-client#createClientAuthEndpoint"):new Error("Invalid Liveblocks client options. For more information: https://liveblocks.io/docs/api-reference/liveblocks-client#createClient")}function rr(t,o){return t.httpSendEndpoint?t.httpSendEndpoint.replace("{roomId}",o):`https://api.liveblocks.io/v2/rooms/${encodeURIComponent(o)}/send-message`}function sr(t,o){return t.publicAuthorizeEndpoint?t.publicAuthorizeEndpoint.replace("{roomId}",o):`https://api.liveblocks.io/v2/rooms/${encodeURIComponent(o)}/public/authorize`}function Ve(t){return t instanceof x?{liveblocksType:"LiveObject",data:Object.fromEntries(Object.entries(t.toObject()).map(([o,e])=>[o,e?Ve(e):""]))}:t instanceof N?{liveblocksType:"LiveMap",data:Object.fromEntries([...t].map(([o,e])=>[o,Ve(e)]))}:t instanceof M?{liveblocksType:"LiveList",data:[...t].map(o=>Ve(o))}:t}function Sn(t){let o={};for(let e in t){let n=t[e];n!==void 0&&(o[e]=V(n))}return o}function ir(t){return Sn(t.toObject())}function ar(t){let o={};for(let[e,n]of t.entries())o[e]=V(n);return o}function Cn(t){return t.map(V)}function dr(t){return Cn(t.toArray())}function V(t){return t instanceof x?ir(t):t instanceof M?dr(t):t instanceof N?ar(t):t instanceof J?t.data:Array.isArray(t)?Cn(t):A(t)?Sn(t):t}function de(t){if(Array.isArray(t))return new M(t.map(de));if(A(t)){let o={};for(let e in t){let n=t[e];n!==void 0&&(o[e]=de(n))}return new x(o)}else return t}function cr(t,o,e){let n=0,r=o.length-1,i=e.length-1,s=o[0],a=e[0];e:{for(;s===a;){if(++n,n>r||n>i)break e;s=o[n],a=e[n]}for(s=o[r],a=e[i];s===a;){if(r--,i--,n>r||n>i)break e;s=o[r],a=e[i]}}if(n>r){if(n<=i)for(;n<=i;)t.insert(de(e[n]),n),n++}else if(n>i){let d=n;for(;d<=r;)t.delete(n),d++}else{for(;n<=r&&n<=i;){s=o[n],a=e[n];let c=t.get(n);Ae(c)&&A(s)&&A(a)?Ln(c,s,a):t.set(n,de(a)),n++}for(;n<=i;)t.insert(de(e[n]),n),n++;let d=n;for(;d<=r;)t.delete(n),d++}}function In(t,o,e,n){if(process.env.NODE_ENV!=="production"){let i=yt(n);if(i){le(`New state path: '${i.path}' value: '${String(i.value)}' is not serializable.
|
|
5
|
+
`)}`),new Error(`Storage mutations rejected by server: ${_.reason}`)}break}}X(u,a)})}function B(){let l=s.buffer.storageOperations;if(l.length>0){for(let g of l)s.unacknowledgedOps.set(T(g.opId),g);Ie()}if(i.getStatus()!=="connected"){s.buffer.storageOperations=[];return}let p=Date.now(),u=p-s.buffer.lastFlushedAt;if(u>o.throttleDelay){let g=jn();if(g.length===0)return;L(g),s.buffer={flushTimerID:void 0,lastFlushedAt:p,messages:[],storageOperations:[],me:null}}else clearTimeout(s.buffer.flushTimerID),s.buffer.flushTimerID=setTimeout(B,o.throttleDelay-u)}function jn(){let l=[];s.buffer.me&&l.push(s.buffer.me.type==="full"?{type:100,targetActor:-1,data:s.buffer.me.data}:{type:100,data:s.buffer.me.data});for(let p of s.buffer.messages)l.push(p);return s.buffer.storageOperations.length>0&&l.push({type:201,ops:s.buffer.storageOperations}),l}function Jn(l){s.buffer.messages.push({type:301,update:l}),B()}function Kn(l,p={shouldQueueEventIfNotReady:!1}){i.getStatus()!=="connected"&&!p.shouldQueueEventIfNotReady||(s.buffer.messages.push({type:103,event:l}),B())}function Ot(l){s.buffer.storageOperations.push(...l),B()}let Te=null,Ce=null;function Et(l){let p=s.buffer.messages;p.some(u=>u.type===200)||p.push({type:200}),l.flush&&B()}function St(){return Te===null&&(Et({flush:!0}),Te=new Promise(l=>{Ce=l}),Ie()),Te}function Bn(){let l=s.root;return l!==void 0?l:(St(),null)}function zn(){return j(this,null,function*(){return s.root!==void 0?Promise.resolve({root:s.root}):(yield St(),{root:T(s.root)})})}function Vn(l){s.buffer.messages.push({type:300,vector:l}),B()}function Wn(){if(s.activeBatch)throw new Error("undo is not allowed during a batch");let l=s.undoStack.pop();if(l===void 0)return;s.pausedHistory=null;let p=me(l,!0);d(()=>{X(p.updates,a),s.redoStack.push(p.reverse),He(a)});for(let u of p.ops)u.type!=="presence"&&s.buffer.storageOperations.push(u);B()}function Fn(){if(s.activeBatch)throw new Error("redo is not allowed during a batch");let l=s.redoStack.pop();if(l===void 0)return;s.pausedHistory=null;let p=me(l,!0);d(()=>{X(p.updates,a),s.undoStack.push(p.reverse),He(a)});for(let u of p.ops)u.type!=="presence"&&s.buffer.storageOperations.push(u);B()}function Hn(l){if(s.activeBatch)return l();let p;return d(()=>{s.activeBatch={ops:[],updates:{storageUpdates:new Map,presence:!1,others:[]},reverseOps:[]};try{p=l()}finally{let u=s.activeBatch;s.activeBatch=null,u.reverseOps.length>0&&We(u.reverseOps,a),u.ops.length>0&&(s.redoStack=[]),u.ops.length>0&&Ot(u.ops),X(u.updates,a),B()}}),p}function $n(){s.pausedHistory=[]}function Gn(){let l=s.pausedHistory;s.pausedHistory=null,l!==null&&l.length>0&&ce(l,d)}function $e(){return s.root===void 0?Te===null?"not-loaded":"loading":s.unacknowledgedOps.size===0?"synchronized":"synchronizing"}let Ct=$e();function Ie(){let l=$e();Ct!==l&&(Ct=l,h.storageStatus.notify(l))}let Yn=new ye(s.others,l=>l.map((p,u)=>gn(`Other ${u}`,p))),It={connection:h.connection.observable,status:h.status.observable,lostConnection:h.lostConnection.observable,customEvent:h.customEvent.observable,others:h.others.observable,me:h.me.observable,error:h.error.observable,storage:h.storage.observable,history:h.history.observable,storageDidLoad:h.storageDidLoad.observable,storageStatus:h.storageStatus.observable,ydoc:h.ydoc.observable};return{__internal:{get buffer(){return s.buffer},get undoStack(){return s.undoStack},get nodeCount(){return s.nodes.size},getSelf_forDevTools:()=>ne.current,getOthers_forDevTools:()=>Yn.current,send:{explicitClose:l=>i._privateSendMachineEvent({type:"EXPLICIT_SOCKET_CLOSE",event:l}),implicitClose:()=>i._privateSendMachineEvent({type:"NAVIGATOR_OFFLINE"})}},id:o.roomId,subscribe:Bo(It),connect:()=>i.connect(),reconnect:()=>i.reconnect(),disconnect:()=>i.disconnect(),destroy:()=>i.destroy(),updatePresence:Pn,updateYDoc:Jn,broadcastEvent:Kn,batch:Hn,history:{undo:Wn,redo:Fn,canUndo:vt,canRedo:gt,pause:$n,resume:Gn},fetchYDoc:Vn,getStorage:zn,getStorageSnapshot:Bn,getStorageStatus:$e,events:It,getStatus:()=>i.getStatus(),getConnectionState:()=>i.getLegacyStatus(),isSelfAware:()=>s.sessionInfo.current!==null,getSelf:()=>te.current,getPresence:()=>s.me.current,getOthers:()=>s.others.current}}function Bo(t){function o(r,i){return t.storage.subscribe(s=>{let a=s.filter(d=>ht(d.node,r));a.length>0&&i(a)})}function e(r,i){return t.storage.subscribe(s=>{for(let a of s)a.node._id===r._id&&i(a.node)})}function n(r,i,s){if(typeof r=="string"&&zo(r)){if(typeof i!="function")throw new Error("Second argument must be a callback function");let a=i;switch(r){case"event":return t.customEvent.subscribe(a);case"my-presence":return t.me.subscribe(a);case"others":{let d=a;return t.others.subscribe(({others:c,event:f})=>d(c,f))}case"error":return t.error.subscribe(a);case"connection":return t.connection.subscribe(a);case"status":return t.status.subscribe(a);case"lost-connection":return t.lostConnection.subscribe(a);case"history":return t.history.subscribe(a);case"storage-status":return t.storageStatus.subscribe(a);default:return U(r,"Unknown event")}}if(i===void 0||typeof r=="function")if(typeof r=="function"){let a=r;return t.storage.subscribe(a)}else throw new Error("Please specify a listener callback");if(I(r)){let a=r;return s!=null&&s.isDeep?o(a,i):e(a,i)}throw new Error(`"${String(r)}" is not a valid event name`)}return n}function zo(t){return t==="my-presence"||t==="others"||t==="event"||t==="error"||t==="history"||t==="status"||t==="storage-status"||t==="lost-connection"||t==="connection"}function Vo(t,o){return e=>{let n=o!=null?o:typeof WebSocket=="undefined"?void 0:WebSocket;if(n===void 0)throw new q("To use Liveblocks client in a non-dom environment, you need to provide a WebSocket polyfill.");let r=e.raw;return new n(`${t}/?token=${r}&version=1.1.1-dual5`)}}function Wo(t,o,e,n){return j(this,null,function*(){return(n||fetch)(e,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`},body:t})})}function Fo(t,o,e){let n=e!=null?e:typeof window=="undefined"?void 0:window.fetch;if(o.type==="public")return()=>j(this,null,function*(){if(n===void 0)throw new q("To use Liveblocks client in a non-dom environment with a publicApiKey, you need to provide a fetch polyfill.");return _n(n,o.url,{room:t,publicApiKey:o.publicApiKey}).then(({token:r})=>je(r))});if(o.type==="private")return()=>j(this,null,function*(){if(n===void 0)throw new q("To use Liveblocks client in a non-dom environment with a url as auth endpoint, you need to provide a fetch polyfill.");return _n(n,o.url,{room:t}).then(({token:r})=>je(r))});if(o.type==="custom")return()=>j(this,null,function*(){let r=yield o.callback(t);if(!r||!r.token)throw new Error('We expect the authentication callback to return a token, but it does not. Hint: the return value should look like: { token: "..." }');return je(r.token)});throw new Error("Internal error. Unexpected authentication type")}function _n(t,o,e){return j(this,null,function*(){let n=yield t(o,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify(e)});if(!n.ok){let s=`${(yield n.text()).trim()||"reason not provided in auth response"} (${n.status} returned by POST ${o})`;throw n.status===401||n.status===403?new q(`Unauthorized: ${s}`):new Error(`Failed to authenticate: ${s}`)}let r;try{r=yield n.json()}catch(s){throw new Error(`Expected a JSON response when doing a POST request on "${o}". ${String(s)}`)}if(!A(r)||typeof r.token!="string")throw new Error(`Expected a JSON response of the form \`{ token: "..." }\` when doing a POST request on "${o}", but got ${JSON.stringify(r)}`);let{token:i}=r;return{token:i}})}var Ho=16,$o=1e3,Go=100,Yo=200,Xo=1e3,qo=3e4,Zo=5e3;function Qo(t){let o=t;return typeof o.liveblocksServer=="string"?o.liveblocksServer:"wss://api.liveblocks.io/v6"}function er(t){var d,c;let o=t,e=tr((d=o.throttle)!=null?d:Go),n=nr((c=o.lostConnectionTimeout)!=null?c:Zo),r=new Map;function i(f){let y=r.get(f);return y||null}function s(f,y){var K,m,h;let b=r.get(f);if(b!==void 0)return b;Ze(y.initialPresence===null||y.initialPresence===void 0,"Please provide an initial presence value for the current user when entering the room.");let E=On({initialPresence:(K=y.initialPresence)!=null?K:{},initialStorage:y.initialStorage},{roomId:f,throttleDelay:e,lostConnectionTimeout:n,polyfills:o.polyfills,delegates:o.mockedDelegates,enableDebugLogging:o.enableDebugLogging,unstable_batchedUpdates:y==null?void 0:y.unstable_batchedUpdates,liveblocksServer:Qo(o),authentication:or(o,f),httpSendEndpoint:rr(o,f),unstable_fallbackToHTTP:!!o.unstable_fallbackToHTTP});if(r.set(f,E),Jt(()=>Array.from(r.keys())),Bt(f,E),(m=y.shouldInitiallyConnect)!=null?m:!0){if(typeof atob=="undefined"){if(((h=o.polyfills)==null?void 0:h.atob)===void 0)throw new Error("You need to polyfill atob to use the client in your environment. Please follow the instructions at https://liveblocks.io/docs/errors/liveblocks-client/atob-polyfill");global.atob=o.polyfills.atob}E.connect()}return E}function a(f){zt(f);let y=r.get(f);y!==void 0&&(y.destroy(),r.delete(f))}return{getRoom:i,enter:s,leave:a}}function En(t,o,e,n,r){if(typeof o!="number"||o<e||o>n)throw new Error(`${t} should be a number between ${r!=null?r:e} and ${n}.`);return o}function tr(t){return En("throttle",t,Ho,$o)}function nr(t){return En("lostConnectionTimeout",t,Yo,qo,Xo)}function or(t,o){let{publicApiKey:e,authEndpoint:n}=t;if(n!==void 0&&e!==void 0)throw new Error("You cannot use both publicApiKey and authEndpoint. Please use either publicApiKey or authEndpoint, but not both. For more information: https://liveblocks.io/docs/api-reference/liveblocks-client#createClient");if(typeof e=="string"){if(e.startsWith("sk_"))throw new Error("Invalid publicApiKey. You are using the secret key which is not supported. Please use the public key instead. For more information: https://liveblocks.io/docs/api-reference/liveblocks-client#createClientPublicKey");if(!e.startsWith("pk_"))throw new Error("Invalid key. Please use the public key format: pk_<public key>. For more information: https://liveblocks.io/docs/api-reference/liveblocks-client#createClientPublicKey");return{type:"public",publicApiKey:e,url:sr(t,o)}}if(typeof n=="string")return{type:"private",url:n};if(typeof n=="function")return{type:"custom",callback:n};throw n!==void 0?new Error("authEndpoint must be a string or a function. For more information: https://liveblocks.io/docs/api-reference/liveblocks-client#createClientAuthEndpoint"):new Error("Invalid Liveblocks client options. For more information: https://liveblocks.io/docs/api-reference/liveblocks-client#createClient")}function rr(t,o){return t.httpSendEndpoint?t.httpSendEndpoint.replace("{roomId}",o):`https://api.liveblocks.io/v2/rooms/${encodeURIComponent(o)}/send-message`}function sr(t,o){return t.publicAuthorizeEndpoint?t.publicAuthorizeEndpoint.replace("{roomId}",o):`https://api.liveblocks.io/v2/rooms/${encodeURIComponent(o)}/public/authorize`}function Ve(t){return t instanceof x?{liveblocksType:"LiveObject",data:Object.fromEntries(Object.entries(t.toObject()).map(([o,e])=>[o,e?Ve(e):""]))}:t instanceof N?{liveblocksType:"LiveMap",data:Object.fromEntries([...t].map(([o,e])=>[o,Ve(e)]))}:t instanceof M?{liveblocksType:"LiveList",data:[...t].map(o=>Ve(o))}:t}function Sn(t){let o={};for(let e in t){let n=t[e];n!==void 0&&(o[e]=V(n))}return o}function ir(t){return Sn(t.toObject())}function ar(t){let o={};for(let[e,n]of t.entries())o[e]=V(n);return o}function Cn(t){return t.map(V)}function dr(t){return Cn(t.toArray())}function V(t){return t instanceof x?ir(t):t instanceof M?dr(t):t instanceof N?ar(t):t instanceof J?t.data:Array.isArray(t)?Cn(t):A(t)?Sn(t):t}function de(t){if(Array.isArray(t))return new M(t.map(de));if(A(t)){let o={};for(let e in t){let n=t[e];n!==void 0&&(o[e]=de(n))}return new x(o)}else return t}function cr(t,o,e){let n=0,r=o.length-1,i=e.length-1,s=o[0],a=e[0];e:{for(;s===a;){if(++n,n>r||n>i)break e;s=o[n],a=e[n]}for(s=o[r],a=e[i];s===a;){if(r--,i--,n>r||n>i)break e;s=o[r],a=e[i]}}if(n>r){if(n<=i)for(;n<=i;)t.insert(de(e[n]),n),n++}else if(n>i){let d=n;for(;d<=r;)t.delete(n),d++}else{for(;n<=r&&n<=i;){s=o[n],a=e[n];let c=t.get(n);Ae(c)&&A(s)&&A(a)?Ln(c,s,a):t.set(n,de(a)),n++}for(;n<=i;)t.insert(de(e[n]),n),n++;let d=n;for(;d<=r;)t.delete(n),d++}}function In(t,o,e,n){if(process.env.NODE_ENV!=="production"){let i=yt(n);if(i){le(`New state path: '${i.path}' value: '${String(i.value)}' is not serializable.
|
|
6
6
|
Only serializable value can be synced with Liveblocks.`);return}}let r=t.get(o);if(n===void 0)t.delete(o);else if(r===void 0)t.set(o,de(n));else{if(e===n)return;he(r)&&Array.isArray(e)&&Array.isArray(n)?cr(r,e,n):Ae(r)&&A(e)&&A(n)?Ln(r,e,n):t.set(o,de(n))}}function Ln(t,o,e){let n={};for(let r in e)In(t,r,o[r],e[r]);for(let r in o)e[r]===void 0&&t.delete(r);Object.keys(n).length>0&&t.update(n)}function lr(t){let o=[];for(;t.parent.type==="HasParent";)he(t.parent.node)?o.push(t.parent.node._indexOfPosition(t.parent.key)):o.push(t.parent.key),t=t.parent.node;return o}function pr(t,o){return o.reduce((e,n)=>ur(e,n),t)}function ur(t,o){let e=lr(o.node);return Tt(t,e,o)}function Tt(t,o,e){var r,i,s,a;let n=o.pop();if(n===void 0)switch(e.type){case"LiveObject":{if(!ae(t))throw new Error("Internal: received update on LiveObject but state was not an object");let d=Object.assign({},t);for(let c in e.updates)if(((r=e.updates[c])==null?void 0:r.type)==="update"){let f=e.node.get(c);f!==void 0&&(d[c]=V(f))}else((i=e.updates[c])==null?void 0:i.type)==="delete"&&delete d[c];return d}case"LiveList":{if(!Array.isArray(t))throw new Error("Internal: received update on LiveList but state was not an array");let d=t.map(c=>c);for(let c of e.updates)c.type==="set"?d=d.map((f,y)=>y===c.index?V(c.item):f):c.type==="insert"?c.index===d.length?d.push(V(c.item)):d=[...d.slice(0,c.index),V(c.item),...d.slice(c.index)]:c.type==="delete"?d.splice(c.index,1):c.type==="move"&&(c.previousIndex>c.index?d=[...d.slice(0,c.index),V(c.item),...d.slice(c.index,c.previousIndex),...d.slice(c.previousIndex+1)]:d=[...d.slice(0,c.previousIndex),...d.slice(c.previousIndex+1,c.index+1),V(c.item),...d.slice(c.index+1)]);return d}case"LiveMap":{if(!ae(t))throw new Error("Internal: received update on LiveMap but state was not an object");let d=Object.assign({},t);for(let c in e.updates)if(((s=e.updates[c])==null?void 0:s.type)==="update"){let f=e.node.get(c);f!==void 0&&(d[c]=V(f))}else((a=e.updates[c])==null?void 0:a.type)==="delete"&&delete d[c];return d}}if(Array.isArray(t)){let d=[...t];return d[n]=Tt(t[n],o,e),d}else if(ae(t)){let d=t[n];return d===void 0?t:P(C({},t),{[n]:Tt(d,o,e)})}else return t}function fr(t,o){if(t.length!==o.length)return!1;for(let e=0;e<t.length;e++)if(!Object.is(t[e],o[e]))return!1;return!0}function hr(t,o){if(typeof t!="object"||t===null||typeof o!="object"||o===null||Object.prototype.toString.call(t)!=="[object Object]"||Object.prototype.toString.call(o)!=="[object Object]")return!1;let e=Object.keys(t);return e.length!==Object.keys(o).length?!1:e.every(n=>Object.prototype.hasOwnProperty.call(o,n)&&Object.is(t[n],o[n]))}function yr(t,o){if(Object.is(t,o))return!0;let e=Array.isArray(t),n=Array.isArray(o);return e||n?!e||!n?!1:fr(t,o):hr(t,o)}var kn=(d=>(d[d.CLOSE_ABNORMAL=1006]="CLOSE_ABNORMAL",d[d.INVALID_MESSAGE_FORMAT=4e3]="INVALID_MESSAGE_FORMAT",d[d.NOT_ALLOWED=4001]="NOT_ALLOWED",d[d.MAX_NUMBER_OF_MESSAGES_PER_SECONDS=4002]="MAX_NUMBER_OF_MESSAGES_PER_SECONDS",d[d.MAX_NUMBER_OF_CONCURRENT_CONNECTIONS=4003]="MAX_NUMBER_OF_CONCURRENT_CONNECTIONS",d[d.MAX_NUMBER_OF_MESSAGES_PER_DAY_PER_APP=4004]="MAX_NUMBER_OF_MESSAGES_PER_DAY_PER_APP",d[d.MAX_NUMBER_OF_CONCURRENT_CONNECTIONS_PER_ROOM=4005]="MAX_NUMBER_OF_CONCURRENT_CONNECTIONS_PER_ROOM",d[d.CLOSE_WITHOUT_RETRY=4999]="CLOSE_WITHOUT_RETRY",d))(kn||{});export{bn as ClientMsgCode,ct as CrdtType,M as LiveList,N as LiveMap,x as LiveObject,dt as OpCode,vn as ServerMsgCode,kn as WebsocketCloseCodes,mt as asArrayWithLegacyMethods,Z as asPos,Xt as assert,U as assertNever,tt as b64decode,er as createClient,Gt as deprecate,Ze as deprecateIf,ao as errorIf,R as freeze,ln as isChildCrdt,De as isJsonArray,ae as isJsonObject,mn as isJsonScalar,A as isPlainObject,lt as isRootCrdt,pr as legacy_patchImmutableObject,V as lsonToJson,z as makePosition,T as nn,In as patchLiveObjectKey,yr as shallow,Yt as throwUsageError,Ve as toPlainLson,ge as tryParseJson,xe as withTimeout};
|
|
7
7
|
//# sourceMappingURL=index.mjs.map
|