@steedos-widgets/liveblocks 6.10.15 → 6.10.16

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/assets.json CHANGED
@@ -3,8 +3,8 @@
3
3
  {
4
4
  "package": "@steedos-widgets/liveblocks",
5
5
  "urls": [
6
- "https://unpkg.com/@steedos-widgets/liveblocks@6.10.15/dist/liveblocks.umd.js",
7
- "https://unpkg.com/@steedos-widgets/liveblocks@6.10.15/dist/liveblocks.umd.css"
6
+ "https://unpkg.com/@steedos-widgets/liveblocks@6.10.16/dist/liveblocks.umd.js",
7
+ "https://unpkg.com/@steedos-widgets/liveblocks@6.10.16/dist/liveblocks.umd.css"
8
8
  ],
9
9
  "library": "BuilderLiveblocks"
10
10
  }
@@ -15,10 +15,10 @@
15
15
  "npm": {
16
16
  "package": "@steedos-widgets/liveblocks"
17
17
  },
18
- "url": "https://unpkg.com/@steedos-widgets/liveblocks@6.10.15/dist/meta.js",
18
+ "url": "https://unpkg.com/@steedos-widgets/liveblocks@6.10.16/dist/meta.js",
19
19
  "urls": {
20
- "default": "https://unpkg.com/@steedos-widgets/liveblocks@6.10.15/dist/meta.js",
21
- "design": "https://unpkg.com/@steedos-widgets/liveblocks@6.10.15/dist/meta.js"
20
+ "default": "https://unpkg.com/@steedos-widgets/liveblocks@6.10.16/dist/meta.js",
21
+ "design": "https://unpkg.com/@steedos-widgets/liveblocks@6.10.16/dist/meta.js"
22
22
  }
23
23
  }
24
24
  ]
@@ -1,4 +1,4 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react"),require("react-dom"),require("lodash")):"function"==typeof define&&define.amd?define(["exports","react","react-dom","lodash"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).BuilderLiveblocks={},e.React,e.ReactDOM,e._)}(this,function(exports,React,ReactDOM,_$1){const global=window;function _interopDefaultLegacy(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function _interopNamespace(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach(function(n){if("default"!==n){var o=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,o.get?o:{enumerable:!0,get:function(){return e[n]}})}}),t.default=e,Object.freeze(t)}var React__default=_interopDefaultLegacy(React),React__namespace=_interopNamespace(React),ReactDOM__namespace=_interopNamespace(ReactDOM),ReactDOM__default=_interopDefaultLegacy(ReactDOM),_$1__namespace=_interopNamespace(_$1),_$1__default=_interopDefaultLegacy(_$1),__defProp=Object.defineProperty,__export=(e,t)=>{for(var n in t)__defProp(e,n,{get:t[n],enumerable:!0})},PKG_NAME$2="@liveblocks/core",PKG_VERSION$2="2.15.1",PKG_FORMAT$2="esm",g="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0!==global?global:{},crossLinkedDocs="https://liveblocks.io/docs/errors/cross-linked",dupesDocs="https://liveblocks.io/docs/errors/dupes",SPACE$1=" ";function error(e){console.error(e)}function detectDupes(e,t,n){const o=Symbol.for(e),r=n?`${t||"dev"} (${n})`:t||"dev";if(g[o])if(g[o]===r);else{error([`Multiple copies of Liveblocks are being loaded in your project. This will cause issues! See ${dupesDocs+SPACE$1}`,"","Conflicts:",`- ${e} ${g[o]} (already loaded)`,`- ${e} ${r} (trying to load this now)`].join("\n"))}else g[o]=r;t&&PKG_VERSION$2&&t!==PKG_VERSION$2&&error([`Cross-linked versions of Liveblocks found, which will cause issues! See ${crossLinkedDocs+SPACE$1}`,"","Conflicts:",`- ${PKG_NAME$2} is at ${PKG_VERSION$2}`,`- ${e} is at ${t}`,"","Always upgrade all Liveblocks packages to the same version number."].join("\n"))}function convertToCommentData(e){const t=e.editedAt?new Date(e.editedAt):void 0,n=new Date(e.createdAt),o=e.reactions.map(e=>({...e,createdAt:new Date(e.createdAt)}));if(e.body)return{...e,reactions:o,createdAt:n,editedAt:t};{const r=new Date(e.deletedAt);return{...e,reactions:o,createdAt:n,editedAt:t,deletedAt:r}}}function convertToThreadData(e){const t=new Date(e.createdAt),n=new Date(e.updatedAt),o=e.comments.map(e=>convertToCommentData(e));return{...e,createdAt:t,updatedAt:n,comments:o}}function convertToCommentUserReaction(e){return{...e,createdAt:new Date(e.createdAt)}}function convertToInboxNotificationData(e){const t=new Date(e.notifiedAt),n=e.readAt?new Date(e.readAt):null;if("activities"in e){const o=e.activities.map(e=>({...e,createdAt:new Date(e.createdAt)}));return{...e,notifiedAt:t,readAt:n,activities:o}}return{...e,notifiedAt:t,readAt:n}}function convertToThreadDeleteInfo(e){const t=new Date(e.deletedAt);return{...e,deletedAt:t}}function convertToInboxNotificationDeleteInfo(e){const t=new Date(e.deletedAt);return{...e,deletedAt:t}}var fancy_console_exports={};__export(fancy_console_exports,{error:()=>error2,errorWithTitle:()=>errorWithTitle,warn:()=>warn$1,warnWithTitle:()=>warnWithTitle});var badge="background:#0e0d12;border-radius:9999px;color:#fff;padding:3px 7px;font-family:sans-serif;font-weight:600;",bold="font-weight:600";function wrap$1(e){return"undefined"==typeof window?console[e]:(t,...n)=>console[e]("%cLiveblocks",badge,t,...n)}var warn$1=wrap$1("warn"),error2=wrap$1("error");function wrapWithTitle(e){return"undefined"==typeof window?console[e]:(t,n,...o)=>console[e](`%cLiveblocks%c ${t}`,badge,bold,n,...o)}var warnWithTitle=wrapWithTitle("warn"),errorWithTitle=wrapWithTitle("error");function raise(e){throw new Error(e)}function isPlainObject$2(e){return null!==e&&"object"==typeof e&&"[object Object]"===Object.prototype.toString.call(e)}function entries(e){return Object.entries(e)}function tryParseJson(e){try{return JSON.parse(e)}catch(e){return}}function deepClone(e){return JSON.parse(JSON.stringify(e))}function b64decode(e){try{const t=e.replace(/-/g,"+").replace(/_/g,"/");return decodeURIComponent(atob(t).split("").map(function(e){return"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)}).join(""))}catch(t){return atob(e)}}function compact(e){return e.filter(e=>null!=e)}function compactObject(e){const t={...e};return Object.keys(e).forEach(e=>{const n=e;void 0===t[n]&&delete t[n]}),t}function wait$1(e){return new Promise(t=>setTimeout(t,e))}async function withTimeout(e,t,n){let o;const r=new Promise((e,r)=>{o=setTimeout(()=>{r(new Error(n))},t)});return Promise.race([e,r]).finally(()=>clearTimeout(o))}function memoizeOnSuccess(e){let t=null;return()=>(null===t&&(t=e().catch(e=>{throw setTimeout(()=>{t=null},5e3),e})),t)}var HttpError=class extends Error{constructor(e,t,n){super(e),this.message=e,this.status=t,this.details=n}},DONT_RETRY_4XX=e=>e instanceof HttpError&&e.status>=400&&e.status<500;async function autoRetry(e,t,n,o=DONT_RETRY_4XX){const r=n.length>0?n[n.length-1]:0;let a=0;for(;;){a++;try{return await e()}catch(e){if(o(e))throw e;if(a>=t)throw new Error(`Failed after ${t} attempts: ${String(e)}`)}const i=n[a-1]??r;warn$1(`Attempt ${a} was unsuccessful. Retrying in ${i} milliseconds.`),await wait$1(i)}}function controlledPromise(){let e,t;return[new Promise((n,o)=>{e=n,t=o}),e,t]}function Promise_withResolvers(){const[e,t,n]=controlledPromise();return{promise:e,resolve:t,reject:n}}function makeEventSource(){const e=new Set;function t(t){return e.add(t),()=>e.delete(t)}function n(e){const n=t(t=>(n(),e(t)));return n}async function o(e){let n;return new Promise(o=>{n=t(t=>{(void 0===e||e(t))&&o(t)})}).finally(()=>n?.())}return{notify:function(t){e.forEach(e=>e(t))},subscribe:t,subscribeOnce:n,count:function(){return e.size},waitUntil:o,[Symbol.dispose]:()=>{e.clear()},observable:{subscribe:t,subscribeOnce:n,waitUntil:o}}}function makeBufferableEventSource(){const e=makeEventSource();let t=null;return{...e,notify:function(n){null!==t?t.push(n):e.notify(n)},pause:function(){t=[]},unpause:function(){if(null!==t){for(const n of t)e.notify(n);t=null}},[Symbol.dispose]:()=>{e[Symbol.dispose](),null!==t&&(t.length=0)}}}function stringify(e,...t){if("object"!=typeof e||null===e||Array.isArray(e))return JSON.stringify(e,...t);const n=Object.keys(e).sort().reduce((t,n)=>(t[n]=e[n],t),{});return JSON.stringify(n,...t)}var DEFAULT_SIZE=50,BatchCall=class{input;resolve;reject;promise;constructor(e){this.input=e;const{promise:t,resolve:n,reject:o}=Promise_withResolvers();this.promise=t,this.resolve=n,this.reject=o}},Batch=class{#e=[];#t;#n;#o;#r;error=!1;constructor(e,t){this.#t=e,this.#n=t.size??DEFAULT_SIZE,this.#o=t.delay}#a(){void 0!==this.#r&&(clearTimeout(this.#r),this.#r=void 0)}#i(){this.#e.length===this.#n?this.#s():1===this.#e.length&&(this.#a(),this.#r=setTimeout(()=>{this.#s()},this.#o))}async#s(){if(0===this.#e.length)return;const e=this.#e.splice(0),t=e.map(e=>e.input);try{const n=await this.#t(t);this.error=!1,e.forEach((t,o)=>{const r=n?.[o];Array.isArray(n)?e.length!==n.length?t.reject(new Error(`Callback must return an array of the same length as the number of provided items. Expected ${e.length}, but got ${n.length}.`)):r instanceof Error?t.reject(r):t.resolve(r):t.reject(new Error("Callback must return an array."))})}catch(t){this.error=!0,e.forEach(e=>{e.reject(t)})}}get(e){const t=this.#e.find(t=>stringify(t.input)===stringify(e));if(t)return t.promise;const n=new BatchCall(e);return this.#e.push(n),this.#i(),n.promise}clear(){this.#e=[],this.error=!1,this.#a()}};function createBatchStore(e){const t=new Map,n=makeEventSource();function o(e){return stringify(e)}function r(e,o){t.set(e,o),n.notify()}return{...n.observable,get:async function(n){const a=o(n);if(!t.has(a))try{r(a,{isLoading:!0});r(a,{isLoading:!1,data:await e.get(n)})}catch(e){r(a,{isLoading:!1,error:e})}},getState:function(e){const n=o(e);return t.get(n)},invalidate:function(e){if(Array.isArray(e))for(const n of e)t.delete(o(n));else t.clear();n.notify()},getBatch:function(){return e},_cacheKeys:function(){return[...t.keys()]}}}function chunk(e,t){const n=[];for(let o=0,r=e.length;o<r;o+=t)n.push(e.slice(o,o+t));return n}var nanoid=(e=21)=>crypto.getRandomValues(new Uint8Array(e)).reduce((e,t)=>e+((t&=63)<36?t.toString(36):t<62?(t-26).toString(36).toUpperCase():t<63?"_":"-"),""),THREAD_ID_PREFIX="th",COMMENT_ID_PREFIX="cm",COMMENT_ATTACHMENT_ID_PREFIX="at";function createOptimisticId(e){return`${e}_${nanoid()}`}function createThreadId(){return createOptimisticId(THREAD_ID_PREFIX)}function createCommentId(){return createOptimisticId(COMMENT_ID_PREFIX)}function createCommentAttachmentId(){return createOptimisticId(COMMENT_ATTACHMENT_ID_PREFIX)}var identifierRegex=/^[a-zA-Z_][a-zA-Z0-9_]*$/;function objectToQuery(e){let t=[];const n=Object.entries(e),o=[],r=[],a=[];return n.forEach(([e,t])=>{if(!identifierRegex.test(e))throw new Error("Key must only contain letters, numbers, _");isSimpleValue(t)?o.push([e,t]):isValueWithOperator(t)?r.push([e,t]):"object"!=typeof t||"startsWith"in t||a.push([e,t])}),t=[...getFiltersFromKeyValuePairs(o),...getFiltersFromKeyValuePairsWithOperator(r)],a.forEach(([e,n])=>{const o=Object.entries(n),r=[],a=[];o.forEach(([t,n])=>{if(isStringEmpty(t))throw new Error("Key cannot be empty");isSimpleValue(n)?r.push([formatFilterKey(e,t),n]):isValueWithOperator(n)&&a.push([formatFilterKey(e,t),n])}),t=[...t,...getFiltersFromKeyValuePairs(r),...getFiltersFromKeyValuePairsWithOperator(a)]}),t.map(({key:e,operator:t,value:n})=>formatFilter(e,t,formatFilterValue(n))).join(" AND ")}var getFiltersFromKeyValuePairs=e=>{const t=[];return e.forEach(([e,n])=>{t.push({key:e,operator:":",value:n})}),t},getFiltersFromKeyValuePairsWithOperator=e=>{const t=[];return e.forEach(([e,n])=>{"startsWith"in n&&"string"==typeof n.startsWith&&t.push({key:e,operator:"^",value:n.startsWith})}),t},isSimpleValue=e=>"string"==typeof e||"number"==typeof e||"boolean"==typeof e,isValueWithOperator=e=>"object"==typeof e&&null!==e&&"startsWith"in e,formatFilter=(e,t,n)=>`${e}${t}${n}`,formatFilterKey=(e,t)=>t?`${e}[${JSON.stringify(t)}]`:e,formatFilterValue=e=>{if("string"==typeof e){if(isStringEmpty(e))throw new Error("Value cannot be empty");return JSON.stringify(e)}return e.toString()},isStringEmpty=e=>!e||""===e.toString().trim();function toURLSearchParams(e){const t=new URLSearchParams;for(const[n,o]of Object.entries(e))null!=o&&t.set(n,o.toString());return t}function urljoin(e,t,n){const o=new URL(t,e);return void 0!==n&&(o.search=(n instanceof URLSearchParams?n:toURLSearchParams(n)).toString()),o.toString()}function url(e,...t){return e.reduce((e,n,o)=>e+encodeURIComponent(t[o-1]??"")+n)}function createApiClient({baseUrl:e,authManager:t,fetchPolyfill:n}){const o=new HttpClient(e,n);const r=new Map;function a(e){let n=r.get(e);if(void 0===n){n=createBatchStore(new Batch(async n=>{const r=n.flat(),{urls:a}=await o.post(url`/v2/c/rooms/${e}/attachments/presigned-urls`,await t.getAuthValue({requestedScope:"comments:read",roomId:e}),{attachmentIds:r});return a.map(e=>e??new Error("There was an error while getting this attachment's URL"))},{delay:50})),r.set(e,n)}return n}const i=new Map;const s=new Batch(async e=>{const n=e.flat();return await async function(e){await o.post(url`/v2/c/inbox-notifications/read`,await t.getAuthValue({requestedScope:"comments:read"}),{inboxNotificationIds:e})}(n),n},{delay:50});return{getThreads:async function(e){let n;e.query&&(n=objectToQuery(e.query));try{const r=await o.get(url`/v2/c/rooms/${e.roomId}/threads`,await t.getAuthValue({requestedScope:"comments:read",roomId:e.roomId}),{cursor:e.cursor,query:n,limit:50});return{threads:r.data.map(convertToThreadData),inboxNotifications:r.inboxNotifications.map(convertToInboxNotificationData),nextCursor:r.meta.nextCursor,requestedAt:new Date(r.meta.requestedAt),permissionHints:r.meta.permissionHints}}catch(e){if(e instanceof HttpError&&404===e.status)return{threads:[],inboxNotifications:[],nextCursor:null,requestedAt:new Date(Date.now()-216e5),permissionHints:{}};throw e}},getThreadsSince:async function(e){const n=await o.get(url`/v2/c/rooms/${e.roomId}/threads/delta`,await t.getAuthValue({requestedScope:"comments:read",roomId:e.roomId}),{since:e.since.toISOString()},{signal:e.signal});return{threads:{updated:n.data.map(convertToThreadData),deleted:n.deletedThreads.map(convertToThreadDeleteInfo)},inboxNotifications:{updated:n.inboxNotifications.map(convertToInboxNotificationData),deleted:n.deletedInboxNotifications.map(convertToInboxNotificationDeleteInfo)},requestedAt:new Date(n.meta.requestedAt),permissionHints:n.meta.permissionHints}},createThread:async function(e){const n=e.commentId??createCommentId(),r=e.threadId??createThreadId();return convertToThreadData(await o.post(url`/v2/c/rooms/${e.roomId}/threads`,await t.getAuthValue({requestedScope:"comments:read",roomId:e.roomId}),{id:r,comment:{id:n,body:e.body,attachmentIds:e.attachmentIds},metadata:e.metadata}))},getThread:async function(e){const n=await o.rawGet(url`/v2/c/rooms/${e.roomId}/thread-with-notification/${e.threadId}`,await t.getAuthValue({requestedScope:"comments:read",roomId:e.roomId}));if(n.ok){const e=await n.json();return{thread:convertToThreadData(e.thread),inboxNotification:e.inboxNotification?convertToInboxNotificationData(e.inboxNotification):void 0}}if(404===n.status)return{thread:void 0,inboxNotification:void 0};throw new Error(`There was an error while getting thread ${e.threadId}.`)},deleteThread:async function(e){await o.delete(url`/v2/c/rooms/${e.roomId}/threads/${e.threadId}`,await t.getAuthValue({requestedScope:"comments:read",roomId:e.roomId}))},editThreadMetadata:async function(e){return await o.post(url`/v2/c/rooms/${e.roomId}/threads/${e.threadId}/metadata`,await t.getAuthValue({requestedScope:"comments:read",roomId:e.roomId}),e.metadata)},createComment:async function(e){const n=e.commentId??createCommentId();return convertToCommentData(await o.post(url`/v2/c/rooms/${e.roomId}/threads/${e.threadId}/comments`,await t.getAuthValue({requestedScope:"comments:read",roomId:e.roomId}),{id:n,body:e.body,attachmentIds:e.attachmentIds}))},editComment:async function(e){return convertToCommentData(await o.post(url`/v2/c/rooms/${e.roomId}/threads/${e.threadId}/comments/${e.commentId}`,await t.getAuthValue({requestedScope:"comments:read",roomId:e.roomId}),{body:e.body,attachmentIds:e.attachmentIds}))},deleteComment:async function(e){await o.delete(url`/v2/c/rooms/${e.roomId}/threads/${e.threadId}/comments/${e.commentId}`,await t.getAuthValue({requestedScope:"comments:read",roomId:e.roomId}))},addReaction:async function(e){return convertToCommentUserReaction(await o.post(url`/v2/c/rooms/${e.roomId}/threads/${e.threadId}/comments/${e.commentId}/reactions`,await t.getAuthValue({requestedScope:"comments:read",roomId:e.roomId}),{emoji:e.emoji}))},removeReaction:async function(e){await o.delete(url`/v2/c/rooms/${e.roomId}/threads/${e.threadId}/comments/${e.commentId}/reactions/${e.emoji}`,await t.getAuthValue({requestedScope:"comments:read",roomId:e.roomId}))},markThreadAsResolved:async function(e){await o.post(url`/v2/c/rooms/${e.roomId}/threads/${e.threadId}/mark-as-resolved`,await t.getAuthValue({requestedScope:"comments:read",roomId:e.roomId}))},markThreadAsUnresolved:async function(e){await o.post(url`/v2/c/rooms/${e.roomId}/threads/${e.threadId}/mark-as-unresolved`,await t.getAuthValue({requestedScope:"comments:read",roomId:e.roomId}))},markRoomInboxNotificationAsRead:async function(e){return function(e){let n=i.get(e);return void 0===n&&(n=new Batch(async n=>{const r=n.flat();return await o.post(url`/v2/c/rooms/${e}/inbox-notifications/read`,await t.getAuthValue({requestedScope:"comments:read",roomId:e}),{inboxNotificationIds:r}),r},{delay:50}),i.set(e,n)),n}(e.roomId).get(e.inboxNotificationId)},updateNotificationSettings:async function(e){return o.post(url`/v2/c/rooms/${e.roomId}/notification-settings`,await t.getAuthValue({requestedScope:"comments:read",roomId:e.roomId}),e.settings)},getNotificationSettings:async function(e){return o.get(url`/v2/c/rooms/${e.roomId}/notification-settings`,await t.getAuthValue({requestedScope:"comments:read",roomId:e.roomId}),void 0,{signal:e.signal})},createTextMention:async function(e){await o.rawPost(url`/v2/c/rooms/${e.roomId}/text-mentions`,await t.getAuthValue({requestedScope:"comments:read",roomId:e.roomId}),{userId:e.userId,mentionId:e.mentionId})},deleteTextMention:async function(e){await o.rawDelete(url`/v2/c/rooms/${e.roomId}/text-mentions/${e.mentionId}`,await t.getAuthValue({requestedScope:"comments:read",roomId:e.roomId}))},getTextVersion:async function(e){return o.rawGet(url`/v2/c/rooms/${e.roomId}/y-version/${e.versionId}`,await t.getAuthValue({requestedScope:"comments:read",roomId:e.roomId}))},createTextVersion:async function(e){await o.rawPost(url`/v2/c/rooms/${e.roomId}/version`,await t.getAuthValue({requestedScope:"comments:read",roomId:e.roomId}))},reportTextEditor:async function(e){await o.rawPost(url`/v2/c/rooms/${e.roomId}/text-metadata`,await t.getAuthValue({requestedScope:"comments:read",roomId:e.roomId}),{type:e.type,rootKey:e.rootKey})},listTextVersions:async function(e){const n=await o.get(url`/v2/c/rooms/${e.roomId}/versions`,await t.getAuthValue({requestedScope:"comments:read",roomId:e.roomId}));return{versions:n.versions.map(({createdAt:e,...t})=>({createdAt:new Date(e),...t})),requestedAt:new Date(n.meta.requestedAt)}},listTextVersionsSince:async function(e){const n=await o.get(url`/v2/c/rooms/${e.roomId}/versions/delta`,await t.getAuthValue({requestedScope:"comments:read",roomId:e.roomId}),{since:e.since.toISOString()},{signal:e.signal});return{versions:n.versions.map(({createdAt:e,...t})=>({createdAt:new Date(e),...t})),requestedAt:new Date(n.meta.requestedAt)}},getAttachmentUrl:function(e){return a(e.roomId).getBatch().get(e.attachmentId)},uploadAttachment:async function(e){const n=e.roomId,r=e.signal,a=e.attachment,i=r?new DOMException(`Upload of attachment ${e.attachment.id} was aborted.`,"AbortError"):void 0;if(r?.aborted)throw i;const s=e=>{if(r?.aborted)throw i;if(e instanceof HttpError&&413===e.status)throw e;return!1},l=5242880,c=[2e3,2e3,2e3,2e3,2e3,2e3,2e3,2e3,2e3,2e3];if(a.size<=l)return autoRetry(async()=>o.putBlob(url`/v2/c/rooms/${n}/attachments/${a.id}/upload/${encodeURIComponent(a.name)}`,await t.getAuthValue({requestedScope:"comments:read",roomId:n}),a.file,{fileSize:a.size},{signal:r}),10,c,s);{let e;const d=[],u=await autoRetry(async()=>o.post(url`/v2/c/rooms/${n}/attachments/${a.id}/multipart/${encodeURIComponent(a.name)}`,await t.getAuthValue({requestedScope:"comments:read",roomId:n}),void 0,{signal:r},{fileSize:a.size}),10,c,s);try{e=u.uploadId;const f=function(e){const t=[];let n=0;for(;n<e.size;){const o=Math.min(n+l,e.size);t.push({partNumber:t.length+1,part:e.slice(n,o)}),n=o}return t}(a.file);if(r?.aborted)throw i;const p=chunk(f,5);for(const e of p){const i=[];for(const{part:l,partNumber:d}of e)i.push(autoRetry(async()=>o.putBlob(url`/v2/c/rooms/${n}/attachments/${a.id}/multipart/${u.uploadId}/${String(d)}`,await t.getAuthValue({requestedScope:"comments:read",roomId:n}),l,void 0,{signal:r}),10,c,s));d.push(...await Promise.all(i))}if(r?.aborted)throw i;const _=d.sort((e,t)=>e.partNumber-t.partNumber);return o.post(url`/v2/c/rooms/${n}/attachments/${a.id}/multipart/${e}/complete`,await t.getAuthValue({requestedScope:"comments:read",roomId:n}),{parts:_},{signal:r})}catch(r){if(e&&r?.name&&("AbortError"===r.name||"TimeoutError"===r.name))try{await o.rawDelete(url`/v2/c/rooms/${n}/attachments/${a.id}/multipart/${e}`,await t.getAuthValue({requestedScope:"comments:read",roomId:n}))}catch(e){}throw r}}},getOrCreateAttachmentUrlsStore:a,streamStorage:async function(e){const n=await o.rawGet(url`/v2/c/rooms/${e.roomId}/storage`,await t.getAuthValue({requestedScope:"room:read",roomId:e.roomId}));return await n.json()},sendMessages:async function(e){return o.rawPost(url`/v2/c/rooms/${e.roomId}/send-message`,await t.getAuthValue({requestedScope:"room:read",roomId:e.roomId}),{nonce:e.nonce,messages:e.messages})},getInboxNotifications:async function(e){const n=await o.get(url`/v2/c/inbox-notifications`,await t.getAuthValue({requestedScope:"comments:read"}),{cursor:e?.cursor,limit:50});return{inboxNotifications:n.inboxNotifications.map(convertToInboxNotificationData),threads:n.threads.map(convertToThreadData),nextCursor:n.meta.nextCursor,requestedAt:new Date(n.meta.requestedAt)}},getInboxNotificationsSince:async function(e){const n=await o.get(url`/v2/c/inbox-notifications/delta`,await t.getAuthValue({requestedScope:"comments:read"}),{since:e.since.toISOString()},{signal:e.signal});return{inboxNotifications:{updated:n.inboxNotifications.map(convertToInboxNotificationData),deleted:n.deletedInboxNotifications.map(convertToInboxNotificationDeleteInfo)},threads:{updated:n.threads.map(convertToThreadData),deleted:n.deletedThreads.map(convertToThreadDeleteInfo)},requestedAt:new Date(n.meta.requestedAt)}},getUnreadInboxNotificationsCount:async function(){const{count:e}=await o.get(url`/v2/c/inbox-notifications/count`,await t.getAuthValue({requestedScope:"comments:read"}));return e},markAllInboxNotificationsAsRead:async function(){await o.post(url`/v2/c/inbox-notifications/read`,await t.getAuthValue({requestedScope:"comments:read"}),{inboxNotificationIds:"all"})},markInboxNotificationAsRead:async function(e){await s.get(e)},deleteAllInboxNotifications:async function(){await o.delete(url`/v2/c/inbox-notifications`,await t.getAuthValue({requestedScope:"comments:read"}))},deleteInboxNotification:async function(e){await o.delete(url`/v2/c/inbox-notifications/${e}`,await t.getAuthValue({requestedScope:"comments:read"}))},getUserThreads_experimental:async function(e){let n;e?.query&&(n=objectToQuery(e.query));const r=await o.get(url`/v2/c/threads`,await t.getAuthValue({requestedScope:"comments:read"}),{cursor:e?.cursor,query:n,limit:50});return{threads:r.threads.map(convertToThreadData),inboxNotifications:r.inboxNotifications.map(convertToInboxNotificationData),nextCursor:r.meta.nextCursor,requestedAt:new Date(r.meta.requestedAt),permissionHints:r.meta.permissionHints}},getUserThreadsSince_experimental:async function(e){const n=await o.get(url`/v2/c/threads/delta`,await t.getAuthValue({requestedScope:"comments:read"}),{since:e.since.toISOString()},{signal:e.signal});return{threads:{updated:n.threads.map(convertToThreadData),deleted:n.deletedThreads.map(convertToThreadDeleteInfo)},inboxNotifications:{updated:n.inboxNotifications.map(convertToInboxNotificationData),deleted:n.deletedInboxNotifications.map(convertToInboxNotificationDeleteInfo)},requestedAt:new Date(n.meta.requestedAt),permissionHints:n.meta.permissionHints}}}}function getBearerTokenFromAuthValue(e){return"public"===e.type?e.publicApiKey:e.token.raw}var HttpClient=class{#l;#c;constructor(e,t){this.#l=e,this.#c=t}async#d(e,t,n,o){e.startsWith("/v2/c/")||raise("This client can only be used to make /v2/c/* requests");const r=urljoin(this.#l,e,o);return await this.#c(r,{...n,headers:{"Content-Type":"application/json; charset=utf-8",...n?.headers,Authorization:`Bearer ${getBearerTokenFromAuthValue(t)}`,"X-LB-Client":PKG_VERSION$2}})}async#u(e,t,n,o){const r=await this.#d(e,t,n,o);if(!r.ok){let e;try{const t=await r.json();e=new HttpError(t.message,r.status,t)}catch{e=new HttpError(r.statusText,r.status)}throw e}let a;try{a=await r.json()}catch{a={}}return a}async rawGet(e,t,n,o){return await this.#d(e,t,o,n)}async rawPost(e,t,n){return await this.#d(e,t,{method:"POST",body:JSON.stringify(n)})}async rawDelete(e,t){return await this.#d(e,t,{method:"DELETE"})}async get(e,t,n,o){return await this.#u(e,t,o,n)}async post(e,t,n,o,r){return await this.#u(e,t,{...o,method:"POST",body:JSON.stringify(n)},r)}async delete(e,t){return await this.#u(e,t,{method:"DELETE"})}async putBlob(e,t,n,o,r){return await this.#u(e,t,{...r,method:"PUT",headers:{"Content-Type":"application/octet-stream"},body:n},o)}};function assertNever(e,t){throw new Error(t)}function assert(e,t){}function nn(e,t="Expected value to be non-nullable"){return e}function distance(e,t){if(e===t)return[0,0];const n=e.split("."),o=t.split("."),r=Math.min(n.length,o.length);let a=0;for(;a<r&&n[a]===o[a];a++);return[n.length-a,o.length-a]}function patterns(e,t){const n=e.split(".");if(t<1||t>n.length+1)throw new Error("Invalid number of levels");const o=[];t>n.length&&o.push("*");for(let e=n.length-t+1;e<n.length;e++){const t=n.slice(0,e);t.length>0&&o.push(t.join(".")+".*")}return o.push(e),o}var SafeContext=class{#f;constructor(e){this.#f=e}get current(){return this.#f}allowPatching(e){const t=this;let n=!0;e({...this.#f,patch(e){if(!n)throw new Error("Can no longer patch stale context");t.#f=Object.assign({},t.#f,e);for(const t of Object.entries(e)){const[e,n]=t;"patch"!==e&&(this[e]=n)}}}),n=!1}},nextId=1,FSM=class{id;#p;#_;#m;#h;#g;#b;events;#v;#y;#E;get#w(){const e=this.#m.values()[Symbol.iterator]().next();if(e.done)throw new Error("No states defined yet");return e.value}get currentState(){if(null===this.#h)throw 0===this.#p?new Error("Not started yet"):new Error("Already stopped");return this.#h}start(){if(0!==this.#p)throw new Error("State machine has already started");return this.#p=1,this.#h=this.#w,this.#C(null),this}stop(){if(1!==this.#p)throw new Error("Cannot stop a state machine that hasn't started yet");this.#x(null),this.#p=2,this.#h=null}constructor(e){this.id=nextId++,this.#p=0,this.#h=null,this.#m=new Set,this.#y=new Map,this.#v=[],this.#E=new Set,this.#g=new Map,this.#_=new SafeContext(e),this.#b={didReceiveEvent:makeEventSource(),willTransition:makeEventSource(),didIgnoreEvent:makeEventSource(),willExitState:makeEventSource(),didEnterState:makeEventSource()},this.events={didReceiveEvent:this.#b.didReceiveEvent.observable,willTransition:this.#b.willTransition.observable,didIgnoreEvent:this.#b.didIgnoreEvent.observable,willExitState:this.#b.willExitState.observable,didEnterState:this.#b.didEnterState.observable}}get context(){return this.#_.current}addState(e){if(0!==this.#p)throw new Error("Already started");return this.#m.add(e),this}onEnter(e,t){if(0!==this.#p)throw new Error("Already started");if(this.#y.has(e))throw new Error(`enter/exit function for ${e} already exists`);return this.#y.set(e,t),this}onEnterAsync(e,t,n,o,r){return this.onEnter(e,()=>{const e=new AbortController,a=e.signal,i=r?setTimeout(()=>{const e=new Error("Timed out");this.#R({type:"ASYNC_ERROR",reason:e},o)},r):void 0;let s=!1;return t(this.#_.current,a).then(e=>{a.aborted||(s=!0,this.#R({type:"ASYNC_OK",data:e},n))},e=>{a.aborted||(s=!0,this.#R({type:"ASYNC_ERROR",reason:e},o))}),()=>{clearTimeout(i),s||e.abort()}})}#S(e){const t=[];if("*"===e)for(const e of this.#m)t.push(e);else if(e.endsWith(".*")){const n=e.slice(0,-1);for(const e of this.#m)e.startsWith(n)&&t.push(e)}else{const n=e;this.#m.has(n)&&t.push(n)}if(0===t.length)throw new Error(`No states match ${JSON.stringify(e)}`);return t}addTransitions(e,t){if(0!==this.#p)throw new Error("Already started");for(const n of this.#S(e)){let o=this.#g.get(n);void 0===o&&(o=new Map,this.#g.set(n,o));for(const[r,a]of Object.entries(t)){if(o.has(r))throw new Error(`Trying to set transition "${r}" on "${n}" (via "${e}"), but a transition already exists there.`);const t=a;if(this.#E.add(r),void 0!==t){const e="function"==typeof t?t:()=>t;o.set(r,e)}}}return this}addTimedTransition(e,t,n){return this.onEnter(e,()=>{const e="function"==typeof t?t(this.#_.current):t,o=setTimeout(()=>{this.#R({type:"TIMER"},n)},e);return()=>{clearTimeout(o)}})}#D(e){return this.#g.get(this.currentState)?.get(e)}#x(e){this.#b.willExitState.notify(this.currentState),this.#_.allowPatching(t=>{e=e??this.#v.length;for(let n=0;n<e;n++)this.#v.pop()?.(t)})}#C(e){const t=patterns(this.currentState,e??this.currentState.split(".").length+1);this.#_.allowPatching(e=>{for(const n of t){const t=this.#y.get(n),o=t?.(e);"function"==typeof o?this.#v.push(o):this.#v.push(null)}}),this.#b.didEnterState.notify(this.currentState)}send(e){if(!this.#E.has(e.type))throw new Error(`Invalid event ${JSON.stringify(e.type)}`);if(2===this.#p)return;const t=this.#D(e.type);if(void 0!==t)return this.#R(e,t);this.#b.didIgnoreEvent.notify(e)}#R(e,t){this.#b.didReceiveEvent.notify(e);const n=this.currentState,o=("function"==typeof t?t:()=>t)(e,this.#_.current);let r,a;if(null===o)return void this.#b.didIgnoreEvent.notify(e);if("string"==typeof o?r=o:(r=o.target,a=Array.isArray(o.effect)?o.effect:[o.effect]),!this.#m.has(r))throw new Error(`Invalid next state name: ${JSON.stringify(r)}`);this.#b.willTransition.notify({from:n,to:r});const[i,s]=distance(this.currentState,r);if(i>0&&this.#x(i),this.#h=r,void 0!==a){const t=a;this.#_.allowPatching(n=>{for(const o of t)"function"==typeof o?o(n,e):n.patch(o)})}s>0&&this.#C(s)}},ServerMsgCode=(e=>(e[e.UPDATE_PRESENCE=100]="UPDATE_PRESENCE",e[e.USER_JOINED=101]="USER_JOINED",e[e.USER_LEFT=102]="USER_LEFT",e[e.BROADCASTED_EVENT=103]="BROADCASTED_EVENT",e[e.ROOM_STATE=104]="ROOM_STATE",e[e.INITIAL_STORAGE_STATE=200]="INITIAL_STORAGE_STATE",e[e.UPDATE_STORAGE=201]="UPDATE_STORAGE",e[e.REJECT_STORAGE_OP=299]="REJECT_STORAGE_OP",e[e.UPDATE_YDOC=300]="UPDATE_YDOC",e[e.THREAD_CREATED=400]="THREAD_CREATED",e[e.THREAD_DELETED=407]="THREAD_DELETED",e[e.THREAD_METADATA_UPDATED=401]="THREAD_METADATA_UPDATED",e[e.THREAD_UPDATED=408]="THREAD_UPDATED",e[e.COMMENT_CREATED=402]="COMMENT_CREATED",e[e.COMMENT_EDITED=403]="COMMENT_EDITED",e[e.COMMENT_DELETED=404]="COMMENT_DELETED",e[e.COMMENT_REACTION_ADDED=405]="COMMENT_REACTION_ADDED",e[e.COMMENT_REACTION_REMOVED=406]="COMMENT_REACTION_REMOVED",e))(ServerMsgCode||{});function shouldDisconnect(e){return 4999===e||e>=4e3&&e<4100}function shouldReauth(e){return e>=4100&&e<4200}function shouldRetryWithoutReauth(e){return 1013===e||e>=4200&&e<4300}function isIdle(e){return"initial"===e||"disconnected"===e}function toNewConnectionStatus(e){const t=e.currentState;switch(t){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":case"@idle.zombie":return e.context.successCount>0?"reconnecting":"connecting";case"@idle.failed":return"disconnected";default:return assertNever(t,"Unknown state")}}var BACKOFF_DELAYS=[250,500,1e3,2e3,4e3,8e3,1e4],RESET_DELAY=BACKOFF_DELAYS[0]-1,BACKOFF_DELAYS_SLOW=[2e3,3e4,6e4,3e5],HEARTBEAT_INTERVAL=3e4,PONG_TIMEOUT=2e3,AUTH_TIMEOUT=1e4,SOCKET_CONNECT_TIMEOUT=1e4,StopRetrying=class extends Error{constructor(e){super(e)}},LiveblocksError=class extends Error{constructor(e,t){super(e),this.code=t}};function nextBackoffDelay(e,t){return t.find(t=>t>e)??t[t.length-1]}function increaseBackoffDelay(e){e.patch({backoffDelay:nextBackoffDelay(e.backoffDelay,BACKOFF_DELAYS)})}function increaseBackoffDelayAggressively(e){e.patch({backoffDelay:nextBackoffDelay(e.backoffDelay,BACKOFF_DELAYS_SLOW)})}function resetSuccessCount(e){e.patch({successCount:0})}function log(e,t){const n=2===e?error2:1===e?warn$1:()=>{};return()=>{n(t)}}function logPrematureErrorOrCloseEvent(e){const t="Connection to Liveblocks websocket server";return n=>{e instanceof Error?warn$1(`${t} could not be established. ${String(e)}`):warn$1(isCloseEvent(e)?`${t} closed prematurely (code: ${e.code}). Retrying in ${n.backoffDelay}ms.`:`${t} could not be established.`)}}function logCloseEvent(e){const t=[`code: ${e.code}`];return e.reason&&t.push(`reason: ${e.reason}`),e=>{warn$1(`Connection to Liveblocks websocket server closed (${t.join(", ")}). Retrying in ${e.backoffDelay}ms.`)}}var logPermanentClose=log(1,"Connection to WebSocket closed permanently. Won't retry.");function isCloseEvent(e){return!(e instanceof Error)&&"close"===e.type}function enableTracing(e){const t=(new Date).getTime();function n(...n){warn$1(`${(((new Date).getTime()-t)/1e3).toFixed(2)} [FSM #${e.id}]`,...n)}const o=[e.events.didReceiveEvent.subscribe(e=>n(`Event ${e.type}`)),e.events.willTransition.subscribe(({from:e,to:t})=>n("Transitioning",e,"→",t)),e.events.didIgnoreEvent.subscribe(e=>n("Ignored event",e.type,e,"(current state won't handle it)"))];return()=>{for(const e of o)e()}}function defineConnectivityEvents(e){const t=makeEventSource(),n=makeEventSource(),o=makeEventSource();let r=null;const a=e.events.didEnterState.subscribe(()=>{const a=toNewConnectionStatus(e);a!==r&&t.notify(a),"connected"===r&&"connected"!==a?o.notify():"connected"!==r&&"connected"===a&&n.notify(),r=a});return{statusDidChange:t.observable,didConnect:n.observable,didDisconnect:o.observable,unsubscribe:a}}var assign=e=>t=>t.patch(e);function createConnectionStateMachine(e,t){const n=makeBufferableEventSource();n.pause();const o=makeEventSource();function r(e,t){return()=>{const n=new LiveblocksError(e,t);o.notify(n)}}const a=new FSM({successCount:0,authValue:null,socket:null,backoffDelay:RESET_DELAY}).addState("@idle.initial").addState("@idle.failed").addState("@idle.zombie").addState("@auth.busy").addState("@auth.backoff").addState("@connecting.busy").addState("@connecting.backoff").addState("@ok.connected").addState("@ok.awaiting-pong");a.addTransitions("*",{RECONNECT:{target:"@auth.backoff",effect:[increaseBackoffDelay,resetSuccessCount]},DISCONNECT:"@idle.initial"}),a.onEnter("@idle.*",resetSuccessCount).addTransitions("@idle.*",{CONNECT:(e,t)=>null!==t.authValue?"@connecting.busy":"@auth.busy"}),a.addTransitions("@auth.backoff",{NAVIGATOR_ONLINE:{target:"@auth.busy",effect:assign({backoffDelay:RESET_DELAY})}}).addTimedTransition("@auth.backoff",e=>e.backoffDelay,"@auth.busy").onEnterAsync("@auth.busy",()=>withTimeout(e.authenticate(),AUTH_TIMEOUT,"Timed out during auth"),e=>({target:"@connecting.busy",effect:assign({authValue:e.data})}),e=>e.reason instanceof StopRetrying?{target:"@idle.failed",effect:[log(2,e.reason.message),r(e.reason.message,-1)]}:{target:"@auth.backoff",effect:[increaseBackoffDelay,log(2,`Authentication failed: ${e.reason instanceof Error?e.reason.message:String(e.reason)}`)]});const i=e=>a.send({type:"EXPLICIT_SOCKET_ERROR",event:e}),s=e=>a.send({type:"EXPLICIT_SOCKET_CLOSE",event:e}),l=e=>"pong"===e.data?a.send({type:"PONG"}):n.notify(e);function c(e){e&&(e.removeEventListener("error",i),e.removeEventListener("close",s),e.removeEventListener("message",l),e.close())}a.addTransitions("@connecting.backoff",{NAVIGATOR_ONLINE:{target:"@connecting.busy",effect:assign({backoffDelay:RESET_DELAY})}}).addTimedTransition("@connecting.backoff",e=>e.backoffDelay,"@connecting.busy").onEnterAsync("@connecting.busy",async(n,o)=>{let r=null,a=null;return withTimeout(new Promise((o,c)=>{if(null===n.authValue)throw new Error("No auth authValue");const d=e.createSocket(n.authValue);function u(e){r=e,d.removeEventListener("message",l),c(e)}a=d;const[f,p]=controlledPromise();function _(e){const t=tryParseJson(e.data);104===t?.type&&p()}t.waitForActorId||p(),d.addEventListener("message",l),t.waitForActorId&&d.addEventListener("message",_),d.addEventListener("error",u),d.addEventListener("close",u),d.addEventListener("open",()=>{d.addEventListener("error",i),d.addEventListener("close",s);const e=()=>{d.removeEventListener("error",u),d.removeEventListener("close",u),d.removeEventListener("message",_)};f.then(()=>{o([d,e])})})}),SOCKET_CONNECT_TIMEOUT,"Timed out during websocket connection").then(([e,t])=>{if(t(),o.aborted)throw new Error("Aborted");if(r)throw r;return e}).catch(e=>{throw c(a),e})},e=>({target:"@ok.connected",effect:assign({socket:e.data,backoffDelay:RESET_DELAY})}),e=>{const t=e.reason;if(t instanceof StopRetrying)return{target:"@idle.failed",effect:[log(2,t.message),r(t.message,-1)]};if(isCloseEvent(t)){if(4109===t.code)return"@auth.busy";if(shouldRetryWithoutReauth(t.code))return{target:"@connecting.backoff",effect:[increaseBackoffDelayAggressively,logPrematureErrorOrCloseEvent(t)]};if(shouldDisconnect(t.code))return{target:"@idle.failed",effect:[log(2,t.reason),r(t.reason,t.code)]}}return{target:"@auth.backoff",effect:[increaseBackoffDelay,logPrematureErrorOrCloseEvent(t)]}});const d={target:"@ok.awaiting-pong",effect:e=>{e.socket?.send("ping")}},u=()=>{const t="undefined"!=typeof document?document:void 0;return"hidden"===t?.visibilityState&&e.canZombie()?"@idle.zombie":d};if(a.addTimedTransition("@ok.connected",HEARTBEAT_INTERVAL,u).addTransitions("@ok.connected",{NAVIGATOR_OFFLINE:u,WINDOW_GOT_FOCUS:d}),a.addTransitions("@idle.zombie",{WINDOW_GOT_FOCUS:"@connecting.backoff"}),a.onEnter("@ok.*",e=>{e.patch({successCount:e.successCount+1});const t=setTimeout(n.unpause,0);return e=>{c(e.socket),e.patch({socket:null}),clearTimeout(t),n.pause()}}).addTransitions("@ok.awaiting-pong",{PONG:"@ok.connected"}).addTimedTransition("@ok.awaiting-pong",PONG_TIMEOUT,{target:"@connecting.busy",effect:log(1,"Received no pong from server, assume implicit connection loss.")}).addTransitions("@ok.*",{EXPLICIT_SOCKET_ERROR:(e,t)=>1===t.socket?.readyState?null:{target:"@connecting.backoff",effect:increaseBackoffDelay},EXPLICIT_SOCKET_CLOSE:e=>shouldDisconnect(e.event.code)?{target:"@idle.failed",effect:[logPermanentClose,r(e.event.reason,e.event.code)]}:shouldReauth(e.event.code)?4109===e.event.code?"@auth.busy":{target:"@auth.backoff",effect:[increaseBackoffDelay,logCloseEvent(e.event)]}:shouldRetryWithoutReauth(e.event.code)?{target:"@connecting.backoff",effect:[increaseBackoffDelayAggressively,logCloseEvent(e.event)]}:{target:"@connecting.backoff",effect:[increaseBackoffDelay,logCloseEvent(e.event)]}}),"undefined"!=typeof document){const e="undefined"!=typeof document?document:void 0,t="undefined"!=typeof window?window:void 0,n=t??e;a.onEnter("*",o=>{function r(){a.send({type:"NAVIGATOR_OFFLINE"})}function i(){a.send({type:"NAVIGATOR_ONLINE"})}function s(){"visible"===e?.visibilityState&&a.send({type:"WINDOW_GOT_FOCUS"})}return t?.addEventListener("online",i),t?.addEventListener("offline",r),n?.addEventListener("visibilitychange",s),()=>{n?.removeEventListener("visibilitychange",s),t?.removeEventListener("online",i),t?.removeEventListener("offline",r),c(o.socket)}})}const f=[],{statusDidChange:p,didConnect:_,didDisconnect:m,unsubscribe:h}=defineConnectivityEvents(a);return f.push(h),t.enableDebugLogging&&f.push(enableTracing(a)),a.start(),{machine:a,cleanups:f,events:{statusDidChange:p,didConnect:_,didDisconnect:m,onMessage:n.observable,onLiveblocksError:o.observable}}}var ManagedSocket=class{#T;#A;events;constructor(e,t=!1,n=!0){const{machine:o,events:r,cleanups:a}=createConnectionStateMachine(e,{waitForActorId:n,enableDebugLogging:t});this.#T=o,this.events=r,this.#A=a}getStatus(){try{return toNewConnectionStatus(this.#T)}catch{return"initial"}}get authValue(){return this.#T.context.authValue}connect(){this.#T.send({type:"CONNECT"})}reconnect(){this.#T.send({type:"RECONNECT"})}disconnect(){this.#T.send({type:"DISCONNECT"})}destroy(){let e;for(this.#T.stop();e=this.#A.pop();)e()}send(e){const t=this.#T.context?.socket;null===t?warn$1("Cannot send: not connected yet",e):1!==t.readyState?warn$1("Cannot send: WebSocket no longer open",e):t.send(e)}_privateSendMachineEvent(e){this.#T.send(e)}},Permission=(e=>(e.Read="room:read",e.Write="room:write",e.PresenceWrite="room:presence:write",e.CommentsWrite="comments:write",e.CommentsRead="comments:read",e))(Permission||{});function canWriteStorage(e){return e.includes("room:write")}function canComment(e){return e.includes("comments:write")||e.includes("room:write")}function isValidAuthTokenPayload(e){return isPlainObject$2(e)&&("acc"===e.k||"id"===e.k||"sec-legacy"===e.k)}function parseAuthToken(e){const t=e.split(".");if(3!==t.length)throw new Error("Authentication error: invalid JWT token");const n=tryParseJson(b64decode(t[1]));if(!n||!isValidAuthTokenPayload(n))throw new Error("Authentication error: expected a valid 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:e,parsed:n}}function createAuthManager(e,t){const n=prepareAuthentication(e),o=new Set,r=[],a=[],i=new Map;function s(e,t){return"comments:read"===e?t.includes("comments:read")||t.includes("comments:write")||t.includes("room:read")||t.includes("room:write"):"room:read"===e&&(t.includes("room:read")||t.includes("room:write"))}async function l(r){const a=e.polyfills?.fetch??("undefined"==typeof window?void 0:window.fetch);if("private"===n.type){if(void 0===a)throw new StopRetrying("To use Liveblocks client in a non-DOM environment with a url as auth endpoint, you need to provide a fetch polyfill.");const e=parseAuthToken((await fetchAuthEndpoint(a,n.url,{room:r.roomId})).token);if(o.has(e.raw))throw new StopRetrying("The same Liveblocks auth token was issued from the backend before. Caching Liveblocks tokens is not supported.");return t?.(e.parsed),e}if("custom"===n.type){const e=await n.callback(r.roomId);if(e&&"object"==typeof e){if("string"==typeof e.token){const n=parseAuthToken(e.token);return t?.(n.parsed),n}if("string"==typeof e.error){const t=`Authentication failed: ${"reason"in e&&"string"==typeof e.reason?e.reason:"Forbidden"}`;throw"forbidden"===e.error?new StopRetrying(t):new Error(t)}}throw new Error('Your authentication callback function should return a token, but it did not. Hint: the return value should look like: { token: "..." }')}throw new Error("Unexpected authentication type. Must be private or custom.")}return{reset:function(){o.clear(),r.length=0,a.length=0,i.clear()},getAuthValue:async function(e){if("public"===n.type)return{type:"public",publicApiKey:n.publicApiKey};const t=function(e){const t=Math.ceil(Date.now()/1e3);for(let n=r.length-1;n>=0;n--){const o=r[n];if(a[n]<=t)r.splice(n,1),a.splice(n,1);else{if("id"===o.parsed.k)return o;if("acc"===o.parsed.k){if(!e.roomId&&0===Object.entries(o.parsed.perms).length)return o;for(const[t,n]of Object.entries(o.parsed.perms))if(e.roomId){if(t.includes("*")&&e.roomId.startsWith(t.replace("*",""))||e.roomId===t&&s(e.requestedScope,n))return o}else if(t.includes("*")&&s(e.requestedScope,n))return o}}}}(e);if(void 0!==t)return{type:"secret",token:t};let c;e.roomId?(c=i.get(e.roomId),void 0===c&&(c=l(e),i.set(e.roomId,c))):(c=i.get("liveblocks-user-token"),void 0===c&&(c=l(e),i.set("liveblocks-user-token",c)));try{const e=await c,t=30,n=Math.floor(Date.now()/1e3)+(e.parsed.exp-e.parsed.iat)-t;return o.add(e.raw),"sec-legacy"!==e.parsed.k&&(r.push(e),a.push(n)),{type:"secret",token:e}}finally{e.roomId?i.delete(e.roomId):i.delete("liveblocks-user-token")}}}}function prepareAuthentication(e){const{publicApiKey:t,authEndpoint:n}=e;if(void 0!==n&&void 0!==t)throw new Error("You cannot simultaneously use `publicApiKey` and `authEndpoint` options. Please pick one and leave the other option unspecified. For more information: https://liveblocks.io/docs/api-reference/liveblocks-client#createClient");if("string"==typeof t){if(t.startsWith("sk_"))throw new Error("Invalid `publicApiKey` option. The value you passed is a secret key, which should not be used from the client. Please only ever pass a public key here. For more information: https://liveblocks.io/docs/api-reference/liveblocks-client#createClientPublicKey");if(!t.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:t}}if("string"==typeof n)return{type:"private",url:n};if("function"==typeof n)return{type:"custom",callback:n};if(void 0!==n)throw new Error("The `authEndpoint` option must be a string or a function. For more information: https://liveblocks.io/docs/api-reference/liveblocks-client#createClientAuthEndpoint");throw new Error("Invalid Liveblocks client options. Please provide either a `publicApiKey` or `authEndpoint` option. They cannot both be empty. For more information: https://liveblocks.io/docs/api-reference/liveblocks-client#createClient")}async function fetchAuthEndpoint(e,t,n){const o=await e(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!o.ok){const e=`${(await o.text()).trim()||"reason not provided in auth response"} (${o.status} returned by POST ${t})`;throw 401===o.status||403===o.status?new StopRetrying(`Unauthorized: ${e}`):new Error(`Failed to authenticate: ${e}`)}let r;try{r=await o.json()}catch(e){throw new Error(`Expected a JSON response when doing a POST request on "${t}". ${String(e)}`)}if(!isPlainObject$2(r)||"string"!=typeof r.token)throw new Error(`Expected a JSON response of the form \`{ token: "..." }\` when doing a POST request on "${t}", but got ${JSON.stringify(r)}`);const{token:a}=r;return{token:a}}var DEFAULT_BASE_URL="https://api.liveblocks.io",kInternal=Symbol(),eventSource=makeEventSource();function unlinkDevTools(e){}eventSource.observable;var freeze$2=e=>e,kSinks=Symbol("kSinks"),kTrigger=Symbol("kTrigger"),signalsToTrigger=null;function batch(e){if(null===signalsToTrigger){signalsToTrigger=new Set;try{e()}finally{for(const e of signalsToTrigger)e[kTrigger]();signalsToTrigger=null}}else e()}function enqueueTrigger(e){signalsToTrigger||raise("Expected to be in an active batch"),signalsToTrigger.add(e)}function merge(e,t){let n=!1;const o={...e};return Object.keys(t).forEach(e=>{const r=e,a=t[r];o[r]!==a&&(void 0===a?delete o[r]:o[r]=a,n=!0)}),n?o:e}var AbstractSignal=class{equals;#O;[kSinks];constructor(e){this.equals=e??Object.is,this.#O=makeEventSource(),this[kSinks]=new Set,this.get=this.get.bind(this),this.subscribe=this.subscribe.bind(this),this.subscribeOnce=this.subscribeOnce.bind(this)}[Symbol.dispose](){this.#O[Symbol.dispose](),this.#O="(disposed)",this.equals="(disposed)"}get hasWatchers(){if(this.#O.count()>0)return!0;for(const e of this[kSinks])if(e.hasWatchers)return!0;return!1}[kTrigger](){this.#O.notify();for(const e of this[kSinks])enqueueTrigger(e)}subscribe(e){return this.#O.subscribe(e)}subscribeOnce(e){const t=this.subscribe(()=>(t(),e()));return t}waitUntil(){throw new Error("waitUntil not supported on Signals")}markSinksDirty(){for(const e of this[kSinks])e.markDirty()}addSink(e){this[kSinks].add(e)}removeSink(e){this[kSinks].delete(e)}asReadonly(){return this}},Signal=class extends AbstractSignal{#I;constructor(e,t){super(t),this.#I=freeze$2(e)}[Symbol.dispose](){super[Symbol.dispose](),this.#I="(disposed)"}get(){return this.#I}set(e){batch(()=>{"function"==typeof e&&(e=e(this.#I)),this.equals(this.#I,e)||(this.#I=freeze$2(e),this.markSinksDirty(),enqueueTrigger(this))})}},PatchableSignal=class extends Signal{constructor(e){super(freeze$2(compactObject(e)))}set(){throw new Error("Don't call .set() directly, use .patch()")}patch(e){super.set(t=>merge(t,e))}},INITIAL=Symbol(),DerivedSignal=class e extends AbstractSignal{#k;#N;#j;#$;static from(...t){const n=t.pop();if("function"!=typeof n&&raise("Invalid .from() call, last argument expected to be a function"),"function"==typeof t[t.length-1]){const o=n,r=t.pop();return new e(t,r,o)}return new e(t,n)}constructor(e,t,n){super(n),this.#N=!0,this.#k=INITIAL,this.#j=e,this.#$=t;for(const t of e)t.addSink(this)}[Symbol.dispose](){for(const e of this.#j)e.removeSink(this);this.#k="(disposed)",this.#j="(disposed)",this.#$="(disposed)"}get isDirty(){return this.#N}#F(){const e=this.#$(...this.#j.map(e=>e.get()));return this.#N=!1,!this.equals(this.#k,e)&&(this.#k=e,!0)}markDirty(){this.#N||(this.#N=!0,this.markSinksDirty())}get(){return this.#N&&this.#F(),this.#k}[kTrigger](){if(!this.hasWatchers)return;this.#F()&&super[kTrigger]()}},MutableSignal=class extends AbstractSignal{#P;constructor(e){super(),this.#P=e}[Symbol.dispose](){super[Symbol.dispose](),this.#P="(disposed)"}get(){return this.#P}mutate(e){batch(()=>{const t=!e||e(this.#P);null!==t&&"object"==typeof t&&"then"in t&&raise("MutableSignal.mutate() does not support async callbacks"),!1!==t&&(this.markSinksDirty(),enqueueTrigger(this))})}},MIN_CODE=32,MAX_CODE=126,NUM_DIGITS=MAX_CODE-MIN_CODE+1,ZERO=nthDigit(0),ONE=nthDigit(1),ZERO_NINE=ZERO+nthDigit(-1);function nthDigit(e){const t=MIN_CODE+(e<0?NUM_DIGITS+e:e);if(t<MIN_CODE||t>MAX_CODE)throw new Error(`Invalid n value: ${e}`);return String.fromCharCode(t)}function makePosition(e,t){return void 0!==e&&void 0!==t?between(e,t):void 0!==e?after$1(e):void 0!==t?before$1(t):ONE}function before$1(e){const t=e.length-1;for(let n=0;n<=t;n++){const o=e.charCodeAt(n);if(!(o<=MIN_CODE))return n===t?o===MIN_CODE+1?e.substring(0,n)+ZERO_NINE:e.substring(0,n)+String.fromCharCode(o-1):e.substring(0,n+1)}return ONE}function after$1(e){for(let t=0;t<=e.length-1;t++){const n=e.charCodeAt(t);if(!(n>=MAX_CODE))return e.substring(0,t)+String.fromCharCode(n+1)}return e+ONE}function between(e,t){if(e<t)return _between(e,t);if(e>t)return _between(t,e);throw new Error("Cannot compute value between two equal positions")}function _between(e,t){let n=0;const o=e.length,r=t.length;for(;;){const a=n<o?e.charCodeAt(n):MIN_CODE,i=n<r?t.charCodeAt(n):MAX_CODE;if(a!==i){if(i-a===1){const t=n+1;let o=e.substring(0,t);o.length<t&&(o+=ZERO.repeat(t-o.length));return o+_between(e.substring(t),"")}return takeN(e,n)+String.fromCharCode(i+a>>1)}n++}}function takeN(e,t){return t<e.length?e.substring(0,t):e+ZERO.repeat(t-e.length)}var MIN_NON_ZERO_CODE=MIN_CODE+1;function isPos(e){if(""===e)return!1;const t=e.length-1,n=e.charCodeAt(t);if(n<MIN_NON_ZERO_CODE||n>MAX_CODE)return!1;for(let n=0;n<t;n++){const t=e.charCodeAt(n);if(t<MIN_CODE||t>MAX_CODE)return!1}return!0}function convertToPos(e){const t=[];for(let n=0;n<e.length;n++){const o=e.charCodeAt(n);t.push(o<MIN_CODE?MIN_CODE:o>MAX_CODE?MAX_CODE:o)}for(;t.length>0&&t[t.length-1]===MIN_CODE;)t.length--;return t.length>0?String.fromCharCode(...t):ONE}function asPos(e){return isPos(e)?e:convertToPos(e)}function isAckOp(e){return 5===e.type&&"ACK"===e.id}function crdtAsLiveNode(e){return e}function HasParent(e,t,n=asPos(t)){return Object.freeze({type:"HasParent",node:e,key:t,pos:n})}var NoParent=Object.freeze({type:"NoParent"});function Orphaned(e,t=asPos(e)){return Object.freeze({type:"Orphaned",oldKey:e,oldPos:t})}var AbstractCrdt=class{#M;#B;#L=NoParent;_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 assertNever(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 assertNever(this.parent,"Unknown state")}}get _pool(){return this.#M}get roomId(){return this.#M?this.#M.roomId:null}get _id(){return this.#B}get parent(){return this.#L}get _parentKey(){switch(this.parent.type){case"HasParent":return this.parent.key;case"NoParent":return null;case"Orphaned":return this.parent.oldKey;default:return assertNever(this.parent,"Unknown state")}}_apply(e,t){return 5===e.type&&"HasParent"===this.parent.type?this.parent.node._detachChild(crdtAsLiveNode(this)):{modified:!1}}_setParentLink(e,t){switch(this.parent.type){case"HasParent":if(this.parent.node!==e)throw new Error("Cannot set parent: node already has a parent");return void(this.#L=HasParent(e,t));case"Orphaned":case"NoParent":return void(this.#L=HasParent(e,t));default:return assertNever(this.parent,"Unknown state")}}_attach(e,t){if(this.#B||this.#M)throw new Error("Cannot attach node: already attached");t.addNode(e,crdtAsLiveNode(this)),this.#B=e,this.#M=t}_detach(){switch(this.#M&&this.#B&&this.#M.deleteNode(this.#B),this.parent.type){case"HasParent":this.#L=Orphaned(this.parent.key,this.parent.pos);break;case"NoParent":this.#L=NoParent;break;case"Orphaned":break;default:assertNever(this.parent,"Unknown state")}this.#M=void 0}#U;#V;#H;invalidate(){void 0===this.#U&&void 0===this.#H||(this.#U=void 0,this.#H=void 0,"HasParent"===this.parent.type&&this.parent.node.invalidate())}toTreeNode(e){return void 0!==this.#H&&this.#V===e||(this.#V=e,this.#H=this._toTreeNode(e)),this.#H}toImmutable(){return void 0===this.#U&&(this.#U=this._toImmutable()),this.#U}};function isRootCrdt(e){return 0===e.type&&!isChildCrdt(e)}function isChildCrdt(e){return void 0!==e.parentId&&void 0!==e.parentKey}var LiveRegister=class e extends AbstractCrdt{#z;constructor(e){super(),this.#z=e}get data(){return this.#z}static _deserialize([t,n],o,r){const a=new e(n.data);return a._attach(t,r),a}_toOps(e,t,n){if(void 0===this._id)throw new Error("Cannot serialize register if parentId or parentKey is undefined");return[{type:8,opId:n?.generateOpId(),id:this._id,parentId:e,parentKey:t,data:this.data}]}_serialize(){if("HasParent"!==this.parent.type)throw new Error("Cannot serialize LiveRegister if parent is missing");return{type:3,parentId:nn(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,t){return super._apply(e,t)}_toTreeNode(e){return{type:"Json",id:this._id??nanoid(),key:e,payload:this.#z}}_toImmutable(){return this.#z}clone(){return deepClone(this.data)}};function compareNodePosition(e,t){const n=e._parentPos,o=t._parentPos;return n===o?0:n<o?-1:1}var LiveList=class e extends AbstractCrdt{#q;#K;#W;constructor(e){let t;super(),this.#q=[],this.#K=new WeakSet,this.#W=new Map;for(const n of e){const e=makePosition(t),o=lsonToLiveNode(n);o._setParentLink(this,e),this.#q.push(o),t=e}}static _deserialize([t],n,o){const r=new e([]);r._attach(t,o);const a=n.get(t);if(void 0===a)return r;for(const[e,t]of a){const a=deserialize$1([e,t],n,o);a._setParentLink(r,t.parentKey),r._insertAndSort(a)}return r}_toOps(e,t,n){if(void 0===this._id)throw new Error("Cannot serialize item is not attached");const o=[],r={id:this._id,opId:n?.generateOpId(),type:2,parentId:e,parentKey:t};o.push(r);for(const e of this.#q){const t=e._getParentKeyOrThrow(),r=HACK_addIntentAndDeletedIdToOperation(e._toOps(this._id,t,n),void 0),a=r[0].opId;void 0!==a&&this.#W.set(t,a),o.push(...r)}return o}_insertAndSort(e){this.#q.push(e),this._sortItems()}_sortItems(){this.#q.sort(compareNodePosition),this.invalidate()}_indexOfPosition(e){return this.#q.findIndex(t=>t._getParentKeyOrThrow()===e)}_attach(e,t){super._attach(e,t);for(const e of this.#q)e._attach(t.generateId(),t)}_detach(){super._detach();for(const e of this.#q)e._detach()}#G(e){if(void 0===this._pool)throw new Error("Can't attach child if managed pool is not present");const{id:t,parentKey:n}=e,o=creationOpToLiveNode(e);o._attach(t,this._pool),o._setParentLink(this,n);const r=e.deletedId,a=this._indexOfPosition(n);if(-1!==a){const t=this.#q[a];if(t._id===r)return t._detach(),this.#q[a]=o,{modified:makeUpdate(this,[setDelta(a,o)]),reverse:[]};{this.#K.add(t),this.#q[a]=o;const n=[setDelta(a,o)],r=this.#Y(e.deletedId);return r&&n.push(r),{modified:makeUpdate(this,n),reverse:[]}}}{const t=[],r=this.#Y(e.deletedId);return r&&t.push(r),this._insertAndSort(o),t.push(insertDelta(this._indexOfPosition(n),o)),{reverse:[],modified:makeUpdate(this,t)}}}#J(e){if(void 0===this._pool)throw new Error("Can't attach child if managed pool is not present");const t=[],n=this.#Y(e.deletedId);n&&t.push(n);const o=this.#W.get(e.parentKey);if(void 0!==o){if(o!==e.opId)return 0===t.length?{modified:!1}:{modified:makeUpdate(this,t),reverse:[]};this.#W.delete(e.parentKey)}const r=this._indexOfPosition(e.parentKey),a=this.#q.find(t=>t._id===e.id);if(void 0!==a){if(a._parentKey===e.parentKey)return{modified:t.length>0&&makeUpdate(this,t),reverse:[]};if(-1!==r){this.#K.add(this.#q[r]);const[e]=this.#q.splice(r,1);t.push(deleteDelta(r,e))}const n=this.#q.indexOf(a);a._setParentLink(this,e.parentKey),this._sortItems();const o=this.#q.indexOf(a);return o!==n&&t.push(moveDelta(n,o,a)),{modified:t.length>0&&makeUpdate(this,t),reverse:[]}}{const n=this._pool.getNode(e.id);if(n&&this.#K.has(n)){n._setParentLink(this,e.parentKey),this.#K.delete(n),this._insertAndSort(n);const o=this.#q.indexOf(n);return{modified:makeUpdate(this,[-1===r?insertDelta(o,n):setDelta(o,n),...t]),reverse:[]}}{-1!==r&&this.#q.splice(r,1);const{newItem:n,newIndex:o}=this.#X(e,e.parentKey);return{modified:makeUpdate(this,[-1===r?insertDelta(o,n):setDelta(o,n),...t]),reverse:[]}}}}#Y(e){if(void 0===e||void 0===this._pool)return null;const t=this._pool.getNode(e);if(void 0===t)return null;const n=this._detachChild(t);return!1===n.modified?null:n.modified.updates[0]}#Z(e){if(void 0===this._pool)throw new Error("Can't attach child if managed pool is not present");const t=asPos(e.parentKey),n=this._indexOfPosition(t);-1!==n&&this.#Q(n,t);const{newItem:o,newIndex:r}=this.#X(e,t);return{modified:makeUpdate(this,[insertDelta(r,o)]),reverse:[]}}#ee(e){const t=this.#q.find(t=>t._id===e.id),n=asPos(e.parentKey),o=this._indexOfPosition(n);if(t){if(t._parentKey===n)return{modified:!1};{const e=this.#q.indexOf(t);-1!==o&&this.#Q(o,n),t._setParentLink(this,n),this._sortItems();const r=this._indexOfPosition(n);return r===e?{modified:!1}:{modified:makeUpdate(this,[moveDelta(e,r,t)]),reverse:[]}}}{const t=nn(this._pool).getNode(e.id);if(t&&this.#K.has(t)){t._setParentLink(this,n),this.#K.delete(t),this._insertAndSort(t);return{modified:makeUpdate(this,[insertDelta(this._indexOfPosition(n),t)]),reverse:[]}}{-1!==o&&this.#Q(o,n);const{newItem:t,newIndex:r}=this.#X(e,n);return{modified:makeUpdate(this,[insertDelta(r,t)]),reverse:[]}}}}#te(e){const{id:t,parentKey:n}=e,o=creationOpToLiveNode(e);if(void 0!==this._pool?.getNode(t))return{modified:!1};o._attach(t,nn(this._pool)),o._setParentLink(this,n);const r=this._indexOfPosition(n);let a=n;if(-1!==r){const e=this.#q[r]?._parentPos,t=this.#q[r+1]?._parentPos;a=makePosition(e,t),o._setParentLink(this,a)}this._insertAndSort(o);return{modified:makeUpdate(this,[insertDelta(this._indexOfPosition(a),o)]),reverse:[{type:5,id:t}]}}#ne(e){const{id:t,parentKey:n}=e,o=creationOpToLiveNode(e);if(void 0!==this._pool?.getNode(t))return{modified:!1};this.#W.set(n,nn(e.opId));const r=this._indexOfPosition(n);o._attach(t,nn(this._pool)),o._setParentLink(this,n);const a=n;if(-1!==r){const t=this.#q[r];t._detach(),this.#q[r]=o;const a=HACK_addIntentAndDeletedIdToOperation(t._toOps(nn(this._id),n,this._pool),e.id),i=[setDelta(r,o)],s=this.#Y(e.deletedId);return s&&i.push(s),{modified:makeUpdate(this,i),reverse:a}}this._insertAndSort(o),this.#Y(e.deletedId);return{reverse:[{type:5,id:t}],modified:makeUpdate(this,[insertDelta(this._indexOfPosition(a),o)])}}_attachChild(e,t){if(void 0===this._pool)throw new Error("Can't attach child if managed pool is not present");let n;return n="set"===e.intent?1===t?this.#G(e):2===t?this.#J(e):this.#ne(e):1===t?this.#Z(e):2===t?this.#ee(e):this.#te(e),!1!==n.modified&&this.invalidate(),n}_detachChild(e){if(e){const t=nn(e._parentKey),n=e._toOps(nn(this._id),t,this._pool),o=this.#q.indexOf(e);if(-1===o)return{modified:!1};const[r]=this.#q.splice(o,1);return this.invalidate(),e._detach(),{modified:makeUpdate(this,[deleteDelta(o,r)]),reverse:n}}return{modified:!1}}#oe(e,t){if(this.#K.has(t)){this.#K.delete(t),t._setParentLink(this,e),this._insertAndSort(t);return{modified:makeUpdate(this,[insertDelta(this.#q.indexOf(t),t)]),reverse:[]}}if(e===t._parentKey)return{modified:!1};const n=this._indexOfPosition(e);if(-1===n){const n=this.#q.indexOf(t);t._setParentLink(this,e),this._sortItems();const o=this.#q.indexOf(t);return o===n?{modified:!1}:{modified:makeUpdate(this,[moveDelta(n,o,t)]),reverse:[]}}{this.#q[n]._setParentLink(this,makePosition(e,this.#q[n+1]?._parentPos));const o=this.#q.indexOf(t);t._setParentLink(this,e),this._sortItems();const r=this.#q.indexOf(t);return r===o?{modified:!1}:{modified:makeUpdate(this,[moveDelta(o,r,t)]),reverse:[]}}}#re(e,t){const n=nn(t._parentKey);if(this.#K.has(t)){const n=this._indexOfPosition(e);return this.#K.delete(t),-1!==n&&this.#q[n]._setParentLink(this,makePosition(e,this.#q[n+1]?._parentPos)),t._setParentLink(this,e),this._insertAndSort(t),{modified:!1}}{if(e===n)return{modified:!1};const o=this.#q.indexOf(t),r=this._indexOfPosition(e);-1!==r&&this.#q[r]._setParentLink(this,makePosition(e,this.#q[r+1]?._parentPos)),t._setParentLink(this,e),this._sortItems();const a=this.#q.indexOf(t);return o===a?{modified:!1}:{modified:makeUpdate(this,[moveDelta(o,a,t)]),reverse:[]}}}#ae(e,t){const n=nn(t._parentKey),o=this.#q.indexOf(t),r=this._indexOfPosition(e);-1!==r&&this.#q[r]._setParentLink(this,makePosition(e,this.#q[r+1]?._parentPos)),t._setParentLink(this,e),this._sortItems();const a=this.#q.indexOf(t);return o===a?{modified:!1}:{modified:makeUpdate(this,[moveDelta(o,a,t)]),reverse:[{type:1,id:nn(t._id),parentKey:n}]}}_setChildKey(e,t,n){return 1===n?this.#oe(e,t):2===n?this.#re(e,t):this.#ae(e,t)}_apply(e,t){return super._apply(e,t)}_serialize(){if("HasParent"!==this.parent.type)throw new Error("Cannot serialize LiveList if parent is missing");return{type:1,parentId:nn(this.parent.node._id,"Parent node expected to have ID"),parentKey:this.parent.key}}get length(){return this.#q.length}push(e){return this._pool?.assertStorageIsWritable(),this.insert(e,this.length)}insert(e,t){if(this._pool?.assertStorageIsWritable(),t<0||t>this.#q.length)throw new Error(`Cannot insert list item at index "${t}". index should be between 0 and ${this.#q.length}`);const n=makePosition(this.#q[t-1]?this.#q[t-1]._parentPos:void 0,this.#q[t]?this.#q[t]._parentPos:void 0),o=lsonToLiveNode(e);if(o._setParentLink(this,n),this._insertAndSort(o),this._pool&&this._id){const e=this._pool.generateId();o._attach(e,this._pool),this._pool.dispatch(o._toOps(this._id,n,this._pool),[{type:5,id:e}],new Map([[this._id,makeUpdate(this,[insertDelta(t,o)])]]))}}move(e,t){if(this._pool?.assertStorageIsWritable(),t<0)throw new Error("targetIndex cannot be less than 0");if(t>=this.#q.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.#q.length)throw new Error("index cannot be greater or equal than the list length");let n=null,o=null;e<t?(o=t===this.#q.length-1?void 0:this.#q[t+1]._parentPos,n=this.#q[t]._parentPos):(o=this.#q[t]._parentPos,n=0===t?void 0:this.#q[t-1]._parentPos);const r=makePosition(n,o),a=this.#q[e],i=a._getParentKeyOrThrow();if(a._setParentLink(this,r),this._sortItems(),this._pool&&this._id){const n=new Map([[this._id,makeUpdate(this,[moveDelta(e,t,a)])]]);this._pool.dispatch([{type:1,id:nn(a._id),opId:this._pool.generateOpId(),parentKey:r}],[{type:1,id:nn(a._id),parentKey:i}],n)}}delete(e){if(this._pool?.assertStorageIsWritable(),e<0||e>=this.#q.length)throw new Error(`Cannot delete list item at index "${e}". index should be between 0 and ${this.#q.length-1}`);const t=this.#q[e];t._detach();const[n]=this.#q.splice(e,1);if(this.invalidate(),this._pool){const o=t._id;if(o){const r=new Map;r.set(nn(this._id),makeUpdate(this,[deleteDelta(e,n)])),this._pool.dispatch([{id:o,opId:this._pool.generateOpId(),type:5}],t._toOps(nn(this._id),t._getParentKeyOrThrow()),r)}}}clear(){if(this._pool?.assertStorageIsWritable(),this._pool){const e=[],t=[],n=[];for(const o of this.#q){o._detach();const r=o._id;r&&(e.push({type:5,id:r,opId:this._pool.generateOpId()}),t.push(...o._toOps(nn(this._id),o._getParentKeyOrThrow())),n.push(deleteDelta(0,o)))}this.#q=[],this.invalidate();const o=new Map;o.set(nn(this._id),makeUpdate(this,n)),this._pool.dispatch(e,t,o)}else{for(const e of this.#q)e._detach();this.#q=[],this.invalidate()}}set(e,t){if(this._pool?.assertStorageIsWritable(),e<0||e>=this.#q.length)throw new Error(`Cannot set list item at index "${e}". index should be between 0 and ${this.#q.length-1}`);const n=this.#q[e],o=n._getParentKeyOrThrow(),r=n._id;n._detach();const a=lsonToLiveNode(t);if(a._setParentLink(this,o),this.#q[e]=a,this.invalidate(),this._pool&&this._id){const t=this._pool.generateId();a._attach(t,this._pool);const i=new Map;i.set(this._id,makeUpdate(this,[setDelta(e,a)]));const s=HACK_addIntentAndDeletedIdToOperation(a._toOps(this._id,o,this._pool),r);this.#W.set(o,nn(s[0].opId));const l=HACK_addIntentAndDeletedIdToOperation(n._toOps(this._id,o,void 0),t);this._pool.dispatch(s,l,i)}}toArray(){return this.#q.map(e=>liveNodeToLson(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.#q.length))return liveNodeToLson(this.#q[e])}indexOf(e,t){return this.toArray().indexOf(e,t)}lastIndexOf(e,t){return this.toArray().lastIndexOf(e,t)}map(e){return this.#q.map((t,n)=>e(liveNodeToLson(t),n))}some(e){return this.toArray().some(e)}[Symbol.iterator](){return new LiveListIterator(this.#q)}#X(e,t){const n=creationOpToLiveNode(e);n._attach(e.id,nn(this._pool)),n._setParentLink(this,t),this._insertAndSort(n);return{newItem:n,newIndex:this._indexOfPosition(t)}}#Q(e,t){const n=makePosition(t,this.#q.length>e+1?this.#q[e+1]?._parentPos:void 0);this.#q[e]._setParentLink(this,n)}_toTreeNode(e){return{type:"LiveList",id:this._id??nanoid(),key:e,payload:this.#q.map((e,t)=>e.toTreeNode(t.toString()))}}toImmutable(){return super.toImmutable()}_toImmutable(){const e=this.#q.map(e=>e.toImmutable());return e}clone(){return new e(this.#q.map(e=>e.clone()))}},LiveListIterator=class{#ie;constructor(e){this.#ie=e[Symbol.iterator]()}[Symbol.iterator](){return this}next(){const e=this.#ie.next();if(e.done)return{done:!0,value:void 0};return{value:liveNodeToLson(e.value)}}};function makeUpdate(e,t){return{node:e,type:"LiveList",updates:t}}function setDelta(e,t){return{index:e,type:"set",item:t instanceof LiveRegister?t.data:t}}function deleteDelta(e,t){return{type:"delete",index:e,deletedItem:t instanceof LiveRegister?t.data:t}}function insertDelta(e,t){return{index:e,type:"insert",item:t instanceof LiveRegister?t.data:t}}function moveDelta(e,t,n){return{type:"move",index:t,item:n instanceof LiveRegister?n.data:n,previousIndex:e}}function HACK_addIntentAndDeletedIdToOperation(e,t){return e.map((e,n)=>{if(0===n){return{...e,intent:"set",deletedId:t}}return e})}var LiveMap=class e extends AbstractCrdt{#se;#le;constructor(e){if(super(),this.#le=new Map,e){const t=[];for(const[n,o]of e){const e=lsonToLiveNode(o);e._setParentLink(this,n),t.push([n,e])}this.#se=new Map(t)}else this.#se=new Map}_toOps(e,t,n){if(void 0===this._id)throw new Error("Cannot serialize item is not attached");const o=[],r={id:this._id,opId:n?.generateOpId(),type:7,parentId:e,parentKey:t};o.push(r);for(const[e,t]of this.#se)o.push(...t._toOps(this._id,e,n));return o}static _deserialize([t,n],o,r){const a=new e;a._attach(t,r);const i=o.get(t);if(void 0===i)return a;for(const[e,t]of i){const n=deserialize$1([e,t],o,r);n._setParentLink(a,t.parentKey),a.#se.set(t.parentKey,n),a.invalidate()}return a}_attach(e,t){super._attach(e,t);for(const[e,n]of this.#se)isLiveNode(n)&&n._attach(t.generateId(),t)}_attachChild(e,t){if(void 0===this._pool)throw new Error("Can't attach child if managed pool is not present");const{id:n,parentKey:o,opId:r}=e,a=o,i=creationOpToLiveNode(e);if(void 0!==this._pool.getNode(n))return{modified:!1};if(2===t){const e=this.#le.get(a);if(e===r)return this.#le.delete(a),{modified:!1};if(void 0!==e)return{modified:!1}}else 1===t&&this.#le.delete(a);const s=this.#se.get(a);let l;if(s){const e=nn(this._id);l=s._toOps(e,a),s._detach()}else l=[{type:5,id:n}];return i._setParentLink(this,a),i._attach(n,this._pool),this.#se.set(a,i),this.invalidate(),{modified:{node:this,type:"LiveMap",updates:{[a]:{type:"update"}}},reverse:l}}_detach(){super._detach();for(const e of this.#se.values())e._detach()}_detachChild(e){const t=nn(this._id),n=nn(e._parentKey),o=e._toOps(t,n,this._pool);for(const[t,n]of this.#se)n===e&&(this.#se.delete(t),this.invalidate());e._detach();return{modified:{node:this,type:"LiveMap",updates:{[n]:{type:"delete"}}},reverse:o}}_serialize(){if("HasParent"!==this.parent.type)throw new Error("Cannot serialize LiveMap if parent is missing");return{type:2,parentId:nn(this.parent.node._id,"Parent node expected to have ID"),parentKey:this.parent.key}}get(e){const t=this.#se.get(e);if(void 0!==t)return liveNodeToLson(t)}set(e,t){this._pool?.assertStorageIsWritable();const n=this.#se.get(e);n&&n._detach();const o=lsonToLiveNode(t);if(o._setParentLink(this,e),this.#se.set(e,o),this.invalidate(),this._pool&&this._id){const t=this._pool.generateId();o._attach(t,this._pool);const r=new Map;r.set(this._id,{node:this,type:"LiveMap",updates:{[e]:{type:"update"}}});const a=o._toOps(this._id,e,this._pool);this.#le.set(e,nn(a[0].opId)),this._pool.dispatch(o._toOps(this._id,e,this._pool),n?n._toOps(this._id,e):[{type:5,id:t}],r)}}get size(){return this.#se.size}has(e){return this.#se.has(e)}delete(e){this._pool?.assertStorageIsWritable();const t=this.#se.get(e);if(void 0===t)return!1;if(t._detach(),this.#se.delete(e),this.invalidate(),this._pool&&t._id){const n=nn(this._id),o=new Map;o.set(n,{node:this,type:"LiveMap",updates:{[e]:{type:"delete"}}}),this._pool.dispatch([{type:5,id:t._id,opId:this._pool.generateOpId()}],t._toOps(n,e),o)}return!0}entries(){const e=this.#se.entries();return{[Symbol.iterator](){return this},next(){const t=e.next();if(t.done)return{done:!0,value:void 0};return{value:[t.value[0],liveNodeToLson(t.value[1])]}}}}[Symbol.iterator](){return this.entries()}keys(){return this.#se.keys()}values(){const e=this.#se.values();return{[Symbol.iterator](){return this},next(){const t=e.next();if(t.done)return{done:!0,value:void 0};return{value:liveNodeToLson(t.value)}}}}forEach(e){for(const t of this)e(t[1],t[0],this)}_toTreeNode(e){return{type:"LiveMap",id:this._id??nanoid(),key:e,payload:Array.from(this.#se.entries()).map(([e,t])=>t.toTreeNode(e))}}toImmutable(){return super.toImmutable()}_toImmutable(){const e=new Map;for(const[t,n]of this.#se)e.set(t,n.toImmutable());return freeze$2(e)}clone(){return new e(Array.from(this.#se).map(([e,t])=>[e,t.clone()]))}},LiveObject=class e extends AbstractCrdt{#se;#ce;static#de(e){const t=new Map;let n=null;for(const[o,r]of e)if(isRootCrdt(r))n=[o,r];else{const e=[o,r],n=t.get(r.parentId);void 0!==n?n.push(e):t.set(r.parentId,[e])}if(null===n)throw new Error("Root can't be null");return[n,t]}static _fromItems(t,n){const[o,r]=e.#de(t);return e._deserialize(o,r,n)}constructor(e={}){super(),this.#ce=new Map;const t=compactObject(e);for(const e of Object.keys(t)){const n=t[e];isLiveNode(n)&&n._setParentLink(this,e)}this.#se=new Map(Object.entries(t))}_toOps(e,t,n){if(void 0===this._id)throw new Error("Cannot serialize item is not attached");const o=n?.generateOpId(),r=[],a={type:4,id:this._id,opId:o,parentId:e,parentKey:t,data:{}};r.push(a);for(const[e,t]of this.#se)isLiveNode(t)?r.push(...t._toOps(this._id,e,n)):a.data[e]=t;return r}static _deserialize([t,n],o,r){const a=new e(n.data);return a._attach(t,r),this._deserializeChildren(a,o,r)}static _deserializeChildren(e,t,n){const o=t.get(nn(e._id));if(void 0===o)return e;for(const[r,a]of o){const o=deserializeToLson([r,a],t,n);isLiveStructure(o)&&o._setParentLink(e,a.parentKey),e.#se.set(a.parentKey,o),e.invalidate()}return e}_attach(e,t){super._attach(e,t);for(const[e,n]of this.#se)isLiveNode(n)&&n._attach(t.generateId(),t)}_attachChild(e,t){if(void 0===this._pool)throw new Error("Can't attach child if managed pool is not present");const{id:n,opId:o,parentKey:r}=e,a=creationOpToLson(e);if(void 0!==this._pool.getNode(n))return this.#ce.get(r)===o&&this.#ce.delete(r),{modified:!1};if(0===t)this.#ce.set(r,nn(o));else if(void 0!==this.#ce.get(r))return this.#ce.get(r)===o?(this.#ce.delete(r),{modified:!1}):{modified:!1};const i=nn(this._id),s=this.#se.get(r);let l;return isLiveNode(s)?(l=s._toOps(i,r),s._detach()):l=void 0===s?[{type:6,id:i,key:r}]:[{type:3,id:i,data:{[r]:s}}],this.#se.set(r,a),this.invalidate(),isLiveStructure(a)&&(a._setParentLink(this,r),a._attach(n,this._pool)),{reverse:l,modified:{node:this,type:"LiveObject",updates:{[r]:{type:"update"}}}}}_detachChild(e){if(e){const t=nn(this._id),n=nn(e._parentKey),o=e._toOps(t,n,this._pool);for(const[t,n]of this.#se)n===e&&(this.#se.delete(t),this.invalidate());e._detach();return{modified:{node:this,type:"LiveObject",updates:{[n]:{type:"delete"}}},reverse:o}}return{modified:!1}}_detach(){super._detach();for(const e of this.#se.values())isLiveNode(e)&&e._detach()}_apply(e,t){return 3===e.type?this.#ue(e,t):6===e.type?this.#fe(e,t):super._apply(e,t)}_serialize(){const e={};for(const[t,n]of this.#se)isLiveNode(n)||(e[t]=n);return"HasParent"===this.parent.type&&this.parent.node._id?{type:0,parentId:this.parent.node._id,parentKey:this.parent.key,data:e}:{type:0,data:e}}#ue(e,t){let n=!1;const o=nn(this._id),r=[],a={type:3,id:o,data:{}};for(const t in e.data){const e=this.#se.get(t);isLiveNode(e)?(r.push(...e._toOps(o,t)),e._detach()):void 0!==e?a.data[t]=e:void 0===e&&r.push({type:6,id:o,key:t})}const i={};for(const o in e.data){const r=e.data[o];if(void 0===r)continue;if(t)this.#ce.set(o,nn(e.opId));else{if(void 0!==this.#ce.get(o)){if(this.#ce.get(o)===e.opId){this.#ce.delete(o);continue}continue}n=!0}const a=this.#se.get(o);isLiveNode(a)&&a._detach(),n=!0,i[o]={type:"update"},this.#se.set(o,r),this.invalidate()}return 0!==Object.keys(a.data).length&&r.unshift(a),n?{modified:{node:this,type:"LiveObject",updates:i},reverse:r}:{modified:!1}}#fe(e,t){const n=e.key;if(!1===this.#se.has(n))return{modified:!1};if(!t&&void 0!==this.#ce.get(n))return{modified:!1};const o=this.#se.get(n),r=nn(this._id);let a=[];return isLiveNode(o)?(a=o._toOps(r,e.key),o._detach()):void 0!==o&&(a=[{type:3,id:r,data:{[n]:o}}]),this.#se.delete(n),this.invalidate(),{modified:{node:this,type:"LiveObject",updates:{[e.key]:{type:"delete"}}},reverse:a}}toObject(){return Object.fromEntries(this.#se)}set(e,t){this._pool?.assertStorageIsWritable(),this.update({[e]:t})}get(e){return this.#se.get(e)}delete(e){this._pool?.assertStorageIsWritable();const t=e,n=this.#se.get(t);if(void 0===n)return;if(void 0===this._pool||void 0===this._id)return isLiveNode(n)&&n._detach(),this.#se.delete(t),void this.invalidate();let o;isLiveNode(n)?(n._detach(),o=n._toOps(this._id,t)):o=[{type:3,data:{[t]:n},id:this._id}],this.#se.delete(t),this.invalidate();const r=new Map;r.set(this._id,{node:this,type:"LiveObject",updates:{[e]:{type:"delete"}}}),this._pool.dispatch([{type:6,key:t,id:this._id,opId:this._pool.generateOpId()}],o,r)}update(e){if(this._pool?.assertStorageIsWritable(),void 0===this._pool||void 0===this._id){for(const t in e){const n=e[t];if(void 0===n)continue;const o=this.#se.get(t);isLiveNode(o)&&o._detach(),isLiveNode(n)&&n._setParentLink(this,t),this.#se.set(t,n),this.invalidate()}return}const t=[],n=[],o=this._pool.generateOpId(),r={},a={id:this._id,type:3,data:{}},i={};for(const s in e){const l=e[s];if(void 0===l)continue;const c=this.#se.get(s);if(isLiveNode(c)?(n.push(...c._toOps(this._id,s)),c._detach()):void 0===c?n.push({type:6,id:this._id,key:s}):a.data[s]=c,isLiveNode(l)){l._setParentLink(this,s),l._attach(this._pool.generateId(),this._pool);const e=l._toOps(this._id,s,this._pool),n=e.find(e=>e.parentId===this._id);n&&this.#ce.set(s,nn(n.opId)),t.push(...e)}else r[s]=l,this.#ce.set(s,o);this.#se.set(s,l),this.invalidate(),i[s]={type:"update"}}0!==Object.keys(a.data).length&&n.unshift(a),0!==Object.keys(r).length&&t.unshift({opId:o,id:this._id,type:3,data:r});const s=new Map;s.set(this._id,{node:this,type:"LiveObject",updates:i}),this._pool.dispatch(t,n,s)}toImmutable(){return super.toImmutable()}toTreeNode(e){return super.toTreeNode(e)}_toTreeNode(e){const t=this._id??nanoid();return{type:"LiveObject",id:t,key:e,payload:Array.from(this.#se.entries()).map(([e,n])=>isLiveNode(n)?n.toTreeNode(e):{type:"Json",id:`${t}:${e}`,key:e,payload:n})}}_toImmutable(){const e={};for(const[t,n]of this.#se)e[t]=isLiveStructure(n)?n.toImmutable():n;return e}clone(){return new e(Object.fromEntries(Array.from(this.#se).map(([e,t])=>[e,isLiveStructure(t)?t.clone():deepClone(t)])))}};function creationOpToLiveNode(e){return lsonToLiveNode(creationOpToLson(e))}function creationOpToLson(e){switch(e.type){case 8:return e.data;case 4:return new LiveObject(e.data);case 7:return new LiveMap;case 2:return new LiveList([]);default:return assertNever(e,"Unknown creation Op")}}function isSameNodeOrChildOf(e,t){return e===t||"HasParent"===e.parent.type&&isSameNodeOrChildOf(e.parent.node,t)}function deserialize$1([e,t],n,o){switch(t.type){case 0:return LiveObject._deserialize([e,t],n,o);case 1:return LiveList._deserialize([e,t],n,o);case 2:return LiveMap._deserialize([e,t],n,o);case 3:return LiveRegister._deserialize([e,t],n,o);default:throw new Error("Unexpected CRDT type")}}function deserializeToLson([e,t],n,o){switch(t.type){case 0:return LiveObject._deserialize([e,t],n,o);case 1:return LiveList._deserialize([e,t],n,o);case 2:return LiveMap._deserialize([e,t],n,o);case 3:return t.data;default:throw new Error("Unexpected CRDT type")}}function isLiveStructure(e){return isLiveList(e)||isLiveMap(e)||isLiveObject(e)}function isLiveNode(e){return isLiveStructure(e)||isLiveRegister(e)}function isLiveList(e){return e instanceof LiveList}function isLiveMap(e){return e instanceof LiveMap}function isLiveObject(e){return e instanceof LiveObject}function isLiveRegister(e){return e instanceof LiveRegister}function cloneLson(e){return void 0===e?void 0:isLiveStructure(e)?e.clone():deepClone(e)}function liveNodeToLson(e){return e instanceof LiveRegister?e.data:e instanceof LiveList||e instanceof LiveMap||e instanceof LiveObject?e:assertNever(e,"Unknown AbstractCrdt")}function lsonToLiveNode(e){return e instanceof LiveObject||e instanceof LiveMap||e instanceof LiveList?e:new LiveRegister(e)}function getTreesDiffOperations(e,t){const n=[];return e.forEach((e,o)=>{t.get(o)||n.push({type:5,id:o})}),t.forEach((t,o)=>{const r=e.get(o);if(r)0===t.type&&(0===r.type&&JSON.stringify(t.data)===JSON.stringify(r.data)||n.push({type:3,id:o,data:t.data})),t.parentKey!==r.parentKey&&n.push({type:1,id:o,parentKey:nn(t.parentKey,"Parent key must not be missing")});else switch(t.type){case 3:n.push({type:8,id:o,parentId:t.parentId,parentKey:t.parentKey,data:t.data});break;case 1:n.push({type:2,id:o,parentId:t.parentId,parentKey:t.parentKey});break;case 0:if(void 0===t.parentId||void 0===t.parentKey)throw new Error("Internal error. Cannot serialize storage root into an operation");n.push({type:4,id:o,parentId:t.parentId,parentKey:t.parentKey,data:t.data});break;case 2:n.push({type:7,id:o,parentId:t.parentId,parentKey:t.parentKey})}}),n}function mergeObjectStorageUpdates(e,t){const n=e.updates;for(const[e,o]of entries(t.updates))n[e]=o;return{...t,updates:n}}function mergeMapStorageUpdates(e,t){const n=e.updates;for(const[e,o]of entries(t.updates))n[e]=o;return{...t,updates:n}}function mergeListStorageUpdates(e,t){const n=e.updates;return{...t,updates:n.concat(t.updates)}}function mergeStorageUpdates(e,t){return void 0===e?t:"LiveObject"===e.type&&"LiveObject"===t.type?mergeObjectStorageUpdates(e,t):"LiveMap"===e.type&&"LiveMap"===t.type?mergeMapStorageUpdates(e,t):"LiveList"===e.type&&"LiveList"===t.type?mergeListStorageUpdates(e,t):t}function isJsonScalar(e){return null===e||"string"==typeof e||"number"==typeof e||"boolean"==typeof e}function isJsonArray(e){return Array.isArray(e)}function isJsonObject(e){return!isJsonScalar(e)&&!isJsonArray(e)}function makeUser(e,t){const{connectionId:n,id:o,info:r}=e,a=canWriteStorage(e.scopes);return freeze$2(compactObject({connectionId:n,id:o,info:r,canWrite:a,canComment:canComment(e.scopes),isReadOnly:!a,presence:t}))}var ManagedOthers=class{#pe;#_e;signal;constructor(){this.#pe=new MutableSignal({connections:new Map,presences:new Map}),this.signal=DerivedSignal.from(this.#pe,e=>compact(Array.from(this.#pe.get().presences.keys()).map(e=>this.getUser(Number(e))))),this.#_e=new Map}get(){return this.signal.get()}connectionIds(){return this.#pe.get().connections.keys()}clearOthers(){this.#pe.mutate(e=>{e.connections.clear(),e.presences.clear(),this.#_e.clear()})}#me(e){const t=this.#pe.get(),n=t.connections.get(e),o=t.presences.get(e);if(void 0!==n&&void 0!==o)return makeUser(n,o)}getUser(e){const t=this.#_e.get(e);if(t)return t;const n=this.#me(e);return n?(this.#_e.set(e,n),n):void 0}#he(e){this.#_e.delete(e)}setConnection(e,t,n,o){this.#pe.mutate(r=>(r.connections.set(e,freeze$2({connectionId:e,id:t,info:n,scopes:o})),!!r.presences.has(e)&&this.#he(e)))}removeConnection(e){this.#pe.mutate(t=>{t.connections.delete(e),t.presences.delete(e),this.#he(e)})}setOther(e,t){this.#pe.mutate(n=>(n.presences.set(e,freeze$2(compactObject(t))),!!n.connections.has(e)&&this.#he(e)))}patchOther(e,t){this.#pe.mutate(n=>{const o=n.presences.get(e);if(void 0===o)return!1;const r=merge(o,t);return o!==r&&(n.presences.set(e,freeze$2(r)),this.#he(e))})}},MAX_SOCKET_MESSAGE_SIZE=1047552;function makeIdFactory(e){let t=0;return()=>`${e}:${t++}`}function userToTreeNode(e,t){return{type:"User",id:`${t.connectionId}`,key:e,payload:{connectionId:t.connectionId,id:t.id,info:t.info,presence:t.presence,isReadOnly:!t.canWrite}}}function installBackgroundTabSpy(){const e="undefined"!=typeof document?document:void 0,t={current:null};function n(){t.current="hidden"===e?.visibilityState?t.current??Date.now():null}e?.addEventListener("visibilitychange",n);return[t,()=>{e?.removeEventListener("visibilitychange",n)}]}function createRoom(e,t){const n=e.initialPresence,o=e.initialStorage,r=t.roomHttpClient,[a,i]=installBackgroundTabSpy(),s={...t.delegates,canZombie:()=>void 0!==t.backgroundKeepAliveTimeout&&null!==a.current&&Date.now()>a.current+t.backgroundKeepAliveTimeout&&"synchronizing"!==K()},l=new ManagedSocket(s,t.enableDebugLogging),c={buffer:{flushTimerID:void 0,lastFlushedAt:0,presenceUpdates:{type:"full",data:n},messages:[],storageOperations:[]},staticSessionInfoSig:new Signal(null),dynamicSessionInfoSig:new Signal(null),myPresence:new PatchableSignal(n),others:new ManagedOthers,initialStorage:o,idFactory:null,yjsProvider:void 0,yjsProviderDidChange:makeEventSource(),clock:0,opClock:0,nodes:new Map,root:void 0,undoStack:[],redoStack:[],pausedHistory:null,activeBatch:null,unacknowledgedOps:new Map,opStackTraces:void 0};let d,u;let f=!1;l.events.onMessage.subscribe(function(e){if("string"!=typeof e.data)return;const t=function(e){const t=tryParseJson(e);return void 0===t?null:isJsonArray(t)?compact(t.map(e=>$(e))):compact([$(t)])}(e.data);if(null===t||0===t.length)return;const n={storageUpdates:new Map,others:[]};for(const e of t)switch(e.type){case 101:{const t=j(e);t&&n.others.push(t);break}case 100:{const t=T(e);t&&n.others.push(t);break}case 103:{const t=c.others.get();_.customEvent.notify({connectionId:e.actor,user:e.actor<0?null:t.find(t=>t.connectionId===e.actor)??null,event:e.event});break}case 102:{const t=A(e);t&&n.others.push(t);break}case 300:_.ydoc.notify(e);break;case 104:n.others.push(O(e));break;case 200:L(e);break;case 201:{const t=S(e.ops,!1);for(const[e,o]of t.updates.storageUpdates)n.storageUpdates.set(e,mergeStorageUpdates(n.storageUpdates.get(e),o));break}case 299:errorWithTitle("Storage mutation rejection error",e.reason);break;case 400:case 407:case 401:case 408:case 405:case 406:case 402:case 403:case 404:_.comments.notify(e)}x(n)}),l.events.statusDidChange.subscribe(function(e){const t=l.authValue;if(null!==t){const e=getBearerTokenFromAuthValue(t);if(e!==d)if(d=e,"secret"===t.type){const e=t.token.parsed;c.staticSessionInfoSig.set({userId:"sec-legacy"===e.k?e.id:e.uid,userInfo:"sec-legacy"===e.k?e.info:e.ui})}else c.staticSessionInfoSig.set({userId:void 0,userInfo:void 0})}_.status.notify(e),v()}),l.events.statusDidChange.subscribe(function(e){"reconnecting"===e?u=setTimeout(()=>{_.lostConnection.notify("lost"),f=!0,c.others.clearOthers(),x({others:[{type:"reset"}]})},t.lostConnectionTimeout):(clearTimeout(u),f&&("disconnected"===e?_.lostConnection.notify("failed"):_.lostConnection.notify("restored"),f=!1))}),l.events.didConnect.subscribe(function(){c.buffer.presenceUpdates={type:"full",data:{...c.myPresence.get()}},null!==M&&U({flush:!1}),F()}),l.events.didDisconnect.subscribe(function(){clearTimeout(c.buffer.flushTimerID)}),l.events.onLiveblocksError.subscribe(e=>{_.error.notify(e)});const p={roomId:t.roomId,getNode:e=>c.nodes.get(e),addNode:(e,t)=>{c.nodes.set(e,t)},deleteNode:e=>{c.nodes.delete(e)},generateId:()=>`${R()}:${c.clock++}`,generateOpId:()=>`${R()}:${c.opClock++}`,dispatch(e,t,n){const o=c.activeBatch;if(o){for(const t of e)o.ops.push(t);for(const[e,t]of n)o.updates.storageUpdates.set(e,mergeStorageUpdates(o.updates.storageUpdates.get(e),t));o.reverseOps.unshift(...t)}else C(t),c.redoStack.length=0,P(e),x({storageUpdates:n})},assertStorageIsWritable:()=>{const e=c.dynamicSessionInfoSig.get()?.scopes;if(void 0===e)return;if(!canWriteStorage(e))throw new Error("Cannot write to storage with a read only user, please ensure the user has write permissions")}},_={status:makeEventSource(),lostConnection:makeEventSource(),customEvent:makeEventSource(),self:makeEventSource(),myPresence:makeEventSource(),others:makeEventSource(),error:makeEventSource(),storageBatch:makeEventSource(),history:makeEventSource(),storageDidLoad:makeEventSource(),storageStatus:makeEventSource(),ydoc:makeEventSource(),comments:makeEventSource()},m=t.roomId;function h(e){const n=JSON.stringify(e),o=c.dynamicSessionInfoSig.get()?.nonce;if(t.unstable_fallbackToHTTP&&o){if((new TextEncoder).encode(n).length>MAX_SOCKET_MESSAGE_SIZE)return r.sendMessages({roomId:m,nonce:o,messages:e}).then(e=>{e.ok||403!==e.status||l.reconnect()}),void warn$1("Message was too large for websockets and sent over HTTP instead")}l.send(n)}const g=DerivedSignal.from(c.staticSessionInfoSig,c.dynamicSessionInfoSig,c.myPresence,(e,t,n)=>{if(null===e||null===t)return null;{const o=canWriteStorage(t.scopes);return{connectionId:t.actor,id:e.userId,info:e.userInfo,presence:n,canWrite:o,canComment:canComment(t.scopes)}}});let b;function v(){const e=g.get();null!==e&&e!==b&&(_.self.notify(e),b=e)}const y=DerivedSignal.from(g,e=>null!==e?userToTreeNode("Me",e):null);function E(e){if(0===e.items.length)throw new Error("Internal error: cannot load storage without items");void 0!==c.root?function(e){if(void 0===c.root)return;const t=new Map;for(const[e,n]of c.nodes)t.set(e,n._serialize());const n=getTreesDiffOperations(t,new Map(e));x(S(n,!1).updates)}(e.items):c.root=LiveObject._fromItems(e.items,p);const t=g.get()?.canWrite??!0,n=c.undoStack.length;for(const e in c.initialStorage)void 0===c.root.get(e)&&(t?c.root.set(e,cloneLson(c.initialStorage[e])):warn$1(`Attempted to populate missing storage key '${e}', but current user has no write access`));c.undoStack.length=n}function w(e){c.undoStack.length>=50&&c.undoStack.shift(),c.undoStack.push(e),N()}function C(e){null!==c.pausedHistory?c.pausedHistory.unshift(...e):w(e)}function x(e){const t=e.storageUpdates,n=e.others;if(void 0!==n&&n.length>0){const e=c.others.get();for(const t of n)_.others.notify({...t,others:e})}if(e.presence&&(v(),_.myPresence.notify(c.myPresence.get())),void 0!==t&&t.size>0){const e=Array.from(t.values());_.storageBatch.notify(e)}G()}function R(){const e=c.dynamicSessionInfoSig.get();if(e)return e.actor;throw new Error("Internal. Tried to get connection id but connection was never open")}function S(e,t){const n={reverse:[],storageUpdates:new Map,presence:!1},o=new Set,r=e.map(e=>"presence"===e.type||e.opId?e:{...e,opId:p.generateOpId()});for(const e of r)if("presence"===e.type){const t={type:"presence",data:{}};for(const n in e.data)t.data[n]=c.myPresence.get()[n];if(c.myPresence.patch(e.data),null===c.buffer.presenceUpdates)c.buffer.presenceUpdates={type:"partial",data:e.data};else for(const t in e.data)c.buffer.presenceUpdates.data[t]=e.data[t];n.reverse.unshift(t),n.presence=!0}else{let r;if(t)r=0;else{const t=nn(e.opId);r=c.unacknowledgedOps.delete(t)?2:1}const a=D(e,r);if(a.modified){const t=a.modified.node._id;t&&o.has(t)||(n.storageUpdates.set(nn(a.modified.node._id),mergeStorageUpdates(n.storageUpdates.get(nn(a.modified.node._id)),a.modified)),n.reverse.unshift(...a.reverse)),2!==e.type&&7!==e.type&&4!==e.type||o.add(nn(e.id))}}return{ops:r,reverse:n.reverse,updates:{storageUpdates:n.storageUpdates,presence:n.presence}}}function D(e,t){if(isAckOp(e))return{modified:!1};switch(e.type){case 6:case 3:case 5:{const n=c.nodes.get(e.id);return void 0===n?{modified:!1}:n._apply(e,0===t)}case 1:{const n=c.nodes.get(e.id);return void 0===n?{modified:!1}:"HasParent"===n.parent.type&&isLiveList(n.parent.node)?n.parent.node._setChildKey(asPos(e.parentKey),n,t):{modified:!1}}case 4:case 2:case 7:case 8:{if(void 0===e.parentId)return{modified:!1};const n=c.nodes.get(e.parentId);return void 0===n?{modified:!1}:n._attachChild(e,t)}}}function T(e){if(void 0!==e.targetActor){const t=c.others.getUser(e.actor);c.others.setOther(e.actor,e.data);const n=c.others.getUser(e.actor);if(void 0===t&&void 0!==n)return{type:"enter",user:n}}else c.others.patchOther(e.actor,e.data);const t=c.others.getUser(e.actor);return t?{type:"update",updates:e.data,user:t}:void 0}function A(e){const t=c.others.getUser(e.actor);return t?(c.others.removeConnection(e.actor),{type:"leave",user:t}):null}function O(e){c.dynamicSessionInfoSig.set({actor:e.actor,nonce:e.nonce,scopes:e.scopes}),c.idFactory=makeIdFactory(e.actor),v();for(const t of c.others.connectionIds()){void 0===e.users[t]&&c.others.removeConnection(t)}for(const t in e.users){const n=e.users[t],o=Number(t);c.others.setConnection(o,n.id,n.info,n.scopes)}return{type:"reset"}}function I(){return c.undoStack.length>0}function k(){return c.redoStack.length>0}function N(){_.history.notify({canUndo:I(),canRedo:k()})}function j(e){c.others.setConnection(e.actor,e.id,e.info,e.scopes),c.buffer.messages.push({type:100,data:c.myPresence.get(),targetActor:e.actor}),F();const t=c.others.getUser(e.actor);return t?{type:"enter",user:t}:void 0}function $(e){return isJsonObject(e)?e:null}function F(){const e=c.buffer.storageOperations;if(e.length>0){for(const t of e)c.unacknowledgedOps.set(nn(t.opId),t);G()}if("connected"!==l.getStatus())return void(c.buffer.storageOperations=[]);const n=Date.now(),o=n-c.buffer.lastFlushedAt;if(o>=t.throttleDelay){const e=function(){const e=[];c.buffer.presenceUpdates&&e.push("full"===c.buffer.presenceUpdates.type?{type:100,targetActor:-1,data:c.buffer.presenceUpdates.data}:{type:100,data:c.buffer.presenceUpdates.data});for(const t of c.buffer.messages)e.push(t);c.buffer.storageOperations.length>0&&e.push({type:201,ops:c.buffer.storageOperations});return e}();if(0===e.length)return;h(e),c.buffer={flushTimerID:void 0,lastFlushedAt:n,messages:[],storageOperations:[],presenceUpdates:null}}else clearTimeout(c.buffer.flushTimerID),c.buffer.flushTimerID=setTimeout(F,t.throttleDelay-o)}function P(e){const{storageOperations:t}=c.buffer;for(const n of e)t.push(n);F()}let M=null,B=null;function L(e){const t=new Map(c.unacknowledgedOps);E(e),function(e){if(0===e.size)return;const t=[],n=S(Array.from(e.values()),!0);t.push({type:201,ops:n.ops}),x(n.updates),h(t)}(t),B?.(),G(),_.storageDidLoad.notify()}function U(e){const n=c.buffer.messages;t.unstable_streamData?async function(){if(!l.authValue)return;L({type:200,items:await r.streamStorage({roomId:m})})}():n.some(e=>200===e.type)||n.push({type:200}),e.flush&&F()}function V(){return null===M&&(U({flush:!0}),M=new Promise(e=>{B=e}),G()),M}function H(){const e=c.root;return void 0!==e?e:(V(),null)}async function z(){return void 0!==c.root?Promise.resolve({root:c.root}):(await V(),{root:nn(c.root)})}const q=t.createSyncSource();function K(){return void 0===c.root?null===M?"not-loaded":"loading":0===c.unacknowledgedOps.size?"synchronized":"synchronizing"}let W=K();function G(){const e=K();W!==e&&(W=e,_.storageStatus.notify(e)),q.setSyncStatus("synchronizing"===e?"synchronizing":"synchronized")}function Y(){return null!==g.get()}function J(){return null!==H()}const X=DerivedSignal.from(c.others.signal,e=>e.map((e,t)=>userToTreeNode(`Other ${t}`,e))),Z={status:_.status.observable,lostConnection:_.lostConnection.observable,customEvent:_.customEvent.observable,others:_.others.observable,self:_.self.observable,myPresence:_.myPresence.observable,error:_.error.observable,storage:_.storageBatch.observable,storageBatch:_.storageBatch.observable,history:_.history.observable,storageDidLoad:_.storageDidLoad.observable,storageStatus:_.storageStatus.observable,ydoc:_.ydoc.observable,comments:_.comments.observable};const Q=t.createSyncSource();function ee(e){return Q.setSyncStatus("synchronizing"===e?"synchronizing":"synchronized")}return Object.defineProperty({[kInternal]:{get presenceBuffer(){return deepClone(c.buffer.presenceUpdates?.data??null)},get undoStack(){return deepClone(c.undoStack)},get nodeCount(){return c.nodes.size},getYjsProvider:()=>c.yjsProvider,setYjsProvider(e){c.yjsProvider?.off("status",ee),c.yjsProvider=e,e?.on("status",ee),c.yjsProviderDidChange.notify()},yjsProviderDidChange:c.yjsProviderDidChange.observable,reportTextEditor:async function(e,t){await r.reportTextEditor({roomId:m,type:e,rootKey:t})},createTextMention:async function(e,t){return r.createTextMention({roomId:m,userId:e,mentionId:t})},deleteTextMention:async function(e){return r.deleteTextMention({roomId:m,mentionId:e})},listTextVersions:async function(){return r.listTextVersions({roomId:m})},listTextVersionsSince:async function(e){return r.listTextVersionsSince({roomId:m,since:e.since,signal:e.signal})},getTextVersion:async function(e){return r.getTextVersion({roomId:m,versionId:e})},createTextVersion:async function(){return r.createTextVersion({roomId:m})},getSelf_forDevTools:()=>y.get(),getOthers_forDevTools:()=>X.get(),simulate:{explicitClose:e=>l._privateSendMachineEvent({type:"EXPLICIT_SOCKET_CLOSE",event:e}),rawSend:e=>l.send(e)},attachmentUrlsStore:r.getOrCreateAttachmentUrlsStore(m)},id:t.roomId,subscribe:makeClassicSubscribeFn(Z),connect:()=>l.connect(),reconnect:()=>l.reconnect(),disconnect:()=>l.disconnect(),destroy:()=>{q.destroy(),c.yjsProvider?.off("status",ee),Q.destroy(),i(),l.destroy()},updatePresence:function(e,t){const n={};null===c.buffer.presenceUpdates&&(c.buffer.presenceUpdates={type:"partial",data:{}});for(const t in e){const o=e[t];void 0!==o&&(c.buffer.presenceUpdates.data[t]=o,n[t]=c.myPresence.get()[t])}c.myPresence.patch(e),c.activeBatch?(t?.addToHistory&&c.activeBatch.reverseOps.unshift({type:"presence",data:n}),c.activeBatch.updates.presence=!0):(F(),t?.addToHistory&&C([{type:"presence",data:n}]),x({presence:!0}))},updateYDoc:function(e,t){const n={type:301,update:e,guid:t};c.buffer.messages.push(n),_.ydoc.notify(n),F()},broadcastEvent:function(e,t={shouldQueueEventIfNotReady:!1}){("connected"===l.getStatus()||t.shouldQueueEventIfNotReady)&&(c.buffer.messages.push({type:103,event:e}),F())},batch:function(e){if(c.activeBatch)return e();let t;c.activeBatch={ops:[],updates:{storageUpdates:new Map,presence:!1,others:[]},reverseOps:[]};try{t=e()}finally{const e=c.activeBatch;c.activeBatch=null,e.reverseOps.length>0&&C(e.reverseOps),e.ops.length>0&&(c.redoStack.length=0),e.ops.length>0&&P(e.ops),x(e.updates),F()}return t},history:{undo:function(){if(c.activeBatch)throw new Error("undo is not allowed during a batch");const e=c.undoStack.pop();if(void 0===e)return;c.pausedHistory=null;const t=S(e,!0);x(t.updates),c.redoStack.push(t.reverse),N();for(const e of t.ops)"presence"!==e.type&&c.buffer.storageOperations.push(e);F()},redo:function(){if(c.activeBatch)throw new Error("redo is not allowed during a batch");const e=c.redoStack.pop();if(void 0===e)return;c.pausedHistory=null;const t=S(e,!0);x(t.updates),c.undoStack.push(t.reverse),N();for(const e of t.ops)"presence"!==e.type&&c.buffer.storageOperations.push(e);F()},canUndo:I,canRedo:k,clear:function(){c.undoStack.length=0,c.redoStack.length=0},pause:function(){null===c.pausedHistory&&(c.pausedHistory=[])},resume:function(){const e=c.pausedHistory;c.pausedHistory=null,null!==e&&e.length>0&&w(e)}},fetchYDoc:function(e,t){c.buffer.messages.find(n=>300===n.type&&n.vector===e&&n.guid===t)||c.buffer.messages.push({type:300,vector:e,guid:t}),F()},getStorage:z,getStorageSnapshot:H,getStorageStatus:K,isPresenceReady:Y,isStorageReady:J,waitUntilPresenceReady:memoizeOnSuccess(async function(){for(;!Y();){const{promise:e,resolve:t}=Promise_withResolvers(),n=Z.self.subscribeOnce(t),o=Z.status.subscribeOnce(t);await e,n(),o()}}),waitUntilStorageReady:memoizeOnSuccess(async function(){for(;!J();)await z()}),events:Z,getStatus:()=>l.getStatus(),getSelf:()=>g.get(),getPresence:()=>c.myPresence.get(),getOthers:()=>c.others.get(),getThreads:async function(e){return r.getThreads({roomId:m,query:e?.query,cursor:e?.cursor})},getThreadsSince:async function(e){return r.getThreadsSince({roomId:m,since:e.since,signal:e.signal})},getThread:async function(e){return r.getThread({roomId:m,threadId:e})},createThread:async function(e){return r.createThread({roomId:m,threadId:e.threadId,commentId:e.commentId,metadata:e.metadata,body:e.body,attachmentIds:e.attachmentIds})},deleteThread:async function(e){return r.deleteThread({roomId:m,threadId:e})},editThreadMetadata:async function({metadata:e,threadId:t}){return r.editThreadMetadata({roomId:m,threadId:t,metadata:e})},markThreadAsResolved:async function(e){return r.markThreadAsResolved({roomId:m,threadId:e})},markThreadAsUnresolved:async function(e){return r.markThreadAsUnresolved({roomId:m,threadId:e})},createComment:async function(e){return r.createComment({roomId:m,threadId:e.threadId,commentId:e.commentId,body:e.body,attachmentIds:e.attachmentIds})},editComment:async function(e){return r.editComment({roomId:m,threadId:e.threadId,commentId:e.commentId,body:e.body,attachmentIds:e.attachmentIds})},deleteComment:async function({threadId:e,commentId:t}){return r.deleteComment({roomId:m,threadId:e,commentId:t})},addReaction:async function({threadId:e,commentId:t,emoji:n}){return r.addReaction({roomId:m,threadId:e,commentId:t,emoji:n})},removeReaction:async function({threadId:e,commentId:t,emoji:n}){return await r.removeReaction({roomId:m,threadId:e,commentId:t,emoji:n})},prepareAttachment:function(e){return{type:"localAttachment",status:"idle",id:createCommentAttachmentId(),name:e.name,size:e.size,mimeType:e.type,file:e}},uploadAttachment:async function(e,t={}){return r.uploadAttachment({roomId:m,attachment:e,signal:t.signal})},getAttachmentUrl:function(e){return r.getAttachmentUrl({roomId:m,attachmentId:e})},getNotificationSettings:function(e){return r.getNotificationSettings({roomId:m,signal:e?.signal})},updateNotificationSettings:function(e){return r.updateNotificationSettings({roomId:m,settings:e})},markInboxNotificationAsRead:async function(e){await r.markRoomInboxNotificationAsRead({roomId:m,inboxNotificationId:e})}},kInternal,{enumerable:!1})}function makeClassicSubscribeFn(e){return function(t,n,o){if("string"==typeof t&&isRoomEventName(t)){if("function"!=typeof n)throw new Error("Second argument must be a callback function");const o=n;switch(t){case"event":return e.customEvent.subscribe(o);case"my-presence":return e.myPresence.subscribe(o);case"others":{const t=o;return e.others.subscribe(e=>{const{others:n,...o}=e;return t(n,o)})}case"error":return e.error.subscribe(o);case"status":return e.status.subscribe(o);case"lost-connection":return e.lostConnection.subscribe(o);case"history":return e.history.subscribe(o);case"storage-status":return e.storageStatus.subscribe(o);case"comments":return e.comments.subscribe(o);default:return assertNever(t,`"${String(t)}" is not a valid event name`)}}if(void 0===n||"function"==typeof t){if("function"==typeof t){const n=t;return e.storageBatch.subscribe(n)}throw new Error("Please specify a listener callback")}if(isLiveNode(t)){const r=t;if(o?.isDeep){return function(t,n){return e.storageBatch.subscribe(e=>{const o=e.filter(e=>isSameNodeOrChildOf(e.node,t));o.length>0&&n(o)})}(r,n)}return function(t,n){return e.storageBatch.subscribe(e=>{for(const o of e)o.node._id===t._id&&n(o.node)})}(r,n)}throw new Error(`${String(t)} is not a value that can be subscribed to.`)}}function isRoomEventName(e){return"my-presence"===e||"others"===e||"event"===e||"error"===e||"history"===e||"status"===e||"storage-status"===e||"lost-connection"===e||"connection"===e||"comments"===e}function makeAuthDelegateForRoom(e,t){return async()=>t.getAuthValue({requestedScope:"room:read",roomId:e})}function makeCreateSocketDelegateForRoom(e,t,n){return o=>{const r=n??("undefined"==typeof WebSocket?void 0:WebSocket);if(void 0===r)throw new StopRetrying("To use Liveblocks client in a non-DOM environment, you need to provide a WebSocket polyfill.");const a=new URL(t);if(a.protocol="http:"===a.protocol?"ws":"wss",a.pathname="/v7",a.searchParams.set("roomId",e),"secret"===o.type)a.searchParams.set("tok",o.token.raw);else{if("public"!==o.type)return assertNever(o,"Unhandled case");a.searchParams.set("pubkey",o.publicApiKey)}return a.searchParams.set("version",PKG_VERSION$2),new r(a.toString())}}var MIN_THROTTLE=16,MAX_THROTTLE=1e3,DEFAULT_THROTTLE=100,MIN_BACKGROUND_KEEP_ALIVE_TIMEOUT=15e3,MIN_LOST_CONNECTION_TIMEOUT=200,RECOMMENDED_MIN_LOST_CONNECTION_TIMEOUT=1e3,MAX_LOST_CONNECTION_TIMEOUT=3e4,DEFAULT_LOST_CONNECTION_TIMEOUT=5e3,RESOLVE_USERS_BATCH_DELAY=50,RESOLVE_ROOMS_INFO_BATCH_DELAY=50;function getBaseUrl(e){return"string"==typeof e&&e.startsWith("http")?e:DEFAULT_BASE_URL}function createClient(e){const t=e,n=getThrottle(t.throttle??DEFAULT_THROTTLE),o=getLostConnectionTimeout(t.lostConnectionTimeout??DEFAULT_LOST_CONNECTION_TIMEOUT),r=getBackgroundKeepAliveTimeout(t.backgroundKeepAliveTimeout),a=getBaseUrl(t.baseUrl),i=new Signal(void 0),s=createAuthManager(e,e=>{const t="sec-legacy"===e.k?e.id:e.uid;i.set(()=>t)}),l=t.polyfills?.fetch||globalThis.fetch?.bind(globalThis),c=createApiClient({baseUrl:a,fetchPolyfill:l,authManager:s}),d=new Map;function u(e){const t=()=>{const n=t;var o;e.unsubs.delete(n)?0===e.unsubs.size&&(unlinkDevTools((o=e.room).id),d.delete(o.id),o.destroy()):warn$1("This leave function was already called. Calling it more than once has no effect.")};return e.unsubs.add(t),{room:e.room,leave:t}}const f=t.resolveUsers,p=createDevelopmentWarning(()=>!f,"Set the resolveUsers option in createClient to specify user info."),_=createBatchStore(new Batch(async e=>{const t=e.flat(),n=await(f?.({userIds:t}));return p(),n??t.map(()=>{})},{delay:RESOLVE_USERS_BATCH_DELAY}));const m=t.resolveRoomsInfo,h=createDevelopmentWarning(()=>!m,"Set the resolveRoomsInfo option in createClient to specify room info."),g=createBatchStore(new Batch(async e=>{const t=e.flat(),n=await(m?.({roomIds:t}));return h(),n??t.map(()=>{})},{delay:RESOLVE_ROOMS_INFO_BATCH_DELAY}));const b=new Map;const v=[],y=new Signal("synchronized");function E(){y.set(v.some(e=>"synchronizing"===e.get())?"synchronizing":v.some(e=>"has-local-changes"===e.get())?"has-local-changes":"synchronized")}function w(){const e=new Signal("synchronized");v.push(e);const t=e.subscribe(()=>E());return{setSyncStatus:function(t){e.set(t)},destroy:function(){t();const n=v.findIndex(t=>t===e);if(n>-1){const[e]=v.splice(n,1);"synchronized"!==e.get()&&E()}}}}{const e=e=>{t.preventUnsavedChanges&&"synchronized"!==y.get()&&e.preventDefault()},n="undefined"!=typeof window?window:void 0;n?.addEventListener("beforeunload",e)}const C=Object.defineProperty({enterRoom:function(e,...i){const l=d.get(e);if(void 0!==l)return u(l);const f=i[0]??{},p=createRoom({initialPresence:("function"==typeof f.initialPresence?f.initialPresence(e):f.initialPresence)??{},initialStorage:("function"==typeof f.initialStorage?f.initialStorage(e):f.initialStorage)??{}},{roomId:e,throttleDelay:n,lostConnectionTimeout:o,backgroundKeepAliveTimeout:r,polyfills:t.polyfills,delegates:t.mockedDelegates??{createSocket:makeCreateSocketDelegateForRoom(e,a,t.polyfills?.WebSocket),authenticate:makeAuthDelegateForRoom(e,s)},enableDebugLogging:t.enableDebugLogging,baseUrl:a,unstable_fallbackToHTTP:!!t.unstable_fallbackToHTTP,unstable_streamData:!!t.unstable_streamData,roomHttpClient:c,createSyncSource:w}),_={room:p,unsubs:new Set};if(d.set(e,_),f.autoConnect??!0){if("undefined"==typeof atob){if(void 0===t.polyfills?.atob)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=t.polyfills.atob}p.connect()}return u(_)},getRoom:function(e){const t=d.get(e)?.room;return t||null},logout:function(){s.reset(),i.set(()=>{});for(const{room:e}of d.values())isIdle(e.getStatus())||e.reconnect()},getInboxNotifications:c.getInboxNotifications,getInboxNotificationsSince:c.getInboxNotificationsSince,getUnreadInboxNotificationsCount:c.getUnreadInboxNotificationsCount,markAllInboxNotificationsAsRead:c.markAllInboxNotificationsAsRead,markInboxNotificationAsRead:c.markInboxNotificationAsRead,deleteAllInboxNotifications:c.deleteAllInboxNotifications,deleteInboxNotification:c.deleteInboxNotification,resolvers:{invalidateUsers:function(e){_.invalidate(e)},invalidateRoomsInfo:function(e){g.invalidate(e)},invalidateMentionSuggestions:function(){b.clear()}},getSyncStatus:function(){const e=y.get();return"synchronizing"===e?e:"synchronized"},events:{syncStatus:y},[kInternal]:{currentUserId:i,mentionSuggestionsCache:b,resolveMentionSuggestions:t.resolveMentionSuggestions,usersStore:_,roomsInfoStore:g,getRoomIds:()=>Array.from(d.keys()),httpClient:c,as:()=>C,createSyncSource:w}},kInternal,{enumerable:!1});return C}function checkBounds(e,t,n,o,r){if("number"!=typeof t||t<n||void 0!==o&&t>o)throw new Error(void 0!==o?`${e} should be between ${r??n} and ${o}.`:`${e} should be at least ${r??n}.`);return t}function getBackgroundKeepAliveTimeout(e){if(void 0!==e)return checkBounds("backgroundKeepAliveTimeout",e,MIN_BACKGROUND_KEEP_ALIVE_TIMEOUT)}function getThrottle(e){return checkBounds("throttle",e,MIN_THROTTLE,MAX_THROTTLE)}function getLostConnectionTimeout(e){return checkBounds("lostConnectionTimeout",e,MIN_LOST_CONNECTION_TIMEOUT,MAX_LOST_CONNECTION_TIMEOUT,RECOMMENDED_MIN_LOST_CONNECTION_TIMEOUT)}function createDevelopmentWarning(e,...t){return()=>{}}function isCommentBodyParagraph(e){return"type"in e&&"paragraph"===e.type}function isCommentBodyText$1(e){return!("type"in e)&&"text"in e&&"string"==typeof e.text}function isCommentBodyMention$1(e){return"type"in e&&"mention"===e.type}function isCommentBodyLink$1(e){return"type"in e&&"link"===e.type}var commentBodyElementsGuards={paragraph:isCommentBodyParagraph,text:isCommentBodyText$1,link:isCommentBodyLink$1,mention:isCommentBodyMention$1},commentBodyElementsTypes={paragraph:"block",text:"inline",link:"inline",mention:"inline"};function traverseCommentBody(e,t,n){if(!e||!e?.content)return;const o="string"==typeof t?t:void 0,r=o?commentBodyElementsTypes[o]:"all",a=o?commentBodyElementsGuards[o]:()=>!0,i="function"==typeof t?t:n;for(const t of e.content)if("all"!==r&&"block"!==r||a(t)&&i?.(t),"all"===r||"inline"===r)for(const e of t.children)a(e)&&i?.(e)}function getMentionedIdsFromCommentBody(e){const t=new Set;return traverseCommentBody(e,"mention",e=>t.add(e.id)),Array.from(t)}var htmlEscapables={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"};new RegExp(Object.keys(htmlEscapables).map(e=>`\\${e}`).join("|"),"g");var markdownEscapables={_:"\\_","*":"\\*","#":"\\#","`":"\\`","~":"\\~","!":"\\!","|":"\\|","(":"\\(",")":"\\)","{":"\\{","}":"\\}","[":"\\[","]":"\\]"};new RegExp(Object.keys(markdownEscapables).map(e=>`\\${e}`).join("|"),"g");var BACKOFF_DELAYS2=[1e3,2e3,4e3,8e3,1e4];function makePoller(e,t,n){const o=performance.now(),r="undefined"!=typeof document?document:void 0,a="undefined"!=typeof window?window:void 0,i=n?.maxStaleTimeMs??Number.POSITIVE_INFINITY,s={inForeground:"hidden"!==r?.visibilityState,lastSuccessfulPollAt:o,count:0,backoff:0};function l(){return s.count>0&&s.inForeground}const c=new FSM({}).addState("@idle").addState("@enabled").addState("@polling");function d(){l()?c.send({type:"START"}):c.send({type:"STOP"})}function u(){performance.now()-s.lastSuccessfulPollAt>i&&c.send({type:"POLL"})}function f(e){s.inForeground=e,d(),u()}function p(){f("hidden"!==r?.visibilityState)}return c.addTransitions("@idle",{START:"@enabled"}),c.addTransitions("@enabled",{STOP:"@idle",POLL:"@polling"}),c.addTimedTransition("@enabled",()=>{const e=s.lastSuccessfulPollAt+t;return Math.max(0,e-performance.now())+s.backoff},"@polling"),c.onEnterAsync("@polling",async(t,n)=>{await e(n),n.aborted||(s.lastSuccessfulPollAt=performance.now())},()=>({target:l()?"@enabled":"@idle",effect:()=>{s.backoff=0}}),()=>({target:l()?"@enabled":"@idle",effect:()=>{s.backoff=BACKOFF_DELAYS2.find(e=>e>s.backoff)??BACKOFF_DELAYS2[BACKOFF_DELAYS2.length-1]}}),3e4),r?.addEventListener("visibilitychange",p),a?.addEventListener("online",p),c.start(),{inc:function(){s.count++,d()},dec:function(){s.count--,s.count<0&&(s.count=0),d()},pollNowIfStale:u,setInForeground:f}}function shallowArray(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!Object.is(e[n],t[n]))return!1;return!0}function shallowObj(e,t){if(!isPlainObject$2(e)||!isPlainObject$2(t))return!1;const n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(n=>Object.prototype.hasOwnProperty.call(t,n)&&Object.is(e[n],t[n]))}function shallow(e,t){if(Object.is(e,t))return!0;const n=Array.isArray(e),o=Array.isArray(t);return n||o?!(!n||!o)&&shallowArray(e,t):shallowObj(e,t)}function bisectRight(e,t,n){let o=0,r=e.length;for(;o<r;){const a=o+(r-o>>1);n(t,e[a])?r=a:o=a+1}return o}var SortedList=class e{#z;#ge;constructor(e,t){this.#ge=t,this.#z=e}static from(t,n){const o=new e([],n);for(const e of t)o.add(e);return o}static fromAlreadySorted(t,n){return new e(t,n)}clone(){return new e(this.#z.slice(),this.#ge)}add(e){const t=bisectRight(this.#z,e,this.#ge);this.#z.splice(t,0,e)}remove(e){const t=this.#z.indexOf(e);return t>=0&&(this.#z.splice(t,1),!0)}get length(){return this.#z.length}*filter(e){for(const t of this.#z)e(t)&&(yield t)}[Symbol.iterator](){return this.#z[Symbol.iterator]()}};detectDupes(PKG_NAME$2,PKG_VERSION$2,PKG_FORMAT$2);var commonjsGlobal="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0!==global?global:"undefined"!=typeof self?self:{},jsxRuntime={exports:{}},reactJsxRuntime_production_min={},hasRequiredReactJsxRuntime_production_min;function requireReactJsxRuntime_production_min(){if(hasRequiredReactJsxRuntime_production_min)return reactJsxRuntime_production_min;hasRequiredReactJsxRuntime_production_min=1;var e=React__default.default,t=Symbol.for("react.element"),n=Symbol.for("react.fragment"),o=Object.prototype.hasOwnProperty,r=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,a={key:!0,ref:!0,__self:!0,__source:!0};function i(e,n,i){var s,l={},c=null,d=null;for(s in void 0!==i&&(c=""+i),void 0!==n.key&&(c=""+n.key),void 0!==n.ref&&(d=n.ref),n)o.call(n,s)&&!a.hasOwnProperty(s)&&(l[s]=n[s]);if(e&&e.defaultProps)for(s in n=e.defaultProps)void 0===l[s]&&(l[s]=n[s]);return{$$typeof:t,type:e,key:c,ref:d,props:l,_owner:r.current}}return reactJsxRuntime_production_min.Fragment=n,reactJsxRuntime_production_min.jsx=i,reactJsxRuntime_production_min.jsxs=i,reactJsxRuntime_production_min}!function(e){e.exports=requireReactJsxRuntime_production_min()}(jsxRuntime);var PKG_NAME$1="@liveblocks/client",PKG_VERSION$1="2.15.1",PKG_FORMAT$1="esm";detectDupes(PKG_NAME$1,PKG_VERSION$1,PKG_FORMAT$1);var RoomContext=React.createContext(null);function useRoomOrNull(){return React.useContext(RoomContext)}function is$1(e,t){return e===t&&(0!==e||1/e==1/t)||e!=e&&t!=t}function useSyncExternalStoreWithSelector(e,t,n,o,r){const a=React.useRef(null);let i;null===a.current?(i={hasValue:!1,value:null},a.current=i):i=a.current;const[s,l]=React.useMemo(()=>{let e,a,s=!1;const l=t=>{if(!s){s=!0,e=t;const n=o(t);if(void 0!==r&&i.hasValue){const e=i.value;if(r(e,n))return a=e,e}return a=n,n}const n=a;if(is$1(e,t))return n;const l=o(t);return void 0!==r&&r(n,l)?(e=t,n):(e=t,a=l,l)},c=void 0===n?null:n;return[()=>l(t()),null===c?void 0:()=>l(c())]},[t,n,o,r]),c=React.useSyncExternalStore(e,s,l);return React.useEffect(()=>{i.hasValue=!0,i.value=c},[c]),React.useDebugValue(c),c}var SECONDS=1e3,MINUTES=60*SECONDS,config$1={SMOOTH_DELAY:1*SECONDS,NOTIFICATIONS_POLL_INTERVAL:1*MINUTES,NOTIFICATIONS_MAX_STALE_TIME:5*SECONDS,ROOM_THREADS_POLL_INTERVAL:5*MINUTES,ROOM_THREADS_MAX_STALE_TIME:5*SECONDS,USER_THREADS_POLL_INTERVAL:1*MINUTES,USER_THREADS_MAX_STALE_TIME:5*SECONDS,HISTORY_VERSIONS_POLL_INTERVAL:1*MINUTES,HISTORY_VERSIONS_MAX_STALE_TIME:5*SECONDS,NOTIFICATION_SETTINGS_POLL_INTERVAL:1*MINUTES,NOTIFICATION_SETTINGS_MAX_STALE_TIME:5*SECONDS};function shallow2(e,t){if(!isPlainObject$2(e)||!isPlainObject$2(t))return shallow(e,t);const n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(n=>Object.prototype.hasOwnProperty.call(t,n)&&shallow(e[n],t[n]))}function useLatest$1(e){const t=React.useRef(e);return React.useEffect(()=>{t.current=e},[e]),t}var noop$2=e=>e;function useInitial$1(e){return React.useReducer(noop$2,e)[0]}function useInitialUnlessFunction(e){const t=useInitial$1(e);if("function"==typeof t){const t=useLatest$1(e);return React.useCallback((...e)=>t.current(...e),[t])}return t}var use=e=>{if("pending"===e.status)throw e;if("fulfilled"===e.status)return e.value;throw"rejected"===e.status?e.reason:(e.status="pending",e.then(t=>{e.status="fulfilled",e.value=t},t=>{e.status="rejected",e.reason=t}),e)};function autobind(e){const t=new Set;t.add("constructor");let n=e.constructor.prototype;do{for(const o of Reflect.ownKeys(n)){if(t.has(o))continue;const r=Reflect.getOwnPropertyDescriptor(n,o);"function"==typeof r?.value&&(t.add(o),e[o]=e[o].bind(e))}}while((n=Reflect.getPrototypeOf(n))&&n!==Object.prototype)}function find(e,t){for(const n of e)if(t(n))return n}function isStartsWith(e){return isPlainObject$2(e)&&isString(e.startsWith)}function isString(e){return"string"==typeof e}function makeThreadsFilter(e){return t=>matchesQuery(t,e)&&matchesMetadata(t,e)}function matchesQuery(e,t){return void 0===t.resolved||e.resolved===t.resolved}function matchesMetadata(e,t){const n=e.metadata;return void 0===t.metadata||Object.entries(t.metadata).every(([e,t])=>matchesOperator(n[e],t))}function matchesOperator(e,t){return isStartsWith(t)?isString(e)&&e.startsWith(t.startsWith):e===t}function sanitizeThread(e){if(e.deletedAt&&e.comments.length>0)return{...e,comments:[]};return e.comments.some(e=>!e.deletedAt)?e:{...e,deletedAt:new Date,comments:[]}}var ThreadDB=class e{#be;#ve;#ye;signal;constructor(){this.#ve=SortedList.from([],(e,t)=>{const n=e.createdAt,o=t.createdAt;return n<o||n===o&&e.id<t.id}),this.#ye=SortedList.from([],(e,t)=>{const n=t.updatedAt,o=e.updatedAt;return n<o||n===o&&t.id<e.id}),this.#be=new Map,this.signal=new MutableSignal(this)}clone(){const t=new e;return t.#be=new Map(this.#be),t.#ve=this.#ve.clone(),t.#ye=this.#ye.clone(),t}get(e){const t=this.getEvenIfDeleted(e);return t?.deletedAt?void 0:t}getEvenIfDeleted(e){return this.#be.get(e)}upsert(e){this.signal.mutate(()=>{const t=(e=sanitizeThread(e)).id,n=this.#be.get(t);if(n){if(n.deletedAt)return!1;this.#ve.remove(n),this.#ye.remove(n)}return e.deletedAt||(this.#ve.add(e),this.#ye.add(e)),this.#be.set(t,e),!0})}upsertIfNewer(e){const t=this.get(e.id);(!t||e.updatedAt>=t.updatedAt)&&this.upsert(e)}applyDelta(e){batch(()=>{for(const t of e.newThreads)this.upsertIfNewer(t);for(const{id:t,deletedAt:n}of e.deletedThreads){this.getEvenIfDeleted(t)&&this.delete(t,n)}})}delete(e,t){const n=this.#be.get(e);n&&!n.deletedAt&&this.upsert({...n,deletedAt:t,updatedAt:t})}findMany(e,t,n){const o="desc"===n?this.#ye:this.#ve,r=[];return void 0!==e&&r.push(t=>t.roomId===e),r.push(makeThreadsFilter(t)),Array.from(o.filter(e=>r.every(t=>t(e))))}};function makeRoomThreadsQueryKey(e,t){return`${e}-${stringify(t??{})}`}function makeUserThreadsQueryKey(e){return`USER_THREADS:${stringify(e??{})}`}function makeNotificationSettingsQueryKey(e){return`${e}:NOTIFICATION_SETTINGS`}function makeVersionsQueryKey(e){return`${e}-VERSIONS`}function usify(e){if("status"in e)return e;const t=e;return t.status="pending",t.then(e=>{t.status="fulfilled",t.value=e},e=>{t.status="rejected",t.reason=e}),t}var noop2=Promise.resolve(),ASYNC_LOADING=Object.freeze({isLoading:!0}),PaginatedResource=class{observable;#O;#Ee;#we;#Ce;constructor(e){this.#we=null,this.#Ee=e,this.#O=makeEventSource(),this.#Ce=null,this.observable=this.#O.observable,autobind(this)}#xe(e){const t=this.#we;null!==t&&(this.#we={...t,...e},this.#O.notify())}async#Re(){const e=this.#we;if(e?.cursor){this.#xe({isFetchingMore:!0});try{const t=await this.#Ee(e.cursor);this.#xe({cursor:t,fetchMoreError:void 0,isFetchingMore:!1})}catch(e){this.#xe({isFetchingMore:!1,fetchMoreError:e})}}}fetchMore(){const e=this.#we;return null===e?.cursor?noop2:(this.#Ce||(this.#Ce=this.#Re().finally(()=>{this.#Ce=null})),this.#Ce)}get(){const e=this.#Se;if(null===e||"pending"===e.status)return ASYNC_LOADING;if("rejected"===e.status)return{isLoading:!1,error:e.reason};const t=this.#we;return{isLoading:!1,data:{fetchMore:this.fetchMore,isFetchingMore:t.isFetchingMore,fetchMoreError:t.fetchMoreError,hasFetchedAll:null===t.cursor}}}#Se=null;waitUntilLoaded(){if(this.#Se)return this.#Se;const e=usify(autoRetry(()=>this.#Ee(void 0),5,[5e3,5e3,1e4,15e3]).then(e=>{this.#we={cursor:e,isFetchingMore:!1,fetchMoreError:void 0}}));return e.then(()=>this.#O.notify(),()=>{this.#O.notify(),setTimeout(()=>{this.#Se=null,this.#O.notify()},5e3)}),this.#Se=e,e}},SinglePageResource=class{observable;#O;#Ee;constructor(e){this.#Ee=e,this.#O=makeEventSource(),this.observable=this.#O.observable,autobind(this)}get(){const e=this.#Se;return null===e||"pending"===e.status?ASYNC_LOADING:"rejected"===e.status?{isLoading:!1,error:e.reason}:{isLoading:!1,data:void 0}}#Se=null;waitUntilLoaded(){if(this.#Se)return this.#Se;const e=usify(autoRetry(()=>this.#Ee(),5,[5e3,5e3,1e4,15e3]));return e.then(()=>this.#O.notify(),()=>{this.#O.notify(),setTimeout(()=>{this.#Se=null,this.#O.notify()},5e3)}),this.#Se=e,e}};function createStore_forNotifications(){const e=new MutableSignal(new Map);return{signal:e.asReadonly(),markAllRead:function(t){e.mutate(e=>{for(const n of e.values())n.readAt=t})},markRead:function(t,n){e.mutate(e=>{const o=e.get(t);return!!o&&(e.set(t,{...o,readAt:n}),!0)})},delete:function(t){e.mutate(e=>e.delete(t))},applyDelta:function(t,n){e.mutate(e=>{let o=!1;for(const n of t){const t=e.get(n.id);if(t){if(1===compareInboxNotifications(t,n))continue}e.set(n.id,n),o=!0}for(const t of n)e.delete(t.id),o=!0;return o})},clear:function(){e.mutate(e=>e.clear())},updateAssociatedNotification:function(t){e.mutate(e=>{const n=find(e.values(),e=>"thread"===e.kind&&e.threadId===t.threadId);return!!n&&(e.set(n.id,{...n,notifiedAt:t.createdAt,readAt:t.createdAt}),!0)})},force_set:t=>e.mutate(t),invalidate:()=>e.mutate()}}function createStore_forRoomNotificationSettings(){const e=new MutableSignal(new Map);return{signal:e.asReadonly(),update:function(t,n){e.mutate(e=>{e.set(t,n)})},invalidate:()=>e.mutate()}}function createStore_forHistoryVersions(){const e=new MutableSignal(new Map);return{signal:e.asReadonly(),update:function(t,n){e.mutate(e=>{const o=e.get(t)??(e.set(t,new Map),e.get(t));for(const e of n)o.set(e.id,e)})},force_set:t=>e.mutate(t),invalidate:()=>e.mutate()}}function createStore_forPermissionHints(){const e=new Signal({});return{signal:e.asReadonly(),update:function(t){e.set(e=>{const n={...e};for(const[e,o]of Object.entries(t)){const t=n[e]??new Set;for(const e of o)t.add(e);n[e]=t}return n})},invalidate:()=>e.set(e=>({...e}))}}function createStore_forOptimistic(e){const t=new Signal([]),n=e[kInternal].createSyncSource();return t.subscribe(()=>n.setSyncStatus(t.get().length>0?"synchronizing":"synchronized")),{signal:t.asReadonly(),add:function(e){const n=nanoid(),o={...e,id:n};return t.set(e=>[...e,o]),n},remove:function(e){t.set(t=>t.filter(t=>t.id!==e))},invalidate:()=>t.set(e=>[...e])}}var UmbrellaStore=class{#De;threads;notifications;roomNotificationSettings;historyVersions;permissionHints;optimisticUpdates;outputs;#Te=null;#Ae;#Oe=new Map;#Ie=new Map;#ke=null;#Ne=new Map;#je=new Map;#$e=new Map;#Fe=new Map;constructor(e){this.#De=e[kInternal].as(),this.optimisticUpdates=createStore_forOptimistic(this.#De),this.permissionHints=createStore_forPermissionHints();this.#Ae=new PaginatedResource(async e=>{const t=await this.#De.getInboxNotifications({cursor:e});this.updateThreadifications(t.threads,t.inboxNotifications),null===this.#Te&&(this.#Te=t.requestedAt);return t.nextCursor}),this.#Ae.observable.subscribe(()=>this.invalidateEntireStore()),this.threads=new ThreadDB,this.notifications=createStore_forNotifications(),this.roomNotificationSettings=createStore_forRoomNotificationSettings(),this.historyVersions=createStore_forHistoryVersions();const t=DerivedSignal.from(this.threads.signal,this.notifications.signal,this.optimisticUpdates.signal,(e,t,n)=>applyOptimisticUpdates_forThreadifications(e,t,n)),n=DerivedSignal.from(t,e=>({threadsDB:e.threadsDB}),shallow),o=DerivedSignal.from(t,e=>({sortedNotifications:e.sortedNotifications,notificationsById:e.notificationsById}),shallow),r=DerivedSignal.from(this.roomNotificationSettings.signal,this.optimisticUpdates.signal,(e,t)=>applyOptimisticUpdates_forSettings(e,t)),a=DerivedSignal.from(this.historyVersions.signal,e=>Object.fromEntries([...e].map(([e,t])=>[e,Object.fromEntries(t)])));this.outputs={threadifications:t,threads:n,notifications:o,settingsByRoomId:r,versionsByRoomId:a},autobind(this)}get1_both(){return this.outputs.threadifications.get()}subscribe1_both(e){return this.outputs.threadifications.subscribe(e)}get1_threads(){return this.outputs.threads.get()}subscribe1_threads(e){return this.outputs.threads.subscribe(e)}get1_notifications(){return this.outputs.notifications.get()}subscribe1_notifications(e){return this.outputs.notifications.subscribe(e)}get2(){return this.outputs.settingsByRoomId.get()}subscribe2(e){return this.outputs.settingsByRoomId.subscribe(e)}get3(){return this.outputs.versionsByRoomId.get()}subscribe3(e){return this.outputs.versionsByRoomId.subscribe(e)}getRoomThreadsLoadingState(e,t){const n=makeRoomThreadsQueryKey(e,t),o=this.#Ie.get(n);if(void 0===o)return ASYNC_LOADING;const r=o.get();if(r.isLoading||r.error)return r;const a=this.get1_threads().threadsDB.findMany(e,t??{},"asc"),i=r.data;return{isLoading:!1,threads:a,hasFetchedAll:i.hasFetchedAll,isFetchingMore:i.isFetchingMore,fetchMoreError:i.fetchMoreError,fetchMore:i.fetchMore}}getUserThreadsLoadingState(e){const t=makeUserThreadsQueryKey(e),n=this.#Ne.get(t);if(void 0===n)return ASYNC_LOADING;const o=n.get();if(o.isLoading||o.error)return o;const r=this.get1_threads().threadsDB.findMany(void 0,e??{},"desc"),a=o.data;return{isLoading:!1,threads:r,hasFetchedAll:a.hasFetchedAll,isFetchingMore:a.isFetchingMore,fetchMoreError:a.fetchMoreError,fetchMore:a.fetchMore}}getInboxNotificationsLoadingState(){const e=this.#Ae.get();if(e.isLoading||e.error)return e;const t=e.data;return{isLoading:!1,inboxNotifications:this.get1_notifications().sortedNotifications,hasFetchedAll:t.hasFetchedAll,isFetchingMore:t.isFetchingMore,fetchMoreError:t.fetchMoreError,fetchMore:t.fetchMore}}getNotificationSettingsLoadingState(e){const t=makeNotificationSettingsQueryKey(e),n=this.#Fe.get(t);if(void 0===n)return ASYNC_LOADING;const o=n.get();return o.isLoading||o.error?o:{isLoading:!1,settings:nn(this.get2()[e])}}getRoomVersionsLoadingState(e){const t=makeVersionsQueryKey(e),n=this.#je.get(t);if(void 0===n)return ASYNC_LOADING;const o=n.get();return o.isLoading||o.error?o:{isLoading:!1,versions:Object.values(this.get3()[e]??{})}}force_set_versions(e){batch(()=>{this.historyVersions.force_set(e),this.invalidateEntireStore()})}force_set_notifications(e){batch(()=>{this.notifications.force_set(e),this.invalidateEntireStore()})}markInboxNotificationRead(e,t,n){batch(()=>{this.optimisticUpdates.remove(n),this.notifications.markRead(e,t)})}markAllInboxNotificationsRead(e,t){batch(()=>{this.optimisticUpdates.remove(e),this.notifications.markAllRead(t)})}deleteInboxNotification(e,t){batch(()=>{this.optimisticUpdates.remove(t),this.notifications.delete(e)})}deleteAllInboxNotifications(e){batch(()=>{this.optimisticUpdates.remove(e),this.notifications.clear()})}createThread(e,t){batch(()=>{this.optimisticUpdates.remove(e),this.threads.upsert(t)})}#Pe(e,t,n,o){batch(()=>{null!==t&&this.optimisticUpdates.remove(t);const r=this.threads,a=r.get(e);a&&(o&&a.updatedAt>o||r.upsert(n(a)))})}patchThread(e,t,n,o){return this.#Pe(e,t,e=>({...e,...compactObject(n)}),o)}addReaction(e,t,n,o,r){this.#Pe(e,t,e=>applyAddReaction(e,n,o),r)}removeReaction(e,t,n,o,r,a){this.#Pe(e,t,e=>applyRemoveReaction(e,n,o,r,a),a)}deleteThread(e,t){return this.#Pe(e,t,e=>({...e,updatedAt:new Date,deletedAt:new Date}))}createComment(e,t){batch(()=>{this.optimisticUpdates.remove(t);const n=this.threads.get(e.threadId);n&&(this.threads.upsert(applyUpsertComment(n,e)),this.notifications.updateAssociatedNotification(e))})}editComment(e,t,n){return this.#Pe(e,t,e=>applyUpsertComment(e,n))}deleteComment(e,t,n,o){return this.#Pe(e,t,e=>applyDeleteComment(e,n,o),o)}updateThreadifications(e,t,n=[],o=[]){batch(()=>{this.threads.applyDelta({newThreads:e,deletedThreads:n}),this.notifications.applyDelta(t,o)})}updateRoomNotificationSettings(e,t,n){batch(()=>{this.optimisticUpdates.remove(t),this.roomNotificationSettings.update(e,n)})}async fetchNotificationsDeltaUpdate(e){const t=this.#Te;if(null===t)return;const n=await this.#De.getInboxNotificationsSince({since:t,signal:e});t<n.requestedAt&&(this.#Te=n.requestedAt),this.updateThreadifications(n.threads.updated,n.inboxNotifications.updated,n.threads.deleted,n.inboxNotifications.deleted)}waitUntilNotificationsLoaded(){return this.#Ae.waitUntilLoaded()}waitUntilRoomThreadsLoaded(e,t){const n=async n=>{const o=await this.#De[kInternal].httpClient.getThreads({roomId:e,cursor:n,query:t});this.updateThreadifications(o.threads,o.inboxNotifications),this.permissionHints.update(o.permissionHints);const r=this.#Oe.get(e);return(void 0===r||r>o.requestedAt)&&this.#Oe.set(e,o.requestedAt),o.nextCursor},o=makeRoomThreadsQueryKey(e,t);let r=this.#Ie.get(o);return void 0===r&&(r=new PaginatedResource(n)),r.observable.subscribe(()=>this.invalidateEntireStore()),this.#Ie.set(o,r),r.waitUntilLoaded()}async fetchRoomThreadsDeltaUpdate(e,t){const n=this.#Oe.get(e);if(void 0===n)return;const o=await this.#De[kInternal].httpClient.getThreadsSince({roomId:e,since:n,signal:t});this.updateThreadifications(o.threads.updated,o.inboxNotifications.updated,o.threads.deleted,o.inboxNotifications.deleted),this.permissionHints.update(o.permissionHints),n<o.requestedAt&&this.#Oe.set(e,o.requestedAt)}waitUntilUserThreadsLoaded(e){const t=makeUserThreadsQueryKey(e),n=async t=>{const n=await this.#De[kInternal].httpClient.getUserThreads_experimental({cursor:t,query:e});return this.updateThreadifications(n.threads,n.inboxNotifications),this.permissionHints.update(n.permissionHints),null===this.#ke&&(this.#ke=n.requestedAt),n.nextCursor};let o=this.#Ne.get(t);return void 0===o&&(o=new PaginatedResource(n)),o.observable.subscribe(()=>this.invalidateEntireStore()),this.#Ne.set(t,o),o.waitUntilLoaded()}invalidateEntireStore(){batch(()=>{this.historyVersions.invalidate(),this.notifications.invalidate(),this.optimisticUpdates.invalidate(),this.permissionHints.invalidate(),this.roomNotificationSettings.invalidate()})}async fetchUserThreadsDeltaUpdate(e){const t=this.#ke;if(null===t)return;const n=await this.#De[kInternal].httpClient.getUserThreadsSince_experimental({since:t,signal:e});t<n.requestedAt&&(this.#Te=n.requestedAt),this.updateThreadifications(n.threads.updated,n.inboxNotifications.updated,n.threads.deleted,n.inboxNotifications.deleted),this.permissionHints.update(n.permissionHints)}waitUntilRoomVersionsLoaded(e){const t=makeVersionsQueryKey(e);let n=this.#je.get(t);if(void 0===n){n=new SinglePageResource(async()=>{const t=this.#De.getRoom(e);if(null===t)throw new HttpError(`Room '${e}' is not available on client`,479);const n=await t[kInternal].listTextVersions();this.historyVersions.update(e,n.versions);const o=this.#$e.get(e);(void 0===o||o>n.requestedAt)&&this.#$e.set(e,n.requestedAt)})}return n.observable.subscribe(()=>this.invalidateEntireStore()),this.#je.set(t,n),n.waitUntilLoaded()}async fetchRoomVersionsDeltaUpdate(e,t){const n=this.#$e.get(e);if(void 0===n)return;const o=nn(this.#De.getRoom(e),`Room with id ${e} is not available on client`),r=await o[kInternal].listTextVersionsSince({since:n,signal:t});this.historyVersions.update(e,r.versions),n<r.requestedAt&&this.#$e.set(e,r.requestedAt)}waitUntilRoomNotificationSettingsLoaded(e){const t=makeNotificationSettingsQueryKey(e);let n=this.#Fe.get(t);if(void 0===n){n=new SinglePageResource(async()=>{const t=this.#De.getRoom(e);if(null===t)throw new HttpError(`Room '${e}' is not available on client`,479);const n=await t.getNotificationSettings();this.roomNotificationSettings.update(e,n)})}return n.observable.subscribe(()=>this.invalidateEntireStore()),this.#Fe.set(t,n),n.waitUntilLoaded()}async refreshRoomNotificationSettings(e,t){const n=nn(this.#De.getRoom(e),`Room with id ${e} is not available on client`),o=await n.getNotificationSettings({signal:t});this.roomNotificationSettings.update(e,o)}};function applyOptimisticUpdates_forThreadifications(e,t,n){const o=e.clone();let r=Object.fromEntries(t);for(const e of n)switch(e.type){case"create-thread":o.upsert(e.thread);break;case"edit-thread-metadata":{const t=o.get(e.threadId);if(void 0===t)break;if(t.updatedAt>e.updatedAt)break;o.upsert({...t,updatedAt:e.updatedAt,metadata:{...t.metadata,...e.metadata}});break}case"mark-thread-as-resolved":{const t=o.get(e.threadId);if(void 0===t)break;o.upsert({...t,resolved:!0});break}case"mark-thread-as-unresolved":{const t=o.get(e.threadId);if(void 0===t)break;o.upsert({...t,resolved:!1});break}case"create-comment":{const t=o.get(e.comment.threadId);if(void 0===t)break;o.upsert(applyUpsertComment(t,e.comment));const n=Object.values(r).find(e=>"thread"===e.kind&&e.threadId===t.id);if(void 0===n)break;r[n.id]={...n,notifiedAt:e.comment.createdAt,readAt:e.comment.createdAt};break}case"edit-comment":{const t=o.get(e.comment.threadId);if(void 0===t)break;o.upsert(applyUpsertComment(t,e.comment));break}case"delete-comment":{const t=o.get(e.threadId);if(void 0===t)break;o.upsert(applyDeleteComment(t,e.commentId,e.deletedAt));break}case"delete-thread":{const t=o.get(e.threadId);if(void 0===t)break;o.upsert({...t,deletedAt:e.deletedAt,updatedAt:e.deletedAt,comments:[]});break}case"add-reaction":{const t=o.get(e.threadId);if(void 0===t)break;o.upsert(applyAddReaction(t,e.commentId,e.reaction));break}case"remove-reaction":{const t=o.get(e.threadId);if(void 0===t)break;o.upsert(applyRemoveReaction(t,e.commentId,e.emoji,e.userId,e.removedAt));break}case"mark-inbox-notification-as-read":{const t=r[e.inboxNotificationId];if(void 0===t)break;r[e.inboxNotificationId]={...t,readAt:e.readAt};break}case"mark-all-inbox-notifications-as-read":for(const t in r){const n=r[t];if(void 0===n)break;r[t]={...n,readAt:e.readAt}}break;case"delete-inbox-notification":delete r[e.inboxNotificationId];break;case"delete-all-inbox-notifications":r={}}return{sortedNotifications:Object.values(r).filter(e=>"thread"!==e.kind||void 0!==o.get(e.threadId)).sort((e,t)=>t.notifiedAt.getTime()-e.notifiedAt.getTime()),notificationsById:r,threadsDB:o}}function applyOptimisticUpdates_forSettings(e,t){const n=Object.fromEntries(e);for(const e of t)switch(e.type){case"update-notification-settings":{const t=n[e.roomId];if(void 0===t)break;n[e.roomId]={...t,...e.settings}}}return n}function compareInboxNotifications(e,t){return e.notifiedAt>t.notifiedAt?1:e.notifiedAt<t.notifiedAt?-1:e.readAt&&t.readAt?e.readAt>t.readAt?1:e.readAt<t.readAt?-1:0:e.readAt||t.readAt?e.readAt?1:-1:0}function applyUpsertComment(e,t){if(void 0!==e.deletedAt)return e;if(t.threadId!==e.id)return fancy_console_exports.warn(`Comment ${t.id} does not belong to thread ${e.id}`),e;const n=e.comments.find(e=>e.id===t.id);if(void 0===n){const n=new Date(Math.max(e.updatedAt.getTime(),t.createdAt.getTime()));return{...e,updatedAt:n,comments:[...e.comments,t]}}if(void 0!==n.deletedAt)return e;if(void 0===n.editedAt||void 0===t.editedAt||n.editedAt<=t.editedAt){const n=e.comments.map(e=>e.id===t.id?t:e);return{...e,updatedAt:new Date(Math.max(e.updatedAt.getTime(),t.editedAt?.getTime()||t.createdAt.getTime())),comments:n}}return e}function applyDeleteComment(e,t,n){if(void 0!==e.deletedAt)return e;const o=e.comments.find(e=>e.id===t);if(void 0===o)return e;if(void 0!==o.deletedAt)return e;const r=e.comments.map(e=>e.id===t?{...e,deletedAt:n,body:void 0,attachments:[]}:e);return r.every(e=>void 0!==e.deletedAt)?{...e,deletedAt:n,updatedAt:n}:{...e,updatedAt:n,comments:r}}function applyAddReaction(e,t,n){if(void 0!==e.deletedAt)return e;const o=e.comments.find(e=>e.id===t);if(void 0===o)return e;if(void 0!==o.deletedAt)return e;const r=e.comments.map(e=>e.id===t?{...e,reactions:upsertReaction(e.reactions,n)}:e);return{...e,updatedAt:new Date(Math.max(n.createdAt.getTime(),e.updatedAt.getTime())),comments:r}}function applyRemoveReaction(e,t,n,o,r){if(void 0!==e.deletedAt)return e;const a=e.comments.find(e=>e.id===t);if(void 0===a)return e;if(void 0!==a.deletedAt)return e;const i=e.comments.map(e=>e.id===t?{...e,reactions:e.reactions.map(e=>e.emoji===n?{...e,users:e.users.filter(e=>e.id!==o)}:e).filter(e=>e.users.length>0)}:e);return{...e,updatedAt:new Date(Math.max(r.getTime(),e.updatedAt.getTime())),comments:i}}function upsertReaction(e,t){const n=e.find(e=>e.emoji===t.emoji);return void 0===n?[...e,{emoji:t.emoji,createdAt:t.createdAt,users:[{id:t.userId}]}]:!1===n.users.some(e=>e.id===t.userId)?e.map(e=>e.emoji===t.emoji?{...e,users:[...e.users,{id:t.userId}]}:e):e}var ClientContext=React.createContext(null);function missingUserError(e){return new Error(`resolveUsers didn't return anything for user '${e}'`)}function missingRoomInfoError(e){return new Error(`resolveRoomsInfo didn't return anything for room '${e}'`)}function identity(e){return e}var _umbrellaStores=new WeakMap,_extras=new WeakMap;function selectUnreadInboxNotificationsCount(e){let t=0;for(const n of e)(null===n.readAt||n.readAt<n.notifiedAt)&&t++;return t}function selectorFor_useUnreadInboxNotificationsCount(e){return e.inboxNotifications?{isLoading:!1,count:selectUnreadInboxNotificationsCount(e.inboxNotifications)}:e}function selectorFor_useUser(e,t){return void 0===e||e?.isLoading?e??{isLoading:!0}:e.error?e:e.data?{isLoading:!1,user:e.data}:{isLoading:!1,error:missingUserError(t)}}function selectorFor_useRoomInfo(e,t){return void 0===e||e?.isLoading?e??{isLoading:!0}:e.error?e:e.data?{isLoading:!1,info:e.data}:{isLoading:!1,error:missingRoomInfoError(t)}}function getUmbrellaStoreForClient(e){let t=_umbrellaStores.get(e);return t||(t=new UmbrellaStore(e),_umbrellaStores.set(e,t)),t}function getLiveblocksExtrasForClient(e){let t=_extras.get(e);return t||(t=makeLiveblocksExtrasForClient(e),_extras.set(e,t)),t}function makeLiveblocksExtrasForClient(e){const t=getUmbrellaStoreForClient(e),n=makePoller(async e=>{try{return await t.fetchNotificationsDeltaUpdate(e)}catch(e){throw console.warn(`Polling new inbox notifications failed: ${String(e)}`),e}},config$1.NOTIFICATIONS_POLL_INTERVAL,{maxStaleTimeMs:config$1.NOTIFICATIONS_MAX_STALE_TIME}),o=makePoller(async e=>{try{return await t.fetchUserThreadsDeltaUpdate(e)}catch(e){throw console.warn(`Polling new user threads failed: ${String(e)}`),e}},config$1.USER_THREADS_POLL_INTERVAL,{maxStaleTimeMs:config$1.USER_THREADS_MAX_STALE_TIME});return{store:t,notificationsPoller:n,userThreadsPoller:o}}function useInboxNotifications_withClient(e,t,n){const{store:o,notificationsPoller:r}=getLiveblocksExtrasForClient(e);return React.useEffect(()=>{o.waitUntilNotificationsLoaded()}),React.useEffect(()=>(r.inc(),r.pollNowIfStale(),()=>{r.dec()}),[r]),useSyncExternalStoreWithSelector(o.subscribe1_notifications,o.getInboxNotificationsLoadingState,o.getInboxNotificationsLoadingState,t,n)}function useInboxNotificationsSuspense_withClient(e){const t=getLiveblocksExtrasForClient(e).store;use(t.waitUntilNotificationsLoaded());const n=useInboxNotifications_withClient(e,identity,shallow);return assert(!n.error),assert(!n.isLoading),n}function useUnreadInboxNotificationsCount_withClient(e){return useInboxNotifications_withClient(e,selectorFor_useUnreadInboxNotificationsCount,shallow)}function useUnreadInboxNotificationsCountSuspense_withClient(e){const t=getLiveblocksExtrasForClient(e).store;use(t.waitUntilNotificationsLoaded());const n=useUnreadInboxNotificationsCount_withClient(e);return assert(!n.isLoading),assert(!n.error),n}function useMarkInboxNotificationAsRead_withClient(e){return React.useCallback(t=>{const{store:n}=getLiveblocksExtrasForClient(e),o=new Date,r=n.optimisticUpdates.add({type:"mark-inbox-notification-as-read",inboxNotificationId:t,readAt:o});e.markInboxNotificationAsRead(t).then(()=>{n.markInboxNotificationRead(t,o,r)},()=>{n.optimisticUpdates.remove(r)})},[e])}function useMarkAllInboxNotificationsAsRead_withClient(e){return React.useCallback(()=>{const{store:t}=getLiveblocksExtrasForClient(e),n=new Date,o=t.optimisticUpdates.add({type:"mark-all-inbox-notifications-as-read",readAt:n});e.markAllInboxNotificationsAsRead().then(()=>{t.markAllInboxNotificationsRead(o,n)},()=>{t.optimisticUpdates.remove(o)})},[e])}function useDeleteInboxNotification_withClient(e){return React.useCallback(t=>{const{store:n}=getLiveblocksExtrasForClient(e),o=new Date,r=n.optimisticUpdates.add({type:"delete-inbox-notification",inboxNotificationId:t,deletedAt:o});e.deleteInboxNotification(t).then(()=>{n.deleteInboxNotification(t,r)},()=>{n.optimisticUpdates.remove(r)})},[e])}function useDeleteAllInboxNotifications_withClient(e){return React.useCallback(()=>{const{store:t}=getLiveblocksExtrasForClient(e),n=new Date,o=t.optimisticUpdates.add({type:"delete-all-inbox-notifications",deletedAt:n});e.deleteAllInboxNotifications().then(()=>{t.deleteAllInboxNotifications(o)},()=>{t.optimisticUpdates.remove(o)})},[e])}function useInboxNotificationThread_withClient(e,t){const{store:n}=getLiveblocksExtrasForClient(e),o=n.get1_both,r=React.useCallback(e=>{const n=e.notificationsById[t]??raise(`Inbox notification with ID "${t}" not found`);"thread"!==n.kind&&raise(`Inbox notification with ID "${t}" is not of kind "thread"`);return e.threadsDB.get(n.threadId)??raise(`Thread with ID "${n.threadId}" not found, this inbox notification might not be of kind "thread"`)},[t]);return useSyncExternalStoreWithSelector(n.subscribe1_both,o,o,r)}function useUser_withClient(e,t){const n=e[kInternal].usersStore,o=React.useCallback(()=>n.getState(t),[n,t]),r=React.useCallback(e=>selectorFor_useUser(e,t),[t]),a=useSyncExternalStoreWithSelector(n.subscribe,o,o,r,shallow);return React.useEffect(()=>{n.get(t)},[n,t,a]),a}function useRoomInfo_withClient(e,t){const n=e[kInternal].roomsInfoStore,o=React.useCallback(()=>n.getState(t),[n,t]),r=React.useCallback(e=>selectorFor_useRoomInfo(e,t),[t]),a=useSyncExternalStoreWithSelector(n.subscribe,o,o,r,shallow);return React.useEffect(()=>{n.get(t)},[n,t,a]),a}function useEnsureNoLiveblocksProvider(e){const t=useClientOrNull();if(!e?.allowNesting&&null!==t)throw new Error("You cannot nest multiple LiveblocksProvider instances in the same React tree.")}function useClientOrNull(){return React.useContext(ClientContext)}function useClient(){return useClientOrNull()??raise("LiveblocksProvider is missing from the React tree.")}function LiveblocksProviderWithClient(e){return useEnsureNoLiveblocksProvider(e),jsxRuntime.exports.jsx(ClientContext.Provider,{value:e.client,children:e.children})}function LiveblocksProvider(e){const{children:t,...n}=e,o={publicApiKey:useInitial$1(n.publicApiKey),throttle:useInitial$1(n.throttle),lostConnectionTimeout:useInitial$1(n.lostConnectionTimeout),backgroundKeepAliveTimeout:useInitial$1(n.backgroundKeepAliveTimeout),polyfills:useInitial$1(n.polyfills),unstable_fallbackToHTTP:useInitial$1(n.unstable_fallbackToHTTP),unstable_streamData:useInitial$1(n.unstable_streamData),preventUnsavedChanges:useInitial$1(n.preventUnsavedChanges),authEndpoint:useInitialUnlessFunction(n.authEndpoint),resolveMentionSuggestions:useInitialUnlessFunction(n.resolveMentionSuggestions),resolveUsers:useInitialUnlessFunction(n.resolveUsers),resolveRoomsInfo:useInitialUnlessFunction(n.resolveRoomsInfo),baseUrl:useInitial$1(n.baseUrl),enableDebugLogging:useInitial$1(n.enableDebugLogging)},r=React.useMemo(()=>createClient(o),[]);return jsxRuntime.exports.jsx(LiveblocksProviderWithClient,{client:r,children:t})}function useInboxNotificationsSuspense(){return useInboxNotificationsSuspense_withClient(useClient())}function useInboxNotificationThread(e){return useInboxNotificationThread_withClient(useClient(),e)}function useMarkAllInboxNotificationsAsRead(){return useMarkAllInboxNotificationsAsRead_withClient(useClient())}function useMarkInboxNotificationAsRead(){return useMarkInboxNotificationAsRead_withClient(useClient())}function useDeleteAllInboxNotifications(){return useDeleteAllInboxNotifications_withClient(useClient())}function useDeleteInboxNotification(){return useDeleteInboxNotification_withClient(useClient())}function useUnreadInboxNotificationsCountSuspense(){return useUnreadInboxNotificationsCountSuspense_withClient(useClient())}function useUser(e){return useUser_withClient(useClient(),e)}function useRoomInfo(e){return useRoomInfo_withClient(useClient(),e)}var _useInboxNotificationThread=useInboxNotificationThread,_useUser=useUser,CreateThreadError=class extends Error{constructor(e,t){super("Create thread failed."),this.cause=e,this.context=t,this.name="CreateThreadError"}},MarkThreadAsResolvedError=class extends Error{constructor(e,t){super("Mark thread as resolved failed."),this.cause=e,this.context=t,this.name="MarkThreadAsResolvedError"}},MarkThreadAsUnresolvedError=class extends Error{constructor(e,t){super("Mark thread as unresolved failed."),this.cause=e,this.context=t,this.name="MarkThreadAsUnresolvedError"}},CreateCommentError=class extends Error{constructor(e,t){super("Create comment failed."),this.cause=e,this.context=t,this.name="CreateCommentError"}},EditCommentError=class extends Error{constructor(e,t){super("Edit comment failed."),this.cause=e,this.context=t,this.name="EditCommentError"}},DeleteCommentError=class extends Error{constructor(e,t){super("Delete comment failed."),this.cause=e,this.context=t,this.name="DeleteCommentError"}},AddReactionError=class extends Error{constructor(e,t){super("Add reaction failed."),this.cause=e,this.context=t,this.name="AddReactionError"}},RemoveReactionError=class extends Error{constructor(e,t){super("Remove reaction failed."),this.cause=e,this.context=t,this.name="RemoveReactionError"}},MarkInboxNotificationAsReadError=class extends Error{constructor(e,t){super("Mark inbox notification as read failed."),this.cause=e,this.context=t,this.name="MarkInboxNotificationAsReadError"}},identity2=e=>e;function useSignal(e,t,n){return useSyncExternalStoreWithSelector(e.subscribe,e.get,e.get,t??identity2,n)}function handleScrollToCommentOnLoad(e,t){if(!1===e)return;if(!t.threads)return;if(!("undefined"!=typeof window))return;const n=window.location.hash.slice(1);if(!n.startsWith("cm_"))return;const o=document.getElementById(n);if(null===o)return;t.threads.flatMap(e=>e.comments).some(e=>e.id===n)&&o.scrollIntoView()}function useScrollToCommentOnLoadEffect(e,t){React.useEffect(()=>{handleScrollToCommentOnLoad(e,t)},[t.isLoading])}var identity3=e=>e;function getCurrentUserId(e){const t=e[kInternal].currentUserId.get();return void 0===t?"anonymous":t}function handleApiError(e){const t=`Request failed with status ${e.status}: ${e.message}`;if("FORBIDDEN"===e.details?.error){const n=[t,e.details.suggestion,e.details.docs].filter(Boolean).join("\n");fancy_console_exports.error(n)}return new Error(t)}Object.freeze([]);var _extras2=new WeakMap;function getRoomExtrasForClient(e){let t=_extras2.get(e);return t||(t=makeRoomExtrasForClient(e),_extras2.set(e,t)),t}function makeRoomExtrasForClient(e){const t=getUmbrellaStoreForClient(e),n=makeEventSource();const o=new Map,r=new Map,a=new Map;return{store:t,commentsErrorEventSource:n.observable,onMutationFailure:function(e,o,r){if(t.optimisticUpdates.remove(o),e instanceof HttpError){const t=handleApiError(e);return void n.notify(r(t))}if(!(e instanceof HttpError))throw e;handleApiError(e)},getOrCreateThreadsPollerForRoomId:function(e){let n=o.get(e);return n||(n=makePoller(async n=>{try{return await t.fetchRoomThreadsDeltaUpdate(e,n)}catch(t){throw fancy_console_exports.warn(`Polling new threads for '${e}' failed: ${String(t)}`),t}},config$1.ROOM_THREADS_POLL_INTERVAL,{maxStaleTimeMs:config$1.ROOM_THREADS_MAX_STALE_TIME}),o.set(e,n)),n},getOrCreateVersionsPollerForRoomId:function(e){let n=r.get(e);return n||(n=makePoller(async n=>{try{return await t.fetchRoomVersionsDeltaUpdate(e,n)}catch(t){throw fancy_console_exports.warn(`Polling new history versions for '${e}' failed: ${String(t)}`),t}},config$1.HISTORY_VERSIONS_POLL_INTERVAL,{maxStaleTimeMs:config$1.HISTORY_VERSIONS_MAX_STALE_TIME}),r.set(e,n)),n},getOrCreateNotificationsSettingsPollerForRoomId:function(e){let n=a.get(e);return n||(n=makePoller(async n=>{try{return await t.refreshRoomNotificationSettings(e,n)}catch(t){throw fancy_console_exports.warn(`Polling notification settings for '${e}' failed: ${String(t)}`),t}},config$1.NOTIFICATION_SETTINGS_POLL_INTERVAL,{maxStaleTimeMs:config$1.NOTIFICATION_SETTINGS_MAX_STALE_TIME}),a.set(e,n)),n}}}function RoomProvider(e){const t=useClient(),[n]=React.useState(()=>new Map),o=React.useCallback((e,o)=>{const r=n.get(e);if(r)return r;const a=t.enterRoom(e,o),i=a.leave;return a.leave=()=>{i(),n.delete(e)},n.set(e,a),a},[t,n]);return jsxRuntime.exports.jsx(RoomProviderInner,{...e,stableEnterRoom:o})}function RoomProviderInner(e){const t=useClient(),{id:n,stableEnterRoom:o}=e,r=useInitial$1({initialPresence:e.initialPresence,initialStorage:e.initialStorage,autoConnect:e.autoConnect??"undefined"!=typeof window}),[{room:a},i]=React.useState(()=>o(n,{...r,autoConnect:!1}));return React.useEffect(()=>{const{store:e}=getRoomExtrasForClient(t);return a.events.comments.subscribe(t=>{!async function(t){if(t.type===ServerMsgCode.THREAD_DELETED)return void e.deleteThread(t.threadId,null);const n=await a.getThread(t.threadId);if(!n.thread)return void e.deleteThread(t.threadId,null);const{thread:o,inboxNotification:r}=n,i=e.get1_threads().threadsDB.getEvenIfDeleted(t.threadId);switch(t.type){case ServerMsgCode.COMMENT_EDITED:case ServerMsgCode.THREAD_METADATA_UPDATED:case ServerMsgCode.THREAD_UPDATED:case ServerMsgCode.COMMENT_REACTION_ADDED:case ServerMsgCode.COMMENT_REACTION_REMOVED:case ServerMsgCode.COMMENT_DELETED:if(!i)break;e.updateThreadifications([o],r?[r]:[]);break;case ServerMsgCode.COMMENT_CREATED:e.updateThreadifications([o],r?[r]:[])}}(t)})},[t,a]),React.useEffect(()=>{const e=o(n,r);i(e);const{room:t,leave:a}=e;return r.autoConnect&&t.connect(),()=>{a()}},[n,r,o]),jsxRuntime.exports.jsx(RoomContext.Provider,{value:a,children:e.children})}function useRoom(){const e=useRoomOrNull();if(null===e)throw new Error("RoomProvider is missing from the React tree.");return e}function useResolveMentionSuggestions(){return useClient()[kInternal].resolveMentionSuggestions}function useMentionSuggestionsCache(){return useClient()[kInternal].mentionSuggestionsCache}function useThreads(e={query:{metadata:{}}}){const{scrollOnLoad:t=!0}=e,n=useClient(),o=useRoom(),{store:r,getOrCreateThreadsPollerForRoomId:a}=getRoomExtrasForClient(n),i=a(o.id);React.useEffect(()=>{r.waitUntilRoomThreadsLoaded(o.id,e.query)}),React.useEffect(()=>(i.inc(),i.pollNowIfStale(),()=>i.dec()),[i]);const s=React.useCallback(()=>r.getRoomThreadsLoadingState(o.id,e.query),[r,o.id,e.query]),l=useSyncExternalStoreWithSelector(r.subscribe1_threads,s,s,identity3,shallow2);return useScrollToCommentOnLoadEffect(t,l),l}function useCreateRoomThread(e){const t=useClient();return React.useCallback(n=>{const o=n.body,r=n.metadata??{},a=n.attachments,i=createThreadId(),s=createCommentId(),l=new Date,c={id:s,threadId:i,roomId:e,createdAt:l,type:"comment",userId:getCurrentUserId(t),body:o,reactions:[],attachments:a??[]},d={id:i,type:"thread",createdAt:l,updatedAt:l,roomId:e,metadata:r,comments:[c],resolved:!1},{store:u,onMutationFailure:f}=getRoomExtrasForClient(t),p=u.optimisticUpdates.add({type:"create-thread",thread:d,roomId:e}),_=a?.map(e=>e.id);return t[kInternal].httpClient.createThread({roomId:e,threadId:i,commentId:s,body:o,metadata:r,attachmentIds:_}).then(e=>{u.createThread(p,e)},t=>f(t,p,t=>new CreateThreadError(t,{roomId:e,threadId:i,commentId:s,body:o,metadata:r}))),d},[t,e])}function useCreateRoomComment(e){const t=useClient();return React.useCallback(({threadId:n,body:o,attachments:r})=>{const a=createCommentId(),i={id:a,threadId:n,roomId:e,type:"comment",createdAt:new Date,userId:getCurrentUserId(t),body:o,reactions:[],attachments:r??[]},{store:s,onMutationFailure:l}=getRoomExtrasForClient(t),c=s.optimisticUpdates.add({type:"create-comment",comment:i}),d=r?.map(e=>e.id);return t[kInternal].httpClient.createComment({roomId:e,threadId:n,commentId:a,body:o,attachmentIds:d}).then(e=>{s.createComment(e,c)},t=>l(t,c,t=>new CreateCommentError(t,{roomId:e,threadId:n,commentId:a,body:o}))),i},[t,e])}function useEditRoomComment(e){const t=useClient();return React.useCallback(({threadId:n,commentId:o,body:r,attachments:a})=>{const i=new Date,{store:s,onMutationFailure:l}=getRoomExtrasForClient(t),c=s.get1_threads().threadsDB.getEvenIfDeleted(n);if(void 0===c)return void fancy_console_exports.warn(`Internal unexpected behavior. Cannot edit comment in thread "${n}" because the thread does not exist in the cache.`);const d=c.comments.find(e=>e.id===o);if(void 0===d||void 0!==d.deletedAt)return void fancy_console_exports.warn(`Internal unexpected behavior. Cannot edit comment "${o}" in thread "${n}" because the comment does not exist in the cache.`);const u=s.optimisticUpdates.add({type:"edit-comment",comment:{...d,editedAt:i,body:r,attachments:a??[]}}),f=a?.map(e=>e.id);t[kInternal].httpClient.editComment({roomId:e,threadId:n,commentId:o,body:r,attachmentIds:f}).then(e=>{s.editComment(n,u,e)},t=>l(t,u,t=>new EditCommentError(t,{roomId:e,threadId:n,commentId:o,body:r})))},[t,e])}function useDeleteRoomComment(e){const t=useClient();return React.useCallback(({threadId:n,commentId:o})=>{const r=new Date,{store:a,onMutationFailure:i}=getRoomExtrasForClient(t),s=a.optimisticUpdates.add({type:"delete-comment",threadId:n,commentId:o,deletedAt:r,roomId:e});t[kInternal].httpClient.deleteComment({roomId:e,threadId:n,commentId:o}).then(()=>{a.deleteComment(n,s,o,r)},t=>i(t,s,t=>new DeleteCommentError(t,{roomId:e,threadId:n,commentId:o})))},[t,e])}function useAddRoomCommentReaction(e){const t=useClient();return React.useCallback(({threadId:n,commentId:o,emoji:r})=>{const a=new Date,i=getCurrentUserId(t),{store:s,onMutationFailure:l}=getRoomExtrasForClient(t),c=s.optimisticUpdates.add({type:"add-reaction",threadId:n,commentId:o,reaction:{emoji:r,userId:i,createdAt:a}});t[kInternal].httpClient.addReaction({roomId:e,threadId:n,commentId:o,emoji:r}).then(e=>{s.addReaction(n,c,o,e,a)},t=>l(t,c,t=>new AddReactionError(t,{roomId:e,threadId:n,commentId:o,emoji:r})))},[t,e])}function useRemoveRoomCommentReaction(e){const t=useClient();return React.useCallback(({threadId:n,commentId:o,emoji:r})=>{const a=getCurrentUserId(t),i=new Date,{store:s,onMutationFailure:l}=getRoomExtrasForClient(t),c=s.optimisticUpdates.add({type:"remove-reaction",threadId:n,commentId:o,emoji:r,userId:a,removedAt:i});t[kInternal].httpClient.removeReaction({roomId:e,threadId:n,commentId:o,emoji:r}).then(()=>{s.removeReaction(n,c,o,r,a,i)},t=>l(t,c,t=>new RemoveReactionError(t,{roomId:e,threadId:n,commentId:o,emoji:r})))},[t,e])}function useMarkRoomThreadAsRead(e){const t=useClient();return React.useCallback(n=>{const{store:o,onMutationFailure:r}=getRoomExtrasForClient(t),a=Object.values(o.get1_notifications().notificationsById).find(e=>"thread"===e.kind&&e.threadId===n);if(!a)return;const i=new Date,s=o.optimisticUpdates.add({type:"mark-inbox-notification-as-read",inboxNotificationId:a.id,readAt:i});t[kInternal].httpClient.markRoomInboxNotificationAsRead({roomId:e,inboxNotificationId:a.id}).then(()=>{o.markInboxNotificationRead(a.id,i,s)},e=>{r(e,s,e=>new MarkInboxNotificationAsReadError(e,{inboxNotificationId:a.id}))})},[t,e])}function useMarkRoomThreadAsResolved(e){const t=useClient();return React.useCallback(n=>{const o=new Date,{store:r,onMutationFailure:a}=getRoomExtrasForClient(t),i=r.optimisticUpdates.add({type:"mark-thread-as-resolved",threadId:n,updatedAt:o});t[kInternal].httpClient.markThreadAsResolved({roomId:e,threadId:n}).then(()=>{r.patchThread(n,i,{resolved:!0},o)},t=>a(t,i,t=>new MarkThreadAsResolvedError(t,{roomId:e,threadId:n})))},[t,e])}function useMarkRoomThreadAsUnresolved(e){const t=useClient();return React.useCallback(n=>{const o=new Date,{store:r,onMutationFailure:a}=getRoomExtrasForClient(t),i=r.optimisticUpdates.add({type:"mark-thread-as-unresolved",threadId:n,updatedAt:o});t[kInternal].httpClient.markThreadAsUnresolved({roomId:e,threadId:n}).then(()=>{r.patchThread(n,i,{resolved:!1},o)},t=>a(t,i,t=>new MarkThreadAsUnresolvedError(t,{roomId:e,threadId:n})))},[t,e])}function useThreadSubscription(e){const t=useClient(),{store:n}=getRoomExtrasForClient(t);return useSignal(n.outputs.threadifications,React.useCallback(t=>{const n=t.sortedNotifications.find(t=>"thread"===t.kind&&t.threadId===e),o=t.threadsDB.get(e);return void 0===n||void 0===o?{status:"not-subscribed"}:{status:"subscribed",unreadSince:n.readAt}},[e]),shallow)}function useThreadsSuspense(e={query:{metadata:{}}}){const t=useClient(),n=useRoom(),{store:o}=getRoomExtrasForClient(t);use(o.waitUntilRoomThreadsLoaded(n.id,e.query));const r=useThreads(e);return assert(!r.error),assert(!r.isLoading),r}function selectorFor_useAttachmentUrl(e){return void 0===e||e?.isLoading?e??{isLoading:!0}:e.error?e:(assert(void 0!==e.data),{isLoading:!1,url:e.data})}function useRoomAttachmentUrl(e,t){const n=useClient()[kInternal].httpClient.getOrCreateAttachmentUrlsStore(t),o=React.useCallback(()=>n.getState(e),[n,e]);return React.useEffect(()=>{n.get(e)},[n,e]),useSyncExternalStoreWithSelector(n.subscribe,o,o,selectorFor_useAttachmentUrl,shallow)}function useRoomPermissions(e){return useSignal(getRoomExtrasForClient(useClient()).store.permissionHints.signal,t=>t[e]??new Set)}var _RoomProvider=RoomProvider,_useThreadsSuspense=useThreadsSuspense,MENTION_SUGGESTIONS_DEBOUNCE=500;function useMentionSuggestions(e,t){const[n,o]=React.useState(),r=React.useRef(),a=useResolveMentionSuggestions(),i=useMentionSuggestionsCache();return React.useEffect(()=>{if(void 0===t||!a)return;const n={text:t,roomId:e},s=stringify(n);let l,c=!1;const d=async()=>{try{r.current=performance.now();const e=await a(n);c||(o(e),i.set(s,e))}catch(e){console.error(e?.message)}};return i.has(s)?o(i.get(s)):!r.current||Math.abs(performance.now()-r.current)>MENTION_SUGGESTIONS_DEBOUNCE?d():l=window.setTimeout(()=>{d()},MENTION_SUGGESTIONS_DEBOUNCE),()=>{c=!0,window.clearTimeout(l)}},[t,e,a,i]),n}function useSyncSource(){const e=useClient()[kInternal].createSyncSource,[t,n]=React.useState();return React.useEffect(()=>{const t=e();return n(t),()=>t.destroy()},[e]),t}function composeEventHandlers(e,t,{checkForDefaultPrevented:n=!0}={}){return function(o){if(e?.(o),!1===n||!o.defaultPrevented)return t?.(o)}}var useLayoutEffect2=globalThis?.document?React__namespace.useLayoutEffect:()=>{},useInsertionEffect=React__namespace[" useInsertionEffect ".trim().toString()]||useLayoutEffect2;function useControllableState$1({prop:e,defaultProp:t,onChange:n=()=>{},caller:o}){const[r,a,i]=useUncontrolledState({defaultProp:t,onChange:n}),s=void 0!==e,l=s?e:r;{const t=React__namespace.useRef(void 0!==e);React__namespace.useEffect(()=>{const e=t.current;if(e!==s){const t=e?"controlled":"uncontrolled",n=s?"controlled":"uncontrolled";console.warn(`${o} is changing from ${t} to ${n}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`)}t.current=s},[s,o])}return[l,React__namespace.useCallback(t=>{if(s){const n=isFunction(t)?t(e):t;n!==e&&i.current?.(n)}else a(t)},[s,e,a,i])]}function useUncontrolledState({defaultProp:e,onChange:t}){const[n,o]=React__namespace.useState(e),r=React__namespace.useRef(n),a=React__namespace.useRef(t);return useInsertionEffect(()=>{a.current=t},[t]),React__namespace.useEffect(()=>{r.current!==n&&(a.current?.(n),r.current=n)},[n,r]),[n,o,a]}function isFunction(e){return"function"==typeof e}function setRef(e,t){if("function"==typeof e)return e(t);null!=e&&(e.current=t)}function composeRefs(...e){return t=>{let n=!1;const o=e.map(e=>{const o=setRef(e,t);return n||"function"!=typeof o||(n=!0),o});if(n)return()=>{for(let t=0;t<o.length;t++){const n=o[t];"function"==typeof n?n():setRef(e[t],null)}}}}function useComposedRefs(...e){return React__namespace.useCallback(composeRefs(...e),e)}function createSlot(e){const t=createSlotClone(e),n=React__namespace.forwardRef((e,n)=>{const{children:o,...r}=e,a=React__namespace.Children.toArray(o),i=a.find(isSlottable);if(i){const e=i.props.children,o=a.map(t=>t===i?React__namespace.Children.count(e)>1?React__namespace.Children.only(null):React__namespace.isValidElement(e)?e.props.children:null:t);return jsxRuntime.exports.jsx(t,{...r,ref:n,children:React__namespace.isValidElement(e)?React__namespace.cloneElement(e,void 0,o):null})}return jsxRuntime.exports.jsx(t,{...r,ref:n,children:o})});return n.displayName=`${e}.Slot`,n}var Slot$2=createSlot("Slot");function createSlotClone(e){const t=React__namespace.forwardRef((e,t)=>{const{children:n,...o}=e;if(React__namespace.isValidElement(n)){const e=getElementRef$1(n),r=mergeProps(o,n.props);return n.type!==React__namespace.Fragment&&(r.ref=t?composeRefs(t,e):e),React__namespace.cloneElement(n,r)}return React__namespace.Children.count(n)>1?React__namespace.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var SLOTTABLE_IDENTIFIER=Symbol("radix.slottable");function createSlottable(e){const t=({children:e})=>jsxRuntime.exports.jsx(jsxRuntime.exports.Fragment,{children:e});return t.displayName=`${e}.Slottable`,t.__radixId=SLOTTABLE_IDENTIFIER,t}var Slottable$1=createSlottable("Slottable");function isSlottable(e){return React__namespace.isValidElement(e)&&"function"==typeof e.type&&"__radixId"in e.type&&e.type.__radixId===SLOTTABLE_IDENTIFIER}function mergeProps(e,t){const n={...t};for(const o in t){const r=e[o],a=t[o];/^on[A-Z]/.test(o)?r&&a?n[o]=(...e)=>{const t=a(...e);return r(...e),t}:r&&(n[o]=r):"style"===o?n[o]={...r,...a}:"className"===o&&(n[o]=[r,a].filter(Boolean).join(" "))}return{...e,...n}}function getElementRef$1(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var NODES=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Primitive=NODES.reduce((e,t)=>{const n=createSlot(`Primitive.${t}`),o=React__namespace.forwardRef((e,o)=>{const{asChild:r,...a}=e,i=r?n:t;return"undefined"!=typeof window&&(window[Symbol.for("radix-ui")]=!0),jsxRuntime.exports.jsx(i,{...a,ref:o})});return o.displayName=`Primitive.${t}`,{...e,[t]:o}},{});function dispatchDiscreteCustomEvent(e,t){e&&ReactDOM__namespace.flushSync(()=>e.dispatchEvent(t))}var NAME$2="Toggle",Toggle=React__namespace.forwardRef((e,t)=>{const{pressed:n,defaultPressed:o,onPressedChange:r,...a}=e,[i,s]=useControllableState$1({prop:n,onChange:r,defaultProp:o??!1,caller:NAME$2});return jsxRuntime.exports.jsx(Primitive.button,{type:"button","aria-pressed":i,"data-state":i?"on":"off","data-disabled":e.disabled?"":void 0,...a,ref:t,onClick:composeEventHandlers(e.onClick,()=>{e.disabled||s(!i)})})});Toggle.displayName=NAME$2;var Root$3=Toggle;function classNames(...e){return e.filter(e=>"string"==typeof e||"number"==typeof e).join(" ")}const ICON_WIDTH=20,ICON_HEIGHT=20;function Icon({children:e,className:t,...n}){return jsxRuntime.exports.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:ICON_WIDTH,height:ICON_HEIGHT,viewBox:`0 0 ${ICON_WIDTH} ${ICON_HEIGHT}`,fill:"none",stroke:"currentColor",strokeWidth:1.5,strokeLinecap:"round",strokeLinejoin:"round",role:"presentation",className:classNames("lb-icon",t),...n,children:e})}function CheckIcon(e){return jsxRuntime.exports.jsx(Icon,{...e,children:jsxRuntime.exports.jsx("path",{d:"M16 6L8 14L4 10"})})}function CrossIcon(e){return jsxRuntime.exports.jsxs(Icon,{...e,children:[jsxRuntime.exports.jsx("path",{d:"M15 5L5 15"}),jsxRuntime.exports.jsx("path",{d:"M5 5L15 15"})]})}function DeleteIcon(e){return jsxRuntime.exports.jsx(Icon,{...e,children:jsxRuntime.exports.jsx("path",{d:"M4.5 6.5h11M14 6.5V14a1.5 1.5 0 0 1-1.5 1.5h-5A1.5 1.5 0 0 1 6 14V6.5M7.5 6.5V5a1 1 0 0 1 1-1h3a1 1 0 0 1 1 1v1.5"})})}function EditIcon(e){return jsxRuntime.exports.jsx(Icon,{...e,children:jsxRuntime.exports.jsx("path",{d:"m11.784 5.797-6.13 6.138a4 4 0 0 0-1.03 1.775L4 16l2.285-.624a4 4 0 0 0 1.776-1.032l6.145-6.152m-2.422-2.395 1.244-1.246c.608-.608 1.826-.81 2.53-.104.7.7.499 1.893-.122 2.515l-1.23 1.23m-2.422-2.395 2.422 2.395"})})}function EllipsisIcon(e){return jsxRuntime.exports.jsxs(Icon,{fill:"currentColor",...e,children:[jsxRuntime.exports.jsx("circle",{cx:5,cy:10,r:.75}),jsxRuntime.exports.jsx("circle",{cx:10,cy:10,r:.75}),jsxRuntime.exports.jsx("circle",{cx:15,cy:10,r:.75})]})}function EmojiAddIcon(e){return jsxRuntime.exports.jsxs(Icon,{...e,children:[jsxRuntime.exports.jsx("path",{d:"M11 3.07A7 7 0 1 0 16.93 9"}),jsxRuntime.exports.jsx("path",{d:"M7.5 11.5S8.25 13 10 13s2.5-1.5 2.5-1.5M8 8h0"}),jsxRuntime.exports.jsx("path",{d:"M12 8h0"}),jsxRuntime.exports.jsx("path",{d:"M13 5h4m-2-2v4"}),jsxRuntime.exports.jsx("circle",{cx:"8",cy:"8",r:".25"}),jsxRuntime.exports.jsx("circle",{cx:"12",cy:"8",r:".25"})]})}const FLOATING_ELEMENT_SIDE_OFFSET=6,FLOATING_ELEMENT_COLLISION_PADDING=10,EMOJI_FONT_FAMILY="'Apple Color Emoji', 'Noto Color Emoji', 'Twemoji Mozilla', 'Android Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', EmojiSymbols, sans-serif",Emoji$1=React.forwardRef(({emoji:e,style:t,asChild:n,...o},r)=>{const a=n?Slot$2:"span";return jsxRuntime.exports.jsx(a,{role:"img","aria-label":e,"data-emoji":e,style:{...t,fontFamily:EMOJI_FONT_FAMILY,display:"inline-flex",alignItems:"center",justifyContent:"center",width:"1em",whiteSpace:"nowrap"},...o,ref:r,children:e})}),Emoji=React.forwardRef(({className:e,...t},n)=>jsxRuntime.exports.jsx(Emoji$1,{className:classNames("lb-emoji",e),...t,ref:n}));function pluralize(e,t,n){return 1===e?t:n??`${t}s`}const defaultOverrides={locale:"en",dir:"ltr",USER_SELF:"you",USER_UNKNOWN:"Anonymous",LIST_REMAINING:e=>`${e} more`,LIST_REMAINING_USERS:e=>`${e} ${pluralize(e,"other")}`,LIST_REMAINING_COMMENTS:e=>`${e} more ${pluralize(e,"comment")}`,EMOJI_PICKER_SEARCH_PLACEHOLDER:"Search…",EMOJI_PICKER_EMPTY:"No emoji found.",EMOJI_PICKER_ERROR:()=>"There was an error while getting the list of emoji.",ATTACHMENT_TOO_LARGE:e=>e?`The file is larger than ${e}`:"The file is too large",ATTACHMENT_ERROR:()=>"The file couldn’t be uploaded.",COMPOSER_INSERT_MENTION:"Mention someone",COMPOSER_INSERT_EMOJI:"Add emoji",COMPOSER_ATTACH_FILES:"Attach files",COMPOSER_REMOVE_ATTACHMENT:"Remove attachment",COMPOSER_PLACEHOLDER:"Write a comment…",COMPOSER_SEND:"Send",COMPOSER_TOGGLE_MARK:e=>{switch(e){case"bold":return"Bold";case"italic":return"Italic";case"strikethrough":return"Strikethrough";case"code":return"Inline code";default:return assertNever(e,"Unexpected mark")}},COMMENT_EDITED:"(edited)",COMMENT_DELETED:"This comment has been deleted.",COMMENT_MORE:"More",COMMENT_EDIT:"Edit comment",COMMENT_EDIT_COMPOSER_PLACEHOLDER:"Edit comment…",COMMENT_EDIT_COMPOSER_CANCEL:"Cancel",COMMENT_EDIT_COMPOSER_SAVE:"Save",COMMENT_DELETE:"Delete comment",COMMENT_DELETE_ATTACHMENT:"Delete attachment",COMMENT_ADD_REACTION:"Add reaction",COMMENT_REACTION_LIST:(e,t)=>jsxRuntime.exports.jsxs(jsxRuntime.exports.Fragment,{children:[e," reacted with ",jsxRuntime.exports.jsx(Emoji,{emoji:t})]}),COMMENT_REACTION_DESCRIPTION:(e,t)=>`${t} ${pluralize(t,"reaction")}, react with ${e}`,THREAD_RESOLVE:"Resolve thread",THREAD_UNRESOLVE:"Re-open thread",THREAD_NEW_INDICATOR:"New",THREAD_NEW_INDICATOR_DESCRIPTION:"New comments",THREAD_COMPOSER_PLACEHOLDER:"Reply to thread…",THREAD_COMPOSER_SEND:"Reply",INBOX_NOTIFICATION_MORE:"More",INBOX_NOTIFICATION_MARK_AS_READ:"Mark as read",INBOX_NOTIFICATION_DELETE:"Delete notification",INBOX_NOTIFICATION_THREAD_COMMENTS_LIST:(e,t)=>jsxRuntime.exports.jsxs(jsxRuntime.exports.Fragment,{children:[e," commented",t?jsxRuntime.exports.jsxs(jsxRuntime.exports.Fragment,{children:[" in ",t]}):jsxRuntime.exports.jsx(jsxRuntime.exports.Fragment,{children:" in a thread"})]}),INBOX_NOTIFICATION_THREAD_MENTION:(e,t)=>jsxRuntime.exports.jsxs(jsxRuntime.exports.Fragment,{children:[e," mentioned you",t?jsxRuntime.exports.jsxs(jsxRuntime.exports.Fragment,{children:[" in ",t]}):null]}),INBOX_NOTIFICATION_TEXT_MENTION:(e,t)=>jsxRuntime.exports.jsxs(jsxRuntime.exports.Fragment,{children:[e," mentioned you",t?jsxRuntime.exports.jsxs(jsxRuntime.exports.Fragment,{children:[" in ",t]}):null]}),HISTORY_VERSION_PREVIEW_AUTHORS_LIST:e=>jsxRuntime.exports.jsxs(jsxRuntime.exports.Fragment,{children:["Edits from ",e]}),HISTORY_VERSION_PREVIEW_RESTORE:"Restore",HISTORY_VERSION_PREVIEW_EMPTY:"No content.",HISTORY_VERSION_PREVIEW_ERROR:()=>"There was an error while getting this version."},OverridesContext=React.createContext(void 0);function useOverrides(e){const t=React.useContext(OverridesContext);return React.useMemo(()=>({...defaultOverrides,...t,...e}),[t,e])}function OverridesProvider({children:e,overrides:t}){const n=React.useContext(OverridesContext),o=React.useMemo(()=>({...defaultOverrides,...n,...t}),[n,t]);return jsxRuntime.exports.jsx(OverridesContext.Provider,{value:o,children:e})}
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react"),require("react-dom"),require("lodash")):"function"==typeof define&&define.amd?define(["exports","react","react-dom","lodash"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).BuilderLiveblocks={},e.React,e.ReactDOM,e._)}(this,function(exports,React,ReactDOM,_$1){const global=window;function _interopDefaultLegacy(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function _interopNamespace(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach(function(n){if("default"!==n){var o=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,o.get?o:{enumerable:!0,get:function(){return e[n]}})}}),t.default=e,Object.freeze(t)}var React__default=_interopDefaultLegacy(React),React__namespace=_interopNamespace(React),ReactDOM__namespace=_interopNamespace(ReactDOM),ReactDOM__default=_interopDefaultLegacy(ReactDOM),_$1__namespace=_interopNamespace(_$1),_$1__default=_interopDefaultLegacy(_$1),__defProp=Object.defineProperty,__export=(e,t)=>{for(var n in t)__defProp(e,n,{get:t[n],enumerable:!0})},PKG_NAME$2="@liveblocks/core",PKG_VERSION$2="2.15.1",PKG_FORMAT$2="esm",g="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0!==global?global:{},crossLinkedDocs="https://liveblocks.io/docs/errors/cross-linked",dupesDocs="https://liveblocks.io/docs/errors/dupes",SPACE$1=" ";function error(e){console.error(e)}function detectDupes(e,t,n){const o=Symbol.for(e),r=n?`${t||"dev"} (${n})`:t||"dev";if(g[o])if(g[o]===r);else{error([`Multiple copies of Liveblocks are being loaded in your project. This will cause issues! See ${dupesDocs+SPACE$1}`,"","Conflicts:",`- ${e} ${g[o]} (already loaded)`,`- ${e} ${r} (trying to load this now)`].join("\n"))}else g[o]=r;t&&PKG_VERSION$2&&t!==PKG_VERSION$2&&error([`Cross-linked versions of Liveblocks found, which will cause issues! See ${crossLinkedDocs+SPACE$1}`,"","Conflicts:",`- ${PKG_NAME$2} is at ${PKG_VERSION$2}`,`- ${e} is at ${t}`,"","Always upgrade all Liveblocks packages to the same version number."].join("\n"))}function convertToCommentData(e){const t=e.editedAt?new Date(e.editedAt):void 0,n=new Date(e.createdAt),o=e.reactions.map(e=>({...e,createdAt:new Date(e.createdAt)}));if(e.body)return{...e,reactions:o,createdAt:n,editedAt:t};{const r=new Date(e.deletedAt);return{...e,reactions:o,createdAt:n,editedAt:t,deletedAt:r}}}function convertToThreadData(e){const t=new Date(e.createdAt),n=new Date(e.updatedAt),o=e.comments.map(e=>convertToCommentData(e));return{...e,createdAt:t,updatedAt:n,comments:o}}function convertToCommentUserReaction(e){return{...e,createdAt:new Date(e.createdAt)}}function convertToInboxNotificationData(e){const t=new Date(e.notifiedAt),n=e.readAt?new Date(e.readAt):null;if("activities"in e){const o=e.activities.map(e=>({...e,createdAt:new Date(e.createdAt)}));return{...e,notifiedAt:t,readAt:n,activities:o}}return{...e,notifiedAt:t,readAt:n}}function convertToThreadDeleteInfo(e){const t=new Date(e.deletedAt);return{...e,deletedAt:t}}function convertToInboxNotificationDeleteInfo(e){const t=new Date(e.deletedAt);return{...e,deletedAt:t}}var fancy_console_exports={};__export(fancy_console_exports,{error:()=>error2,errorWithTitle:()=>errorWithTitle,warn:()=>warn$1,warnWithTitle:()=>warnWithTitle});var badge="background:#0e0d12;border-radius:9999px;color:#fff;padding:3px 7px;font-family:sans-serif;font-weight:600;",bold="font-weight:600";function wrap$1(e){return"undefined"==typeof window?console[e]:(t,...n)=>console[e]("%cLiveblocks",badge,t,...n)}var warn$1=wrap$1("warn"),error2=wrap$1("error");function wrapWithTitle(e){return"undefined"==typeof window?console[e]:(t,n,...o)=>console[e](`%cLiveblocks%c ${t}`,badge,bold,n,...o)}var warnWithTitle=wrapWithTitle("warn"),errorWithTitle=wrapWithTitle("error");function raise(e){throw new Error(e)}function isPlainObject$2(e){return null!==e&&"object"==typeof e&&"[object Object]"===Object.prototype.toString.call(e)}function entries(e){return Object.entries(e)}function tryParseJson(e){try{return JSON.parse(e)}catch(e){return}}function deepClone(e){return JSON.parse(JSON.stringify(e))}function b64decode(e){try{const t=e.replace(/-/g,"+").replace(/_/g,"/");return decodeURIComponent(atob(t).split("").map(function(e){return"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)}).join(""))}catch(t){return atob(e)}}function compact(e){return e.filter(e=>null!=e)}function compactObject(e){const t={...e};return Object.keys(e).forEach(e=>{const n=e;void 0===t[n]&&delete t[n]}),t}function wait$1(e){return new Promise(t=>setTimeout(t,e))}async function withTimeout(e,t,n){let o;const r=new Promise((e,r)=>{o=setTimeout(()=>{r(new Error(n))},t)});return Promise.race([e,r]).finally(()=>clearTimeout(o))}function memoizeOnSuccess(e){let t=null;return()=>(null===t&&(t=e().catch(e=>{throw setTimeout(()=>{t=null},5e3),e})),t)}var HttpError=class extends Error{constructor(e,t,n){super(e),this.message=e,this.status=t,this.details=n}},DONT_RETRY_4XX=e=>e instanceof HttpError&&e.status>=400&&e.status<500;async function autoRetry(e,t,n,o=DONT_RETRY_4XX){const r=n.length>0?n[n.length-1]:0;let a=0;for(;;){a++;try{return await e()}catch(e){if(o(e))throw e;if(a>=t)throw new Error(`Failed after ${t} attempts: ${String(e)}`)}const i=n[a-1]??r;warn$1(`Attempt ${a} was unsuccessful. Retrying in ${i} milliseconds.`),await wait$1(i)}}function controlledPromise(){let e,t;return[new Promise((n,o)=>{e=n,t=o}),e,t]}function Promise_withResolvers(){const[e,t,n]=controlledPromise();return{promise:e,resolve:t,reject:n}}function makeEventSource(){const e=new Set;function t(t){return e.add(t),()=>e.delete(t)}function n(e){const n=t(t=>(n(),e(t)));return n}async function o(e){let n;return new Promise(o=>{n=t(t=>{(void 0===e||e(t))&&o(t)})}).finally(()=>n?.())}return{notify:function(t){e.forEach(e=>e(t))},subscribe:t,subscribeOnce:n,count:function(){return e.size},waitUntil:o,[Symbol.dispose]:()=>{e.clear()},observable:{subscribe:t,subscribeOnce:n,waitUntil:o}}}function makeBufferableEventSource(){const e=makeEventSource();let t=null;return{...e,notify:function(n){null!==t?t.push(n):e.notify(n)},pause:function(){t=[]},unpause:function(){if(null!==t){for(const n of t)e.notify(n);t=null}},[Symbol.dispose]:()=>{e[Symbol.dispose](),null!==t&&(t.length=0)}}}function stringify(e,...t){if("object"!=typeof e||null===e||Array.isArray(e))return JSON.stringify(e,...t);const n=Object.keys(e).sort().reduce((t,n)=>(t[n]=e[n],t),{});return JSON.stringify(n,...t)}var DEFAULT_SIZE=50,BatchCall=class{input;resolve;reject;promise;constructor(e){this.input=e;const{promise:t,resolve:n,reject:o}=Promise_withResolvers();this.promise=t,this.resolve=n,this.reject=o}},Batch=class{#e=[];#t;#n;#o;#r;error=!1;constructor(e,t){this.#t=e,this.#n=t.size??DEFAULT_SIZE,this.#o=t.delay}#a(){void 0!==this.#r&&(clearTimeout(this.#r),this.#r=void 0)}#i(){this.#e.length===this.#n?this.#s():1===this.#e.length&&(this.#a(),this.#r=setTimeout(()=>{this.#s()},this.#o))}async#s(){if(0===this.#e.length)return;const e=this.#e.splice(0),t=e.map(e=>e.input);try{const n=await this.#t(t);this.error=!1,e.forEach((t,o)=>{const r=n?.[o];Array.isArray(n)?e.length!==n.length?t.reject(new Error(`Callback must return an array of the same length as the number of provided items. Expected ${e.length}, but got ${n.length}.`)):r instanceof Error?t.reject(r):t.resolve(r):t.reject(new Error("Callback must return an array."))})}catch(t){this.error=!0,e.forEach(e=>{e.reject(t)})}}get(e){const t=this.#e.find(t=>stringify(t.input)===stringify(e));if(t)return t.promise;const n=new BatchCall(e);return this.#e.push(n),this.#i(),n.promise}clear(){this.#e=[],this.error=!1,this.#a()}};function createBatchStore(e){const t=new Map,n=makeEventSource();function o(e){return stringify(e)}function r(e,o){t.set(e,o),n.notify()}return{...n.observable,get:async function(n){const a=o(n);if(!t.has(a))try{r(a,{isLoading:!0});r(a,{isLoading:!1,data:await e.get(n)})}catch(e){r(a,{isLoading:!1,error:e})}},getState:function(e){const n=o(e);return t.get(n)},invalidate:function(e){if(Array.isArray(e))for(const n of e)t.delete(o(n));else t.clear();n.notify()},getBatch:function(){return e},_cacheKeys:function(){return[...t.keys()]}}}function chunk(e,t){const n=[];for(let o=0,r=e.length;o<r;o+=t)n.push(e.slice(o,o+t));return n}var nanoid=(e=21)=>crypto.getRandomValues(new Uint8Array(e)).reduce((e,t)=>e+((t&=63)<36?t.toString(36):t<62?(t-26).toString(36).toUpperCase():t<63?"_":"-"),""),THREAD_ID_PREFIX="th",COMMENT_ID_PREFIX="cm",COMMENT_ATTACHMENT_ID_PREFIX="at";function createOptimisticId(e){return`${e}_${nanoid()}`}function createThreadId(){return createOptimisticId(THREAD_ID_PREFIX)}function createCommentId(){return createOptimisticId(COMMENT_ID_PREFIX)}function createCommentAttachmentId(){return createOptimisticId(COMMENT_ATTACHMENT_ID_PREFIX)}var identifierRegex=/^[a-zA-Z_][a-zA-Z0-9_]*$/;function objectToQuery(e){let t=[];const n=Object.entries(e),o=[],r=[],a=[];return n.forEach(([e,t])=>{if(!identifierRegex.test(e))throw new Error("Key must only contain letters, numbers, _");isSimpleValue(t)?o.push([e,t]):isValueWithOperator(t)?r.push([e,t]):"object"!=typeof t||"startsWith"in t||a.push([e,t])}),t=[...getFiltersFromKeyValuePairs(o),...getFiltersFromKeyValuePairsWithOperator(r)],a.forEach(([e,n])=>{const o=Object.entries(n),r=[],a=[];o.forEach(([t,n])=>{if(isStringEmpty(t))throw new Error("Key cannot be empty");isSimpleValue(n)?r.push([formatFilterKey(e,t),n]):isValueWithOperator(n)&&a.push([formatFilterKey(e,t),n])}),t=[...t,...getFiltersFromKeyValuePairs(r),...getFiltersFromKeyValuePairsWithOperator(a)]}),t.map(({key:e,operator:t,value:n})=>formatFilter(e,t,formatFilterValue(n))).join(" AND ")}var getFiltersFromKeyValuePairs=e=>{const t=[];return e.forEach(([e,n])=>{t.push({key:e,operator:":",value:n})}),t},getFiltersFromKeyValuePairsWithOperator=e=>{const t=[];return e.forEach(([e,n])=>{"startsWith"in n&&"string"==typeof n.startsWith&&t.push({key:e,operator:"^",value:n.startsWith})}),t},isSimpleValue=e=>"string"==typeof e||"number"==typeof e||"boolean"==typeof e,isValueWithOperator=e=>"object"==typeof e&&null!==e&&"startsWith"in e,formatFilter=(e,t,n)=>`${e}${t}${n}`,formatFilterKey=(e,t)=>t?`${e}[${JSON.stringify(t)}]`:e,formatFilterValue=e=>{if("string"==typeof e){if(isStringEmpty(e))throw new Error("Value cannot be empty");return JSON.stringify(e)}return e.toString()},isStringEmpty=e=>!e||""===e.toString().trim();function toURLSearchParams(e){const t=new URLSearchParams;for(const[n,o]of Object.entries(e))null!=o&&t.set(n,o.toString());return t}function urljoin(e,t,n){const o=new URL(t,e);return void 0!==n&&(o.search=(n instanceof URLSearchParams?n:toURLSearchParams(n)).toString()),o.toString()}function url(e,...t){return e.reduce((e,n,o)=>e+encodeURIComponent(t[o-1]??"")+n)}function createApiClient({baseUrl:e,authManager:t,fetchPolyfill:n}){const o=new HttpClient(e,n);const r=new Map;function a(e){let n=r.get(e);if(void 0===n){n=createBatchStore(new Batch(async n=>{const r=n.flat(),{urls:a}=await o.post(url`/v2/c/rooms/${e}/attachments/presigned-urls`,await t.getAuthValue({requestedScope:"comments:read",roomId:e}),{attachmentIds:r});return a.map(e=>e??new Error("There was an error while getting this attachment's URL"))},{delay:50})),r.set(e,n)}return n}const i=new Map;const s=new Batch(async e=>{const n=e.flat();return await async function(e){await o.post(url`/v2/c/inbox-notifications/read`,await t.getAuthValue({requestedScope:"comments:read"}),{inboxNotificationIds:e})}(n),n},{delay:50});return{getThreads:async function(e){let n;e.query&&(n=objectToQuery(e.query));try{const r=await o.get(url`/v2/c/rooms/${e.roomId}/threads`,await t.getAuthValue({requestedScope:"comments:read",roomId:e.roomId}),{cursor:e.cursor,query:n,limit:50});return{threads:r.data.map(convertToThreadData),inboxNotifications:r.inboxNotifications.map(convertToInboxNotificationData),nextCursor:r.meta.nextCursor,requestedAt:new Date(r.meta.requestedAt),permissionHints:r.meta.permissionHints}}catch(e){if(e instanceof HttpError&&404===e.status)return{threads:[],inboxNotifications:[],nextCursor:null,requestedAt:new Date(Date.now()-216e5),permissionHints:{}};throw e}},getThreadsSince:async function(e){const n=await o.get(url`/v2/c/rooms/${e.roomId}/threads/delta`,await t.getAuthValue({requestedScope:"comments:read",roomId:e.roomId}),{since:e.since.toISOString()},{signal:e.signal});return{threads:{updated:n.data.map(convertToThreadData),deleted:n.deletedThreads.map(convertToThreadDeleteInfo)},inboxNotifications:{updated:n.inboxNotifications.map(convertToInboxNotificationData),deleted:n.deletedInboxNotifications.map(convertToInboxNotificationDeleteInfo)},requestedAt:new Date(n.meta.requestedAt),permissionHints:n.meta.permissionHints}},createThread:async function(e){const n=e.commentId??createCommentId(),r=e.threadId??createThreadId();return convertToThreadData(await o.post(url`/v2/c/rooms/${e.roomId}/threads`,await t.getAuthValue({requestedScope:"comments:read",roomId:e.roomId}),{id:r,comment:{id:n,body:e.body,attachmentIds:e.attachmentIds},metadata:e.metadata}))},getThread:async function(e){const n=await o.rawGet(url`/v2/c/rooms/${e.roomId}/thread-with-notification/${e.threadId}`,await t.getAuthValue({requestedScope:"comments:read",roomId:e.roomId}));if(n.ok){const e=await n.json();return{thread:convertToThreadData(e.thread),inboxNotification:e.inboxNotification?convertToInboxNotificationData(e.inboxNotification):void 0}}if(404===n.status)return{thread:void 0,inboxNotification:void 0};throw new Error(`There was an error while getting thread ${e.threadId}.`)},deleteThread:async function(e){await o.delete(url`/v2/c/rooms/${e.roomId}/threads/${e.threadId}`,await t.getAuthValue({requestedScope:"comments:read",roomId:e.roomId}))},editThreadMetadata:async function(e){return await o.post(url`/v2/c/rooms/${e.roomId}/threads/${e.threadId}/metadata`,await t.getAuthValue({requestedScope:"comments:read",roomId:e.roomId}),e.metadata)},createComment:async function(e){const n=e.commentId??createCommentId();return convertToCommentData(await o.post(url`/v2/c/rooms/${e.roomId}/threads/${e.threadId}/comments`,await t.getAuthValue({requestedScope:"comments:read",roomId:e.roomId}),{id:n,body:e.body,attachmentIds:e.attachmentIds}))},editComment:async function(e){return convertToCommentData(await o.post(url`/v2/c/rooms/${e.roomId}/threads/${e.threadId}/comments/${e.commentId}`,await t.getAuthValue({requestedScope:"comments:read",roomId:e.roomId}),{body:e.body,attachmentIds:e.attachmentIds}))},deleteComment:async function(e){await o.delete(url`/v2/c/rooms/${e.roomId}/threads/${e.threadId}/comments/${e.commentId}`,await t.getAuthValue({requestedScope:"comments:read",roomId:e.roomId}))},addReaction:async function(e){return convertToCommentUserReaction(await o.post(url`/v2/c/rooms/${e.roomId}/threads/${e.threadId}/comments/${e.commentId}/reactions`,await t.getAuthValue({requestedScope:"comments:read",roomId:e.roomId}),{emoji:e.emoji}))},removeReaction:async function(e){await o.delete(url`/v2/c/rooms/${e.roomId}/threads/${e.threadId}/comments/${e.commentId}/reactions/${e.emoji}`,await t.getAuthValue({requestedScope:"comments:read",roomId:e.roomId}))},markThreadAsResolved:async function(e){await o.post(url`/v2/c/rooms/${e.roomId}/threads/${e.threadId}/mark-as-resolved`,await t.getAuthValue({requestedScope:"comments:read",roomId:e.roomId}))},markThreadAsUnresolved:async function(e){await o.post(url`/v2/c/rooms/${e.roomId}/threads/${e.threadId}/mark-as-unresolved`,await t.getAuthValue({requestedScope:"comments:read",roomId:e.roomId}))},markRoomInboxNotificationAsRead:async function(e){return function(e){let n=i.get(e);return void 0===n&&(n=new Batch(async n=>{const r=n.flat();return await o.post(url`/v2/c/rooms/${e}/inbox-notifications/read`,await t.getAuthValue({requestedScope:"comments:read",roomId:e}),{inboxNotificationIds:r}),r},{delay:50}),i.set(e,n)),n}(e.roomId).get(e.inboxNotificationId)},updateNotificationSettings:async function(e){return o.post(url`/v2/c/rooms/${e.roomId}/notification-settings`,await t.getAuthValue({requestedScope:"comments:read",roomId:e.roomId}),e.settings)},getNotificationSettings:async function(e){return o.get(url`/v2/c/rooms/${e.roomId}/notification-settings`,await t.getAuthValue({requestedScope:"comments:read",roomId:e.roomId}),void 0,{signal:e.signal})},createTextMention:async function(e){await o.rawPost(url`/v2/c/rooms/${e.roomId}/text-mentions`,await t.getAuthValue({requestedScope:"comments:read",roomId:e.roomId}),{userId:e.userId,mentionId:e.mentionId})},deleteTextMention:async function(e){await o.rawDelete(url`/v2/c/rooms/${e.roomId}/text-mentions/${e.mentionId}`,await t.getAuthValue({requestedScope:"comments:read",roomId:e.roomId}))},getTextVersion:async function(e){return o.rawGet(url`/v2/c/rooms/${e.roomId}/y-version/${e.versionId}`,await t.getAuthValue({requestedScope:"comments:read",roomId:e.roomId}))},createTextVersion:async function(e){await o.rawPost(url`/v2/c/rooms/${e.roomId}/version`,await t.getAuthValue({requestedScope:"comments:read",roomId:e.roomId}))},reportTextEditor:async function(e){await o.rawPost(url`/v2/c/rooms/${e.roomId}/text-metadata`,await t.getAuthValue({requestedScope:"comments:read",roomId:e.roomId}),{type:e.type,rootKey:e.rootKey})},listTextVersions:async function(e){const n=await o.get(url`/v2/c/rooms/${e.roomId}/versions`,await t.getAuthValue({requestedScope:"comments:read",roomId:e.roomId}));return{versions:n.versions.map(({createdAt:e,...t})=>({createdAt:new Date(e),...t})),requestedAt:new Date(n.meta.requestedAt)}},listTextVersionsSince:async function(e){const n=await o.get(url`/v2/c/rooms/${e.roomId}/versions/delta`,await t.getAuthValue({requestedScope:"comments:read",roomId:e.roomId}),{since:e.since.toISOString()},{signal:e.signal});return{versions:n.versions.map(({createdAt:e,...t})=>({createdAt:new Date(e),...t})),requestedAt:new Date(n.meta.requestedAt)}},getAttachmentUrl:function(e){return a(e.roomId).getBatch().get(e.attachmentId)},uploadAttachment:async function(e){const n=e.roomId,r=e.signal,a=e.attachment,i=r?new DOMException(`Upload of attachment ${e.attachment.id} was aborted.`,"AbortError"):void 0;if(r?.aborted)throw i;const s=e=>{if(r?.aborted)throw i;if(e instanceof HttpError&&413===e.status)throw e;return!1},l=524288e3,c=[2e3,2e3,2e3,2e3,2e3,2e3,2e3,2e3,2e3,2e3];if(a.size<=l)return autoRetry(async()=>o.putBlob(url`/v2/c/rooms/${n}/attachments/${a.id}/upload/${encodeURIComponent(a.name)}`,await t.getAuthValue({requestedScope:"comments:read",roomId:n}),a.file,{fileSize:a.size},{signal:r}),10,c,s);{let e;const d=[],u=await autoRetry(async()=>o.post(url`/v2/c/rooms/${n}/attachments/${a.id}/multipart/${encodeURIComponent(a.name)}`,await t.getAuthValue({requestedScope:"comments:read",roomId:n}),void 0,{signal:r},{fileSize:a.size}),10,c,s);try{e=u.uploadId;const f=function(e){const t=[];let n=0;for(;n<e.size;){const o=Math.min(n+l,e.size);t.push({partNumber:t.length+1,part:e.slice(n,o)}),n=o}return t}(a.file);if(r?.aborted)throw i;const p=chunk(f,5);for(const e of p){const i=[];for(const{part:l,partNumber:d}of e)i.push(autoRetry(async()=>o.putBlob(url`/v2/c/rooms/${n}/attachments/${a.id}/multipart/${u.uploadId}/${String(d)}`,await t.getAuthValue({requestedScope:"comments:read",roomId:n}),l,void 0,{signal:r}),10,c,s));d.push(...await Promise.all(i))}if(r?.aborted)throw i;const _=d.sort((e,t)=>e.partNumber-t.partNumber);return o.post(url`/v2/c/rooms/${n}/attachments/${a.id}/multipart/${e}/complete`,await t.getAuthValue({requestedScope:"comments:read",roomId:n}),{parts:_},{signal:r})}catch(r){if(e&&r?.name&&("AbortError"===r.name||"TimeoutError"===r.name))try{await o.rawDelete(url`/v2/c/rooms/${n}/attachments/${a.id}/multipart/${e}`,await t.getAuthValue({requestedScope:"comments:read",roomId:n}))}catch(e){}throw r}}},getOrCreateAttachmentUrlsStore:a,streamStorage:async function(e){const n=await o.rawGet(url`/v2/c/rooms/${e.roomId}/storage`,await t.getAuthValue({requestedScope:"room:read",roomId:e.roomId}));return await n.json()},sendMessages:async function(e){return o.rawPost(url`/v2/c/rooms/${e.roomId}/send-message`,await t.getAuthValue({requestedScope:"room:read",roomId:e.roomId}),{nonce:e.nonce,messages:e.messages})},getInboxNotifications:async function(e){const n=await o.get(url`/v2/c/inbox-notifications`,await t.getAuthValue({requestedScope:"comments:read"}),{cursor:e?.cursor,limit:50});return{inboxNotifications:n.inboxNotifications.map(convertToInboxNotificationData),threads:n.threads.map(convertToThreadData),nextCursor:n.meta.nextCursor,requestedAt:new Date(n.meta.requestedAt)}},getInboxNotificationsSince:async function(e){const n=await o.get(url`/v2/c/inbox-notifications/delta`,await t.getAuthValue({requestedScope:"comments:read"}),{since:e.since.toISOString()},{signal:e.signal});return{inboxNotifications:{updated:n.inboxNotifications.map(convertToInboxNotificationData),deleted:n.deletedInboxNotifications.map(convertToInboxNotificationDeleteInfo)},threads:{updated:n.threads.map(convertToThreadData),deleted:n.deletedThreads.map(convertToThreadDeleteInfo)},requestedAt:new Date(n.meta.requestedAt)}},getUnreadInboxNotificationsCount:async function(){const{count:e}=await o.get(url`/v2/c/inbox-notifications/count`,await t.getAuthValue({requestedScope:"comments:read"}));return e},markAllInboxNotificationsAsRead:async function(){await o.post(url`/v2/c/inbox-notifications/read`,await t.getAuthValue({requestedScope:"comments:read"}),{inboxNotificationIds:"all"})},markInboxNotificationAsRead:async function(e){await s.get(e)},deleteAllInboxNotifications:async function(){await o.delete(url`/v2/c/inbox-notifications`,await t.getAuthValue({requestedScope:"comments:read"}))},deleteInboxNotification:async function(e){await o.delete(url`/v2/c/inbox-notifications/${e}`,await t.getAuthValue({requestedScope:"comments:read"}))},getUserThreads_experimental:async function(e){let n;e?.query&&(n=objectToQuery(e.query));const r=await o.get(url`/v2/c/threads`,await t.getAuthValue({requestedScope:"comments:read"}),{cursor:e?.cursor,query:n,limit:50});return{threads:r.threads.map(convertToThreadData),inboxNotifications:r.inboxNotifications.map(convertToInboxNotificationData),nextCursor:r.meta.nextCursor,requestedAt:new Date(r.meta.requestedAt),permissionHints:r.meta.permissionHints}},getUserThreadsSince_experimental:async function(e){const n=await o.get(url`/v2/c/threads/delta`,await t.getAuthValue({requestedScope:"comments:read"}),{since:e.since.toISOString()},{signal:e.signal});return{threads:{updated:n.threads.map(convertToThreadData),deleted:n.deletedThreads.map(convertToThreadDeleteInfo)},inboxNotifications:{updated:n.inboxNotifications.map(convertToInboxNotificationData),deleted:n.deletedInboxNotifications.map(convertToInboxNotificationDeleteInfo)},requestedAt:new Date(n.meta.requestedAt),permissionHints:n.meta.permissionHints}}}}function getBearerTokenFromAuthValue(e){return"public"===e.type?e.publicApiKey:e.token.raw}var HttpClient=class{#l;#c;constructor(e,t){this.#l=e,this.#c=t}async#d(e,t,n,o){e.startsWith("/v2/c/")||raise("This client can only be used to make /v2/c/* requests");const r=urljoin(this.#l,e,o);return await this.#c(r,{...n,headers:{"Content-Type":"application/json; charset=utf-8",...n?.headers,Authorization:`Bearer ${getBearerTokenFromAuthValue(t)}`,"X-LB-Client":PKG_VERSION$2}})}async#u(e,t,n,o){const r=await this.#d(e,t,n,o);if(!r.ok){let e;try{const t=await r.json();e=new HttpError(t.message,r.status,t)}catch{e=new HttpError(r.statusText,r.status)}throw e}let a;try{a=await r.json()}catch{a={}}return a}async rawGet(e,t,n,o){return await this.#d(e,t,o,n)}async rawPost(e,t,n){return await this.#d(e,t,{method:"POST",body:JSON.stringify(n)})}async rawDelete(e,t){return await this.#d(e,t,{method:"DELETE"})}async get(e,t,n,o){return await this.#u(e,t,o,n)}async post(e,t,n,o,r){return await this.#u(e,t,{...o,method:"POST",body:JSON.stringify(n)},r)}async delete(e,t){return await this.#u(e,t,{method:"DELETE"})}async putBlob(e,t,n,o,r){return await this.#u(e,t,{...r,method:"PUT",headers:{"Content-Type":"application/octet-stream"},body:n},o)}};function assertNever(e,t){throw new Error(t)}function assert(e,t){}function nn(e,t="Expected value to be non-nullable"){return e}function distance(e,t){if(e===t)return[0,0];const n=e.split("."),o=t.split("."),r=Math.min(n.length,o.length);let a=0;for(;a<r&&n[a]===o[a];a++);return[n.length-a,o.length-a]}function patterns(e,t){const n=e.split(".");if(t<1||t>n.length+1)throw new Error("Invalid number of levels");const o=[];t>n.length&&o.push("*");for(let e=n.length-t+1;e<n.length;e++){const t=n.slice(0,e);t.length>0&&o.push(t.join(".")+".*")}return o.push(e),o}var SafeContext=class{#f;constructor(e){this.#f=e}get current(){return this.#f}allowPatching(e){const t=this;let n=!0;e({...this.#f,patch(e){if(!n)throw new Error("Can no longer patch stale context");t.#f=Object.assign({},t.#f,e);for(const t of Object.entries(e)){const[e,n]=t;"patch"!==e&&(this[e]=n)}}}),n=!1}},nextId=1,FSM=class{id;#p;#_;#m;#h;#g;#b;events;#v;#y;#E;get#w(){const e=this.#m.values()[Symbol.iterator]().next();if(e.done)throw new Error("No states defined yet");return e.value}get currentState(){if(null===this.#h)throw 0===this.#p?new Error("Not started yet"):new Error("Already stopped");return this.#h}start(){if(0!==this.#p)throw new Error("State machine has already started");return this.#p=1,this.#h=this.#w,this.#C(null),this}stop(){if(1!==this.#p)throw new Error("Cannot stop a state machine that hasn't started yet");this.#x(null),this.#p=2,this.#h=null}constructor(e){this.id=nextId++,this.#p=0,this.#h=null,this.#m=new Set,this.#y=new Map,this.#v=[],this.#E=new Set,this.#g=new Map,this.#_=new SafeContext(e),this.#b={didReceiveEvent:makeEventSource(),willTransition:makeEventSource(),didIgnoreEvent:makeEventSource(),willExitState:makeEventSource(),didEnterState:makeEventSource()},this.events={didReceiveEvent:this.#b.didReceiveEvent.observable,willTransition:this.#b.willTransition.observable,didIgnoreEvent:this.#b.didIgnoreEvent.observable,willExitState:this.#b.willExitState.observable,didEnterState:this.#b.didEnterState.observable}}get context(){return this.#_.current}addState(e){if(0!==this.#p)throw new Error("Already started");return this.#m.add(e),this}onEnter(e,t){if(0!==this.#p)throw new Error("Already started");if(this.#y.has(e))throw new Error(`enter/exit function for ${e} already exists`);return this.#y.set(e,t),this}onEnterAsync(e,t,n,o,r){return this.onEnter(e,()=>{const e=new AbortController,a=e.signal,i=r?setTimeout(()=>{const e=new Error("Timed out");this.#R({type:"ASYNC_ERROR",reason:e},o)},r):void 0;let s=!1;return t(this.#_.current,a).then(e=>{a.aborted||(s=!0,this.#R({type:"ASYNC_OK",data:e},n))},e=>{a.aborted||(s=!0,this.#R({type:"ASYNC_ERROR",reason:e},o))}),()=>{clearTimeout(i),s||e.abort()}})}#S(e){const t=[];if("*"===e)for(const e of this.#m)t.push(e);else if(e.endsWith(".*")){const n=e.slice(0,-1);for(const e of this.#m)e.startsWith(n)&&t.push(e)}else{const n=e;this.#m.has(n)&&t.push(n)}if(0===t.length)throw new Error(`No states match ${JSON.stringify(e)}`);return t}addTransitions(e,t){if(0!==this.#p)throw new Error("Already started");for(const n of this.#S(e)){let o=this.#g.get(n);void 0===o&&(o=new Map,this.#g.set(n,o));for(const[r,a]of Object.entries(t)){if(o.has(r))throw new Error(`Trying to set transition "${r}" on "${n}" (via "${e}"), but a transition already exists there.`);const t=a;if(this.#E.add(r),void 0!==t){const e="function"==typeof t?t:()=>t;o.set(r,e)}}}return this}addTimedTransition(e,t,n){return this.onEnter(e,()=>{const e="function"==typeof t?t(this.#_.current):t,o=setTimeout(()=>{this.#R({type:"TIMER"},n)},e);return()=>{clearTimeout(o)}})}#D(e){return this.#g.get(this.currentState)?.get(e)}#x(e){this.#b.willExitState.notify(this.currentState),this.#_.allowPatching(t=>{e=e??this.#v.length;for(let n=0;n<e;n++)this.#v.pop()?.(t)})}#C(e){const t=patterns(this.currentState,e??this.currentState.split(".").length+1);this.#_.allowPatching(e=>{for(const n of t){const t=this.#y.get(n),o=t?.(e);"function"==typeof o?this.#v.push(o):this.#v.push(null)}}),this.#b.didEnterState.notify(this.currentState)}send(e){if(!this.#E.has(e.type))throw new Error(`Invalid event ${JSON.stringify(e.type)}`);if(2===this.#p)return;const t=this.#D(e.type);if(void 0!==t)return this.#R(e,t);this.#b.didIgnoreEvent.notify(e)}#R(e,t){this.#b.didReceiveEvent.notify(e);const n=this.currentState,o=("function"==typeof t?t:()=>t)(e,this.#_.current);let r,a;if(null===o)return void this.#b.didIgnoreEvent.notify(e);if("string"==typeof o?r=o:(r=o.target,a=Array.isArray(o.effect)?o.effect:[o.effect]),!this.#m.has(r))throw new Error(`Invalid next state name: ${JSON.stringify(r)}`);this.#b.willTransition.notify({from:n,to:r});const[i,s]=distance(this.currentState,r);if(i>0&&this.#x(i),this.#h=r,void 0!==a){const t=a;this.#_.allowPatching(n=>{for(const o of t)"function"==typeof o?o(n,e):n.patch(o)})}s>0&&this.#C(s)}},ServerMsgCode=(e=>(e[e.UPDATE_PRESENCE=100]="UPDATE_PRESENCE",e[e.USER_JOINED=101]="USER_JOINED",e[e.USER_LEFT=102]="USER_LEFT",e[e.BROADCASTED_EVENT=103]="BROADCASTED_EVENT",e[e.ROOM_STATE=104]="ROOM_STATE",e[e.INITIAL_STORAGE_STATE=200]="INITIAL_STORAGE_STATE",e[e.UPDATE_STORAGE=201]="UPDATE_STORAGE",e[e.REJECT_STORAGE_OP=299]="REJECT_STORAGE_OP",e[e.UPDATE_YDOC=300]="UPDATE_YDOC",e[e.THREAD_CREATED=400]="THREAD_CREATED",e[e.THREAD_DELETED=407]="THREAD_DELETED",e[e.THREAD_METADATA_UPDATED=401]="THREAD_METADATA_UPDATED",e[e.THREAD_UPDATED=408]="THREAD_UPDATED",e[e.COMMENT_CREATED=402]="COMMENT_CREATED",e[e.COMMENT_EDITED=403]="COMMENT_EDITED",e[e.COMMENT_DELETED=404]="COMMENT_DELETED",e[e.COMMENT_REACTION_ADDED=405]="COMMENT_REACTION_ADDED",e[e.COMMENT_REACTION_REMOVED=406]="COMMENT_REACTION_REMOVED",e))(ServerMsgCode||{});function shouldDisconnect(e){return 4999===e||e>=4e3&&e<4100}function shouldReauth(e){return e>=4100&&e<4200}function shouldRetryWithoutReauth(e){return 1013===e||e>=4200&&e<4300}function isIdle(e){return"initial"===e||"disconnected"===e}function toNewConnectionStatus(e){const t=e.currentState;switch(t){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":case"@idle.zombie":return e.context.successCount>0?"reconnecting":"connecting";case"@idle.failed":return"disconnected";default:return assertNever(t,"Unknown state")}}var BACKOFF_DELAYS=[250,500,1e3,2e3,4e3,8e3,1e4],RESET_DELAY=BACKOFF_DELAYS[0]-1,BACKOFF_DELAYS_SLOW=[2e3,3e4,6e4,3e5],HEARTBEAT_INTERVAL=3e4,PONG_TIMEOUT=2e3,AUTH_TIMEOUT=1e4,SOCKET_CONNECT_TIMEOUT=1e4,StopRetrying=class extends Error{constructor(e){super(e)}},LiveblocksError=class extends Error{constructor(e,t){super(e),this.code=t}};function nextBackoffDelay(e,t){return t.find(t=>t>e)??t[t.length-1]}function increaseBackoffDelay(e){e.patch({backoffDelay:nextBackoffDelay(e.backoffDelay,BACKOFF_DELAYS)})}function increaseBackoffDelayAggressively(e){e.patch({backoffDelay:nextBackoffDelay(e.backoffDelay,BACKOFF_DELAYS_SLOW)})}function resetSuccessCount(e){e.patch({successCount:0})}function log(e,t){const n=2===e?error2:1===e?warn$1:()=>{};return()=>{n(t)}}function logPrematureErrorOrCloseEvent(e){const t="Connection to Liveblocks websocket server";return n=>{e instanceof Error?warn$1(`${t} could not be established. ${String(e)}`):warn$1(isCloseEvent(e)?`${t} closed prematurely (code: ${e.code}). Retrying in ${n.backoffDelay}ms.`:`${t} could not be established.`)}}function logCloseEvent(e){const t=[`code: ${e.code}`];return e.reason&&t.push(`reason: ${e.reason}`),e=>{warn$1(`Connection to Liveblocks websocket server closed (${t.join(", ")}). Retrying in ${e.backoffDelay}ms.`)}}var logPermanentClose=log(1,"Connection to WebSocket closed permanently. Won't retry.");function isCloseEvent(e){return!(e instanceof Error)&&"close"===e.type}function enableTracing(e){const t=(new Date).getTime();function n(...n){warn$1(`${(((new Date).getTime()-t)/1e3).toFixed(2)} [FSM #${e.id}]`,...n)}const o=[e.events.didReceiveEvent.subscribe(e=>n(`Event ${e.type}`)),e.events.willTransition.subscribe(({from:e,to:t})=>n("Transitioning",e,"→",t)),e.events.didIgnoreEvent.subscribe(e=>n("Ignored event",e.type,e,"(current state won't handle it)"))];return()=>{for(const e of o)e()}}function defineConnectivityEvents(e){const t=makeEventSource(),n=makeEventSource(),o=makeEventSource();let r=null;const a=e.events.didEnterState.subscribe(()=>{const a=toNewConnectionStatus(e);a!==r&&t.notify(a),"connected"===r&&"connected"!==a?o.notify():"connected"!==r&&"connected"===a&&n.notify(),r=a});return{statusDidChange:t.observable,didConnect:n.observable,didDisconnect:o.observable,unsubscribe:a}}var assign=e=>t=>t.patch(e);function createConnectionStateMachine(e,t){const n=makeBufferableEventSource();n.pause();const o=makeEventSource();function r(e,t){return()=>{const n=new LiveblocksError(e,t);o.notify(n)}}const a=new FSM({successCount:0,authValue:null,socket:null,backoffDelay:RESET_DELAY}).addState("@idle.initial").addState("@idle.failed").addState("@idle.zombie").addState("@auth.busy").addState("@auth.backoff").addState("@connecting.busy").addState("@connecting.backoff").addState("@ok.connected").addState("@ok.awaiting-pong");a.addTransitions("*",{RECONNECT:{target:"@auth.backoff",effect:[increaseBackoffDelay,resetSuccessCount]},DISCONNECT:"@idle.initial"}),a.onEnter("@idle.*",resetSuccessCount).addTransitions("@idle.*",{CONNECT:(e,t)=>null!==t.authValue?"@connecting.busy":"@auth.busy"}),a.addTransitions("@auth.backoff",{NAVIGATOR_ONLINE:{target:"@auth.busy",effect:assign({backoffDelay:RESET_DELAY})}}).addTimedTransition("@auth.backoff",e=>e.backoffDelay,"@auth.busy").onEnterAsync("@auth.busy",()=>withTimeout(e.authenticate(),AUTH_TIMEOUT,"Timed out during auth"),e=>({target:"@connecting.busy",effect:assign({authValue:e.data})}),e=>e.reason instanceof StopRetrying?{target:"@idle.failed",effect:[log(2,e.reason.message),r(e.reason.message,-1)]}:{target:"@auth.backoff",effect:[increaseBackoffDelay,log(2,`Authentication failed: ${e.reason instanceof Error?e.reason.message:String(e.reason)}`)]});const i=e=>a.send({type:"EXPLICIT_SOCKET_ERROR",event:e}),s=e=>a.send({type:"EXPLICIT_SOCKET_CLOSE",event:e}),l=e=>"pong"===e.data?a.send({type:"PONG"}):n.notify(e);function c(e){e&&(e.removeEventListener("error",i),e.removeEventListener("close",s),e.removeEventListener("message",l),e.close())}a.addTransitions("@connecting.backoff",{NAVIGATOR_ONLINE:{target:"@connecting.busy",effect:assign({backoffDelay:RESET_DELAY})}}).addTimedTransition("@connecting.backoff",e=>e.backoffDelay,"@connecting.busy").onEnterAsync("@connecting.busy",async(n,o)=>{let r=null,a=null;return withTimeout(new Promise((o,c)=>{if(null===n.authValue)throw new Error("No auth authValue");const d=e.createSocket(n.authValue);function u(e){r=e,d.removeEventListener("message",l),c(e)}a=d;const[f,p]=controlledPromise();function _(e){const t=tryParseJson(e.data);104===t?.type&&p()}t.waitForActorId||p(),d.addEventListener("message",l),t.waitForActorId&&d.addEventListener("message",_),d.addEventListener("error",u),d.addEventListener("close",u),d.addEventListener("open",()=>{d.addEventListener("error",i),d.addEventListener("close",s);const e=()=>{d.removeEventListener("error",u),d.removeEventListener("close",u),d.removeEventListener("message",_)};f.then(()=>{o([d,e])})})}),SOCKET_CONNECT_TIMEOUT,"Timed out during websocket connection").then(([e,t])=>{if(t(),o.aborted)throw new Error("Aborted");if(r)throw r;return e}).catch(e=>{throw c(a),e})},e=>({target:"@ok.connected",effect:assign({socket:e.data,backoffDelay:RESET_DELAY})}),e=>{const t=e.reason;if(t instanceof StopRetrying)return{target:"@idle.failed",effect:[log(2,t.message),r(t.message,-1)]};if(isCloseEvent(t)){if(4109===t.code)return"@auth.busy";if(shouldRetryWithoutReauth(t.code))return{target:"@connecting.backoff",effect:[increaseBackoffDelayAggressively,logPrematureErrorOrCloseEvent(t)]};if(shouldDisconnect(t.code))return{target:"@idle.failed",effect:[log(2,t.reason),r(t.reason,t.code)]}}return{target:"@auth.backoff",effect:[increaseBackoffDelay,logPrematureErrorOrCloseEvent(t)]}});const d={target:"@ok.awaiting-pong",effect:e=>{e.socket?.send("ping")}},u=()=>{const t="undefined"!=typeof document?document:void 0;return"hidden"===t?.visibilityState&&e.canZombie()?"@idle.zombie":d};if(a.addTimedTransition("@ok.connected",HEARTBEAT_INTERVAL,u).addTransitions("@ok.connected",{NAVIGATOR_OFFLINE:u,WINDOW_GOT_FOCUS:d}),a.addTransitions("@idle.zombie",{WINDOW_GOT_FOCUS:"@connecting.backoff"}),a.onEnter("@ok.*",e=>{e.patch({successCount:e.successCount+1});const t=setTimeout(n.unpause,0);return e=>{c(e.socket),e.patch({socket:null}),clearTimeout(t),n.pause()}}).addTransitions("@ok.awaiting-pong",{PONG:"@ok.connected"}).addTimedTransition("@ok.awaiting-pong",PONG_TIMEOUT,{target:"@connecting.busy",effect:log(1,"Received no pong from server, assume implicit connection loss.")}).addTransitions("@ok.*",{EXPLICIT_SOCKET_ERROR:(e,t)=>1===t.socket?.readyState?null:{target:"@connecting.backoff",effect:increaseBackoffDelay},EXPLICIT_SOCKET_CLOSE:e=>shouldDisconnect(e.event.code)?{target:"@idle.failed",effect:[logPermanentClose,r(e.event.reason,e.event.code)]}:shouldReauth(e.event.code)?4109===e.event.code?"@auth.busy":{target:"@auth.backoff",effect:[increaseBackoffDelay,logCloseEvent(e.event)]}:shouldRetryWithoutReauth(e.event.code)?{target:"@connecting.backoff",effect:[increaseBackoffDelayAggressively,logCloseEvent(e.event)]}:{target:"@connecting.backoff",effect:[increaseBackoffDelay,logCloseEvent(e.event)]}}),"undefined"!=typeof document){const e="undefined"!=typeof document?document:void 0,t="undefined"!=typeof window?window:void 0,n=t??e;a.onEnter("*",o=>{function r(){a.send({type:"NAVIGATOR_OFFLINE"})}function i(){a.send({type:"NAVIGATOR_ONLINE"})}function s(){"visible"===e?.visibilityState&&a.send({type:"WINDOW_GOT_FOCUS"})}return t?.addEventListener("online",i),t?.addEventListener("offline",r),n?.addEventListener("visibilitychange",s),()=>{n?.removeEventListener("visibilitychange",s),t?.removeEventListener("online",i),t?.removeEventListener("offline",r),c(o.socket)}})}const f=[],{statusDidChange:p,didConnect:_,didDisconnect:m,unsubscribe:h}=defineConnectivityEvents(a);return f.push(h),t.enableDebugLogging&&f.push(enableTracing(a)),a.start(),{machine:a,cleanups:f,events:{statusDidChange:p,didConnect:_,didDisconnect:m,onMessage:n.observable,onLiveblocksError:o.observable}}}var ManagedSocket=class{#T;#A;events;constructor(e,t=!1,n=!0){const{machine:o,events:r,cleanups:a}=createConnectionStateMachine(e,{waitForActorId:n,enableDebugLogging:t});this.#T=o,this.events=r,this.#A=a}getStatus(){try{return toNewConnectionStatus(this.#T)}catch{return"initial"}}get authValue(){return this.#T.context.authValue}connect(){this.#T.send({type:"CONNECT"})}reconnect(){this.#T.send({type:"RECONNECT"})}disconnect(){this.#T.send({type:"DISCONNECT"})}destroy(){let e;for(this.#T.stop();e=this.#A.pop();)e()}send(e){const t=this.#T.context?.socket;null===t?warn$1("Cannot send: not connected yet",e):1!==t.readyState?warn$1("Cannot send: WebSocket no longer open",e):t.send(e)}_privateSendMachineEvent(e){this.#T.send(e)}},Permission=(e=>(e.Read="room:read",e.Write="room:write",e.PresenceWrite="room:presence:write",e.CommentsWrite="comments:write",e.CommentsRead="comments:read",e))(Permission||{});function canWriteStorage(e){return e.includes("room:write")}function canComment(e){return e.includes("comments:write")||e.includes("room:write")}function isValidAuthTokenPayload(e){return isPlainObject$2(e)&&("acc"===e.k||"id"===e.k||"sec-legacy"===e.k)}function parseAuthToken(e){const t=e.split(".");if(3!==t.length)throw new Error("Authentication error: invalid JWT token");const n=tryParseJson(b64decode(t[1]));if(!n||!isValidAuthTokenPayload(n))throw new Error("Authentication error: expected a valid 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:e,parsed:n}}function createAuthManager(e,t){const n=prepareAuthentication(e),o=new Set,r=[],a=[],i=new Map;function s(e,t){return"comments:read"===e?t.includes("comments:read")||t.includes("comments:write")||t.includes("room:read")||t.includes("room:write"):"room:read"===e&&(t.includes("room:read")||t.includes("room:write"))}async function l(r){const a=e.polyfills?.fetch??("undefined"==typeof window?void 0:window.fetch);if("private"===n.type){if(void 0===a)throw new StopRetrying("To use Liveblocks client in a non-DOM environment with a url as auth endpoint, you need to provide a fetch polyfill.");const e=parseAuthToken((await fetchAuthEndpoint(a,n.url,{room:r.roomId})).token);if(o.has(e.raw))throw new StopRetrying("The same Liveblocks auth token was issued from the backend before. Caching Liveblocks tokens is not supported.");return t?.(e.parsed),e}if("custom"===n.type){const e=await n.callback(r.roomId);if(e&&"object"==typeof e){if("string"==typeof e.token){const n=parseAuthToken(e.token);return t?.(n.parsed),n}if("string"==typeof e.error){const t=`Authentication failed: ${"reason"in e&&"string"==typeof e.reason?e.reason:"Forbidden"}`;throw"forbidden"===e.error?new StopRetrying(t):new Error(t)}}throw new Error('Your authentication callback function should return a token, but it did not. Hint: the return value should look like: { token: "..." }')}throw new Error("Unexpected authentication type. Must be private or custom.")}return{reset:function(){o.clear(),r.length=0,a.length=0,i.clear()},getAuthValue:async function(e){if("public"===n.type)return{type:"public",publicApiKey:n.publicApiKey};const t=function(e){const t=Math.ceil(Date.now()/1e3);for(let n=r.length-1;n>=0;n--){const o=r[n];if(a[n]<=t)r.splice(n,1),a.splice(n,1);else{if("id"===o.parsed.k)return o;if("acc"===o.parsed.k){if(!e.roomId&&0===Object.entries(o.parsed.perms).length)return o;for(const[t,n]of Object.entries(o.parsed.perms))if(e.roomId){if(t.includes("*")&&e.roomId.startsWith(t.replace("*",""))||e.roomId===t&&s(e.requestedScope,n))return o}else if(t.includes("*")&&s(e.requestedScope,n))return o}}}}(e);if(void 0!==t)return{type:"secret",token:t};let c;e.roomId?(c=i.get(e.roomId),void 0===c&&(c=l(e),i.set(e.roomId,c))):(c=i.get("liveblocks-user-token"),void 0===c&&(c=l(e),i.set("liveblocks-user-token",c)));try{const e=await c,t=30,n=Math.floor(Date.now()/1e3)+(e.parsed.exp-e.parsed.iat)-t;return o.add(e.raw),"sec-legacy"!==e.parsed.k&&(r.push(e),a.push(n)),{type:"secret",token:e}}finally{e.roomId?i.delete(e.roomId):i.delete("liveblocks-user-token")}}}}function prepareAuthentication(e){const{publicApiKey:t,authEndpoint:n}=e;if(void 0!==n&&void 0!==t)throw new Error("You cannot simultaneously use `publicApiKey` and `authEndpoint` options. Please pick one and leave the other option unspecified. For more information: https://liveblocks.io/docs/api-reference/liveblocks-client#createClient");if("string"==typeof t){if(t.startsWith("sk_"))throw new Error("Invalid `publicApiKey` option. The value you passed is a secret key, which should not be used from the client. Please only ever pass a public key here. For more information: https://liveblocks.io/docs/api-reference/liveblocks-client#createClientPublicKey");if(!t.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:t}}if("string"==typeof n)return{type:"private",url:n};if("function"==typeof n)return{type:"custom",callback:n};if(void 0!==n)throw new Error("The `authEndpoint` option must be a string or a function. For more information: https://liveblocks.io/docs/api-reference/liveblocks-client#createClientAuthEndpoint");throw new Error("Invalid Liveblocks client options. Please provide either a `publicApiKey` or `authEndpoint` option. They cannot both be empty. For more information: https://liveblocks.io/docs/api-reference/liveblocks-client#createClient")}async function fetchAuthEndpoint(e,t,n){const o=await e(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!o.ok){const e=`${(await o.text()).trim()||"reason not provided in auth response"} (${o.status} returned by POST ${t})`;throw 401===o.status||403===o.status?new StopRetrying(`Unauthorized: ${e}`):new Error(`Failed to authenticate: ${e}`)}let r;try{r=await o.json()}catch(e){throw new Error(`Expected a JSON response when doing a POST request on "${t}". ${String(e)}`)}if(!isPlainObject$2(r)||"string"!=typeof r.token)throw new Error(`Expected a JSON response of the form \`{ token: "..." }\` when doing a POST request on "${t}", but got ${JSON.stringify(r)}`);const{token:a}=r;return{token:a}}var DEFAULT_BASE_URL="https://api.liveblocks.io",kInternal=Symbol(),eventSource=makeEventSource();function unlinkDevTools(e){}eventSource.observable;var freeze$2=e=>e,kSinks=Symbol("kSinks"),kTrigger=Symbol("kTrigger"),signalsToTrigger=null;function batch(e){if(null===signalsToTrigger){signalsToTrigger=new Set;try{e()}finally{for(const e of signalsToTrigger)e[kTrigger]();signalsToTrigger=null}}else e()}function enqueueTrigger(e){signalsToTrigger||raise("Expected to be in an active batch"),signalsToTrigger.add(e)}function merge(e,t){let n=!1;const o={...e};return Object.keys(t).forEach(e=>{const r=e,a=t[r];o[r]!==a&&(void 0===a?delete o[r]:o[r]=a,n=!0)}),n?o:e}var AbstractSignal=class{equals;#O;[kSinks];constructor(e){this.equals=e??Object.is,this.#O=makeEventSource(),this[kSinks]=new Set,this.get=this.get.bind(this),this.subscribe=this.subscribe.bind(this),this.subscribeOnce=this.subscribeOnce.bind(this)}[Symbol.dispose](){this.#O[Symbol.dispose](),this.#O="(disposed)",this.equals="(disposed)"}get hasWatchers(){if(this.#O.count()>0)return!0;for(const e of this[kSinks])if(e.hasWatchers)return!0;return!1}[kTrigger](){this.#O.notify();for(const e of this[kSinks])enqueueTrigger(e)}subscribe(e){return this.#O.subscribe(e)}subscribeOnce(e){const t=this.subscribe(()=>(t(),e()));return t}waitUntil(){throw new Error("waitUntil not supported on Signals")}markSinksDirty(){for(const e of this[kSinks])e.markDirty()}addSink(e){this[kSinks].add(e)}removeSink(e){this[kSinks].delete(e)}asReadonly(){return this}},Signal=class extends AbstractSignal{#I;constructor(e,t){super(t),this.#I=freeze$2(e)}[Symbol.dispose](){super[Symbol.dispose](),this.#I="(disposed)"}get(){return this.#I}set(e){batch(()=>{"function"==typeof e&&(e=e(this.#I)),this.equals(this.#I,e)||(this.#I=freeze$2(e),this.markSinksDirty(),enqueueTrigger(this))})}},PatchableSignal=class extends Signal{constructor(e){super(freeze$2(compactObject(e)))}set(){throw new Error("Don't call .set() directly, use .patch()")}patch(e){super.set(t=>merge(t,e))}},INITIAL=Symbol(),DerivedSignal=class e extends AbstractSignal{#k;#N;#j;#$;static from(...t){const n=t.pop();if("function"!=typeof n&&raise("Invalid .from() call, last argument expected to be a function"),"function"==typeof t[t.length-1]){const o=n,r=t.pop();return new e(t,r,o)}return new e(t,n)}constructor(e,t,n){super(n),this.#N=!0,this.#k=INITIAL,this.#j=e,this.#$=t;for(const t of e)t.addSink(this)}[Symbol.dispose](){for(const e of this.#j)e.removeSink(this);this.#k="(disposed)",this.#j="(disposed)",this.#$="(disposed)"}get isDirty(){return this.#N}#F(){const e=this.#$(...this.#j.map(e=>e.get()));return this.#N=!1,!this.equals(this.#k,e)&&(this.#k=e,!0)}markDirty(){this.#N||(this.#N=!0,this.markSinksDirty())}get(){return this.#N&&this.#F(),this.#k}[kTrigger](){if(!this.hasWatchers)return;this.#F()&&super[kTrigger]()}},MutableSignal=class extends AbstractSignal{#P;constructor(e){super(),this.#P=e}[Symbol.dispose](){super[Symbol.dispose](),this.#P="(disposed)"}get(){return this.#P}mutate(e){batch(()=>{const t=!e||e(this.#P);null!==t&&"object"==typeof t&&"then"in t&&raise("MutableSignal.mutate() does not support async callbacks"),!1!==t&&(this.markSinksDirty(),enqueueTrigger(this))})}},MIN_CODE=32,MAX_CODE=126,NUM_DIGITS=MAX_CODE-MIN_CODE+1,ZERO=nthDigit(0),ONE=nthDigit(1),ZERO_NINE=ZERO+nthDigit(-1);function nthDigit(e){const t=MIN_CODE+(e<0?NUM_DIGITS+e:e);if(t<MIN_CODE||t>MAX_CODE)throw new Error(`Invalid n value: ${e}`);return String.fromCharCode(t)}function makePosition(e,t){return void 0!==e&&void 0!==t?between(e,t):void 0!==e?after$1(e):void 0!==t?before$1(t):ONE}function before$1(e){const t=e.length-1;for(let n=0;n<=t;n++){const o=e.charCodeAt(n);if(!(o<=MIN_CODE))return n===t?o===MIN_CODE+1?e.substring(0,n)+ZERO_NINE:e.substring(0,n)+String.fromCharCode(o-1):e.substring(0,n+1)}return ONE}function after$1(e){for(let t=0;t<=e.length-1;t++){const n=e.charCodeAt(t);if(!(n>=MAX_CODE))return e.substring(0,t)+String.fromCharCode(n+1)}return e+ONE}function between(e,t){if(e<t)return _between(e,t);if(e>t)return _between(t,e);throw new Error("Cannot compute value between two equal positions")}function _between(e,t){let n=0;const o=e.length,r=t.length;for(;;){const a=n<o?e.charCodeAt(n):MIN_CODE,i=n<r?t.charCodeAt(n):MAX_CODE;if(a!==i){if(i-a===1){const t=n+1;let o=e.substring(0,t);o.length<t&&(o+=ZERO.repeat(t-o.length));return o+_between(e.substring(t),"")}return takeN(e,n)+String.fromCharCode(i+a>>1)}n++}}function takeN(e,t){return t<e.length?e.substring(0,t):e+ZERO.repeat(t-e.length)}var MIN_NON_ZERO_CODE=MIN_CODE+1;function isPos(e){if(""===e)return!1;const t=e.length-1,n=e.charCodeAt(t);if(n<MIN_NON_ZERO_CODE||n>MAX_CODE)return!1;for(let n=0;n<t;n++){const t=e.charCodeAt(n);if(t<MIN_CODE||t>MAX_CODE)return!1}return!0}function convertToPos(e){const t=[];for(let n=0;n<e.length;n++){const o=e.charCodeAt(n);t.push(o<MIN_CODE?MIN_CODE:o>MAX_CODE?MAX_CODE:o)}for(;t.length>0&&t[t.length-1]===MIN_CODE;)t.length--;return t.length>0?String.fromCharCode(...t):ONE}function asPos(e){return isPos(e)?e:convertToPos(e)}function isAckOp(e){return 5===e.type&&"ACK"===e.id}function crdtAsLiveNode(e){return e}function HasParent(e,t,n=asPos(t)){return Object.freeze({type:"HasParent",node:e,key:t,pos:n})}var NoParent=Object.freeze({type:"NoParent"});function Orphaned(e,t=asPos(e)){return Object.freeze({type:"Orphaned",oldKey:e,oldPos:t})}var AbstractCrdt=class{#M;#B;#L=NoParent;_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 assertNever(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 assertNever(this.parent,"Unknown state")}}get _pool(){return this.#M}get roomId(){return this.#M?this.#M.roomId:null}get _id(){return this.#B}get parent(){return this.#L}get _parentKey(){switch(this.parent.type){case"HasParent":return this.parent.key;case"NoParent":return null;case"Orphaned":return this.parent.oldKey;default:return assertNever(this.parent,"Unknown state")}}_apply(e,t){return 5===e.type&&"HasParent"===this.parent.type?this.parent.node._detachChild(crdtAsLiveNode(this)):{modified:!1}}_setParentLink(e,t){switch(this.parent.type){case"HasParent":if(this.parent.node!==e)throw new Error("Cannot set parent: node already has a parent");return void(this.#L=HasParent(e,t));case"Orphaned":case"NoParent":return void(this.#L=HasParent(e,t));default:return assertNever(this.parent,"Unknown state")}}_attach(e,t){if(this.#B||this.#M)throw new Error("Cannot attach node: already attached");t.addNode(e,crdtAsLiveNode(this)),this.#B=e,this.#M=t}_detach(){switch(this.#M&&this.#B&&this.#M.deleteNode(this.#B),this.parent.type){case"HasParent":this.#L=Orphaned(this.parent.key,this.parent.pos);break;case"NoParent":this.#L=NoParent;break;case"Orphaned":break;default:assertNever(this.parent,"Unknown state")}this.#M=void 0}#U;#V;#H;invalidate(){void 0===this.#U&&void 0===this.#H||(this.#U=void 0,this.#H=void 0,"HasParent"===this.parent.type&&this.parent.node.invalidate())}toTreeNode(e){return void 0!==this.#H&&this.#V===e||(this.#V=e,this.#H=this._toTreeNode(e)),this.#H}toImmutable(){return void 0===this.#U&&(this.#U=this._toImmutable()),this.#U}};function isRootCrdt(e){return 0===e.type&&!isChildCrdt(e)}function isChildCrdt(e){return void 0!==e.parentId&&void 0!==e.parentKey}var LiveRegister=class e extends AbstractCrdt{#z;constructor(e){super(),this.#z=e}get data(){return this.#z}static _deserialize([t,n],o,r){const a=new e(n.data);return a._attach(t,r),a}_toOps(e,t,n){if(void 0===this._id)throw new Error("Cannot serialize register if parentId or parentKey is undefined");return[{type:8,opId:n?.generateOpId(),id:this._id,parentId:e,parentKey:t,data:this.data}]}_serialize(){if("HasParent"!==this.parent.type)throw new Error("Cannot serialize LiveRegister if parent is missing");return{type:3,parentId:nn(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,t){return super._apply(e,t)}_toTreeNode(e){return{type:"Json",id:this._id??nanoid(),key:e,payload:this.#z}}_toImmutable(){return this.#z}clone(){return deepClone(this.data)}};function compareNodePosition(e,t){const n=e._parentPos,o=t._parentPos;return n===o?0:n<o?-1:1}var LiveList=class e extends AbstractCrdt{#q;#K;#W;constructor(e){let t;super(),this.#q=[],this.#K=new WeakSet,this.#W=new Map;for(const n of e){const e=makePosition(t),o=lsonToLiveNode(n);o._setParentLink(this,e),this.#q.push(o),t=e}}static _deserialize([t],n,o){const r=new e([]);r._attach(t,o);const a=n.get(t);if(void 0===a)return r;for(const[e,t]of a){const a=deserialize$1([e,t],n,o);a._setParentLink(r,t.parentKey),r._insertAndSort(a)}return r}_toOps(e,t,n){if(void 0===this._id)throw new Error("Cannot serialize item is not attached");const o=[],r={id:this._id,opId:n?.generateOpId(),type:2,parentId:e,parentKey:t};o.push(r);for(const e of this.#q){const t=e._getParentKeyOrThrow(),r=HACK_addIntentAndDeletedIdToOperation(e._toOps(this._id,t,n),void 0),a=r[0].opId;void 0!==a&&this.#W.set(t,a),o.push(...r)}return o}_insertAndSort(e){this.#q.push(e),this._sortItems()}_sortItems(){this.#q.sort(compareNodePosition),this.invalidate()}_indexOfPosition(e){return this.#q.findIndex(t=>t._getParentKeyOrThrow()===e)}_attach(e,t){super._attach(e,t);for(const e of this.#q)e._attach(t.generateId(),t)}_detach(){super._detach();for(const e of this.#q)e._detach()}#G(e){if(void 0===this._pool)throw new Error("Can't attach child if managed pool is not present");const{id:t,parentKey:n}=e,o=creationOpToLiveNode(e);o._attach(t,this._pool),o._setParentLink(this,n);const r=e.deletedId,a=this._indexOfPosition(n);if(-1!==a){const t=this.#q[a];if(t._id===r)return t._detach(),this.#q[a]=o,{modified:makeUpdate(this,[setDelta(a,o)]),reverse:[]};{this.#K.add(t),this.#q[a]=o;const n=[setDelta(a,o)],r=this.#Y(e.deletedId);return r&&n.push(r),{modified:makeUpdate(this,n),reverse:[]}}}{const t=[],r=this.#Y(e.deletedId);return r&&t.push(r),this._insertAndSort(o),t.push(insertDelta(this._indexOfPosition(n),o)),{reverse:[],modified:makeUpdate(this,t)}}}#J(e){if(void 0===this._pool)throw new Error("Can't attach child if managed pool is not present");const t=[],n=this.#Y(e.deletedId);n&&t.push(n);const o=this.#W.get(e.parentKey);if(void 0!==o){if(o!==e.opId)return 0===t.length?{modified:!1}:{modified:makeUpdate(this,t),reverse:[]};this.#W.delete(e.parentKey)}const r=this._indexOfPosition(e.parentKey),a=this.#q.find(t=>t._id===e.id);if(void 0!==a){if(a._parentKey===e.parentKey)return{modified:t.length>0&&makeUpdate(this,t),reverse:[]};if(-1!==r){this.#K.add(this.#q[r]);const[e]=this.#q.splice(r,1);t.push(deleteDelta(r,e))}const n=this.#q.indexOf(a);a._setParentLink(this,e.parentKey),this._sortItems();const o=this.#q.indexOf(a);return o!==n&&t.push(moveDelta(n,o,a)),{modified:t.length>0&&makeUpdate(this,t),reverse:[]}}{const n=this._pool.getNode(e.id);if(n&&this.#K.has(n)){n._setParentLink(this,e.parentKey),this.#K.delete(n),this._insertAndSort(n);const o=this.#q.indexOf(n);return{modified:makeUpdate(this,[-1===r?insertDelta(o,n):setDelta(o,n),...t]),reverse:[]}}{-1!==r&&this.#q.splice(r,1);const{newItem:n,newIndex:o}=this.#X(e,e.parentKey);return{modified:makeUpdate(this,[-1===r?insertDelta(o,n):setDelta(o,n),...t]),reverse:[]}}}}#Y(e){if(void 0===e||void 0===this._pool)return null;const t=this._pool.getNode(e);if(void 0===t)return null;const n=this._detachChild(t);return!1===n.modified?null:n.modified.updates[0]}#Z(e){if(void 0===this._pool)throw new Error("Can't attach child if managed pool is not present");const t=asPos(e.parentKey),n=this._indexOfPosition(t);-1!==n&&this.#Q(n,t);const{newItem:o,newIndex:r}=this.#X(e,t);return{modified:makeUpdate(this,[insertDelta(r,o)]),reverse:[]}}#ee(e){const t=this.#q.find(t=>t._id===e.id),n=asPos(e.parentKey),o=this._indexOfPosition(n);if(t){if(t._parentKey===n)return{modified:!1};{const e=this.#q.indexOf(t);-1!==o&&this.#Q(o,n),t._setParentLink(this,n),this._sortItems();const r=this._indexOfPosition(n);return r===e?{modified:!1}:{modified:makeUpdate(this,[moveDelta(e,r,t)]),reverse:[]}}}{const t=nn(this._pool).getNode(e.id);if(t&&this.#K.has(t)){t._setParentLink(this,n),this.#K.delete(t),this._insertAndSort(t);return{modified:makeUpdate(this,[insertDelta(this._indexOfPosition(n),t)]),reverse:[]}}{-1!==o&&this.#Q(o,n);const{newItem:t,newIndex:r}=this.#X(e,n);return{modified:makeUpdate(this,[insertDelta(r,t)]),reverse:[]}}}}#te(e){const{id:t,parentKey:n}=e,o=creationOpToLiveNode(e);if(void 0!==this._pool?.getNode(t))return{modified:!1};o._attach(t,nn(this._pool)),o._setParentLink(this,n);const r=this._indexOfPosition(n);let a=n;if(-1!==r){const e=this.#q[r]?._parentPos,t=this.#q[r+1]?._parentPos;a=makePosition(e,t),o._setParentLink(this,a)}this._insertAndSort(o);return{modified:makeUpdate(this,[insertDelta(this._indexOfPosition(a),o)]),reverse:[{type:5,id:t}]}}#ne(e){const{id:t,parentKey:n}=e,o=creationOpToLiveNode(e);if(void 0!==this._pool?.getNode(t))return{modified:!1};this.#W.set(n,nn(e.opId));const r=this._indexOfPosition(n);o._attach(t,nn(this._pool)),o._setParentLink(this,n);const a=n;if(-1!==r){const t=this.#q[r];t._detach(),this.#q[r]=o;const a=HACK_addIntentAndDeletedIdToOperation(t._toOps(nn(this._id),n,this._pool),e.id),i=[setDelta(r,o)],s=this.#Y(e.deletedId);return s&&i.push(s),{modified:makeUpdate(this,i),reverse:a}}this._insertAndSort(o),this.#Y(e.deletedId);return{reverse:[{type:5,id:t}],modified:makeUpdate(this,[insertDelta(this._indexOfPosition(a),o)])}}_attachChild(e,t){if(void 0===this._pool)throw new Error("Can't attach child if managed pool is not present");let n;return n="set"===e.intent?1===t?this.#G(e):2===t?this.#J(e):this.#ne(e):1===t?this.#Z(e):2===t?this.#ee(e):this.#te(e),!1!==n.modified&&this.invalidate(),n}_detachChild(e){if(e){const t=nn(e._parentKey),n=e._toOps(nn(this._id),t,this._pool),o=this.#q.indexOf(e);if(-1===o)return{modified:!1};const[r]=this.#q.splice(o,1);return this.invalidate(),e._detach(),{modified:makeUpdate(this,[deleteDelta(o,r)]),reverse:n}}return{modified:!1}}#oe(e,t){if(this.#K.has(t)){this.#K.delete(t),t._setParentLink(this,e),this._insertAndSort(t);return{modified:makeUpdate(this,[insertDelta(this.#q.indexOf(t),t)]),reverse:[]}}if(e===t._parentKey)return{modified:!1};const n=this._indexOfPosition(e);if(-1===n){const n=this.#q.indexOf(t);t._setParentLink(this,e),this._sortItems();const o=this.#q.indexOf(t);return o===n?{modified:!1}:{modified:makeUpdate(this,[moveDelta(n,o,t)]),reverse:[]}}{this.#q[n]._setParentLink(this,makePosition(e,this.#q[n+1]?._parentPos));const o=this.#q.indexOf(t);t._setParentLink(this,e),this._sortItems();const r=this.#q.indexOf(t);return r===o?{modified:!1}:{modified:makeUpdate(this,[moveDelta(o,r,t)]),reverse:[]}}}#re(e,t){const n=nn(t._parentKey);if(this.#K.has(t)){const n=this._indexOfPosition(e);return this.#K.delete(t),-1!==n&&this.#q[n]._setParentLink(this,makePosition(e,this.#q[n+1]?._parentPos)),t._setParentLink(this,e),this._insertAndSort(t),{modified:!1}}{if(e===n)return{modified:!1};const o=this.#q.indexOf(t),r=this._indexOfPosition(e);-1!==r&&this.#q[r]._setParentLink(this,makePosition(e,this.#q[r+1]?._parentPos)),t._setParentLink(this,e),this._sortItems();const a=this.#q.indexOf(t);return o===a?{modified:!1}:{modified:makeUpdate(this,[moveDelta(o,a,t)]),reverse:[]}}}#ae(e,t){const n=nn(t._parentKey),o=this.#q.indexOf(t),r=this._indexOfPosition(e);-1!==r&&this.#q[r]._setParentLink(this,makePosition(e,this.#q[r+1]?._parentPos)),t._setParentLink(this,e),this._sortItems();const a=this.#q.indexOf(t);return o===a?{modified:!1}:{modified:makeUpdate(this,[moveDelta(o,a,t)]),reverse:[{type:1,id:nn(t._id),parentKey:n}]}}_setChildKey(e,t,n){return 1===n?this.#oe(e,t):2===n?this.#re(e,t):this.#ae(e,t)}_apply(e,t){return super._apply(e,t)}_serialize(){if("HasParent"!==this.parent.type)throw new Error("Cannot serialize LiveList if parent is missing");return{type:1,parentId:nn(this.parent.node._id,"Parent node expected to have ID"),parentKey:this.parent.key}}get length(){return this.#q.length}push(e){return this._pool?.assertStorageIsWritable(),this.insert(e,this.length)}insert(e,t){if(this._pool?.assertStorageIsWritable(),t<0||t>this.#q.length)throw new Error(`Cannot insert list item at index "${t}". index should be between 0 and ${this.#q.length}`);const n=makePosition(this.#q[t-1]?this.#q[t-1]._parentPos:void 0,this.#q[t]?this.#q[t]._parentPos:void 0),o=lsonToLiveNode(e);if(o._setParentLink(this,n),this._insertAndSort(o),this._pool&&this._id){const e=this._pool.generateId();o._attach(e,this._pool),this._pool.dispatch(o._toOps(this._id,n,this._pool),[{type:5,id:e}],new Map([[this._id,makeUpdate(this,[insertDelta(t,o)])]]))}}move(e,t){if(this._pool?.assertStorageIsWritable(),t<0)throw new Error("targetIndex cannot be less than 0");if(t>=this.#q.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.#q.length)throw new Error("index cannot be greater or equal than the list length");let n=null,o=null;e<t?(o=t===this.#q.length-1?void 0:this.#q[t+1]._parentPos,n=this.#q[t]._parentPos):(o=this.#q[t]._parentPos,n=0===t?void 0:this.#q[t-1]._parentPos);const r=makePosition(n,o),a=this.#q[e],i=a._getParentKeyOrThrow();if(a._setParentLink(this,r),this._sortItems(),this._pool&&this._id){const n=new Map([[this._id,makeUpdate(this,[moveDelta(e,t,a)])]]);this._pool.dispatch([{type:1,id:nn(a._id),opId:this._pool.generateOpId(),parentKey:r}],[{type:1,id:nn(a._id),parentKey:i}],n)}}delete(e){if(this._pool?.assertStorageIsWritable(),e<0||e>=this.#q.length)throw new Error(`Cannot delete list item at index "${e}". index should be between 0 and ${this.#q.length-1}`);const t=this.#q[e];t._detach();const[n]=this.#q.splice(e,1);if(this.invalidate(),this._pool){const o=t._id;if(o){const r=new Map;r.set(nn(this._id),makeUpdate(this,[deleteDelta(e,n)])),this._pool.dispatch([{id:o,opId:this._pool.generateOpId(),type:5}],t._toOps(nn(this._id),t._getParentKeyOrThrow()),r)}}}clear(){if(this._pool?.assertStorageIsWritable(),this._pool){const e=[],t=[],n=[];for(const o of this.#q){o._detach();const r=o._id;r&&(e.push({type:5,id:r,opId:this._pool.generateOpId()}),t.push(...o._toOps(nn(this._id),o._getParentKeyOrThrow())),n.push(deleteDelta(0,o)))}this.#q=[],this.invalidate();const o=new Map;o.set(nn(this._id),makeUpdate(this,n)),this._pool.dispatch(e,t,o)}else{for(const e of this.#q)e._detach();this.#q=[],this.invalidate()}}set(e,t){if(this._pool?.assertStorageIsWritable(),e<0||e>=this.#q.length)throw new Error(`Cannot set list item at index "${e}". index should be between 0 and ${this.#q.length-1}`);const n=this.#q[e],o=n._getParentKeyOrThrow(),r=n._id;n._detach();const a=lsonToLiveNode(t);if(a._setParentLink(this,o),this.#q[e]=a,this.invalidate(),this._pool&&this._id){const t=this._pool.generateId();a._attach(t,this._pool);const i=new Map;i.set(this._id,makeUpdate(this,[setDelta(e,a)]));const s=HACK_addIntentAndDeletedIdToOperation(a._toOps(this._id,o,this._pool),r);this.#W.set(o,nn(s[0].opId));const l=HACK_addIntentAndDeletedIdToOperation(n._toOps(this._id,o,void 0),t);this._pool.dispatch(s,l,i)}}toArray(){return this.#q.map(e=>liveNodeToLson(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.#q.length))return liveNodeToLson(this.#q[e])}indexOf(e,t){return this.toArray().indexOf(e,t)}lastIndexOf(e,t){return this.toArray().lastIndexOf(e,t)}map(e){return this.#q.map((t,n)=>e(liveNodeToLson(t),n))}some(e){return this.toArray().some(e)}[Symbol.iterator](){return new LiveListIterator(this.#q)}#X(e,t){const n=creationOpToLiveNode(e);n._attach(e.id,nn(this._pool)),n._setParentLink(this,t),this._insertAndSort(n);return{newItem:n,newIndex:this._indexOfPosition(t)}}#Q(e,t){const n=makePosition(t,this.#q.length>e+1?this.#q[e+1]?._parentPos:void 0);this.#q[e]._setParentLink(this,n)}_toTreeNode(e){return{type:"LiveList",id:this._id??nanoid(),key:e,payload:this.#q.map((e,t)=>e.toTreeNode(t.toString()))}}toImmutable(){return super.toImmutable()}_toImmutable(){const e=this.#q.map(e=>e.toImmutable());return e}clone(){return new e(this.#q.map(e=>e.clone()))}},LiveListIterator=class{#ie;constructor(e){this.#ie=e[Symbol.iterator]()}[Symbol.iterator](){return this}next(){const e=this.#ie.next();if(e.done)return{done:!0,value:void 0};return{value:liveNodeToLson(e.value)}}};function makeUpdate(e,t){return{node:e,type:"LiveList",updates:t}}function setDelta(e,t){return{index:e,type:"set",item:t instanceof LiveRegister?t.data:t}}function deleteDelta(e,t){return{type:"delete",index:e,deletedItem:t instanceof LiveRegister?t.data:t}}function insertDelta(e,t){return{index:e,type:"insert",item:t instanceof LiveRegister?t.data:t}}function moveDelta(e,t,n){return{type:"move",index:t,item:n instanceof LiveRegister?n.data:n,previousIndex:e}}function HACK_addIntentAndDeletedIdToOperation(e,t){return e.map((e,n)=>{if(0===n){return{...e,intent:"set",deletedId:t}}return e})}var LiveMap=class e extends AbstractCrdt{#se;#le;constructor(e){if(super(),this.#le=new Map,e){const t=[];for(const[n,o]of e){const e=lsonToLiveNode(o);e._setParentLink(this,n),t.push([n,e])}this.#se=new Map(t)}else this.#se=new Map}_toOps(e,t,n){if(void 0===this._id)throw new Error("Cannot serialize item is not attached");const o=[],r={id:this._id,opId:n?.generateOpId(),type:7,parentId:e,parentKey:t};o.push(r);for(const[e,t]of this.#se)o.push(...t._toOps(this._id,e,n));return o}static _deserialize([t,n],o,r){const a=new e;a._attach(t,r);const i=o.get(t);if(void 0===i)return a;for(const[e,t]of i){const n=deserialize$1([e,t],o,r);n._setParentLink(a,t.parentKey),a.#se.set(t.parentKey,n),a.invalidate()}return a}_attach(e,t){super._attach(e,t);for(const[e,n]of this.#se)isLiveNode(n)&&n._attach(t.generateId(),t)}_attachChild(e,t){if(void 0===this._pool)throw new Error("Can't attach child if managed pool is not present");const{id:n,parentKey:o,opId:r}=e,a=o,i=creationOpToLiveNode(e);if(void 0!==this._pool.getNode(n))return{modified:!1};if(2===t){const e=this.#le.get(a);if(e===r)return this.#le.delete(a),{modified:!1};if(void 0!==e)return{modified:!1}}else 1===t&&this.#le.delete(a);const s=this.#se.get(a);let l;if(s){const e=nn(this._id);l=s._toOps(e,a),s._detach()}else l=[{type:5,id:n}];return i._setParentLink(this,a),i._attach(n,this._pool),this.#se.set(a,i),this.invalidate(),{modified:{node:this,type:"LiveMap",updates:{[a]:{type:"update"}}},reverse:l}}_detach(){super._detach();for(const e of this.#se.values())e._detach()}_detachChild(e){const t=nn(this._id),n=nn(e._parentKey),o=e._toOps(t,n,this._pool);for(const[t,n]of this.#se)n===e&&(this.#se.delete(t),this.invalidate());e._detach();return{modified:{node:this,type:"LiveMap",updates:{[n]:{type:"delete"}}},reverse:o}}_serialize(){if("HasParent"!==this.parent.type)throw new Error("Cannot serialize LiveMap if parent is missing");return{type:2,parentId:nn(this.parent.node._id,"Parent node expected to have ID"),parentKey:this.parent.key}}get(e){const t=this.#se.get(e);if(void 0!==t)return liveNodeToLson(t)}set(e,t){this._pool?.assertStorageIsWritable();const n=this.#se.get(e);n&&n._detach();const o=lsonToLiveNode(t);if(o._setParentLink(this,e),this.#se.set(e,o),this.invalidate(),this._pool&&this._id){const t=this._pool.generateId();o._attach(t,this._pool);const r=new Map;r.set(this._id,{node:this,type:"LiveMap",updates:{[e]:{type:"update"}}});const a=o._toOps(this._id,e,this._pool);this.#le.set(e,nn(a[0].opId)),this._pool.dispatch(o._toOps(this._id,e,this._pool),n?n._toOps(this._id,e):[{type:5,id:t}],r)}}get size(){return this.#se.size}has(e){return this.#se.has(e)}delete(e){this._pool?.assertStorageIsWritable();const t=this.#se.get(e);if(void 0===t)return!1;if(t._detach(),this.#se.delete(e),this.invalidate(),this._pool&&t._id){const n=nn(this._id),o=new Map;o.set(n,{node:this,type:"LiveMap",updates:{[e]:{type:"delete"}}}),this._pool.dispatch([{type:5,id:t._id,opId:this._pool.generateOpId()}],t._toOps(n,e),o)}return!0}entries(){const e=this.#se.entries();return{[Symbol.iterator](){return this},next(){const t=e.next();if(t.done)return{done:!0,value:void 0};return{value:[t.value[0],liveNodeToLson(t.value[1])]}}}}[Symbol.iterator](){return this.entries()}keys(){return this.#se.keys()}values(){const e=this.#se.values();return{[Symbol.iterator](){return this},next(){const t=e.next();if(t.done)return{done:!0,value:void 0};return{value:liveNodeToLson(t.value)}}}}forEach(e){for(const t of this)e(t[1],t[0],this)}_toTreeNode(e){return{type:"LiveMap",id:this._id??nanoid(),key:e,payload:Array.from(this.#se.entries()).map(([e,t])=>t.toTreeNode(e))}}toImmutable(){return super.toImmutable()}_toImmutable(){const e=new Map;for(const[t,n]of this.#se)e.set(t,n.toImmutable());return freeze$2(e)}clone(){return new e(Array.from(this.#se).map(([e,t])=>[e,t.clone()]))}},LiveObject=class e extends AbstractCrdt{#se;#ce;static#de(e){const t=new Map;let n=null;for(const[o,r]of e)if(isRootCrdt(r))n=[o,r];else{const e=[o,r],n=t.get(r.parentId);void 0!==n?n.push(e):t.set(r.parentId,[e])}if(null===n)throw new Error("Root can't be null");return[n,t]}static _fromItems(t,n){const[o,r]=e.#de(t);return e._deserialize(o,r,n)}constructor(e={}){super(),this.#ce=new Map;const t=compactObject(e);for(const e of Object.keys(t)){const n=t[e];isLiveNode(n)&&n._setParentLink(this,e)}this.#se=new Map(Object.entries(t))}_toOps(e,t,n){if(void 0===this._id)throw new Error("Cannot serialize item is not attached");const o=n?.generateOpId(),r=[],a={type:4,id:this._id,opId:o,parentId:e,parentKey:t,data:{}};r.push(a);for(const[e,t]of this.#se)isLiveNode(t)?r.push(...t._toOps(this._id,e,n)):a.data[e]=t;return r}static _deserialize([t,n],o,r){const a=new e(n.data);return a._attach(t,r),this._deserializeChildren(a,o,r)}static _deserializeChildren(e,t,n){const o=t.get(nn(e._id));if(void 0===o)return e;for(const[r,a]of o){const o=deserializeToLson([r,a],t,n);isLiveStructure(o)&&o._setParentLink(e,a.parentKey),e.#se.set(a.parentKey,o),e.invalidate()}return e}_attach(e,t){super._attach(e,t);for(const[e,n]of this.#se)isLiveNode(n)&&n._attach(t.generateId(),t)}_attachChild(e,t){if(void 0===this._pool)throw new Error("Can't attach child if managed pool is not present");const{id:n,opId:o,parentKey:r}=e,a=creationOpToLson(e);if(void 0!==this._pool.getNode(n))return this.#ce.get(r)===o&&this.#ce.delete(r),{modified:!1};if(0===t)this.#ce.set(r,nn(o));else if(void 0!==this.#ce.get(r))return this.#ce.get(r)===o?(this.#ce.delete(r),{modified:!1}):{modified:!1};const i=nn(this._id),s=this.#se.get(r);let l;return isLiveNode(s)?(l=s._toOps(i,r),s._detach()):l=void 0===s?[{type:6,id:i,key:r}]:[{type:3,id:i,data:{[r]:s}}],this.#se.set(r,a),this.invalidate(),isLiveStructure(a)&&(a._setParentLink(this,r),a._attach(n,this._pool)),{reverse:l,modified:{node:this,type:"LiveObject",updates:{[r]:{type:"update"}}}}}_detachChild(e){if(e){const t=nn(this._id),n=nn(e._parentKey),o=e._toOps(t,n,this._pool);for(const[t,n]of this.#se)n===e&&(this.#se.delete(t),this.invalidate());e._detach();return{modified:{node:this,type:"LiveObject",updates:{[n]:{type:"delete"}}},reverse:o}}return{modified:!1}}_detach(){super._detach();for(const e of this.#se.values())isLiveNode(e)&&e._detach()}_apply(e,t){return 3===e.type?this.#ue(e,t):6===e.type?this.#fe(e,t):super._apply(e,t)}_serialize(){const e={};for(const[t,n]of this.#se)isLiveNode(n)||(e[t]=n);return"HasParent"===this.parent.type&&this.parent.node._id?{type:0,parentId:this.parent.node._id,parentKey:this.parent.key,data:e}:{type:0,data:e}}#ue(e,t){let n=!1;const o=nn(this._id),r=[],a={type:3,id:o,data:{}};for(const t in e.data){const e=this.#se.get(t);isLiveNode(e)?(r.push(...e._toOps(o,t)),e._detach()):void 0!==e?a.data[t]=e:void 0===e&&r.push({type:6,id:o,key:t})}const i={};for(const o in e.data){const r=e.data[o];if(void 0===r)continue;if(t)this.#ce.set(o,nn(e.opId));else{if(void 0!==this.#ce.get(o)){if(this.#ce.get(o)===e.opId){this.#ce.delete(o);continue}continue}n=!0}const a=this.#se.get(o);isLiveNode(a)&&a._detach(),n=!0,i[o]={type:"update"},this.#se.set(o,r),this.invalidate()}return 0!==Object.keys(a.data).length&&r.unshift(a),n?{modified:{node:this,type:"LiveObject",updates:i},reverse:r}:{modified:!1}}#fe(e,t){const n=e.key;if(!1===this.#se.has(n))return{modified:!1};if(!t&&void 0!==this.#ce.get(n))return{modified:!1};const o=this.#se.get(n),r=nn(this._id);let a=[];return isLiveNode(o)?(a=o._toOps(r,e.key),o._detach()):void 0!==o&&(a=[{type:3,id:r,data:{[n]:o}}]),this.#se.delete(n),this.invalidate(),{modified:{node:this,type:"LiveObject",updates:{[e.key]:{type:"delete"}}},reverse:a}}toObject(){return Object.fromEntries(this.#se)}set(e,t){this._pool?.assertStorageIsWritable(),this.update({[e]:t})}get(e){return this.#se.get(e)}delete(e){this._pool?.assertStorageIsWritable();const t=e,n=this.#se.get(t);if(void 0===n)return;if(void 0===this._pool||void 0===this._id)return isLiveNode(n)&&n._detach(),this.#se.delete(t),void this.invalidate();let o;isLiveNode(n)?(n._detach(),o=n._toOps(this._id,t)):o=[{type:3,data:{[t]:n},id:this._id}],this.#se.delete(t),this.invalidate();const r=new Map;r.set(this._id,{node:this,type:"LiveObject",updates:{[e]:{type:"delete"}}}),this._pool.dispatch([{type:6,key:t,id:this._id,opId:this._pool.generateOpId()}],o,r)}update(e){if(this._pool?.assertStorageIsWritable(),void 0===this._pool||void 0===this._id){for(const t in e){const n=e[t];if(void 0===n)continue;const o=this.#se.get(t);isLiveNode(o)&&o._detach(),isLiveNode(n)&&n._setParentLink(this,t),this.#se.set(t,n),this.invalidate()}return}const t=[],n=[],o=this._pool.generateOpId(),r={},a={id:this._id,type:3,data:{}},i={};for(const s in e){const l=e[s];if(void 0===l)continue;const c=this.#se.get(s);if(isLiveNode(c)?(n.push(...c._toOps(this._id,s)),c._detach()):void 0===c?n.push({type:6,id:this._id,key:s}):a.data[s]=c,isLiveNode(l)){l._setParentLink(this,s),l._attach(this._pool.generateId(),this._pool);const e=l._toOps(this._id,s,this._pool),n=e.find(e=>e.parentId===this._id);n&&this.#ce.set(s,nn(n.opId)),t.push(...e)}else r[s]=l,this.#ce.set(s,o);this.#se.set(s,l),this.invalidate(),i[s]={type:"update"}}0!==Object.keys(a.data).length&&n.unshift(a),0!==Object.keys(r).length&&t.unshift({opId:o,id:this._id,type:3,data:r});const s=new Map;s.set(this._id,{node:this,type:"LiveObject",updates:i}),this._pool.dispatch(t,n,s)}toImmutable(){return super.toImmutable()}toTreeNode(e){return super.toTreeNode(e)}_toTreeNode(e){const t=this._id??nanoid();return{type:"LiveObject",id:t,key:e,payload:Array.from(this.#se.entries()).map(([e,n])=>isLiveNode(n)?n.toTreeNode(e):{type:"Json",id:`${t}:${e}`,key:e,payload:n})}}_toImmutable(){const e={};for(const[t,n]of this.#se)e[t]=isLiveStructure(n)?n.toImmutable():n;return e}clone(){return new e(Object.fromEntries(Array.from(this.#se).map(([e,t])=>[e,isLiveStructure(t)?t.clone():deepClone(t)])))}};function creationOpToLiveNode(e){return lsonToLiveNode(creationOpToLson(e))}function creationOpToLson(e){switch(e.type){case 8:return e.data;case 4:return new LiveObject(e.data);case 7:return new LiveMap;case 2:return new LiveList([]);default:return assertNever(e,"Unknown creation Op")}}function isSameNodeOrChildOf(e,t){return e===t||"HasParent"===e.parent.type&&isSameNodeOrChildOf(e.parent.node,t)}function deserialize$1([e,t],n,o){switch(t.type){case 0:return LiveObject._deserialize([e,t],n,o);case 1:return LiveList._deserialize([e,t],n,o);case 2:return LiveMap._deserialize([e,t],n,o);case 3:return LiveRegister._deserialize([e,t],n,o);default:throw new Error("Unexpected CRDT type")}}function deserializeToLson([e,t],n,o){switch(t.type){case 0:return LiveObject._deserialize([e,t],n,o);case 1:return LiveList._deserialize([e,t],n,o);case 2:return LiveMap._deserialize([e,t],n,o);case 3:return t.data;default:throw new Error("Unexpected CRDT type")}}function isLiveStructure(e){return isLiveList(e)||isLiveMap(e)||isLiveObject(e)}function isLiveNode(e){return isLiveStructure(e)||isLiveRegister(e)}function isLiveList(e){return e instanceof LiveList}function isLiveMap(e){return e instanceof LiveMap}function isLiveObject(e){return e instanceof LiveObject}function isLiveRegister(e){return e instanceof LiveRegister}function cloneLson(e){return void 0===e?void 0:isLiveStructure(e)?e.clone():deepClone(e)}function liveNodeToLson(e){return e instanceof LiveRegister?e.data:e instanceof LiveList||e instanceof LiveMap||e instanceof LiveObject?e:assertNever(e,"Unknown AbstractCrdt")}function lsonToLiveNode(e){return e instanceof LiveObject||e instanceof LiveMap||e instanceof LiveList?e:new LiveRegister(e)}function getTreesDiffOperations(e,t){const n=[];return e.forEach((e,o)=>{t.get(o)||n.push({type:5,id:o})}),t.forEach((t,o)=>{const r=e.get(o);if(r)0===t.type&&(0===r.type&&JSON.stringify(t.data)===JSON.stringify(r.data)||n.push({type:3,id:o,data:t.data})),t.parentKey!==r.parentKey&&n.push({type:1,id:o,parentKey:nn(t.parentKey,"Parent key must not be missing")});else switch(t.type){case 3:n.push({type:8,id:o,parentId:t.parentId,parentKey:t.parentKey,data:t.data});break;case 1:n.push({type:2,id:o,parentId:t.parentId,parentKey:t.parentKey});break;case 0:if(void 0===t.parentId||void 0===t.parentKey)throw new Error("Internal error. Cannot serialize storage root into an operation");n.push({type:4,id:o,parentId:t.parentId,parentKey:t.parentKey,data:t.data});break;case 2:n.push({type:7,id:o,parentId:t.parentId,parentKey:t.parentKey})}}),n}function mergeObjectStorageUpdates(e,t){const n=e.updates;for(const[e,o]of entries(t.updates))n[e]=o;return{...t,updates:n}}function mergeMapStorageUpdates(e,t){const n=e.updates;for(const[e,o]of entries(t.updates))n[e]=o;return{...t,updates:n}}function mergeListStorageUpdates(e,t){const n=e.updates;return{...t,updates:n.concat(t.updates)}}function mergeStorageUpdates(e,t){return void 0===e?t:"LiveObject"===e.type&&"LiveObject"===t.type?mergeObjectStorageUpdates(e,t):"LiveMap"===e.type&&"LiveMap"===t.type?mergeMapStorageUpdates(e,t):"LiveList"===e.type&&"LiveList"===t.type?mergeListStorageUpdates(e,t):t}function isJsonScalar(e){return null===e||"string"==typeof e||"number"==typeof e||"boolean"==typeof e}function isJsonArray(e){return Array.isArray(e)}function isJsonObject(e){return!isJsonScalar(e)&&!isJsonArray(e)}function makeUser(e,t){const{connectionId:n,id:o,info:r}=e,a=canWriteStorage(e.scopes);return freeze$2(compactObject({connectionId:n,id:o,info:r,canWrite:a,canComment:canComment(e.scopes),isReadOnly:!a,presence:t}))}var ManagedOthers=class{#pe;#_e;signal;constructor(){this.#pe=new MutableSignal({connections:new Map,presences:new Map}),this.signal=DerivedSignal.from(this.#pe,e=>compact(Array.from(this.#pe.get().presences.keys()).map(e=>this.getUser(Number(e))))),this.#_e=new Map}get(){return this.signal.get()}connectionIds(){return this.#pe.get().connections.keys()}clearOthers(){this.#pe.mutate(e=>{e.connections.clear(),e.presences.clear(),this.#_e.clear()})}#me(e){const t=this.#pe.get(),n=t.connections.get(e),o=t.presences.get(e);if(void 0!==n&&void 0!==o)return makeUser(n,o)}getUser(e){const t=this.#_e.get(e);if(t)return t;const n=this.#me(e);return n?(this.#_e.set(e,n),n):void 0}#he(e){this.#_e.delete(e)}setConnection(e,t,n,o){this.#pe.mutate(r=>(r.connections.set(e,freeze$2({connectionId:e,id:t,info:n,scopes:o})),!!r.presences.has(e)&&this.#he(e)))}removeConnection(e){this.#pe.mutate(t=>{t.connections.delete(e),t.presences.delete(e),this.#he(e)})}setOther(e,t){this.#pe.mutate(n=>(n.presences.set(e,freeze$2(compactObject(t))),!!n.connections.has(e)&&this.#he(e)))}patchOther(e,t){this.#pe.mutate(n=>{const o=n.presences.get(e);if(void 0===o)return!1;const r=merge(o,t);return o!==r&&(n.presences.set(e,freeze$2(r)),this.#he(e))})}},MAX_SOCKET_MESSAGE_SIZE=1047552;function makeIdFactory(e){let t=0;return()=>`${e}:${t++}`}function userToTreeNode(e,t){return{type:"User",id:`${t.connectionId}`,key:e,payload:{connectionId:t.connectionId,id:t.id,info:t.info,presence:t.presence,isReadOnly:!t.canWrite}}}function installBackgroundTabSpy(){const e="undefined"!=typeof document?document:void 0,t={current:null};function n(){t.current="hidden"===e?.visibilityState?t.current??Date.now():null}e?.addEventListener("visibilitychange",n);return[t,()=>{e?.removeEventListener("visibilitychange",n)}]}function createRoom(e,t){const n=e.initialPresence,o=e.initialStorage,r=t.roomHttpClient,[a,i]=installBackgroundTabSpy(),s={...t.delegates,canZombie:()=>void 0!==t.backgroundKeepAliveTimeout&&null!==a.current&&Date.now()>a.current+t.backgroundKeepAliveTimeout&&"synchronizing"!==K()},l=new ManagedSocket(s,t.enableDebugLogging),c={buffer:{flushTimerID:void 0,lastFlushedAt:0,presenceUpdates:{type:"full",data:n},messages:[],storageOperations:[]},staticSessionInfoSig:new Signal(null),dynamicSessionInfoSig:new Signal(null),myPresence:new PatchableSignal(n),others:new ManagedOthers,initialStorage:o,idFactory:null,yjsProvider:void 0,yjsProviderDidChange:makeEventSource(),clock:0,opClock:0,nodes:new Map,root:void 0,undoStack:[],redoStack:[],pausedHistory:null,activeBatch:null,unacknowledgedOps:new Map,opStackTraces:void 0};let d,u;let f=!1;l.events.onMessage.subscribe(function(e){if("string"!=typeof e.data)return;const t=function(e){const t=tryParseJson(e);return void 0===t?null:isJsonArray(t)?compact(t.map(e=>$(e))):compact([$(t)])}(e.data);if(null===t||0===t.length)return;const n={storageUpdates:new Map,others:[]};for(const e of t)switch(e.type){case 101:{const t=j(e);t&&n.others.push(t);break}case 100:{const t=T(e);t&&n.others.push(t);break}case 103:{const t=c.others.get();_.customEvent.notify({connectionId:e.actor,user:e.actor<0?null:t.find(t=>t.connectionId===e.actor)??null,event:e.event});break}case 102:{const t=A(e);t&&n.others.push(t);break}case 300:_.ydoc.notify(e);break;case 104:n.others.push(O(e));break;case 200:L(e);break;case 201:{const t=S(e.ops,!1);for(const[e,o]of t.updates.storageUpdates)n.storageUpdates.set(e,mergeStorageUpdates(n.storageUpdates.get(e),o));break}case 299:errorWithTitle("Storage mutation rejection error",e.reason);break;case 400:case 407:case 401:case 408:case 405:case 406:case 402:case 403:case 404:_.comments.notify(e)}x(n)}),l.events.statusDidChange.subscribe(function(e){const t=l.authValue;if(null!==t){const e=getBearerTokenFromAuthValue(t);if(e!==d)if(d=e,"secret"===t.type){const e=t.token.parsed;c.staticSessionInfoSig.set({userId:"sec-legacy"===e.k?e.id:e.uid,userInfo:"sec-legacy"===e.k?e.info:e.ui})}else c.staticSessionInfoSig.set({userId:void 0,userInfo:void 0})}_.status.notify(e),v()}),l.events.statusDidChange.subscribe(function(e){"reconnecting"===e?u=setTimeout(()=>{_.lostConnection.notify("lost"),f=!0,c.others.clearOthers(),x({others:[{type:"reset"}]})},t.lostConnectionTimeout):(clearTimeout(u),f&&("disconnected"===e?_.lostConnection.notify("failed"):_.lostConnection.notify("restored"),f=!1))}),l.events.didConnect.subscribe(function(){c.buffer.presenceUpdates={type:"full",data:{...c.myPresence.get()}},null!==M&&U({flush:!1}),F()}),l.events.didDisconnect.subscribe(function(){clearTimeout(c.buffer.flushTimerID)}),l.events.onLiveblocksError.subscribe(e=>{_.error.notify(e)});const p={roomId:t.roomId,getNode:e=>c.nodes.get(e),addNode:(e,t)=>{c.nodes.set(e,t)},deleteNode:e=>{c.nodes.delete(e)},generateId:()=>`${R()}:${c.clock++}`,generateOpId:()=>`${R()}:${c.opClock++}`,dispatch(e,t,n){const o=c.activeBatch;if(o){for(const t of e)o.ops.push(t);for(const[e,t]of n)o.updates.storageUpdates.set(e,mergeStorageUpdates(o.updates.storageUpdates.get(e),t));o.reverseOps.unshift(...t)}else C(t),c.redoStack.length=0,P(e),x({storageUpdates:n})},assertStorageIsWritable:()=>{const e=c.dynamicSessionInfoSig.get()?.scopes;if(void 0===e)return;if(!canWriteStorage(e))throw new Error("Cannot write to storage with a read only user, please ensure the user has write permissions")}},_={status:makeEventSource(),lostConnection:makeEventSource(),customEvent:makeEventSource(),self:makeEventSource(),myPresence:makeEventSource(),others:makeEventSource(),error:makeEventSource(),storageBatch:makeEventSource(),history:makeEventSource(),storageDidLoad:makeEventSource(),storageStatus:makeEventSource(),ydoc:makeEventSource(),comments:makeEventSource()},m=t.roomId;function h(e){const n=JSON.stringify(e),o=c.dynamicSessionInfoSig.get()?.nonce;if(t.unstable_fallbackToHTTP&&o){if((new TextEncoder).encode(n).length>MAX_SOCKET_MESSAGE_SIZE)return r.sendMessages({roomId:m,nonce:o,messages:e}).then(e=>{e.ok||403!==e.status||l.reconnect()}),void warn$1("Message was too large for websockets and sent over HTTP instead")}l.send(n)}const g=DerivedSignal.from(c.staticSessionInfoSig,c.dynamicSessionInfoSig,c.myPresence,(e,t,n)=>{if(null===e||null===t)return null;{const o=canWriteStorage(t.scopes);return{connectionId:t.actor,id:e.userId,info:e.userInfo,presence:n,canWrite:o,canComment:canComment(t.scopes)}}});let b;function v(){const e=g.get();null!==e&&e!==b&&(_.self.notify(e),b=e)}const y=DerivedSignal.from(g,e=>null!==e?userToTreeNode("Me",e):null);function E(e){if(0===e.items.length)throw new Error("Internal error: cannot load storage without items");void 0!==c.root?function(e){if(void 0===c.root)return;const t=new Map;for(const[e,n]of c.nodes)t.set(e,n._serialize());const n=getTreesDiffOperations(t,new Map(e));x(S(n,!1).updates)}(e.items):c.root=LiveObject._fromItems(e.items,p);const t=g.get()?.canWrite??!0,n=c.undoStack.length;for(const e in c.initialStorage)void 0===c.root.get(e)&&(t?c.root.set(e,cloneLson(c.initialStorage[e])):warn$1(`Attempted to populate missing storage key '${e}', but current user has no write access`));c.undoStack.length=n}function w(e){c.undoStack.length>=50&&c.undoStack.shift(),c.undoStack.push(e),N()}function C(e){null!==c.pausedHistory?c.pausedHistory.unshift(...e):w(e)}function x(e){const t=e.storageUpdates,n=e.others;if(void 0!==n&&n.length>0){const e=c.others.get();for(const t of n)_.others.notify({...t,others:e})}if(e.presence&&(v(),_.myPresence.notify(c.myPresence.get())),void 0!==t&&t.size>0){const e=Array.from(t.values());_.storageBatch.notify(e)}G()}function R(){const e=c.dynamicSessionInfoSig.get();if(e)return e.actor;throw new Error("Internal. Tried to get connection id but connection was never open")}function S(e,t){const n={reverse:[],storageUpdates:new Map,presence:!1},o=new Set,r=e.map(e=>"presence"===e.type||e.opId?e:{...e,opId:p.generateOpId()});for(const e of r)if("presence"===e.type){const t={type:"presence",data:{}};for(const n in e.data)t.data[n]=c.myPresence.get()[n];if(c.myPresence.patch(e.data),null===c.buffer.presenceUpdates)c.buffer.presenceUpdates={type:"partial",data:e.data};else for(const t in e.data)c.buffer.presenceUpdates.data[t]=e.data[t];n.reverse.unshift(t),n.presence=!0}else{let r;if(t)r=0;else{const t=nn(e.opId);r=c.unacknowledgedOps.delete(t)?2:1}const a=D(e,r);if(a.modified){const t=a.modified.node._id;t&&o.has(t)||(n.storageUpdates.set(nn(a.modified.node._id),mergeStorageUpdates(n.storageUpdates.get(nn(a.modified.node._id)),a.modified)),n.reverse.unshift(...a.reverse)),2!==e.type&&7!==e.type&&4!==e.type||o.add(nn(e.id))}}return{ops:r,reverse:n.reverse,updates:{storageUpdates:n.storageUpdates,presence:n.presence}}}function D(e,t){if(isAckOp(e))return{modified:!1};switch(e.type){case 6:case 3:case 5:{const n=c.nodes.get(e.id);return void 0===n?{modified:!1}:n._apply(e,0===t)}case 1:{const n=c.nodes.get(e.id);return void 0===n?{modified:!1}:"HasParent"===n.parent.type&&isLiveList(n.parent.node)?n.parent.node._setChildKey(asPos(e.parentKey),n,t):{modified:!1}}case 4:case 2:case 7:case 8:{if(void 0===e.parentId)return{modified:!1};const n=c.nodes.get(e.parentId);return void 0===n?{modified:!1}:n._attachChild(e,t)}}}function T(e){if(void 0!==e.targetActor){const t=c.others.getUser(e.actor);c.others.setOther(e.actor,e.data);const n=c.others.getUser(e.actor);if(void 0===t&&void 0!==n)return{type:"enter",user:n}}else c.others.patchOther(e.actor,e.data);const t=c.others.getUser(e.actor);return t?{type:"update",updates:e.data,user:t}:void 0}function A(e){const t=c.others.getUser(e.actor);return t?(c.others.removeConnection(e.actor),{type:"leave",user:t}):null}function O(e){c.dynamicSessionInfoSig.set({actor:e.actor,nonce:e.nonce,scopes:e.scopes}),c.idFactory=makeIdFactory(e.actor),v();for(const t of c.others.connectionIds()){void 0===e.users[t]&&c.others.removeConnection(t)}for(const t in e.users){const n=e.users[t],o=Number(t);c.others.setConnection(o,n.id,n.info,n.scopes)}return{type:"reset"}}function I(){return c.undoStack.length>0}function k(){return c.redoStack.length>0}function N(){_.history.notify({canUndo:I(),canRedo:k()})}function j(e){c.others.setConnection(e.actor,e.id,e.info,e.scopes),c.buffer.messages.push({type:100,data:c.myPresence.get(),targetActor:e.actor}),F();const t=c.others.getUser(e.actor);return t?{type:"enter",user:t}:void 0}function $(e){return isJsonObject(e)?e:null}function F(){const e=c.buffer.storageOperations;if(e.length>0){for(const t of e)c.unacknowledgedOps.set(nn(t.opId),t);G()}if("connected"!==l.getStatus())return void(c.buffer.storageOperations=[]);const n=Date.now(),o=n-c.buffer.lastFlushedAt;if(o>=t.throttleDelay){const e=function(){const e=[];c.buffer.presenceUpdates&&e.push("full"===c.buffer.presenceUpdates.type?{type:100,targetActor:-1,data:c.buffer.presenceUpdates.data}:{type:100,data:c.buffer.presenceUpdates.data});for(const t of c.buffer.messages)e.push(t);c.buffer.storageOperations.length>0&&e.push({type:201,ops:c.buffer.storageOperations});return e}();if(0===e.length)return;h(e),c.buffer={flushTimerID:void 0,lastFlushedAt:n,messages:[],storageOperations:[],presenceUpdates:null}}else clearTimeout(c.buffer.flushTimerID),c.buffer.flushTimerID=setTimeout(F,t.throttleDelay-o)}function P(e){const{storageOperations:t}=c.buffer;for(const n of e)t.push(n);F()}let M=null,B=null;function L(e){const t=new Map(c.unacknowledgedOps);E(e),function(e){if(0===e.size)return;const t=[],n=S(Array.from(e.values()),!0);t.push({type:201,ops:n.ops}),x(n.updates),h(t)}(t),B?.(),G(),_.storageDidLoad.notify()}function U(e){const n=c.buffer.messages;t.unstable_streamData?async function(){if(!l.authValue)return;L({type:200,items:await r.streamStorage({roomId:m})})}():n.some(e=>200===e.type)||n.push({type:200}),e.flush&&F()}function V(){return null===M&&(U({flush:!0}),M=new Promise(e=>{B=e}),G()),M}function H(){const e=c.root;return void 0!==e?e:(V(),null)}async function z(){return void 0!==c.root?Promise.resolve({root:c.root}):(await V(),{root:nn(c.root)})}const q=t.createSyncSource();function K(){return void 0===c.root?null===M?"not-loaded":"loading":0===c.unacknowledgedOps.size?"synchronized":"synchronizing"}let W=K();function G(){const e=K();W!==e&&(W=e,_.storageStatus.notify(e)),q.setSyncStatus("synchronizing"===e?"synchronizing":"synchronized")}function Y(){return null!==g.get()}function J(){return null!==H()}const X=DerivedSignal.from(c.others.signal,e=>e.map((e,t)=>userToTreeNode(`Other ${t}`,e))),Z={status:_.status.observable,lostConnection:_.lostConnection.observable,customEvent:_.customEvent.observable,others:_.others.observable,self:_.self.observable,myPresence:_.myPresence.observable,error:_.error.observable,storage:_.storageBatch.observable,storageBatch:_.storageBatch.observable,history:_.history.observable,storageDidLoad:_.storageDidLoad.observable,storageStatus:_.storageStatus.observable,ydoc:_.ydoc.observable,comments:_.comments.observable};const Q=t.createSyncSource();function ee(e){return Q.setSyncStatus("synchronizing"===e?"synchronizing":"synchronized")}return Object.defineProperty({[kInternal]:{get presenceBuffer(){return deepClone(c.buffer.presenceUpdates?.data??null)},get undoStack(){return deepClone(c.undoStack)},get nodeCount(){return c.nodes.size},getYjsProvider:()=>c.yjsProvider,setYjsProvider(e){c.yjsProvider?.off("status",ee),c.yjsProvider=e,e?.on("status",ee),c.yjsProviderDidChange.notify()},yjsProviderDidChange:c.yjsProviderDidChange.observable,reportTextEditor:async function(e,t){await r.reportTextEditor({roomId:m,type:e,rootKey:t})},createTextMention:async function(e,t){return r.createTextMention({roomId:m,userId:e,mentionId:t})},deleteTextMention:async function(e){return r.deleteTextMention({roomId:m,mentionId:e})},listTextVersions:async function(){return r.listTextVersions({roomId:m})},listTextVersionsSince:async function(e){return r.listTextVersionsSince({roomId:m,since:e.since,signal:e.signal})},getTextVersion:async function(e){return r.getTextVersion({roomId:m,versionId:e})},createTextVersion:async function(){return r.createTextVersion({roomId:m})},getSelf_forDevTools:()=>y.get(),getOthers_forDevTools:()=>X.get(),simulate:{explicitClose:e=>l._privateSendMachineEvent({type:"EXPLICIT_SOCKET_CLOSE",event:e}),rawSend:e=>l.send(e)},attachmentUrlsStore:r.getOrCreateAttachmentUrlsStore(m)},id:t.roomId,subscribe:makeClassicSubscribeFn(Z),connect:()=>l.connect(),reconnect:()=>l.reconnect(),disconnect:()=>l.disconnect(),destroy:()=>{q.destroy(),c.yjsProvider?.off("status",ee),Q.destroy(),i(),l.destroy()},updatePresence:function(e,t){const n={};null===c.buffer.presenceUpdates&&(c.buffer.presenceUpdates={type:"partial",data:{}});for(const t in e){const o=e[t];void 0!==o&&(c.buffer.presenceUpdates.data[t]=o,n[t]=c.myPresence.get()[t])}c.myPresence.patch(e),c.activeBatch?(t?.addToHistory&&c.activeBatch.reverseOps.unshift({type:"presence",data:n}),c.activeBatch.updates.presence=!0):(F(),t?.addToHistory&&C([{type:"presence",data:n}]),x({presence:!0}))},updateYDoc:function(e,t){const n={type:301,update:e,guid:t};c.buffer.messages.push(n),_.ydoc.notify(n),F()},broadcastEvent:function(e,t={shouldQueueEventIfNotReady:!1}){("connected"===l.getStatus()||t.shouldQueueEventIfNotReady)&&(c.buffer.messages.push({type:103,event:e}),F())},batch:function(e){if(c.activeBatch)return e();let t;c.activeBatch={ops:[],updates:{storageUpdates:new Map,presence:!1,others:[]},reverseOps:[]};try{t=e()}finally{const e=c.activeBatch;c.activeBatch=null,e.reverseOps.length>0&&C(e.reverseOps),e.ops.length>0&&(c.redoStack.length=0),e.ops.length>0&&P(e.ops),x(e.updates),F()}return t},history:{undo:function(){if(c.activeBatch)throw new Error("undo is not allowed during a batch");const e=c.undoStack.pop();if(void 0===e)return;c.pausedHistory=null;const t=S(e,!0);x(t.updates),c.redoStack.push(t.reverse),N();for(const e of t.ops)"presence"!==e.type&&c.buffer.storageOperations.push(e);F()},redo:function(){if(c.activeBatch)throw new Error("redo is not allowed during a batch");const e=c.redoStack.pop();if(void 0===e)return;c.pausedHistory=null;const t=S(e,!0);x(t.updates),c.undoStack.push(t.reverse),N();for(const e of t.ops)"presence"!==e.type&&c.buffer.storageOperations.push(e);F()},canUndo:I,canRedo:k,clear:function(){c.undoStack.length=0,c.redoStack.length=0},pause:function(){null===c.pausedHistory&&(c.pausedHistory=[])},resume:function(){const e=c.pausedHistory;c.pausedHistory=null,null!==e&&e.length>0&&w(e)}},fetchYDoc:function(e,t){c.buffer.messages.find(n=>300===n.type&&n.vector===e&&n.guid===t)||c.buffer.messages.push({type:300,vector:e,guid:t}),F()},getStorage:z,getStorageSnapshot:H,getStorageStatus:K,isPresenceReady:Y,isStorageReady:J,waitUntilPresenceReady:memoizeOnSuccess(async function(){for(;!Y();){const{promise:e,resolve:t}=Promise_withResolvers(),n=Z.self.subscribeOnce(t),o=Z.status.subscribeOnce(t);await e,n(),o()}}),waitUntilStorageReady:memoizeOnSuccess(async function(){for(;!J();)await z()}),events:Z,getStatus:()=>l.getStatus(),getSelf:()=>g.get(),getPresence:()=>c.myPresence.get(),getOthers:()=>c.others.get(),getThreads:async function(e){return r.getThreads({roomId:m,query:e?.query,cursor:e?.cursor})},getThreadsSince:async function(e){return r.getThreadsSince({roomId:m,since:e.since,signal:e.signal})},getThread:async function(e){return r.getThread({roomId:m,threadId:e})},createThread:async function(e){return r.createThread({roomId:m,threadId:e.threadId,commentId:e.commentId,metadata:e.metadata,body:e.body,attachmentIds:e.attachmentIds})},deleteThread:async function(e){return r.deleteThread({roomId:m,threadId:e})},editThreadMetadata:async function({metadata:e,threadId:t}){return r.editThreadMetadata({roomId:m,threadId:t,metadata:e})},markThreadAsResolved:async function(e){return r.markThreadAsResolved({roomId:m,threadId:e})},markThreadAsUnresolved:async function(e){return r.markThreadAsUnresolved({roomId:m,threadId:e})},createComment:async function(e){return r.createComment({roomId:m,threadId:e.threadId,commentId:e.commentId,body:e.body,attachmentIds:e.attachmentIds})},editComment:async function(e){return r.editComment({roomId:m,threadId:e.threadId,commentId:e.commentId,body:e.body,attachmentIds:e.attachmentIds})},deleteComment:async function({threadId:e,commentId:t}){return r.deleteComment({roomId:m,threadId:e,commentId:t})},addReaction:async function({threadId:e,commentId:t,emoji:n}){return r.addReaction({roomId:m,threadId:e,commentId:t,emoji:n})},removeReaction:async function({threadId:e,commentId:t,emoji:n}){return await r.removeReaction({roomId:m,threadId:e,commentId:t,emoji:n})},prepareAttachment:function(e){return{type:"localAttachment",status:"idle",id:createCommentAttachmentId(),name:e.name,size:e.size,mimeType:e.type,file:e}},uploadAttachment:async function(e,t={}){return r.uploadAttachment({roomId:m,attachment:e,signal:t.signal})},getAttachmentUrl:function(e){return r.getAttachmentUrl({roomId:m,attachmentId:e})},getNotificationSettings:function(e){return r.getNotificationSettings({roomId:m,signal:e?.signal})},updateNotificationSettings:function(e){return r.updateNotificationSettings({roomId:m,settings:e})},markInboxNotificationAsRead:async function(e){await r.markRoomInboxNotificationAsRead({roomId:m,inboxNotificationId:e})}},kInternal,{enumerable:!1})}function makeClassicSubscribeFn(e){return function(t,n,o){if("string"==typeof t&&isRoomEventName(t)){if("function"!=typeof n)throw new Error("Second argument must be a callback function");const o=n;switch(t){case"event":return e.customEvent.subscribe(o);case"my-presence":return e.myPresence.subscribe(o);case"others":{const t=o;return e.others.subscribe(e=>{const{others:n,...o}=e;return t(n,o)})}case"error":return e.error.subscribe(o);case"status":return e.status.subscribe(o);case"lost-connection":return e.lostConnection.subscribe(o);case"history":return e.history.subscribe(o);case"storage-status":return e.storageStatus.subscribe(o);case"comments":return e.comments.subscribe(o);default:return assertNever(t,`"${String(t)}" is not a valid event name`)}}if(void 0===n||"function"==typeof t){if("function"==typeof t){const n=t;return e.storageBatch.subscribe(n)}throw new Error("Please specify a listener callback")}if(isLiveNode(t)){const r=t;if(o?.isDeep){return function(t,n){return e.storageBatch.subscribe(e=>{const o=e.filter(e=>isSameNodeOrChildOf(e.node,t));o.length>0&&n(o)})}(r,n)}return function(t,n){return e.storageBatch.subscribe(e=>{for(const o of e)o.node._id===t._id&&n(o.node)})}(r,n)}throw new Error(`${String(t)} is not a value that can be subscribed to.`)}}function isRoomEventName(e){return"my-presence"===e||"others"===e||"event"===e||"error"===e||"history"===e||"status"===e||"storage-status"===e||"lost-connection"===e||"connection"===e||"comments"===e}function makeAuthDelegateForRoom(e,t){return async()=>t.getAuthValue({requestedScope:"room:read",roomId:e})}function makeCreateSocketDelegateForRoom(e,t,n){return o=>{const r=n??("undefined"==typeof WebSocket?void 0:WebSocket);if(void 0===r)throw new StopRetrying("To use Liveblocks client in a non-DOM environment, you need to provide a WebSocket polyfill.");const a=new URL(t);if(a.protocol="http:"===a.protocol?"ws":"wss",a.pathname="/v7",a.searchParams.set("roomId",e),"secret"===o.type)a.searchParams.set("tok",o.token.raw);else{if("public"!==o.type)return assertNever(o,"Unhandled case");a.searchParams.set("pubkey",o.publicApiKey)}return a.searchParams.set("version",PKG_VERSION$2),new r(a.toString())}}var MIN_THROTTLE=16,MAX_THROTTLE=1e3,DEFAULT_THROTTLE=100,MIN_BACKGROUND_KEEP_ALIVE_TIMEOUT=15e3,MIN_LOST_CONNECTION_TIMEOUT=200,RECOMMENDED_MIN_LOST_CONNECTION_TIMEOUT=1e3,MAX_LOST_CONNECTION_TIMEOUT=3e4,DEFAULT_LOST_CONNECTION_TIMEOUT=5e3,RESOLVE_USERS_BATCH_DELAY=50,RESOLVE_ROOMS_INFO_BATCH_DELAY=50;function getBaseUrl(e){return"string"==typeof e&&e.startsWith("http")?e:DEFAULT_BASE_URL}function createClient(e){const t=e,n=getThrottle(t.throttle??DEFAULT_THROTTLE),o=getLostConnectionTimeout(t.lostConnectionTimeout??DEFAULT_LOST_CONNECTION_TIMEOUT),r=getBackgroundKeepAliveTimeout(t.backgroundKeepAliveTimeout),a=getBaseUrl(t.baseUrl),i=new Signal(void 0),s=createAuthManager(e,e=>{const t="sec-legacy"===e.k?e.id:e.uid;i.set(()=>t)}),l=t.polyfills?.fetch||globalThis.fetch?.bind(globalThis),c=createApiClient({baseUrl:a,fetchPolyfill:l,authManager:s}),d=new Map;function u(e){const t=()=>{const n=t;var o;e.unsubs.delete(n)?0===e.unsubs.size&&(unlinkDevTools((o=e.room).id),d.delete(o.id),o.destroy()):warn$1("This leave function was already called. Calling it more than once has no effect.")};return e.unsubs.add(t),{room:e.room,leave:t}}const f=t.resolveUsers,p=createDevelopmentWarning(()=>!f,"Set the resolveUsers option in createClient to specify user info."),_=createBatchStore(new Batch(async e=>{const t=e.flat(),n=await(f?.({userIds:t}));return p(),n??t.map(()=>{})},{delay:RESOLVE_USERS_BATCH_DELAY}));const m=t.resolveRoomsInfo,h=createDevelopmentWarning(()=>!m,"Set the resolveRoomsInfo option in createClient to specify room info."),g=createBatchStore(new Batch(async e=>{const t=e.flat(),n=await(m?.({roomIds:t}));return h(),n??t.map(()=>{})},{delay:RESOLVE_ROOMS_INFO_BATCH_DELAY}));const b=new Map;const v=[],y=new Signal("synchronized");function E(){y.set(v.some(e=>"synchronizing"===e.get())?"synchronizing":v.some(e=>"has-local-changes"===e.get())?"has-local-changes":"synchronized")}function w(){const e=new Signal("synchronized");v.push(e);const t=e.subscribe(()=>E());return{setSyncStatus:function(t){e.set(t)},destroy:function(){t();const n=v.findIndex(t=>t===e);if(n>-1){const[e]=v.splice(n,1);"synchronized"!==e.get()&&E()}}}}{const e=e=>{t.preventUnsavedChanges&&"synchronized"!==y.get()&&e.preventDefault()},n="undefined"!=typeof window?window:void 0;n?.addEventListener("beforeunload",e)}const C=Object.defineProperty({enterRoom:function(e,...i){const l=d.get(e);if(void 0!==l)return u(l);const f=i[0]??{},p=createRoom({initialPresence:("function"==typeof f.initialPresence?f.initialPresence(e):f.initialPresence)??{},initialStorage:("function"==typeof f.initialStorage?f.initialStorage(e):f.initialStorage)??{}},{roomId:e,throttleDelay:n,lostConnectionTimeout:o,backgroundKeepAliveTimeout:r,polyfills:t.polyfills,delegates:t.mockedDelegates??{createSocket:makeCreateSocketDelegateForRoom(e,a,t.polyfills?.WebSocket),authenticate:makeAuthDelegateForRoom(e,s)},enableDebugLogging:t.enableDebugLogging,baseUrl:a,unstable_fallbackToHTTP:!!t.unstable_fallbackToHTTP,unstable_streamData:!!t.unstable_streamData,roomHttpClient:c,createSyncSource:w}),_={room:p,unsubs:new Set};if(d.set(e,_),f.autoConnect??!0){if("undefined"==typeof atob){if(void 0===t.polyfills?.atob)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=t.polyfills.atob}p.connect()}return u(_)},getRoom:function(e){const t=d.get(e)?.room;return t||null},logout:function(){s.reset(),i.set(()=>{});for(const{room:e}of d.values())isIdle(e.getStatus())||e.reconnect()},getInboxNotifications:c.getInboxNotifications,getInboxNotificationsSince:c.getInboxNotificationsSince,getUnreadInboxNotificationsCount:c.getUnreadInboxNotificationsCount,markAllInboxNotificationsAsRead:c.markAllInboxNotificationsAsRead,markInboxNotificationAsRead:c.markInboxNotificationAsRead,deleteAllInboxNotifications:c.deleteAllInboxNotifications,deleteInboxNotification:c.deleteInboxNotification,resolvers:{invalidateUsers:function(e){_.invalidate(e)},invalidateRoomsInfo:function(e){g.invalidate(e)},invalidateMentionSuggestions:function(){b.clear()}},getSyncStatus:function(){const e=y.get();return"synchronizing"===e?e:"synchronized"},events:{syncStatus:y},[kInternal]:{currentUserId:i,mentionSuggestionsCache:b,resolveMentionSuggestions:t.resolveMentionSuggestions,usersStore:_,roomsInfoStore:g,getRoomIds:()=>Array.from(d.keys()),httpClient:c,as:()=>C,createSyncSource:w}},kInternal,{enumerable:!1});return C}function checkBounds(e,t,n,o,r){if("number"!=typeof t||t<n||void 0!==o&&t>o)throw new Error(void 0!==o?`${e} should be between ${r??n} and ${o}.`:`${e} should be at least ${r??n}.`);return t}function getBackgroundKeepAliveTimeout(e){if(void 0!==e)return checkBounds("backgroundKeepAliveTimeout",e,MIN_BACKGROUND_KEEP_ALIVE_TIMEOUT)}function getThrottle(e){return checkBounds("throttle",e,MIN_THROTTLE,MAX_THROTTLE)}function getLostConnectionTimeout(e){return checkBounds("lostConnectionTimeout",e,MIN_LOST_CONNECTION_TIMEOUT,MAX_LOST_CONNECTION_TIMEOUT,RECOMMENDED_MIN_LOST_CONNECTION_TIMEOUT)}function createDevelopmentWarning(e,...t){return()=>{}}function isCommentBodyParagraph(e){return"type"in e&&"paragraph"===e.type}function isCommentBodyText$1(e){return!("type"in e)&&"text"in e&&"string"==typeof e.text}function isCommentBodyMention$1(e){return"type"in e&&"mention"===e.type}function isCommentBodyLink$1(e){return"type"in e&&"link"===e.type}var commentBodyElementsGuards={paragraph:isCommentBodyParagraph,text:isCommentBodyText$1,link:isCommentBodyLink$1,mention:isCommentBodyMention$1},commentBodyElementsTypes={paragraph:"block",text:"inline",link:"inline",mention:"inline"};function traverseCommentBody(e,t,n){if(!e||!e?.content)return;const o="string"==typeof t?t:void 0,r=o?commentBodyElementsTypes[o]:"all",a=o?commentBodyElementsGuards[o]:()=>!0,i="function"==typeof t?t:n;for(const t of e.content)if("all"!==r&&"block"!==r||a(t)&&i?.(t),"all"===r||"inline"===r)for(const e of t.children)a(e)&&i?.(e)}function getMentionedIdsFromCommentBody(e){const t=new Set;return traverseCommentBody(e,"mention",e=>t.add(e.id)),Array.from(t)}var htmlEscapables={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"};new RegExp(Object.keys(htmlEscapables).map(e=>`\\${e}`).join("|"),"g");var markdownEscapables={_:"\\_","*":"\\*","#":"\\#","`":"\\`","~":"\\~","!":"\\!","|":"\\|","(":"\\(",")":"\\)","{":"\\{","}":"\\}","[":"\\[","]":"\\]"};new RegExp(Object.keys(markdownEscapables).map(e=>`\\${e}`).join("|"),"g");var BACKOFF_DELAYS2=[1e3,2e3,4e3,8e3,1e4];function makePoller(e,t,n){const o=performance.now(),r="undefined"!=typeof document?document:void 0,a="undefined"!=typeof window?window:void 0,i=n?.maxStaleTimeMs??Number.POSITIVE_INFINITY,s={inForeground:"hidden"!==r?.visibilityState,lastSuccessfulPollAt:o,count:0,backoff:0};function l(){return s.count>0&&s.inForeground}const c=new FSM({}).addState("@idle").addState("@enabled").addState("@polling");function d(){l()?c.send({type:"START"}):c.send({type:"STOP"})}function u(){performance.now()-s.lastSuccessfulPollAt>i&&c.send({type:"POLL"})}function f(e){s.inForeground=e,d(),u()}function p(){f("hidden"!==r?.visibilityState)}return c.addTransitions("@idle",{START:"@enabled"}),c.addTransitions("@enabled",{STOP:"@idle",POLL:"@polling"}),c.addTimedTransition("@enabled",()=>{const e=s.lastSuccessfulPollAt+t;return Math.max(0,e-performance.now())+s.backoff},"@polling"),c.onEnterAsync("@polling",async(t,n)=>{await e(n),n.aborted||(s.lastSuccessfulPollAt=performance.now())},()=>({target:l()?"@enabled":"@idle",effect:()=>{s.backoff=0}}),()=>({target:l()?"@enabled":"@idle",effect:()=>{s.backoff=BACKOFF_DELAYS2.find(e=>e>s.backoff)??BACKOFF_DELAYS2[BACKOFF_DELAYS2.length-1]}}),3e4),r?.addEventListener("visibilitychange",p),a?.addEventListener("online",p),c.start(),{inc:function(){s.count++,d()},dec:function(){s.count--,s.count<0&&(s.count=0),d()},pollNowIfStale:u,setInForeground:f}}function shallowArray(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!Object.is(e[n],t[n]))return!1;return!0}function shallowObj(e,t){if(!isPlainObject$2(e)||!isPlainObject$2(t))return!1;const n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(n=>Object.prototype.hasOwnProperty.call(t,n)&&Object.is(e[n],t[n]))}function shallow(e,t){if(Object.is(e,t))return!0;const n=Array.isArray(e),o=Array.isArray(t);return n||o?!(!n||!o)&&shallowArray(e,t):shallowObj(e,t)}function bisectRight(e,t,n){let o=0,r=e.length;for(;o<r;){const a=o+(r-o>>1);n(t,e[a])?r=a:o=a+1}return o}var SortedList=class e{#z;#ge;constructor(e,t){this.#ge=t,this.#z=e}static from(t,n){const o=new e([],n);for(const e of t)o.add(e);return o}static fromAlreadySorted(t,n){return new e(t,n)}clone(){return new e(this.#z.slice(),this.#ge)}add(e){const t=bisectRight(this.#z,e,this.#ge);this.#z.splice(t,0,e)}remove(e){const t=this.#z.indexOf(e);return t>=0&&(this.#z.splice(t,1),!0)}get length(){return this.#z.length}*filter(e){for(const t of this.#z)e(t)&&(yield t)}[Symbol.iterator](){return this.#z[Symbol.iterator]()}};detectDupes(PKG_NAME$2,PKG_VERSION$2,PKG_FORMAT$2);var commonjsGlobal="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0!==global?global:"undefined"!=typeof self?self:{},jsxRuntime={exports:{}},reactJsxRuntime_production_min={},hasRequiredReactJsxRuntime_production_min;function requireReactJsxRuntime_production_min(){if(hasRequiredReactJsxRuntime_production_min)return reactJsxRuntime_production_min;hasRequiredReactJsxRuntime_production_min=1;var e=React__default.default,t=Symbol.for("react.element"),n=Symbol.for("react.fragment"),o=Object.prototype.hasOwnProperty,r=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,a={key:!0,ref:!0,__self:!0,__source:!0};function i(e,n,i){var s,l={},c=null,d=null;for(s in void 0!==i&&(c=""+i),void 0!==n.key&&(c=""+n.key),void 0!==n.ref&&(d=n.ref),n)o.call(n,s)&&!a.hasOwnProperty(s)&&(l[s]=n[s]);if(e&&e.defaultProps)for(s in n=e.defaultProps)void 0===l[s]&&(l[s]=n[s]);return{$$typeof:t,type:e,key:c,ref:d,props:l,_owner:r.current}}return reactJsxRuntime_production_min.Fragment=n,reactJsxRuntime_production_min.jsx=i,reactJsxRuntime_production_min.jsxs=i,reactJsxRuntime_production_min}!function(e){e.exports=requireReactJsxRuntime_production_min()}(jsxRuntime);var PKG_NAME$1="@liveblocks/client",PKG_VERSION$1="2.15.1",PKG_FORMAT$1="esm";detectDupes(PKG_NAME$1,PKG_VERSION$1,PKG_FORMAT$1);var RoomContext=React.createContext(null);function useRoomOrNull(){return React.useContext(RoomContext)}function is$1(e,t){return e===t&&(0!==e||1/e==1/t)||e!=e&&t!=t}function useSyncExternalStoreWithSelector(e,t,n,o,r){const a=React.useRef(null);let i;null===a.current?(i={hasValue:!1,value:null},a.current=i):i=a.current;const[s,l]=React.useMemo(()=>{let e,a,s=!1;const l=t=>{if(!s){s=!0,e=t;const n=o(t);if(void 0!==r&&i.hasValue){const e=i.value;if(r(e,n))return a=e,e}return a=n,n}const n=a;if(is$1(e,t))return n;const l=o(t);return void 0!==r&&r(n,l)?(e=t,n):(e=t,a=l,l)},c=void 0===n?null:n;return[()=>l(t()),null===c?void 0:()=>l(c())]},[t,n,o,r]),c=React.useSyncExternalStore(e,s,l);return React.useEffect(()=>{i.hasValue=!0,i.value=c},[c]),React.useDebugValue(c),c}var SECONDS=1e3,MINUTES=60*SECONDS,config$1={SMOOTH_DELAY:1*SECONDS,NOTIFICATIONS_POLL_INTERVAL:1*MINUTES,NOTIFICATIONS_MAX_STALE_TIME:5*SECONDS,ROOM_THREADS_POLL_INTERVAL:5*MINUTES,ROOM_THREADS_MAX_STALE_TIME:5*SECONDS,USER_THREADS_POLL_INTERVAL:1*MINUTES,USER_THREADS_MAX_STALE_TIME:5*SECONDS,HISTORY_VERSIONS_POLL_INTERVAL:1*MINUTES,HISTORY_VERSIONS_MAX_STALE_TIME:5*SECONDS,NOTIFICATION_SETTINGS_POLL_INTERVAL:1*MINUTES,NOTIFICATION_SETTINGS_MAX_STALE_TIME:5*SECONDS};function shallow2(e,t){if(!isPlainObject$2(e)||!isPlainObject$2(t))return shallow(e,t);const n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(n=>Object.prototype.hasOwnProperty.call(t,n)&&shallow(e[n],t[n]))}function useLatest$1(e){const t=React.useRef(e);return React.useEffect(()=>{t.current=e},[e]),t}var noop$2=e=>e;function useInitial$1(e){return React.useReducer(noop$2,e)[0]}function useInitialUnlessFunction(e){const t=useInitial$1(e);if("function"==typeof t){const t=useLatest$1(e);return React.useCallback((...e)=>t.current(...e),[t])}return t}var use=e=>{if("pending"===e.status)throw e;if("fulfilled"===e.status)return e.value;throw"rejected"===e.status?e.reason:(e.status="pending",e.then(t=>{e.status="fulfilled",e.value=t},t=>{e.status="rejected",e.reason=t}),e)};function autobind(e){const t=new Set;t.add("constructor");let n=e.constructor.prototype;do{for(const o of Reflect.ownKeys(n)){if(t.has(o))continue;const r=Reflect.getOwnPropertyDescriptor(n,o);"function"==typeof r?.value&&(t.add(o),e[o]=e[o].bind(e))}}while((n=Reflect.getPrototypeOf(n))&&n!==Object.prototype)}function find(e,t){for(const n of e)if(t(n))return n}function isStartsWith(e){return isPlainObject$2(e)&&isString(e.startsWith)}function isString(e){return"string"==typeof e}function makeThreadsFilter(e){return t=>matchesQuery(t,e)&&matchesMetadata(t,e)}function matchesQuery(e,t){return void 0===t.resolved||e.resolved===t.resolved}function matchesMetadata(e,t){const n=e.metadata;return void 0===t.metadata||Object.entries(t.metadata).every(([e,t])=>matchesOperator(n[e],t))}function matchesOperator(e,t){return isStartsWith(t)?isString(e)&&e.startsWith(t.startsWith):e===t}function sanitizeThread(e){if(e.deletedAt&&e.comments.length>0)return{...e,comments:[]};return e.comments.some(e=>!e.deletedAt)?e:{...e,deletedAt:new Date,comments:[]}}var ThreadDB=class e{#be;#ve;#ye;signal;constructor(){this.#ve=SortedList.from([],(e,t)=>{const n=e.createdAt,o=t.createdAt;return n<o||n===o&&e.id<t.id}),this.#ye=SortedList.from([],(e,t)=>{const n=t.updatedAt,o=e.updatedAt;return n<o||n===o&&t.id<e.id}),this.#be=new Map,this.signal=new MutableSignal(this)}clone(){const t=new e;return t.#be=new Map(this.#be),t.#ve=this.#ve.clone(),t.#ye=this.#ye.clone(),t}get(e){const t=this.getEvenIfDeleted(e);return t?.deletedAt?void 0:t}getEvenIfDeleted(e){return this.#be.get(e)}upsert(e){this.signal.mutate(()=>{const t=(e=sanitizeThread(e)).id,n=this.#be.get(t);if(n){if(n.deletedAt)return!1;this.#ve.remove(n),this.#ye.remove(n)}return e.deletedAt||(this.#ve.add(e),this.#ye.add(e)),this.#be.set(t,e),!0})}upsertIfNewer(e){const t=this.get(e.id);(!t||e.updatedAt>=t.updatedAt)&&this.upsert(e)}applyDelta(e){batch(()=>{for(const t of e.newThreads)this.upsertIfNewer(t);for(const{id:t,deletedAt:n}of e.deletedThreads){this.getEvenIfDeleted(t)&&this.delete(t,n)}})}delete(e,t){const n=this.#be.get(e);n&&!n.deletedAt&&this.upsert({...n,deletedAt:t,updatedAt:t})}findMany(e,t,n){const o="desc"===n?this.#ye:this.#ve,r=[];return void 0!==e&&r.push(t=>t.roomId===e),r.push(makeThreadsFilter(t)),Array.from(o.filter(e=>r.every(t=>t(e))))}};function makeRoomThreadsQueryKey(e,t){return`${e}-${stringify(t??{})}`}function makeUserThreadsQueryKey(e){return`USER_THREADS:${stringify(e??{})}`}function makeNotificationSettingsQueryKey(e){return`${e}:NOTIFICATION_SETTINGS`}function makeVersionsQueryKey(e){return`${e}-VERSIONS`}function usify(e){if("status"in e)return e;const t=e;return t.status="pending",t.then(e=>{t.status="fulfilled",t.value=e},e=>{t.status="rejected",t.reason=e}),t}var noop2=Promise.resolve(),ASYNC_LOADING=Object.freeze({isLoading:!0}),PaginatedResource=class{observable;#O;#Ee;#we;#Ce;constructor(e){this.#we=null,this.#Ee=e,this.#O=makeEventSource(),this.#Ce=null,this.observable=this.#O.observable,autobind(this)}#xe(e){const t=this.#we;null!==t&&(this.#we={...t,...e},this.#O.notify())}async#Re(){const e=this.#we;if(e?.cursor){this.#xe({isFetchingMore:!0});try{const t=await this.#Ee(e.cursor);this.#xe({cursor:t,fetchMoreError:void 0,isFetchingMore:!1})}catch(e){this.#xe({isFetchingMore:!1,fetchMoreError:e})}}}fetchMore(){const e=this.#we;return null===e?.cursor?noop2:(this.#Ce||(this.#Ce=this.#Re().finally(()=>{this.#Ce=null})),this.#Ce)}get(){const e=this.#Se;if(null===e||"pending"===e.status)return ASYNC_LOADING;if("rejected"===e.status)return{isLoading:!1,error:e.reason};const t=this.#we;return{isLoading:!1,data:{fetchMore:this.fetchMore,isFetchingMore:t.isFetchingMore,fetchMoreError:t.fetchMoreError,hasFetchedAll:null===t.cursor}}}#Se=null;waitUntilLoaded(){if(this.#Se)return this.#Se;const e=usify(autoRetry(()=>this.#Ee(void 0),5,[5e3,5e3,1e4,15e3]).then(e=>{this.#we={cursor:e,isFetchingMore:!1,fetchMoreError:void 0}}));return e.then(()=>this.#O.notify(),()=>{this.#O.notify(),setTimeout(()=>{this.#Se=null,this.#O.notify()},5e3)}),this.#Se=e,e}},SinglePageResource=class{observable;#O;#Ee;constructor(e){this.#Ee=e,this.#O=makeEventSource(),this.observable=this.#O.observable,autobind(this)}get(){const e=this.#Se;return null===e||"pending"===e.status?ASYNC_LOADING:"rejected"===e.status?{isLoading:!1,error:e.reason}:{isLoading:!1,data:void 0}}#Se=null;waitUntilLoaded(){if(this.#Se)return this.#Se;const e=usify(autoRetry(()=>this.#Ee(),5,[5e3,5e3,1e4,15e3]));return e.then(()=>this.#O.notify(),()=>{this.#O.notify(),setTimeout(()=>{this.#Se=null,this.#O.notify()},5e3)}),this.#Se=e,e}};function createStore_forNotifications(){const e=new MutableSignal(new Map);return{signal:e.asReadonly(),markAllRead:function(t){e.mutate(e=>{for(const n of e.values())n.readAt=t})},markRead:function(t,n){e.mutate(e=>{const o=e.get(t);return!!o&&(e.set(t,{...o,readAt:n}),!0)})},delete:function(t){e.mutate(e=>e.delete(t))},applyDelta:function(t,n){e.mutate(e=>{let o=!1;for(const n of t){const t=e.get(n.id);if(t){if(1===compareInboxNotifications(t,n))continue}e.set(n.id,n),o=!0}for(const t of n)e.delete(t.id),o=!0;return o})},clear:function(){e.mutate(e=>e.clear())},updateAssociatedNotification:function(t){e.mutate(e=>{const n=find(e.values(),e=>"thread"===e.kind&&e.threadId===t.threadId);return!!n&&(e.set(n.id,{...n,notifiedAt:t.createdAt,readAt:t.createdAt}),!0)})},force_set:t=>e.mutate(t),invalidate:()=>e.mutate()}}function createStore_forRoomNotificationSettings(){const e=new MutableSignal(new Map);return{signal:e.asReadonly(),update:function(t,n){e.mutate(e=>{e.set(t,n)})},invalidate:()=>e.mutate()}}function createStore_forHistoryVersions(){const e=new MutableSignal(new Map);return{signal:e.asReadonly(),update:function(t,n){e.mutate(e=>{const o=e.get(t)??(e.set(t,new Map),e.get(t));for(const e of n)o.set(e.id,e)})},force_set:t=>e.mutate(t),invalidate:()=>e.mutate()}}function createStore_forPermissionHints(){const e=new Signal({});return{signal:e.asReadonly(),update:function(t){e.set(e=>{const n={...e};for(const[e,o]of Object.entries(t)){const t=n[e]??new Set;for(const e of o)t.add(e);n[e]=t}return n})},invalidate:()=>e.set(e=>({...e}))}}function createStore_forOptimistic(e){const t=new Signal([]),n=e[kInternal].createSyncSource();return t.subscribe(()=>n.setSyncStatus(t.get().length>0?"synchronizing":"synchronized")),{signal:t.asReadonly(),add:function(e){const n=nanoid(),o={...e,id:n};return t.set(e=>[...e,o]),n},remove:function(e){t.set(t=>t.filter(t=>t.id!==e))},invalidate:()=>t.set(e=>[...e])}}var UmbrellaStore=class{#De;threads;notifications;roomNotificationSettings;historyVersions;permissionHints;optimisticUpdates;outputs;#Te=null;#Ae;#Oe=new Map;#Ie=new Map;#ke=null;#Ne=new Map;#je=new Map;#$e=new Map;#Fe=new Map;constructor(e){this.#De=e[kInternal].as(),this.optimisticUpdates=createStore_forOptimistic(this.#De),this.permissionHints=createStore_forPermissionHints();this.#Ae=new PaginatedResource(async e=>{const t=await this.#De.getInboxNotifications({cursor:e});this.updateThreadifications(t.threads,t.inboxNotifications),null===this.#Te&&(this.#Te=t.requestedAt);return t.nextCursor}),this.#Ae.observable.subscribe(()=>this.invalidateEntireStore()),this.threads=new ThreadDB,this.notifications=createStore_forNotifications(),this.roomNotificationSettings=createStore_forRoomNotificationSettings(),this.historyVersions=createStore_forHistoryVersions();const t=DerivedSignal.from(this.threads.signal,this.notifications.signal,this.optimisticUpdates.signal,(e,t,n)=>applyOptimisticUpdates_forThreadifications(e,t,n)),n=DerivedSignal.from(t,e=>({threadsDB:e.threadsDB}),shallow),o=DerivedSignal.from(t,e=>({sortedNotifications:e.sortedNotifications,notificationsById:e.notificationsById}),shallow),r=DerivedSignal.from(this.roomNotificationSettings.signal,this.optimisticUpdates.signal,(e,t)=>applyOptimisticUpdates_forSettings(e,t)),a=DerivedSignal.from(this.historyVersions.signal,e=>Object.fromEntries([...e].map(([e,t])=>[e,Object.fromEntries(t)])));this.outputs={threadifications:t,threads:n,notifications:o,settingsByRoomId:r,versionsByRoomId:a},autobind(this)}get1_both(){return this.outputs.threadifications.get()}subscribe1_both(e){return this.outputs.threadifications.subscribe(e)}get1_threads(){return this.outputs.threads.get()}subscribe1_threads(e){return this.outputs.threads.subscribe(e)}get1_notifications(){return this.outputs.notifications.get()}subscribe1_notifications(e){return this.outputs.notifications.subscribe(e)}get2(){return this.outputs.settingsByRoomId.get()}subscribe2(e){return this.outputs.settingsByRoomId.subscribe(e)}get3(){return this.outputs.versionsByRoomId.get()}subscribe3(e){return this.outputs.versionsByRoomId.subscribe(e)}getRoomThreadsLoadingState(e,t){const n=makeRoomThreadsQueryKey(e,t),o=this.#Ie.get(n);if(void 0===o)return ASYNC_LOADING;const r=o.get();if(r.isLoading||r.error)return r;const a=this.get1_threads().threadsDB.findMany(e,t??{},"asc"),i=r.data;return{isLoading:!1,threads:a,hasFetchedAll:i.hasFetchedAll,isFetchingMore:i.isFetchingMore,fetchMoreError:i.fetchMoreError,fetchMore:i.fetchMore}}getUserThreadsLoadingState(e){const t=makeUserThreadsQueryKey(e),n=this.#Ne.get(t);if(void 0===n)return ASYNC_LOADING;const o=n.get();if(o.isLoading||o.error)return o;const r=this.get1_threads().threadsDB.findMany(void 0,e??{},"desc"),a=o.data;return{isLoading:!1,threads:r,hasFetchedAll:a.hasFetchedAll,isFetchingMore:a.isFetchingMore,fetchMoreError:a.fetchMoreError,fetchMore:a.fetchMore}}getInboxNotificationsLoadingState(){const e=this.#Ae.get();if(e.isLoading||e.error)return e;const t=e.data;return{isLoading:!1,inboxNotifications:this.get1_notifications().sortedNotifications,hasFetchedAll:t.hasFetchedAll,isFetchingMore:t.isFetchingMore,fetchMoreError:t.fetchMoreError,fetchMore:t.fetchMore}}getNotificationSettingsLoadingState(e){const t=makeNotificationSettingsQueryKey(e),n=this.#Fe.get(t);if(void 0===n)return ASYNC_LOADING;const o=n.get();return o.isLoading||o.error?o:{isLoading:!1,settings:nn(this.get2()[e])}}getRoomVersionsLoadingState(e){const t=makeVersionsQueryKey(e),n=this.#je.get(t);if(void 0===n)return ASYNC_LOADING;const o=n.get();return o.isLoading||o.error?o:{isLoading:!1,versions:Object.values(this.get3()[e]??{})}}force_set_versions(e){batch(()=>{this.historyVersions.force_set(e),this.invalidateEntireStore()})}force_set_notifications(e){batch(()=>{this.notifications.force_set(e),this.invalidateEntireStore()})}markInboxNotificationRead(e,t,n){batch(()=>{this.optimisticUpdates.remove(n),this.notifications.markRead(e,t)})}markAllInboxNotificationsRead(e,t){batch(()=>{this.optimisticUpdates.remove(e),this.notifications.markAllRead(t)})}deleteInboxNotification(e,t){batch(()=>{this.optimisticUpdates.remove(t),this.notifications.delete(e)})}deleteAllInboxNotifications(e){batch(()=>{this.optimisticUpdates.remove(e),this.notifications.clear()})}createThread(e,t){batch(()=>{this.optimisticUpdates.remove(e),this.threads.upsert(t)})}#Pe(e,t,n,o){batch(()=>{null!==t&&this.optimisticUpdates.remove(t);const r=this.threads,a=r.get(e);a&&(o&&a.updatedAt>o||r.upsert(n(a)))})}patchThread(e,t,n,o){return this.#Pe(e,t,e=>({...e,...compactObject(n)}),o)}addReaction(e,t,n,o,r){this.#Pe(e,t,e=>applyAddReaction(e,n,o),r)}removeReaction(e,t,n,o,r,a){this.#Pe(e,t,e=>applyRemoveReaction(e,n,o,r,a),a)}deleteThread(e,t){return this.#Pe(e,t,e=>({...e,updatedAt:new Date,deletedAt:new Date}))}createComment(e,t){batch(()=>{this.optimisticUpdates.remove(t);const n=this.threads.get(e.threadId);n&&(this.threads.upsert(applyUpsertComment(n,e)),this.notifications.updateAssociatedNotification(e))})}editComment(e,t,n){return this.#Pe(e,t,e=>applyUpsertComment(e,n))}deleteComment(e,t,n,o){return this.#Pe(e,t,e=>applyDeleteComment(e,n,o),o)}updateThreadifications(e,t,n=[],o=[]){batch(()=>{this.threads.applyDelta({newThreads:e,deletedThreads:n}),this.notifications.applyDelta(t,o)})}updateRoomNotificationSettings(e,t,n){batch(()=>{this.optimisticUpdates.remove(t),this.roomNotificationSettings.update(e,n)})}async fetchNotificationsDeltaUpdate(e){const t=this.#Te;if(null===t)return;const n=await this.#De.getInboxNotificationsSince({since:t,signal:e});t<n.requestedAt&&(this.#Te=n.requestedAt),this.updateThreadifications(n.threads.updated,n.inboxNotifications.updated,n.threads.deleted,n.inboxNotifications.deleted)}waitUntilNotificationsLoaded(){return this.#Ae.waitUntilLoaded()}waitUntilRoomThreadsLoaded(e,t){const n=async n=>{const o=await this.#De[kInternal].httpClient.getThreads({roomId:e,cursor:n,query:t});this.updateThreadifications(o.threads,o.inboxNotifications),this.permissionHints.update(o.permissionHints);const r=this.#Oe.get(e);return(void 0===r||r>o.requestedAt)&&this.#Oe.set(e,o.requestedAt),o.nextCursor},o=makeRoomThreadsQueryKey(e,t);let r=this.#Ie.get(o);return void 0===r&&(r=new PaginatedResource(n)),r.observable.subscribe(()=>this.invalidateEntireStore()),this.#Ie.set(o,r),r.waitUntilLoaded()}async fetchRoomThreadsDeltaUpdate(e,t){const n=this.#Oe.get(e);if(void 0===n)return;const o=await this.#De[kInternal].httpClient.getThreadsSince({roomId:e,since:n,signal:t});this.updateThreadifications(o.threads.updated,o.inboxNotifications.updated,o.threads.deleted,o.inboxNotifications.deleted),this.permissionHints.update(o.permissionHints),n<o.requestedAt&&this.#Oe.set(e,o.requestedAt)}waitUntilUserThreadsLoaded(e){const t=makeUserThreadsQueryKey(e),n=async t=>{const n=await this.#De[kInternal].httpClient.getUserThreads_experimental({cursor:t,query:e});return this.updateThreadifications(n.threads,n.inboxNotifications),this.permissionHints.update(n.permissionHints),null===this.#ke&&(this.#ke=n.requestedAt),n.nextCursor};let o=this.#Ne.get(t);return void 0===o&&(o=new PaginatedResource(n)),o.observable.subscribe(()=>this.invalidateEntireStore()),this.#Ne.set(t,o),o.waitUntilLoaded()}invalidateEntireStore(){batch(()=>{this.historyVersions.invalidate(),this.notifications.invalidate(),this.optimisticUpdates.invalidate(),this.permissionHints.invalidate(),this.roomNotificationSettings.invalidate()})}async fetchUserThreadsDeltaUpdate(e){const t=this.#ke;if(null===t)return;const n=await this.#De[kInternal].httpClient.getUserThreadsSince_experimental({since:t,signal:e});t<n.requestedAt&&(this.#Te=n.requestedAt),this.updateThreadifications(n.threads.updated,n.inboxNotifications.updated,n.threads.deleted,n.inboxNotifications.deleted),this.permissionHints.update(n.permissionHints)}waitUntilRoomVersionsLoaded(e){const t=makeVersionsQueryKey(e);let n=this.#je.get(t);if(void 0===n){n=new SinglePageResource(async()=>{const t=this.#De.getRoom(e);if(null===t)throw new HttpError(`Room '${e}' is not available on client`,479);const n=await t[kInternal].listTextVersions();this.historyVersions.update(e,n.versions);const o=this.#$e.get(e);(void 0===o||o>n.requestedAt)&&this.#$e.set(e,n.requestedAt)})}return n.observable.subscribe(()=>this.invalidateEntireStore()),this.#je.set(t,n),n.waitUntilLoaded()}async fetchRoomVersionsDeltaUpdate(e,t){const n=this.#$e.get(e);if(void 0===n)return;const o=nn(this.#De.getRoom(e),`Room with id ${e} is not available on client`),r=await o[kInternal].listTextVersionsSince({since:n,signal:t});this.historyVersions.update(e,r.versions),n<r.requestedAt&&this.#$e.set(e,r.requestedAt)}waitUntilRoomNotificationSettingsLoaded(e){const t=makeNotificationSettingsQueryKey(e);let n=this.#Fe.get(t);if(void 0===n){n=new SinglePageResource(async()=>{const t=this.#De.getRoom(e);if(null===t)throw new HttpError(`Room '${e}' is not available on client`,479);const n=await t.getNotificationSettings();this.roomNotificationSettings.update(e,n)})}return n.observable.subscribe(()=>this.invalidateEntireStore()),this.#Fe.set(t,n),n.waitUntilLoaded()}async refreshRoomNotificationSettings(e,t){const n=nn(this.#De.getRoom(e),`Room with id ${e} is not available on client`),o=await n.getNotificationSettings({signal:t});this.roomNotificationSettings.update(e,o)}};function applyOptimisticUpdates_forThreadifications(e,t,n){const o=e.clone();let r=Object.fromEntries(t);for(const e of n)switch(e.type){case"create-thread":o.upsert(e.thread);break;case"edit-thread-metadata":{const t=o.get(e.threadId);if(void 0===t)break;if(t.updatedAt>e.updatedAt)break;o.upsert({...t,updatedAt:e.updatedAt,metadata:{...t.metadata,...e.metadata}});break}case"mark-thread-as-resolved":{const t=o.get(e.threadId);if(void 0===t)break;o.upsert({...t,resolved:!0});break}case"mark-thread-as-unresolved":{const t=o.get(e.threadId);if(void 0===t)break;o.upsert({...t,resolved:!1});break}case"create-comment":{const t=o.get(e.comment.threadId);if(void 0===t)break;o.upsert(applyUpsertComment(t,e.comment));const n=Object.values(r).find(e=>"thread"===e.kind&&e.threadId===t.id);if(void 0===n)break;r[n.id]={...n,notifiedAt:e.comment.createdAt,readAt:e.comment.createdAt};break}case"edit-comment":{const t=o.get(e.comment.threadId);if(void 0===t)break;o.upsert(applyUpsertComment(t,e.comment));break}case"delete-comment":{const t=o.get(e.threadId);if(void 0===t)break;o.upsert(applyDeleteComment(t,e.commentId,e.deletedAt));break}case"delete-thread":{const t=o.get(e.threadId);if(void 0===t)break;o.upsert({...t,deletedAt:e.deletedAt,updatedAt:e.deletedAt,comments:[]});break}case"add-reaction":{const t=o.get(e.threadId);if(void 0===t)break;o.upsert(applyAddReaction(t,e.commentId,e.reaction));break}case"remove-reaction":{const t=o.get(e.threadId);if(void 0===t)break;o.upsert(applyRemoveReaction(t,e.commentId,e.emoji,e.userId,e.removedAt));break}case"mark-inbox-notification-as-read":{const t=r[e.inboxNotificationId];if(void 0===t)break;r[e.inboxNotificationId]={...t,readAt:e.readAt};break}case"mark-all-inbox-notifications-as-read":for(const t in r){const n=r[t];if(void 0===n)break;r[t]={...n,readAt:e.readAt}}break;case"delete-inbox-notification":delete r[e.inboxNotificationId];break;case"delete-all-inbox-notifications":r={}}return{sortedNotifications:Object.values(r).filter(e=>"thread"!==e.kind||void 0!==o.get(e.threadId)).sort((e,t)=>t.notifiedAt.getTime()-e.notifiedAt.getTime()),notificationsById:r,threadsDB:o}}function applyOptimisticUpdates_forSettings(e,t){const n=Object.fromEntries(e);for(const e of t)switch(e.type){case"update-notification-settings":{const t=n[e.roomId];if(void 0===t)break;n[e.roomId]={...t,...e.settings}}}return n}function compareInboxNotifications(e,t){return e.notifiedAt>t.notifiedAt?1:e.notifiedAt<t.notifiedAt?-1:e.readAt&&t.readAt?e.readAt>t.readAt?1:e.readAt<t.readAt?-1:0:e.readAt||t.readAt?e.readAt?1:-1:0}function applyUpsertComment(e,t){if(void 0!==e.deletedAt)return e;if(t.threadId!==e.id)return fancy_console_exports.warn(`Comment ${t.id} does not belong to thread ${e.id}`),e;const n=e.comments.find(e=>e.id===t.id);if(void 0===n){const n=new Date(Math.max(e.updatedAt.getTime(),t.createdAt.getTime()));return{...e,updatedAt:n,comments:[...e.comments,t]}}if(void 0!==n.deletedAt)return e;if(void 0===n.editedAt||void 0===t.editedAt||n.editedAt<=t.editedAt){const n=e.comments.map(e=>e.id===t.id?t:e);return{...e,updatedAt:new Date(Math.max(e.updatedAt.getTime(),t.editedAt?.getTime()||t.createdAt.getTime())),comments:n}}return e}function applyDeleteComment(e,t,n){if(void 0!==e.deletedAt)return e;const o=e.comments.find(e=>e.id===t);if(void 0===o)return e;if(void 0!==o.deletedAt)return e;const r=e.comments.map(e=>e.id===t?{...e,deletedAt:n,body:void 0,attachments:[]}:e);return r.every(e=>void 0!==e.deletedAt)?{...e,deletedAt:n,updatedAt:n}:{...e,updatedAt:n,comments:r}}function applyAddReaction(e,t,n){if(void 0!==e.deletedAt)return e;const o=e.comments.find(e=>e.id===t);if(void 0===o)return e;if(void 0!==o.deletedAt)return e;const r=e.comments.map(e=>e.id===t?{...e,reactions:upsertReaction(e.reactions,n)}:e);return{...e,updatedAt:new Date(Math.max(n.createdAt.getTime(),e.updatedAt.getTime())),comments:r}}function applyRemoveReaction(e,t,n,o,r){if(void 0!==e.deletedAt)return e;const a=e.comments.find(e=>e.id===t);if(void 0===a)return e;if(void 0!==a.deletedAt)return e;const i=e.comments.map(e=>e.id===t?{...e,reactions:e.reactions.map(e=>e.emoji===n?{...e,users:e.users.filter(e=>e.id!==o)}:e).filter(e=>e.users.length>0)}:e);return{...e,updatedAt:new Date(Math.max(r.getTime(),e.updatedAt.getTime())),comments:i}}function upsertReaction(e,t){const n=e.find(e=>e.emoji===t.emoji);return void 0===n?[...e,{emoji:t.emoji,createdAt:t.createdAt,users:[{id:t.userId}]}]:!1===n.users.some(e=>e.id===t.userId)?e.map(e=>e.emoji===t.emoji?{...e,users:[...e.users,{id:t.userId}]}:e):e}var ClientContext=React.createContext(null);function missingUserError(e){return new Error(`resolveUsers didn't return anything for user '${e}'`)}function missingRoomInfoError(e){return new Error(`resolveRoomsInfo didn't return anything for room '${e}'`)}function identity(e){return e}var _umbrellaStores=new WeakMap,_extras=new WeakMap;function selectUnreadInboxNotificationsCount(e){let t=0;for(const n of e)(null===n.readAt||n.readAt<n.notifiedAt)&&t++;return t}function selectorFor_useUnreadInboxNotificationsCount(e){return e.inboxNotifications?{isLoading:!1,count:selectUnreadInboxNotificationsCount(e.inboxNotifications)}:e}function selectorFor_useUser(e,t){return void 0===e||e?.isLoading?e??{isLoading:!0}:e.error?e:e.data?{isLoading:!1,user:e.data}:{isLoading:!1,error:missingUserError(t)}}function selectorFor_useRoomInfo(e,t){return void 0===e||e?.isLoading?e??{isLoading:!0}:e.error?e:e.data?{isLoading:!1,info:e.data}:{isLoading:!1,error:missingRoomInfoError(t)}}function getUmbrellaStoreForClient(e){let t=_umbrellaStores.get(e);return t||(t=new UmbrellaStore(e),_umbrellaStores.set(e,t)),t}function getLiveblocksExtrasForClient(e){let t=_extras.get(e);return t||(t=makeLiveblocksExtrasForClient(e),_extras.set(e,t)),t}function makeLiveblocksExtrasForClient(e){const t=getUmbrellaStoreForClient(e),n=makePoller(async e=>{try{return await t.fetchNotificationsDeltaUpdate(e)}catch(e){throw console.warn(`Polling new inbox notifications failed: ${String(e)}`),e}},config$1.NOTIFICATIONS_POLL_INTERVAL,{maxStaleTimeMs:config$1.NOTIFICATIONS_MAX_STALE_TIME}),o=makePoller(async e=>{try{return await t.fetchUserThreadsDeltaUpdate(e)}catch(e){throw console.warn(`Polling new user threads failed: ${String(e)}`),e}},config$1.USER_THREADS_POLL_INTERVAL,{maxStaleTimeMs:config$1.USER_THREADS_MAX_STALE_TIME});return{store:t,notificationsPoller:n,userThreadsPoller:o}}function useInboxNotifications_withClient(e,t,n){const{store:o,notificationsPoller:r}=getLiveblocksExtrasForClient(e);return React.useEffect(()=>{o.waitUntilNotificationsLoaded()}),React.useEffect(()=>(r.inc(),r.pollNowIfStale(),()=>{r.dec()}),[r]),useSyncExternalStoreWithSelector(o.subscribe1_notifications,o.getInboxNotificationsLoadingState,o.getInboxNotificationsLoadingState,t,n)}function useInboxNotificationsSuspense_withClient(e){const t=getLiveblocksExtrasForClient(e).store;use(t.waitUntilNotificationsLoaded());const n=useInboxNotifications_withClient(e,identity,shallow);return assert(!n.error),assert(!n.isLoading),n}function useUnreadInboxNotificationsCount_withClient(e){return useInboxNotifications_withClient(e,selectorFor_useUnreadInboxNotificationsCount,shallow)}function useUnreadInboxNotificationsCountSuspense_withClient(e){const t=getLiveblocksExtrasForClient(e).store;use(t.waitUntilNotificationsLoaded());const n=useUnreadInboxNotificationsCount_withClient(e);return assert(!n.isLoading),assert(!n.error),n}function useMarkInboxNotificationAsRead_withClient(e){return React.useCallback(t=>{const{store:n}=getLiveblocksExtrasForClient(e),o=new Date,r=n.optimisticUpdates.add({type:"mark-inbox-notification-as-read",inboxNotificationId:t,readAt:o});e.markInboxNotificationAsRead(t).then(()=>{n.markInboxNotificationRead(t,o,r)},()=>{n.optimisticUpdates.remove(r)})},[e])}function useMarkAllInboxNotificationsAsRead_withClient(e){return React.useCallback(()=>{const{store:t}=getLiveblocksExtrasForClient(e),n=new Date,o=t.optimisticUpdates.add({type:"mark-all-inbox-notifications-as-read",readAt:n});e.markAllInboxNotificationsAsRead().then(()=>{t.markAllInboxNotificationsRead(o,n)},()=>{t.optimisticUpdates.remove(o)})},[e])}function useDeleteInboxNotification_withClient(e){return React.useCallback(t=>{const{store:n}=getLiveblocksExtrasForClient(e),o=new Date,r=n.optimisticUpdates.add({type:"delete-inbox-notification",inboxNotificationId:t,deletedAt:o});e.deleteInboxNotification(t).then(()=>{n.deleteInboxNotification(t,r)},()=>{n.optimisticUpdates.remove(r)})},[e])}function useDeleteAllInboxNotifications_withClient(e){return React.useCallback(()=>{const{store:t}=getLiveblocksExtrasForClient(e),n=new Date,o=t.optimisticUpdates.add({type:"delete-all-inbox-notifications",deletedAt:n});e.deleteAllInboxNotifications().then(()=>{t.deleteAllInboxNotifications(o)},()=>{t.optimisticUpdates.remove(o)})},[e])}function useInboxNotificationThread_withClient(e,t){const{store:n}=getLiveblocksExtrasForClient(e),o=n.get1_both,r=React.useCallback(e=>{const n=e.notificationsById[t]??raise(`Inbox notification with ID "${t}" not found`);"thread"!==n.kind&&raise(`Inbox notification with ID "${t}" is not of kind "thread"`);return e.threadsDB.get(n.threadId)??raise(`Thread with ID "${n.threadId}" not found, this inbox notification might not be of kind "thread"`)},[t]);return useSyncExternalStoreWithSelector(n.subscribe1_both,o,o,r)}function useUser_withClient(e,t){const n=e[kInternal].usersStore,o=React.useCallback(()=>n.getState(t),[n,t]),r=React.useCallback(e=>selectorFor_useUser(e,t),[t]),a=useSyncExternalStoreWithSelector(n.subscribe,o,o,r,shallow);return React.useEffect(()=>{n.get(t)},[n,t,a]),a}function useRoomInfo_withClient(e,t){const n=e[kInternal].roomsInfoStore,o=React.useCallback(()=>n.getState(t),[n,t]),r=React.useCallback(e=>selectorFor_useRoomInfo(e,t),[t]),a=useSyncExternalStoreWithSelector(n.subscribe,o,o,r,shallow);return React.useEffect(()=>{n.get(t)},[n,t,a]),a}function useEnsureNoLiveblocksProvider(e){const t=useClientOrNull();if(!e?.allowNesting&&null!==t)throw new Error("You cannot nest multiple LiveblocksProvider instances in the same React tree.")}function useClientOrNull(){return React.useContext(ClientContext)}function useClient(){return useClientOrNull()??raise("LiveblocksProvider is missing from the React tree.")}function LiveblocksProviderWithClient(e){return useEnsureNoLiveblocksProvider(e),jsxRuntime.exports.jsx(ClientContext.Provider,{value:e.client,children:e.children})}function LiveblocksProvider(e){const{children:t,...n}=e,o={publicApiKey:useInitial$1(n.publicApiKey),throttle:useInitial$1(n.throttle),lostConnectionTimeout:useInitial$1(n.lostConnectionTimeout),backgroundKeepAliveTimeout:useInitial$1(n.backgroundKeepAliveTimeout),polyfills:useInitial$1(n.polyfills),unstable_fallbackToHTTP:useInitial$1(n.unstable_fallbackToHTTP),unstable_streamData:useInitial$1(n.unstable_streamData),preventUnsavedChanges:useInitial$1(n.preventUnsavedChanges),authEndpoint:useInitialUnlessFunction(n.authEndpoint),resolveMentionSuggestions:useInitialUnlessFunction(n.resolveMentionSuggestions),resolveUsers:useInitialUnlessFunction(n.resolveUsers),resolveRoomsInfo:useInitialUnlessFunction(n.resolveRoomsInfo),baseUrl:useInitial$1(n.baseUrl),enableDebugLogging:useInitial$1(n.enableDebugLogging)},r=React.useMemo(()=>createClient(o),[]);return jsxRuntime.exports.jsx(LiveblocksProviderWithClient,{client:r,children:t})}function useInboxNotificationsSuspense(){return useInboxNotificationsSuspense_withClient(useClient())}function useInboxNotificationThread(e){return useInboxNotificationThread_withClient(useClient(),e)}function useMarkAllInboxNotificationsAsRead(){return useMarkAllInboxNotificationsAsRead_withClient(useClient())}function useMarkInboxNotificationAsRead(){return useMarkInboxNotificationAsRead_withClient(useClient())}function useDeleteAllInboxNotifications(){return useDeleteAllInboxNotifications_withClient(useClient())}function useDeleteInboxNotification(){return useDeleteInboxNotification_withClient(useClient())}function useUnreadInboxNotificationsCountSuspense(){return useUnreadInboxNotificationsCountSuspense_withClient(useClient())}function useUser(e){return useUser_withClient(useClient(),e)}function useRoomInfo(e){return useRoomInfo_withClient(useClient(),e)}var _useInboxNotificationThread=useInboxNotificationThread,_useUser=useUser,CreateThreadError=class extends Error{constructor(e,t){super("Create thread failed."),this.cause=e,this.context=t,this.name="CreateThreadError"}},MarkThreadAsResolvedError=class extends Error{constructor(e,t){super("Mark thread as resolved failed."),this.cause=e,this.context=t,this.name="MarkThreadAsResolvedError"}},MarkThreadAsUnresolvedError=class extends Error{constructor(e,t){super("Mark thread as unresolved failed."),this.cause=e,this.context=t,this.name="MarkThreadAsUnresolvedError"}},CreateCommentError=class extends Error{constructor(e,t){super("Create comment failed."),this.cause=e,this.context=t,this.name="CreateCommentError"}},EditCommentError=class extends Error{constructor(e,t){super("Edit comment failed."),this.cause=e,this.context=t,this.name="EditCommentError"}},DeleteCommentError=class extends Error{constructor(e,t){super("Delete comment failed."),this.cause=e,this.context=t,this.name="DeleteCommentError"}},AddReactionError=class extends Error{constructor(e,t){super("Add reaction failed."),this.cause=e,this.context=t,this.name="AddReactionError"}},RemoveReactionError=class extends Error{constructor(e,t){super("Remove reaction failed."),this.cause=e,this.context=t,this.name="RemoveReactionError"}},MarkInboxNotificationAsReadError=class extends Error{constructor(e,t){super("Mark inbox notification as read failed."),this.cause=e,this.context=t,this.name="MarkInboxNotificationAsReadError"}},identity2=e=>e;function useSignal(e,t,n){return useSyncExternalStoreWithSelector(e.subscribe,e.get,e.get,t??identity2,n)}function handleScrollToCommentOnLoad(e,t){if(!1===e)return;if(!t.threads)return;if(!("undefined"!=typeof window))return;const n=window.location.hash.slice(1);if(!n.startsWith("cm_"))return;const o=document.getElementById(n);if(null===o)return;t.threads.flatMap(e=>e.comments).some(e=>e.id===n)&&o.scrollIntoView()}function useScrollToCommentOnLoadEffect(e,t){React.useEffect(()=>{handleScrollToCommentOnLoad(e,t)},[t.isLoading])}var identity3=e=>e;function getCurrentUserId(e){const t=e[kInternal].currentUserId.get();return void 0===t?"anonymous":t}function handleApiError(e){const t=`Request failed with status ${e.status}: ${e.message}`;if("FORBIDDEN"===e.details?.error){const n=[t,e.details.suggestion,e.details.docs].filter(Boolean).join("\n");fancy_console_exports.error(n)}return new Error(t)}Object.freeze([]);var _extras2=new WeakMap;function getRoomExtrasForClient(e){let t=_extras2.get(e);return t||(t=makeRoomExtrasForClient(e),_extras2.set(e,t)),t}function makeRoomExtrasForClient(e){const t=getUmbrellaStoreForClient(e),n=makeEventSource();const o=new Map,r=new Map,a=new Map;return{store:t,commentsErrorEventSource:n.observable,onMutationFailure:function(e,o,r){if(t.optimisticUpdates.remove(o),e instanceof HttpError){const t=handleApiError(e);return void n.notify(r(t))}if(!(e instanceof HttpError))throw e;handleApiError(e)},getOrCreateThreadsPollerForRoomId:function(e){let n=o.get(e);return n||(n=makePoller(async n=>{try{return await t.fetchRoomThreadsDeltaUpdate(e,n)}catch(t){throw fancy_console_exports.warn(`Polling new threads for '${e}' failed: ${String(t)}`),t}},config$1.ROOM_THREADS_POLL_INTERVAL,{maxStaleTimeMs:config$1.ROOM_THREADS_MAX_STALE_TIME}),o.set(e,n)),n},getOrCreateVersionsPollerForRoomId:function(e){let n=r.get(e);return n||(n=makePoller(async n=>{try{return await t.fetchRoomVersionsDeltaUpdate(e,n)}catch(t){throw fancy_console_exports.warn(`Polling new history versions for '${e}' failed: ${String(t)}`),t}},config$1.HISTORY_VERSIONS_POLL_INTERVAL,{maxStaleTimeMs:config$1.HISTORY_VERSIONS_MAX_STALE_TIME}),r.set(e,n)),n},getOrCreateNotificationsSettingsPollerForRoomId:function(e){let n=a.get(e);return n||(n=makePoller(async n=>{try{return await t.refreshRoomNotificationSettings(e,n)}catch(t){throw fancy_console_exports.warn(`Polling notification settings for '${e}' failed: ${String(t)}`),t}},config$1.NOTIFICATION_SETTINGS_POLL_INTERVAL,{maxStaleTimeMs:config$1.NOTIFICATION_SETTINGS_MAX_STALE_TIME}),a.set(e,n)),n}}}function RoomProvider(e){const t=useClient(),[n]=React.useState(()=>new Map),o=React.useCallback((e,o)=>{const r=n.get(e);if(r)return r;const a=t.enterRoom(e,o),i=a.leave;return a.leave=()=>{i(),n.delete(e)},n.set(e,a),a},[t,n]);return jsxRuntime.exports.jsx(RoomProviderInner,{...e,stableEnterRoom:o})}function RoomProviderInner(e){const t=useClient(),{id:n,stableEnterRoom:o}=e,r=useInitial$1({initialPresence:e.initialPresence,initialStorage:e.initialStorage,autoConnect:e.autoConnect??"undefined"!=typeof window}),[{room:a},i]=React.useState(()=>o(n,{...r,autoConnect:!1}));return React.useEffect(()=>{const{store:e}=getRoomExtrasForClient(t);return a.events.comments.subscribe(t=>{!async function(t){if(t.type===ServerMsgCode.THREAD_DELETED)return void e.deleteThread(t.threadId,null);const n=await a.getThread(t.threadId);if(!n.thread)return void e.deleteThread(t.threadId,null);const{thread:o,inboxNotification:r}=n,i=e.get1_threads().threadsDB.getEvenIfDeleted(t.threadId);switch(t.type){case ServerMsgCode.COMMENT_EDITED:case ServerMsgCode.THREAD_METADATA_UPDATED:case ServerMsgCode.THREAD_UPDATED:case ServerMsgCode.COMMENT_REACTION_ADDED:case ServerMsgCode.COMMENT_REACTION_REMOVED:case ServerMsgCode.COMMENT_DELETED:if(!i)break;e.updateThreadifications([o],r?[r]:[]);break;case ServerMsgCode.COMMENT_CREATED:e.updateThreadifications([o],r?[r]:[])}}(t)})},[t,a]),React.useEffect(()=>{const e=o(n,r);i(e);const{room:t,leave:a}=e;return r.autoConnect&&t.connect(),()=>{a()}},[n,r,o]),jsxRuntime.exports.jsx(RoomContext.Provider,{value:a,children:e.children})}function useRoom(){const e=useRoomOrNull();if(null===e)throw new Error("RoomProvider is missing from the React tree.");return e}function useResolveMentionSuggestions(){return useClient()[kInternal].resolveMentionSuggestions}function useMentionSuggestionsCache(){return useClient()[kInternal].mentionSuggestionsCache}function useThreads(e={query:{metadata:{}}}){const{scrollOnLoad:t=!0}=e,n=useClient(),o=useRoom(),{store:r,getOrCreateThreadsPollerForRoomId:a}=getRoomExtrasForClient(n),i=a(o.id);React.useEffect(()=>{r.waitUntilRoomThreadsLoaded(o.id,e.query)}),React.useEffect(()=>(i.inc(),i.pollNowIfStale(),()=>i.dec()),[i]);const s=React.useCallback(()=>r.getRoomThreadsLoadingState(o.id,e.query),[r,o.id,e.query]),l=useSyncExternalStoreWithSelector(r.subscribe1_threads,s,s,identity3,shallow2);return useScrollToCommentOnLoadEffect(t,l),l}function useCreateRoomThread(e){const t=useClient();return React.useCallback(n=>{const o=n.body,r=n.metadata??{},a=n.attachments,i=createThreadId(),s=createCommentId(),l=new Date,c={id:s,threadId:i,roomId:e,createdAt:l,type:"comment",userId:getCurrentUserId(t),body:o,reactions:[],attachments:a??[]},d={id:i,type:"thread",createdAt:l,updatedAt:l,roomId:e,metadata:r,comments:[c],resolved:!1},{store:u,onMutationFailure:f}=getRoomExtrasForClient(t),p=u.optimisticUpdates.add({type:"create-thread",thread:d,roomId:e}),_=a?.map(e=>e.id);return t[kInternal].httpClient.createThread({roomId:e,threadId:i,commentId:s,body:o,metadata:r,attachmentIds:_}).then(e=>{u.createThread(p,e)},t=>f(t,p,t=>new CreateThreadError(t,{roomId:e,threadId:i,commentId:s,body:o,metadata:r}))),d},[t,e])}function useCreateRoomComment(e){const t=useClient();return React.useCallback(({threadId:n,body:o,attachments:r})=>{const a=createCommentId(),i={id:a,threadId:n,roomId:e,type:"comment",createdAt:new Date,userId:getCurrentUserId(t),body:o,reactions:[],attachments:r??[]},{store:s,onMutationFailure:l}=getRoomExtrasForClient(t),c=s.optimisticUpdates.add({type:"create-comment",comment:i}),d=r?.map(e=>e.id);return t[kInternal].httpClient.createComment({roomId:e,threadId:n,commentId:a,body:o,attachmentIds:d}).then(e=>{s.createComment(e,c)},t=>l(t,c,t=>new CreateCommentError(t,{roomId:e,threadId:n,commentId:a,body:o}))),i},[t,e])}function useEditRoomComment(e){const t=useClient();return React.useCallback(({threadId:n,commentId:o,body:r,attachments:a})=>{const i=new Date,{store:s,onMutationFailure:l}=getRoomExtrasForClient(t),c=s.get1_threads().threadsDB.getEvenIfDeleted(n);if(void 0===c)return void fancy_console_exports.warn(`Internal unexpected behavior. Cannot edit comment in thread "${n}" because the thread does not exist in the cache.`);const d=c.comments.find(e=>e.id===o);if(void 0===d||void 0!==d.deletedAt)return void fancy_console_exports.warn(`Internal unexpected behavior. Cannot edit comment "${o}" in thread "${n}" because the comment does not exist in the cache.`);const u=s.optimisticUpdates.add({type:"edit-comment",comment:{...d,editedAt:i,body:r,attachments:a??[]}}),f=a?.map(e=>e.id);t[kInternal].httpClient.editComment({roomId:e,threadId:n,commentId:o,body:r,attachmentIds:f}).then(e=>{s.editComment(n,u,e)},t=>l(t,u,t=>new EditCommentError(t,{roomId:e,threadId:n,commentId:o,body:r})))},[t,e])}function useDeleteRoomComment(e){const t=useClient();return React.useCallback(({threadId:n,commentId:o})=>{const r=new Date,{store:a,onMutationFailure:i}=getRoomExtrasForClient(t),s=a.optimisticUpdates.add({type:"delete-comment",threadId:n,commentId:o,deletedAt:r,roomId:e});t[kInternal].httpClient.deleteComment({roomId:e,threadId:n,commentId:o}).then(()=>{a.deleteComment(n,s,o,r)},t=>i(t,s,t=>new DeleteCommentError(t,{roomId:e,threadId:n,commentId:o})))},[t,e])}function useAddRoomCommentReaction(e){const t=useClient();return React.useCallback(({threadId:n,commentId:o,emoji:r})=>{const a=new Date,i=getCurrentUserId(t),{store:s,onMutationFailure:l}=getRoomExtrasForClient(t),c=s.optimisticUpdates.add({type:"add-reaction",threadId:n,commentId:o,reaction:{emoji:r,userId:i,createdAt:a}});t[kInternal].httpClient.addReaction({roomId:e,threadId:n,commentId:o,emoji:r}).then(e=>{s.addReaction(n,c,o,e,a)},t=>l(t,c,t=>new AddReactionError(t,{roomId:e,threadId:n,commentId:o,emoji:r})))},[t,e])}function useRemoveRoomCommentReaction(e){const t=useClient();return React.useCallback(({threadId:n,commentId:o,emoji:r})=>{const a=getCurrentUserId(t),i=new Date,{store:s,onMutationFailure:l}=getRoomExtrasForClient(t),c=s.optimisticUpdates.add({type:"remove-reaction",threadId:n,commentId:o,emoji:r,userId:a,removedAt:i});t[kInternal].httpClient.removeReaction({roomId:e,threadId:n,commentId:o,emoji:r}).then(()=>{s.removeReaction(n,c,o,r,a,i)},t=>l(t,c,t=>new RemoveReactionError(t,{roomId:e,threadId:n,commentId:o,emoji:r})))},[t,e])}function useMarkRoomThreadAsRead(e){const t=useClient();return React.useCallback(n=>{const{store:o,onMutationFailure:r}=getRoomExtrasForClient(t),a=Object.values(o.get1_notifications().notificationsById).find(e=>"thread"===e.kind&&e.threadId===n);if(!a)return;const i=new Date,s=o.optimisticUpdates.add({type:"mark-inbox-notification-as-read",inboxNotificationId:a.id,readAt:i});t[kInternal].httpClient.markRoomInboxNotificationAsRead({roomId:e,inboxNotificationId:a.id}).then(()=>{o.markInboxNotificationRead(a.id,i,s)},e=>{r(e,s,e=>new MarkInboxNotificationAsReadError(e,{inboxNotificationId:a.id}))})},[t,e])}function useMarkRoomThreadAsResolved(e){const t=useClient();return React.useCallback(n=>{const o=new Date,{store:r,onMutationFailure:a}=getRoomExtrasForClient(t),i=r.optimisticUpdates.add({type:"mark-thread-as-resolved",threadId:n,updatedAt:o});t[kInternal].httpClient.markThreadAsResolved({roomId:e,threadId:n}).then(()=>{r.patchThread(n,i,{resolved:!0},o)},t=>a(t,i,t=>new MarkThreadAsResolvedError(t,{roomId:e,threadId:n})))},[t,e])}function useMarkRoomThreadAsUnresolved(e){const t=useClient();return React.useCallback(n=>{const o=new Date,{store:r,onMutationFailure:a}=getRoomExtrasForClient(t),i=r.optimisticUpdates.add({type:"mark-thread-as-unresolved",threadId:n,updatedAt:o});t[kInternal].httpClient.markThreadAsUnresolved({roomId:e,threadId:n}).then(()=>{r.patchThread(n,i,{resolved:!1},o)},t=>a(t,i,t=>new MarkThreadAsUnresolvedError(t,{roomId:e,threadId:n})))},[t,e])}function useThreadSubscription(e){const t=useClient(),{store:n}=getRoomExtrasForClient(t);return useSignal(n.outputs.threadifications,React.useCallback(t=>{const n=t.sortedNotifications.find(t=>"thread"===t.kind&&t.threadId===e),o=t.threadsDB.get(e);return void 0===n||void 0===o?{status:"not-subscribed"}:{status:"subscribed",unreadSince:n.readAt}},[e]),shallow)}function useThreadsSuspense(e={query:{metadata:{}}}){const t=useClient(),n=useRoom(),{store:o}=getRoomExtrasForClient(t);use(o.waitUntilRoomThreadsLoaded(n.id,e.query));const r=useThreads(e);return assert(!r.error),assert(!r.isLoading),r}function selectorFor_useAttachmentUrl(e){return void 0===e||e?.isLoading?e??{isLoading:!0}:e.error?e:(assert(void 0!==e.data),{isLoading:!1,url:e.data})}function useRoomAttachmentUrl(e,t){const n=useClient()[kInternal].httpClient.getOrCreateAttachmentUrlsStore(t),o=React.useCallback(()=>n.getState(e),[n,e]);return React.useEffect(()=>{n.get(e)},[n,e]),useSyncExternalStoreWithSelector(n.subscribe,o,o,selectorFor_useAttachmentUrl,shallow)}function useRoomPermissions(e){return useSignal(getRoomExtrasForClient(useClient()).store.permissionHints.signal,t=>t[e]??new Set)}var _RoomProvider=RoomProvider,_useThreadsSuspense=useThreadsSuspense,MENTION_SUGGESTIONS_DEBOUNCE=500;function useMentionSuggestions(e,t){const[n,o]=React.useState(),r=React.useRef(),a=useResolveMentionSuggestions(),i=useMentionSuggestionsCache();return React.useEffect(()=>{if(void 0===t||!a)return;const n={text:t,roomId:e},s=stringify(n);let l,c=!1;const d=async()=>{try{r.current=performance.now();const e=await a(n);c||(o(e),i.set(s,e))}catch(e){console.error(e?.message)}};return i.has(s)?o(i.get(s)):!r.current||Math.abs(performance.now()-r.current)>MENTION_SUGGESTIONS_DEBOUNCE?d():l=window.setTimeout(()=>{d()},MENTION_SUGGESTIONS_DEBOUNCE),()=>{c=!0,window.clearTimeout(l)}},[t,e,a,i]),n}function useSyncSource(){const e=useClient()[kInternal].createSyncSource,[t,n]=React.useState();return React.useEffect(()=>{const t=e();return n(t),()=>t.destroy()},[e]),t}function composeEventHandlers(e,t,{checkForDefaultPrevented:n=!0}={}){return function(o){if(e?.(o),!1===n||!o.defaultPrevented)return t?.(o)}}var useLayoutEffect2=globalThis?.document?React__namespace.useLayoutEffect:()=>{},useInsertionEffect=React__namespace[" useInsertionEffect ".trim().toString()]||useLayoutEffect2;function useControllableState$1({prop:e,defaultProp:t,onChange:n=()=>{},caller:o}){const[r,a,i]=useUncontrolledState({defaultProp:t,onChange:n}),s=void 0!==e,l=s?e:r;{const t=React__namespace.useRef(void 0!==e);React__namespace.useEffect(()=>{const e=t.current;if(e!==s){const t=e?"controlled":"uncontrolled",n=s?"controlled":"uncontrolled";console.warn(`${o} is changing from ${t} to ${n}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`)}t.current=s},[s,o])}return[l,React__namespace.useCallback(t=>{if(s){const n=isFunction(t)?t(e):t;n!==e&&i.current?.(n)}else a(t)},[s,e,a,i])]}function useUncontrolledState({defaultProp:e,onChange:t}){const[n,o]=React__namespace.useState(e),r=React__namespace.useRef(n),a=React__namespace.useRef(t);return useInsertionEffect(()=>{a.current=t},[t]),React__namespace.useEffect(()=>{r.current!==n&&(a.current?.(n),r.current=n)},[n,r]),[n,o,a]}function isFunction(e){return"function"==typeof e}function setRef(e,t){if("function"==typeof e)return e(t);null!=e&&(e.current=t)}function composeRefs(...e){return t=>{let n=!1;const o=e.map(e=>{const o=setRef(e,t);return n||"function"!=typeof o||(n=!0),o});if(n)return()=>{for(let t=0;t<o.length;t++){const n=o[t];"function"==typeof n?n():setRef(e[t],null)}}}}function useComposedRefs(...e){return React__namespace.useCallback(composeRefs(...e),e)}function createSlot(e){const t=createSlotClone(e),n=React__namespace.forwardRef((e,n)=>{const{children:o,...r}=e,a=React__namespace.Children.toArray(o),i=a.find(isSlottable);if(i){const e=i.props.children,o=a.map(t=>t===i?React__namespace.Children.count(e)>1?React__namespace.Children.only(null):React__namespace.isValidElement(e)?e.props.children:null:t);return jsxRuntime.exports.jsx(t,{...r,ref:n,children:React__namespace.isValidElement(e)?React__namespace.cloneElement(e,void 0,o):null})}return jsxRuntime.exports.jsx(t,{...r,ref:n,children:o})});return n.displayName=`${e}.Slot`,n}var Slot$2=createSlot("Slot");function createSlotClone(e){const t=React__namespace.forwardRef((e,t)=>{const{children:n,...o}=e;if(React__namespace.isValidElement(n)){const e=getElementRef$1(n),r=mergeProps(o,n.props);return n.type!==React__namespace.Fragment&&(r.ref=t?composeRefs(t,e):e),React__namespace.cloneElement(n,r)}return React__namespace.Children.count(n)>1?React__namespace.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var SLOTTABLE_IDENTIFIER=Symbol("radix.slottable");function createSlottable(e){const t=({children:e})=>jsxRuntime.exports.jsx(jsxRuntime.exports.Fragment,{children:e});return t.displayName=`${e}.Slottable`,t.__radixId=SLOTTABLE_IDENTIFIER,t}var Slottable$1=createSlottable("Slottable");function isSlottable(e){return React__namespace.isValidElement(e)&&"function"==typeof e.type&&"__radixId"in e.type&&e.type.__radixId===SLOTTABLE_IDENTIFIER}function mergeProps(e,t){const n={...t};for(const o in t){const r=e[o],a=t[o];/^on[A-Z]/.test(o)?r&&a?n[o]=(...e)=>{const t=a(...e);return r(...e),t}:r&&(n[o]=r):"style"===o?n[o]={...r,...a}:"className"===o&&(n[o]=[r,a].filter(Boolean).join(" "))}return{...e,...n}}function getElementRef$1(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var NODES=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Primitive=NODES.reduce((e,t)=>{const n=createSlot(`Primitive.${t}`),o=React__namespace.forwardRef((e,o)=>{const{asChild:r,...a}=e,i=r?n:t;return"undefined"!=typeof window&&(window[Symbol.for("radix-ui")]=!0),jsxRuntime.exports.jsx(i,{...a,ref:o})});return o.displayName=`Primitive.${t}`,{...e,[t]:o}},{});function dispatchDiscreteCustomEvent(e,t){e&&ReactDOM__namespace.flushSync(()=>e.dispatchEvent(t))}var NAME$2="Toggle",Toggle=React__namespace.forwardRef((e,t)=>{const{pressed:n,defaultPressed:o,onPressedChange:r,...a}=e,[i,s]=useControllableState$1({prop:n,onChange:r,defaultProp:o??!1,caller:NAME$2});return jsxRuntime.exports.jsx(Primitive.button,{type:"button","aria-pressed":i,"data-state":i?"on":"off","data-disabled":e.disabled?"":void 0,...a,ref:t,onClick:composeEventHandlers(e.onClick,()=>{e.disabled||s(!i)})})});Toggle.displayName=NAME$2;var Root$3=Toggle;function classNames(...e){return e.filter(e=>"string"==typeof e||"number"==typeof e).join(" ")}const ICON_WIDTH=20,ICON_HEIGHT=20;function Icon({children:e,className:t,...n}){return jsxRuntime.exports.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:ICON_WIDTH,height:ICON_HEIGHT,viewBox:`0 0 ${ICON_WIDTH} ${ICON_HEIGHT}`,fill:"none",stroke:"currentColor",strokeWidth:1.5,strokeLinecap:"round",strokeLinejoin:"round",role:"presentation",className:classNames("lb-icon",t),...n,children:e})}function CheckIcon(e){return jsxRuntime.exports.jsx(Icon,{...e,children:jsxRuntime.exports.jsx("path",{d:"M16 6L8 14L4 10"})})}function CrossIcon(e){return jsxRuntime.exports.jsxs(Icon,{...e,children:[jsxRuntime.exports.jsx("path",{d:"M15 5L5 15"}),jsxRuntime.exports.jsx("path",{d:"M5 5L15 15"})]})}function DeleteIcon(e){return jsxRuntime.exports.jsx(Icon,{...e,children:jsxRuntime.exports.jsx("path",{d:"M4.5 6.5h11M14 6.5V14a1.5 1.5 0 0 1-1.5 1.5h-5A1.5 1.5 0 0 1 6 14V6.5M7.5 6.5V5a1 1 0 0 1 1-1h3a1 1 0 0 1 1 1v1.5"})})}function EditIcon(e){return jsxRuntime.exports.jsx(Icon,{...e,children:jsxRuntime.exports.jsx("path",{d:"m11.784 5.797-6.13 6.138a4 4 0 0 0-1.03 1.775L4 16l2.285-.624a4 4 0 0 0 1.776-1.032l6.145-6.152m-2.422-2.395 1.244-1.246c.608-.608 1.826-.81 2.53-.104.7.7.499 1.893-.122 2.515l-1.23 1.23m-2.422-2.395 2.422 2.395"})})}function EllipsisIcon(e){return jsxRuntime.exports.jsxs(Icon,{fill:"currentColor",...e,children:[jsxRuntime.exports.jsx("circle",{cx:5,cy:10,r:.75}),jsxRuntime.exports.jsx("circle",{cx:10,cy:10,r:.75}),jsxRuntime.exports.jsx("circle",{cx:15,cy:10,r:.75})]})}function EmojiAddIcon(e){return jsxRuntime.exports.jsxs(Icon,{...e,children:[jsxRuntime.exports.jsx("path",{d:"M11 3.07A7 7 0 1 0 16.93 9"}),jsxRuntime.exports.jsx("path",{d:"M7.5 11.5S8.25 13 10 13s2.5-1.5 2.5-1.5M8 8h0"}),jsxRuntime.exports.jsx("path",{d:"M12 8h0"}),jsxRuntime.exports.jsx("path",{d:"M13 5h4m-2-2v4"}),jsxRuntime.exports.jsx("circle",{cx:"8",cy:"8",r:".25"}),jsxRuntime.exports.jsx("circle",{cx:"12",cy:"8",r:".25"})]})}const FLOATING_ELEMENT_SIDE_OFFSET=6,FLOATING_ELEMENT_COLLISION_PADDING=10,EMOJI_FONT_FAMILY="'Apple Color Emoji', 'Noto Color Emoji', 'Twemoji Mozilla', 'Android Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', EmojiSymbols, sans-serif",Emoji$1=React.forwardRef(({emoji:e,style:t,asChild:n,...o},r)=>{const a=n?Slot$2:"span";return jsxRuntime.exports.jsx(a,{role:"img","aria-label":e,"data-emoji":e,style:{...t,fontFamily:EMOJI_FONT_FAMILY,display:"inline-flex",alignItems:"center",justifyContent:"center",width:"1em",whiteSpace:"nowrap"},...o,ref:r,children:e})}),Emoji=React.forwardRef(({className:e,...t},n)=>jsxRuntime.exports.jsx(Emoji$1,{className:classNames("lb-emoji",e),...t,ref:n}));function pluralize(e,t,n){return 1===e?t:n??`${t}s`}const defaultOverrides={locale:"en",dir:"ltr",USER_SELF:"you",USER_UNKNOWN:"Anonymous",LIST_REMAINING:e=>`${e} more`,LIST_REMAINING_USERS:e=>`${e} ${pluralize(e,"other")}`,LIST_REMAINING_COMMENTS:e=>`${e} more ${pluralize(e,"comment")}`,EMOJI_PICKER_SEARCH_PLACEHOLDER:"Search…",EMOJI_PICKER_EMPTY:"No emoji found.",EMOJI_PICKER_ERROR:()=>"There was an error while getting the list of emoji.",ATTACHMENT_TOO_LARGE:e=>e?`The file is larger than ${e}`:"The file is too large",ATTACHMENT_ERROR:()=>"The file couldn’t be uploaded.",COMPOSER_INSERT_MENTION:"Mention someone",COMPOSER_INSERT_EMOJI:"Add emoji",COMPOSER_ATTACH_FILES:"Attach files",COMPOSER_REMOVE_ATTACHMENT:"Remove attachment",COMPOSER_PLACEHOLDER:"Write a comment…",COMPOSER_SEND:"Send",COMPOSER_TOGGLE_MARK:e=>{switch(e){case"bold":return"Bold";case"italic":return"Italic";case"strikethrough":return"Strikethrough";case"code":return"Inline code";default:return assertNever(e,"Unexpected mark")}},COMMENT_EDITED:"(edited)",COMMENT_DELETED:"This comment has been deleted.",COMMENT_MORE:"More",COMMENT_EDIT:"Edit comment",COMMENT_EDIT_COMPOSER_PLACEHOLDER:"Edit comment…",COMMENT_EDIT_COMPOSER_CANCEL:"Cancel",COMMENT_EDIT_COMPOSER_SAVE:"Save",COMMENT_DELETE:"Delete comment",COMMENT_DELETE_ATTACHMENT:"Delete attachment",COMMENT_ADD_REACTION:"Add reaction",COMMENT_REACTION_LIST:(e,t)=>jsxRuntime.exports.jsxs(jsxRuntime.exports.Fragment,{children:[e," reacted with ",jsxRuntime.exports.jsx(Emoji,{emoji:t})]}),COMMENT_REACTION_DESCRIPTION:(e,t)=>`${t} ${pluralize(t,"reaction")}, react with ${e}`,THREAD_RESOLVE:"Resolve thread",THREAD_UNRESOLVE:"Re-open thread",THREAD_NEW_INDICATOR:"New",THREAD_NEW_INDICATOR_DESCRIPTION:"New comments",THREAD_COMPOSER_PLACEHOLDER:"Reply to thread…",THREAD_COMPOSER_SEND:"Reply",INBOX_NOTIFICATION_MORE:"More",INBOX_NOTIFICATION_MARK_AS_READ:"Mark as read",INBOX_NOTIFICATION_DELETE:"Delete notification",INBOX_NOTIFICATION_THREAD_COMMENTS_LIST:(e,t)=>jsxRuntime.exports.jsxs(jsxRuntime.exports.Fragment,{children:[e," commented",t?jsxRuntime.exports.jsxs(jsxRuntime.exports.Fragment,{children:[" in ",t]}):jsxRuntime.exports.jsx(jsxRuntime.exports.Fragment,{children:" in a thread"})]}),INBOX_NOTIFICATION_THREAD_MENTION:(e,t)=>jsxRuntime.exports.jsxs(jsxRuntime.exports.Fragment,{children:[e," mentioned you",t?jsxRuntime.exports.jsxs(jsxRuntime.exports.Fragment,{children:[" in ",t]}):null]}),INBOX_NOTIFICATION_TEXT_MENTION:(e,t)=>jsxRuntime.exports.jsxs(jsxRuntime.exports.Fragment,{children:[e," mentioned you",t?jsxRuntime.exports.jsxs(jsxRuntime.exports.Fragment,{children:[" in ",t]}):null]}),HISTORY_VERSION_PREVIEW_AUTHORS_LIST:e=>jsxRuntime.exports.jsxs(jsxRuntime.exports.Fragment,{children:["Edits from ",e]}),HISTORY_VERSION_PREVIEW_RESTORE:"Restore",HISTORY_VERSION_PREVIEW_EMPTY:"No content.",HISTORY_VERSION_PREVIEW_ERROR:()=>"There was an error while getting this version."},OverridesContext=React.createContext(void 0);function useOverrides(e){const t=React.useContext(OverridesContext);return React.useMemo(()=>({...defaultOverrides,...t,...e}),[t,e])}function OverridesProvider({children:e,overrides:t}){const n=React.useContext(OverridesContext),o=React.useMemo(()=>({...defaultOverrides,...n,...t}),[n,t]);return jsxRuntime.exports.jsx(OverridesContext.Provider,{value:o,children:e})}
2
2
  /*!
3
3
  * is-plain-object <https://github.com/jonschlinkert/is-plain-object>
4
4
  *
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@steedos-widgets/liveblocks",
3
3
  "private": false,
4
- "version": "6.10.15",
4
+ "version": "6.10.16",
5
5
  "main": "dist/liveblocks.cjs.js",
6
6
  "module": "dist/liveblocks.esm.js",
7
7
  "unpkg": "dist/liveblocks.umd.js",
@@ -55,10 +55,10 @@
55
55
  "@liveblocks/react": "2.15.1",
56
56
  "@liveblocks/react-ui": "2.15.1",
57
57
  "@rollup/plugin-replace": "^5.0.2",
58
- "@steedos-widgets/amis-lib": "6.10.15",
58
+ "@steedos-widgets/amis-lib": "6.10.16",
59
59
  "clsx": "2.1.1",
60
60
  "emojibase-data": "^16.0.2",
61
61
  "react-error-boundary": "^4.1.2"
62
62
  },
63
- "gitHead": "1a448c53bbc6759d5fdbf9e33034ffb66139aa5e"
63
+ "gitHead": "49bec09b54f82b9cbfd7802714c775197e8580d7"
64
64
  }