@liveblocks/core 1.1.0 → 1.1.1-dual1

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.mjs ADDED
@@ -0,0 +1,7 @@
1
+ var Yn=Object.defineProperty,Xn=Object.defineProperties;var qn=Object.getOwnPropertyDescriptors;var Pt=Object.getOwnPropertySymbols;var Zn=Object.prototype.hasOwnProperty,Qn=Object.prototype.propertyIsEnumerable;var Rt=(t,o,e)=>o in t?Yn(t,o,{enumerable:!0,configurable:!0,writable:!0,value:e}):t[o]=e,C=(t,o)=>{for(var e in o||(o={}))Zn.call(o,e)&&Rt(t,e,o[e]);if(Pt)for(var e of Pt(o))Qn.call(o,e)&&Rt(t,e,o[e]);return t},x=(t,o)=>Xn(t,qn(o));var N=(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 N(this,null,function*(){let E;return new Promise(G=>{E=i(J=>{(b===void 0||b(J))&&G(J)})}).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 wt=!1;function Mt(t){wt=t}function V(t,o){if(process.env.NODE_ENV==="production"||typeof window=="undefined")return;let e=x(C({},t),{source:"liveblocks-devtools-client"});(o!=null&&o.force||wt)&&window.postMessage(e,"*")}var Ut=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"&&Ut.notify(t.data)});var $e=Ut.observable;var Dt="1.1.1-dual1",At=!1;function jt(t){process.env.NODE_ENV==="production"||typeof window=="undefined"||At||(At=!0,$e.subscribe(o=>{switch(o.msg){case"connect":{Mt(!0);for(let e of t())V({msg:"room::available",roomId:e,clientVersion:Dt});break}}}),V({msg:"wake-up-devtools"},{force:!0}))}var Ge=new Map;function Xe(t){var e;let o=(e=Ge.get(t))!=null?e:[];Ge.delete(t);for(let n of o)n()}function eo(t){Xe(t.id),ro(t),Ge.set(t.id,[t.events.status.subscribe(()=>to(t)),t.events.storageDidLoad.subscribeOnce(()=>Nt(t)),t.events.storage.subscribe(()=>Nt(t)),t.events.me.subscribe(()=>no(t)),t.events.others.subscribe(()=>oo(t))])}function to(t){V({msg:"room::sync::partial",roomId:t.id,status:t.getStatus()})}function Nt(t){let o=t.getStorageSnapshot();o&&V({msg:"room::sync::partial",roomId:t.id,storage:o.toTreeNode("root").payload})}function no(t){let o=t.__internal.getSelf_forDevTools();o&&V({msg:"room::sync::partial",roomId:t.id,me:o})}function oo(t){let o=t.__internal.getOthers_forDevTools();o&&V({msg:"room::sync::partial",roomId:t.id,others:o})}function ro(t){var r;let o=t.getStorageSnapshot(),e=t.__internal.getSelf_forDevTools(),n=t.__internal.getOthers_forDevTools();V({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 Ye=new Map;function Jt(t){let o=Ye.get(t);Ye.delete(t),o&&o()}function Kt(t,o){process.env.NODE_ENV==="production"||typeof window=="undefined"||(V({msg:"room::available",roomId:t,clientVersion:Dt}),Jt(t),Ye.set(t,$e.subscribe(e=>{switch(e.msg){case"room::subscribe":{e.roomId===t&&eo(o);break}case"room::unsubscribe":{e.roomId===t&&Xe(t);break}}})))}function Bt(t){process.env.NODE_ENV==="production"||typeof window=="undefined"||(Xe(t),Jt(t),V({msg:"room::unavailable",roomId:t}))}var zt="background:#0e0d12;border-radius:9999px;color:#fff;padding:3px 7px;font-family:sans-serif;font-weight:600;",so="font-weight:600";function Wt(t){return typeof window=="undefined"||process.env.NODE_ENV==="test"?console[t]:(o,...e)=>console[t]("%cLiveblocks",zt,o,...e)}var F=Wt("warn"),le=Wt("error");function Vt(t){return typeof window=="undefined"||process.env.NODE_ENV==="test"?console[t]:(o,e,...n)=>console[t](`%cLiveblocks%c ${o}`,zt,so,e,...n)}var Ft=Vt("warn"),ve=Vt("error");var Ht=new Set;function $t(t,o=t){process.env.NODE_ENV!=="production"&&(Ht.has(o)||(Ht.add(o),ve("Deprecation warning",t)))}function qe(t,o,e=o){process.env.NODE_ENV!=="production"&&t&&$t(o,e)}function Gt(t){if(process.env.NODE_ENV!=="production"){let o=new Error(t);throw o.name="Usage error",ve("Usage error",t),o}}function io(t,o){process.env.NODE_ENV!=="production"&&t&&Gt(o)}function M(t,o){throw new Error(o)}function Yt(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 Yt(t!=null,o),t}function ao(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 co(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 Ze=class{constructor(o){this.curr=o}get current(){return this.curr}allowPatching(o){let e=this,n=!0,r=x(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 lo=1,Le=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=lo++,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 Ze(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=co(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]=ao(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 U(t){return t!==null&&typeof t=="object"&&Object.prototype.toString.call(t)==="[object Object]"}function Xt(t){let o={};for(let[e,n]of t)o[e]=n;return o}function Qe(t){return Object.entries(t)}function ge(t){try{return JSON.parse(t)}catch(o){return}}function et(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 N(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 ot(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 tn(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 M(o,"Unknown state")}}var nn=[250,500,1e3,2e3,4e3,8e3,1e4],Ee=nn[0]-1,po=[2e3,3e4,6e4,3e5],uo=3e4,fo=2e3,ho=1e4,yo=1e4,q=class extends Error{constructor(o){super(o)}},nt=class extends Error{constructor(e,n){super(e);this.code=n}};function on(t,o=nn){var e;return(e=o.find(n=>n>t))!=null?e:o[o.length-1]}function pe(t){t.patch({backoffDelay:on(t.backoffDelay)})}function qt(t){t.patch({backoffDelay:on(t.backoffDelay,po)})}function Zt(t){t.patch({successCount:0})}function ue(t,o){let e=t===2?le:t===1?F:()=>{};return()=>{e(o)}}function Qt(t){let o="Connection to Liveblocks websocket server";return e=>{t instanceof Error?F(`${o} could not be established. ${String(t)}`):F(rt(t)?`${o} closed prematurely (code: ${t.code}). Retrying in ${e.backoffDelay}ms.`:`${o} could not be established.`)}}function tt(t){return o=>{F(`Connection to Liveblocks websocket server closed (code: ${t.code}). Retrying in ${o.backoffDelay}ms.`)}}var mo=ue(1,"Connection to WebSocket closed permanently. Won't retry.");function rt(t){return!(t instanceof Error)&&t.type==="close"}function en(t){return rt(t)&&t.code>=4e3&&t.code<4100}function To(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 bo(t){let o=O(),e=O(),n=O(),r=null,i=t.events.didEnterState.subscribe(()=>{let s=tn(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 vo(t,o){let e=O();e.pause();let n=O(),r={successCount:0,token:null,socket:null,backoffDelay:Ee},i=new Le(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,Zt]},DISCONNECT:"@idle.initial"}),i.onEnter("@idle.*",Zt).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(),ho),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=>N(this,null,function*(){let h=null,k=new Promise((te,ne)=>{if(m.token===null)throw new Error("No auth token");let R=t.createSocket(m.token);function Y(ce){h=ce,R.removeEventListener("message",d),ne(ce)}R.addEventListener("message",d),R.addEventListener("error",Y),R.addEventListener("close",Y),R.addEventListener("open",()=>{R.addEventListener("error",s),R.addEventListener("close",a),te([R,()=>{R.removeEventListener("error",Y),R.removeEventListener("close",Y)}])})});return xe(k,yo).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)}:rt(h)&&h.code===4999?{target:"@idle.failed",effect:ue(2,h.reason)}:en(h)&&h.code!==4001?{target:"@connecting.backoff",effect:[qt,Qt(h)]}:{target:"@auth.backoff",effect:[pe,Qt(h)]}});let f={target:"@ok.awaiting-pong",effect:m=>{var h;(h=m.socket)==null||h.send("ping")}};if(i.addTimedTransition("@ok.connected",uo,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 k=>{c(k.socket),k.patch({socket:null}),clearTimeout(h),e.pause()}}).addTransitions("@ok.awaiting-pong",{PONG:"@ok.connected"}).addTimedTransition("@ok.awaiting-pong",fo,{target:"@connecting.busy",effect:ue(1,"Received no pong from server, assume implicit connection loss.")}).addTransitions("@ok.*",{EXPLICIT_SOCKET_ERROR:(m,h)=>{var k;return((k=h.socket)==null?void 0:k.readyState)===1?null:{target:"@connecting.backoff",effect:pe}},EXPLICIT_SOCKET_CLOSE:m=>m.event.code===4999?{target:"@idle.failed",effect:mo}:m.event.code===4001?{target:"@auth.backoff",effect:[pe,tt(m.event)]}:en(m.event)?{target:"@connecting.backoff",effect:[qt,tt(m.event),()=>{let h=new nt(m.event.reason,m.event.code);n.notify(h)}]}:{target:"@connecting.backoff",effect:[pe,tt(m.event)]}}),typeof document!="undefined"){let m=typeof document!="undefined"?document:void 0,h=typeof window!="undefined"?window:void 0,k=h!=null?h:m;i.onEnter("*",te=>{function ne(){i.send({type:"NAVIGATOR_OFFLINE"})}function R(){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",R),h==null||h.addEventListener("offline",ne),k==null||k.addEventListener("visibilitychange",Y),()=>{k==null||k.removeEventListener("visibilitychange",Y),h==null||h.removeEventListener("online",R),h==null||h.removeEventListener("offline",ne),c(te.socket)}})}let y=[],{statusDidChange:b,didConnect:E,didDisconnect:G,unsubscribe:J}=bo(i);return y.push(J),o&&y.push(To(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}=vo(o,e);this.machine=n,this.events=r,this.cleanups=i}getLegacyStatus(){return ot(this.getStatus())}getStatus(){try{return tn(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 rn=it(0),we=it(1),go=rn+it(-1);function it(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?Eo(t,o):t!==void 0?Oo(t):o!==void 0?_o(o):we}function _o(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)+go:t.substring(0,e)+String.fromCharCode(n-1):t.substring(0,e+1)}return we}function Oo(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 Eo(t,o){if(t<o)return st(t,o);if(t>o)return st(o,t);throw new Error("Cannot compute value between two equal positions")}function st(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+st(d,"")}else return So(t,e)+String.fromCharCode(s+i>>1)}}function So(t,o){return o<t.length?t.substring(0,o):t+rn.repeat(o-t.length)}var Co=32+1;function Io(t){if(t==="")return!1;let o=t.length-1,e=t.charCodeAt(o);if(e<Co||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 Io(t)?t:ko(t)}var at=(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))(at||{});function sn(t){return t.type===5&&t.id==="ACK"}function an(t,o,e=Z(o)){return Object.freeze({type:"HasParent",node:t,key:o,pos:e})}var dn=Object.freeze({type:"NoParent"});function Lo(t,o=Z(t)){return Object.freeze({type:"Orphaned",oldKey:t,oldPos:o})}var H=class{constructor(){this._parent=dn}_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 M(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 M(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 M(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=an(o,e);return;case"Orphaned":case"NoParent":{this._parent=an(o,e);return}default:return M(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=Lo(this.parent.key,this.parent.pos);break}case"NoParent":{this._parent=dn;break}case"Orphaned":break;default:M(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 dt=(r=>(r[r.OBJECT=0]="OBJECT",r[r.LIST=1]="LIST",r[r.MAP=2]="MAP",r[r.REGISTER=3]="REGISTER",r))(dt||{});function ct(t){return t.type===0&&!cn(t)}function cn(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 D=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 xo(t,o){let e=t._parentPos,n=o._parentPos;return e===n?0:e<n?-1:1}var j=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(xo),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=lt(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=lt(a._toOps(this._id,i,this._pool),s);this._unacknowledgedSets.set(i,T(y[0].opId));let b=lt(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 pt(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)}},pt=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 D?o.data:o}}function Me(t){return{index:t,type:"delete"}}function $(t,o){return{index:t,type:"insert",item:o instanceof D?o.data:o}}function se(t,o,e){return{index:o,type:"move",previousIndex:t,item:e instanceof D?e.data:e}}function lt(t,o){return t.map((e,n)=>n===0?x(C({},e),{intent:"set",deletedId:o}):e)}var P=process.env.NODE_ENV==="production"?t=>t:Object.freeze;var B=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 P(e)}};var w=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(ct(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=pn([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=ut(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 Xt(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),J=G.find(m=>m.parentId===this._id);J&&this._propToLastUpdate.set(y,T(J.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(ut(t))}function ut(t){switch(t.type){case 8:return t.data;case 4:return new w(t.data);case 7:return new B;case 2:return new j;default:return M(t,"Unknown creation Op")}}function ft(t,o){return t===o?!0:t.parent.type==="HasParent"?ft(t.parent.node,o):!1}function Ue([t,o],e,n){switch(o.type){case 0:return w._deserialize([t,o],e,n);case 1:return j._deserialize([t,o],e,n);case 2:return B._deserialize([t,o],e,n);case 3:return D._deserialize([t,o],e,n);default:throw new Error("Unexpected CRDT type")}}function pn([t,o],e,n){switch(o.type){case 0:return w._deserialize([t,o],e,n);case 1:return j._deserialize([t,o],e,n);case 2:return B._deserialize([t,o],e,n);case 3:return o.data;default:throw new Error("Unexpected CRDT type")}}function Se(t){return he(t)||Po(t)||Ae(t)}function I(t){return Se(t)||Ro(t)}function he(t){return t instanceof j}function Po(t){return t instanceof B}function Ae(t){return t instanceof w}function Ro(t){return t instanceof D}function Q(t){return t instanceof D?t.data:t instanceof j||t instanceof B||t instanceof w?t:M(t,"Unknown AbstractCrdt")}function re(t){return t instanceof w||t instanceof B||t instanceof j?t:new D(t)}function fn(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 wo(t,o){let e=t.updates;for(let[n,r]of Qe(o.updates))e[n]=r;return x(C({},o),{updates:e})}function Mo(t,o){let e=t.updates;for(let[n,r]of Qe(o.updates))e[n]=r;return x(C({},o),{updates:e})}function Uo(t,o){let e=t.updates;return x(C({},o),{updates:e.concat(o.updates)})}function Ne(t,o){return t===void 0?o:t.type==="LiveObject"&&o.type==="LiveObject"?wo(t,o):t.type==="LiveMap"&&o.type==="LiveMap"?Mo(t,o):t.type==="LiveList"&&o.type==="LiveList"?Uo(t,o):o}function un(t){let o=typeof t;return t==null||o==="string"||o==="boolean"||o==="number"||Array.isArray(t)||U(t)}function ht(t,o=""){if(!un)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(!un(n))return{path:r,value:n};if(typeof n=="object"){let i=ht(n,r);if(i)return i}}return!1}function hn(t,o){let e={name:t};if(typeof Error.captureStackTrace=="function")return Error.captureStackTrace(e,o),e.stack}function yn(t){return t===null||typeof t=="string"||typeof t=="number"||typeof t=="boolean"}function De(t){return Array.isArray(t)}function ae(t){return!yn(t)&&!De(t)}function mn(t){let o=Date.now()/1e3;return!(o<=t.exp-300&&o>=t.iat-300)}function Ao(t){return Array.isArray(t)&&t.every(o=>typeof o=="string")}function No(t){return U(t)&&typeof t.iat=="number"&&typeof t.exp=="number"&&typeof t.actor=="number"&&(t.id===void 0||typeof t.id=="string")&&Ao(t.scopes)}function je(t){let o=t.split(".");if(o.length!==3)throw new Error("Authentication error: invalid JWT token");let e=ge(et(o[1]));if(!(e&&No(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 Tn=(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))(Tn||{});var bn=(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))(bn||{});function yt(t){return Object.defineProperty(t,"count",{value:t.length,enumerable:!1}),Object.defineProperty(t,"toArray",{value:()=>t,enumerable:!1}),P(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 Do(t,o){return P(Oe(x(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 yt(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 Do(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]=P({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]=P(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]=P(i),this._invalidateUser(e))}};var Be=class extends ee{constructor(e){super();this._data=P(Oe(e))}_toImmutable(){return this._data}patch(e){let n=this._data,r=Je(n,e);n!==r&&(this._data=P(r),this.invalidate())}};var ze=class extends ee{constructor(e){super();this._value=P(e)}_toImmutable(){return this._value}set(e){this._value=P(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 Jo(t){let o=0;return()=>`${t}:${o++}`}function vn(t,o){return{type:"User",id:`${o.connectionId}`,key:t,payload:o}}function _n(t,o){var It,kt,Lt,xt;let e=typeof t.initialPresence=="function"?t.initialPresence(o.roomId):t.initialPresence,n=typeof t.initialStorage=="function"?t.initialStorage(o.roomId):t.initialStorage,r=(Lt=o.delegates)!=null?Lt:{authenticate:Vo(o.roomId,o.authentication,(It=o.polyfills)==null?void 0:It.fetch),createSocket:zo(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=(xt=o.unstable_batchedUpdates)!=null?xt: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:Ve(p.scopes)}),c=p),d(()=>{h.status.notify(l),h.connection.notify(ot(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=Jo(l.actor),Te!==null&&Ot({flush:!1}),K()}function J(){clearTimeout(s.buffer.flushTimerID)}i.events.onMessage.subscribe(Nn),i.events.statusDidChange.subscribe(f),i.events.statusDidChange.subscribe(E),i.events.didConnect.subscribe(G),i.events.didDisconnect.subscribe(J),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:()=>`${Tt()}:${s.clock++}`,generateOpId:()=>`${Tt()}:${s.opClock++}`,dispatch(l,p,u){let g=s.activeBatch;if(process.env.NODE_ENV!=="production"){let _=hn("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=[],_t(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 k(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(mn(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?vn("Me",l):null);function R(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=w._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,A]of s.nodes)u.set(v,A._serialize());let g=fn(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),Fe(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 Tt(){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?x(C({},v),{opId:m.generateOpId()}):v);for(let v of _)if(v.type==="presence"){let A={type:"presence",data:{}};for(let L in v.data)A.data[L]=s.me.current[L];if(s.me.patch(v.data),s.buffer.me===null)s.buffer.me={type:"partial",data:v.data};else for(let L in v.data)s.buffer.me.data[L]=v.data[L];u.reverse.unshift(A),u.presence=!0}else{let A;if(p)A=0;else{let be=T(v.opId);process.env.NODE_ENV!=="production"&&T(s.opStackTraces).delete(be),A=s.unacknowledgedOps.delete(be)?2:1}let L=Ln(v,A);if(L.modified){let be=L.modified.node._id;be&&g.has(be)||(u.storageUpdates.set(T(L.modified.node._id),Ne(u.storageUpdates.get(T(L.modified.node._id)),L.modified)),u.reverse.unshift(...L.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 Ln(l,p){if(sn(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 xn(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):(K(),d(()=>{p!=null&&p.addToHistory&&We([{type:"presence",data:u}],a),X({presence:!0},a)}))}function Ve(l){return l.includes("room:read")&&l.includes("room:presence:write")&&!l.includes("room:write")}function Pn(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 Rn(l){let p=s.others.getUser(l.actor);return p?(s.others.removeConnection(l.actor),{type:"leave",user:p}):null}function wn(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,Ve(u.scopes))}return{type:"reset"}}function bt(){return s.undoStack.length>0}function vt(){return s.redoStack.length>0}function Fe(l){l(()=>{h.history.notify({canUndo:bt(),canRedo:vt()})})}function Mn(l){s.others.setConnection(l.actor,l.id,l.info,Ve(l.scopes)),s.buffer.messages.push({type:100,data:s.me.current,targetActor:l.actor}),K();let p=s.others.getUser(l.actor);return p?{type:"enter",user:p}:void 0}function gt(l){return ae(l)?l:null}function Un(l){let p=ge(l);return p===void 0?null:De(p)?_e(p.map(u=>gt(u))):_e([gt(p)])}function An(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),k(u)}function Nn(l){if(typeof l.data!="string")return;let p=Un(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=Mn(_);v&&u.others.push(v);break}case 100:{let v=Pn(_);v&&u.others.push(v);break}case 103:{h.customEvent.notify({connectionId:_.actor,event:_.event});break}case 102:{let v=Rn(_);v&&u.others.push(v);break}case 300:{h.ydoc.notify(_.update);break}case 104:{u.others.push(wn(_));break}case 200:{let v=new Map(s.unacknowledgedOps);R(_,a),An(v,a),Ce==null||Ce(),Ie(),h.storageDidLoad.notify();break}case 201:{let v=me(_.ops,!1);for(let[A,L]of v.updates.storageUpdates)u.storageUpdates.set(A,Ne(u.storageUpdates.get(A),L));break}case 299:{if(ve("Storage mutation rejection error",_.reason),process.env.NODE_ENV!=="production"){let v=new Set;for(let A of _.opIds){let L=(g=s.opStackTraces)==null?void 0:g.get(A);L&&v.add(L)}throw v.size>0&&Ft("The following function calls caused the rejected storage mutations:",`
2
+
3
+ ${Array.from(v).join(`
4
+
5
+ `)}`),new Error(`Storage mutations rejected by server: ${_.reason}`)}break}}X(u,a)})}function K(){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=Dn();if(g.length===0)return;k(g),s.buffer={flushTimerID:void 0,lastFlushedAt:p,messages:[],storageOperations:[],me:null}}else clearTimeout(s.buffer.flushTimerID),s.buffer.flushTimerID=setTimeout(K,o.throttleDelay-u)}function Dn(){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}),K()}function Jn(l,p={shouldQueueEventIfNotReady:!1}){i.getStatus()!=="connected"&&!p.shouldQueueEventIfNotReady||(s.buffer.messages.push({type:103,event:l}),K())}function _t(l){s.buffer.storageOperations.push(...l),K()}let Te=null,Ce=null;function Ot(l){let p=s.buffer.messages;p.some(u=>u.type===200)||p.push({type:200}),l.flush&&K()}function Et(){return Te===null&&(Ot({flush:!0}),Te=new Promise(l=>{Ce=l}),Ie()),Te}function Kn(){let l=s.root;return l!==void 0?l:(Et(),null)}function Bn(){return N(this,null,function*(){return s.root!==void 0?Promise.resolve({root:s.root}):(yield Et(),{root:T(s.root)})})}function zn(l){s.buffer.messages.push({type:300,vector:l}),K()}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),Fe(a)});for(let u of p.ops)u.type!=="presence"&&s.buffer.storageOperations.push(u);K()}function Vn(){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),Fe(a)});for(let u of p.ops)u.type!=="presence"&&s.buffer.storageOperations.push(u);K()}function Fn(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&&_t(u.ops),X(u.updates,a),K()}}),p}function Hn(){s.pausedHistory=[]}function $n(){let l=s.pausedHistory;s.pausedHistory=null,l!==null&&l.length>0&&ce(l,d)}function He(){return s.root===void 0?Te===null?"not-loaded":"loading":s.unacknowledgedOps.size===0?"synchronized":"synchronizing"}let St=He();function Ie(){let l=He();St!==l&&(St=l,h.storageStatus.notify(l))}let Gn=new ye(s.others,l=>l.map((p,u)=>vn(`Other ${u}`,p))),Ct={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:()=>Gn.current,send:{explicitClose:l=>i._privateSendMachineEvent({type:"EXPLICIT_SOCKET_CLOSE",event:l}),implicitClose:()=>i._privateSendMachineEvent({type:"NAVIGATOR_OFFLINE"})}},id:o.roomId,subscribe:Ko(Ct),connect:()=>i.connect(),reconnect:()=>i.reconnect(),disconnect:()=>i.disconnect(),destroy:()=>i.destroy(),updatePresence:xn,updateYDoc:jn,broadcastEvent:Jn,batch:Fn,history:{undo:Wn,redo:Vn,canUndo:bt,canRedo:vt,pause:Hn,resume:$n},fetchYDoc:zn,getStorage:Bn,getStorageSnapshot:Kn,getStorageStatus:He,events:Ct,getStatus:()=>i.getStatus(),getConnectionState:()=>i.getLegacyStatus(),isSelfAware:()=>s.sessionInfo.current!==null,getSelf:()=>te.current,getPresence:()=>s.me.current,getOthers:()=>s.others.current}}function Ko(t){function o(r,i){return t.storage.subscribe(s=>{let a=s.filter(d=>ft(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"&&Bo(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 M(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 Bo(t){return t==="my-presence"||t==="others"||t==="event"||t==="error"||t==="history"||t==="status"||t==="storage-status"||t==="lost-connection"||t==="connection"}function zo(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-dual1`)}}function Wo(t,o,e,n){return N(this,null,function*(){return(n||fetch)(e,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`},body:t})})}function Vo(t,o,e){let n=e!=null?e:typeof window=="undefined"?void 0:window.fetch;if(o.type==="public")return()=>N(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 gn(n,o.url,{room:t,publicApiKey:o.publicApiKey}).then(({token:r})=>je(r))});if(o.type==="private")return()=>N(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 gn(n,o.url,{room:t}).then(({token:r})=>je(r))});if(o.type==="custom")return()=>N(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 gn(t,o,e){return N(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(!U(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 Fo=16,Ho=1e3,$o=100,Go=200,Yo=1e3,Xo=3e4,qo=5e3;function Zo(t){let o=t;return typeof o.liveblocksServer=="string"?o.liveblocksServer:"wss://api.liveblocks.io/v6"}function Qo(t){var d,c;let o=t,e=er((d=o.throttle)!=null?d:$o),n=tr((c=o.lostConnectionTimeout)!=null?c:qo),r=new Map;function i(f){let y=r.get(f);return y||null}function s(f,y){var J,m,h;let b=r.get(f);if(b!==void 0)return b;qe(y.initialPresence===null||y.initialPresence===void 0,"Please provide an initial presence value for the current user when entering the room.");let E=_n({initialPresence:(J=y.initialPresence)!=null?J:{},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:Zo(o),authentication:nr(o,f),httpSendEndpoint:or(o,f),unstable_fallbackToHTTP:!!o.unstable_fallbackToHTTP});if(r.set(f,E),jt(()=>Array.from(r.keys())),Kt(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){Bt(f);let y=r.get(f);y!==void 0&&(y.destroy(),r.delete(f))}return{getRoom:i,enter:s,leave:a}}function On(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 er(t){return On("throttle",t,Fo,Ho)}function tr(t){return On("lostConnectionTimeout",t,Go,Xo,Yo)}function nr(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:rr(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 or(t,o){return t.httpSendEndpoint?t.httpSendEndpoint.replace("{roomId}",o):`https://api.liveblocks.io/v2/rooms/${encodeURIComponent(o)}/send-message`}function rr(t,o){return t.publicAuthorizeEndpoint?t.publicAuthorizeEndpoint.replace("{roomId}",o):`https://api.liveblocks.io/v2/rooms/${encodeURIComponent(o)}/public/authorize`}function En(t){let o={};for(let e in t){let n=t[e];n!==void 0&&(o[e]=W(n))}return o}function sr(t){return En(t.toObject())}function ir(t){let o={};for(let[e,n]of t.entries())o[e]=W(n);return o}function Sn(t){return t.map(W)}function ar(t){return Sn(t.toArray())}function W(t){return t instanceof w?sr(t):t instanceof j?ar(t):t instanceof B?ir(t):t instanceof D?t.data:Array.isArray(t)?Sn(t):U(t)?En(t):t}function de(t){if(Array.isArray(t))return new j(t.map(de));if(U(t)){let o={};for(let e in t){let n=t[e];n!==void 0&&(o[e]=de(n))}return new w(o)}else return t}function dr(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)&&U(s)&&U(a)?In(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 Cn(t,o,e,n){if(process.env.NODE_ENV!=="production"){let i=ht(n);if(i){le(`New state path: '${i.path}' value: '${String(i.value)}' is not serializable.
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)?dr(r,e,n):Ae(r)&&U(e)&&U(n)?In(r,e,n):t.set(o,de(n))}}function In(t,o,e){let n={};for(let r in e)Cn(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 cr(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 lr(t,o){return o.reduce((e,n)=>pr(e,n),t)}function pr(t,o){let e=cr(o.node);return mt(t,e,o)}function mt(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]=W(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?W(c.item):f):c.type==="insert"?c.index===d.length?d.push(W(c.item)):d=[...d.slice(0,c.index),W(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),W(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),W(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]=W(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]=mt(t[n],o,e),d}else if(ae(t)){let d=t[n];return d===void 0?t:x(C({},t),{[n]:mt(d,o,e)})}else return t}function ur(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 fr(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 hr(t,o){if(Object.is(t,o))return!0;let e=Array.isArray(t),n=Array.isArray(o);return e||n?!e||!n?!1:ur(t,o):fr(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{Tn as ClientMsgCode,dt as CrdtType,j as LiveList,B as LiveMap,w as LiveObject,at as OpCode,bn as ServerMsgCode,kn as WebsocketCloseCodes,yt as asArrayWithLegacyMethods,Z as asPos,Yt as assert,M as assertNever,et as b64decode,Qo as createClient,$t as deprecate,qe as deprecateIf,io as errorIf,P as freeze,cn as isChildCrdt,De as isJsonArray,ae as isJsonObject,yn as isJsonScalar,U as isPlainObject,ct as isRootCrdt,lr as legacy_patchImmutableObject,W as lsonToJson,z as makePosition,T as nn,Cn as patchLiveObjectKey,hr as shallow,Gt as throwUsageError,ge as tryParseJson,xe as withTimeout};
7
+ //# sourceMappingURL=index.mjs.map