@liveblocks/core 1.11.3 → 1.12.0-lexical2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var __defProp = Object.defineProperty;
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var __defProp = Object.defineProperty;
2
2
  var __export = (target, all) => {
3
3
  for (var name in all)
4
4
  __defProp(target, name, { get: all[name], enumerable: true });
@@ -6,7 +6,7 @@ var __export = (target, all) => {
6
6
 
7
7
  // src/version.ts
8
8
  var PKG_NAME = "@liveblocks/core";
9
- var PKG_VERSION = "1.11.3";
9
+ var PKG_VERSION = "1.12.0-lexical2";
10
10
  var PKG_FORMAT = "cjs";
11
11
 
12
12
  // src/dupe-detection.ts
@@ -1389,7 +1389,6 @@ function createAuthManager(authOptions) {
1389
1389
  room: options.roomId
1390
1390
  });
1391
1391
  const parsed = parseAuthToken(response.token);
1392
- verifyTokenPermissions(parsed, options);
1393
1392
  if (seenTokens.has(parsed.raw)) {
1394
1393
  throw new StopRetrying(
1395
1394
  "The same Liveblocks auth token was issued from the backend before. Caching Liveblocks tokens is not supported."
@@ -1402,7 +1401,6 @@ function createAuthManager(authOptions) {
1402
1401
  if (response && typeof response === "object") {
1403
1402
  if (typeof response.token === "string") {
1404
1403
  const parsed = parseAuthToken(response.token);
1405
- verifyTokenPermissions(parsed, options);
1406
1404
  return parsed;
1407
1405
  } else if (typeof response.error === "string") {
1408
1406
  const reason = `Authentication failed: ${"reason" in response && typeof response.reason === "string" ? response.reason : "Forbidden"}`;
@@ -1421,23 +1419,6 @@ function createAuthManager(authOptions) {
1421
1419
  "Unexpected authentication type. Must be private or custom."
1422
1420
  );
1423
1421
  }
1424
- function verifyTokenPermissions(parsedToken, options) {
1425
- if (!options.roomId && parsedToken.parsed.k === "acc" /* ACCESS_TOKEN */) {
1426
- if (Object.entries(parsedToken.parsed.perms).length === 0) {
1427
- return;
1428
- }
1429
- for (const [resource, scopes] of Object.entries(
1430
- parsedToken.parsed.perms
1431
- )) {
1432
- if (resource.includes("*") && hasCorrespondingScopes(options.requestedScope, scopes)) {
1433
- return;
1434
- }
1435
- }
1436
- throw new StopRetrying(
1437
- "The issued access token doesn't grant enough permissions. Please follow the instructions at https://liveblocks.io/docs/errors/liveblocks-client/access-tokens-not-enough-permissions"
1438
- );
1439
- }
1440
- }
1441
1422
  async function getAuthValue(requestOptions) {
1442
1423
  if (authentication.type === "public") {
1443
1424
  return { type: "public", publicApiKey: authentication.publicApiKey };
@@ -1561,430 +1542,564 @@ async function fetchAuthEndpoint(fetch2, endpoint, body) {
1561
1542
  return { token };
1562
1543
  }
1563
1544
 
1564
- // src/constants.ts
1565
- var DEFAULT_BASE_URL = "https://api.liveblocks.io";
1545
+ // ../../node_modules/nanoid/index.js
1546
+ var _crypto = require('crypto'); var _crypto2 = _interopRequireDefault(_crypto);
1566
1547
 
1567
- // src/internal.ts
1568
- var kInternal = Symbol();
1548
+ // ../../node_modules/nanoid/url-alphabet/index.js
1549
+ var urlAlphabet = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";
1569
1550
 
1570
- // src/devtools/bridge.ts
1571
- var _bridgeActive = false;
1572
- function activateBridge(allowed) {
1573
- _bridgeActive = allowed;
1574
- }
1575
- function sendToPanel(message, options) {
1576
- if (process.env.NODE_ENV === "production" || typeof window === "undefined") {
1577
- return;
1578
- }
1579
- const fullMsg = {
1580
- ...message,
1581
- source: "liveblocks-devtools-client"
1582
- };
1583
- if (!(_optionalChain([options, 'optionalAccess', _38 => _38.force]) || _bridgeActive)) {
1584
- return;
1551
+ // ../../node_modules/nanoid/index.js
1552
+ var POOL_SIZE_MULTIPLIER = 128;
1553
+ var pool;
1554
+ var poolOffset;
1555
+ var fillPool = (bytes) => {
1556
+ if (!pool || pool.length < bytes) {
1557
+ pool = Buffer.allocUnsafe(bytes * POOL_SIZE_MULTIPLIER);
1558
+ _crypto2.default.randomFillSync(pool);
1559
+ poolOffset = 0;
1560
+ } else if (poolOffset + bytes > pool.length) {
1561
+ _crypto2.default.randomFillSync(pool);
1562
+ poolOffset = 0;
1563
+ }
1564
+ poolOffset += bytes;
1565
+ };
1566
+ var nanoid = (size = 21) => {
1567
+ fillPool(size -= 0);
1568
+ let id = "";
1569
+ for (let i = poolOffset - size; i < poolOffset; i++) {
1570
+ id += urlAlphabet[pool[i] & 63];
1585
1571
  }
1586
- window.postMessage(fullMsg, "*");
1587
- }
1588
- var eventSource = makeEventSource();
1589
- if (process.env.NODE_ENV !== "production" && typeof window !== "undefined") {
1590
- window.addEventListener("message", (event) => {
1591
- if (event.source === window && _optionalChain([event, 'access', _39 => _39.data, 'optionalAccess', _40 => _40.source]) === "liveblocks-devtools-panel") {
1592
- eventSource.notify(event.data);
1593
- } else {
1594
- }
1595
- });
1596
- }
1597
- var onMessageFromPanel = eventSource.observable;
1572
+ return id;
1573
+ };
1598
1574
 
1599
- // src/devtools/index.ts
1600
- var VERSION = PKG_VERSION || "dev";
1601
- var _devtoolsSetupHasRun = false;
1602
- function setupDevTools(getAllRooms) {
1603
- if (process.env.NODE_ENV === "production" || typeof window === "undefined") {
1604
- return;
1605
- }
1606
- if (_devtoolsSetupHasRun) {
1607
- return;
1608
- }
1609
- _devtoolsSetupHasRun = true;
1610
- onMessageFromPanel.subscribe((msg) => {
1611
- switch (msg.msg) {
1612
- case "connect": {
1613
- activateBridge(true);
1614
- for (const roomId of getAllRooms()) {
1615
- sendToPanel({
1616
- msg: "room::available",
1617
- roomId,
1618
- clientVersion: VERSION
1619
- });
1620
- }
1621
- break;
1622
- }
1623
- }
1624
- });
1625
- sendToPanel({ msg: "wake-up-devtools" }, { force: true });
1626
- }
1627
- var unsubsByRoomId = /* @__PURE__ */ new Map();
1628
- function stopSyncStream(roomId) {
1629
- const unsubs = _nullishCoalesce(unsubsByRoomId.get(roomId), () => ( []));
1630
- unsubsByRoomId.delete(roomId);
1631
- for (const unsub of unsubs) {
1632
- unsub();
1633
- }
1634
- }
1635
- function startSyncStream(room) {
1636
- stopSyncStream(room.id);
1637
- fullSync(room);
1638
- unsubsByRoomId.set(room.id, [
1639
- // When the connection status changes
1640
- room.events.status.subscribe(() => partialSyncConnection(room)),
1641
- // When storage initializes, send the update
1642
- room.events.storageDidLoad.subscribeOnce(() => partialSyncStorage(room)),
1643
- // Any time storage updates, send the new storage root
1644
- room.events.storage.subscribe(() => partialSyncStorage(room)),
1645
- // Any time "me" or "others" updates, send the new values accordingly
1646
- room.events.self.subscribe(() => partialSyncMe(room)),
1647
- room.events.others.subscribe(() => partialSyncOthers(room)),
1648
- // Any time ydoc is updated, forward the update
1649
- room.events.ydoc.subscribe((update) => syncYdocUpdate(room, update)),
1650
- // Any time a custom room event is received, forward it
1651
- room.events.customEvent.subscribe(
1652
- (eventData) => forwardEvent(room, eventData)
1653
- )
1654
- ]);
1575
+ // src/comments/lib/createIds.ts
1576
+ var THREAD_ID_PREFIX = "th";
1577
+ var COMMENT_ID_PREFIX = "cm";
1578
+ var INBOX_NOTIFICATION_ID_PREFIX = "in";
1579
+ function createOptimisticId(prefix) {
1580
+ return `${prefix}_${nanoid()}`;
1655
1581
  }
1656
- function syncYdocUpdate(room, update) {
1657
- sendToPanel({
1658
- msg: "room::sync::ydoc",
1659
- roomId: room.id,
1660
- update
1661
- });
1662
- }
1663
- var loadedAt = Date.now();
1664
- var eventCounter = 0;
1665
- function nextEventId() {
1666
- return `event-${loadedAt}-${eventCounter++}`;
1582
+ function createThreadId() {
1583
+ return createOptimisticId(THREAD_ID_PREFIX);
1667
1584
  }
1668
- function forwardEvent(room, eventData) {
1669
- sendToPanel({
1670
- msg: "room::events::custom-event",
1671
- roomId: room.id,
1672
- event: {
1673
- type: "CustomEvent",
1674
- id: nextEventId(),
1675
- key: "Event",
1676
- connectionId: eventData.connectionId,
1677
- payload: eventData.event
1678
- }
1679
- });
1585
+ function createCommentId() {
1586
+ return createOptimisticId(COMMENT_ID_PREFIX);
1680
1587
  }
1681
- function partialSyncConnection(room) {
1682
- sendToPanel({
1683
- msg: "room::sync::partial",
1684
- roomId: room.id,
1685
- status: room.getStatus()
1686
- });
1588
+ function createInboxNotificationId() {
1589
+ return createOptimisticId(INBOX_NOTIFICATION_ID_PREFIX);
1687
1590
  }
1688
- function partialSyncStorage(room) {
1689
- const root = room.getStorageSnapshot();
1690
- if (root) {
1691
- sendToPanel({
1692
- msg: "room::sync::partial",
1693
- roomId: room.id,
1694
- storage: root.toTreeNode("root").payload
1695
- });
1591
+
1592
+ // src/lib/create-store.ts
1593
+ function createStore(initialState) {
1594
+ let state = initialState;
1595
+ const subscribers = /* @__PURE__ */ new Set();
1596
+ function get() {
1597
+ return state;
1696
1598
  }
1697
- }
1698
- function partialSyncMe(room) {
1699
- const me = room[kInternal].getSelf_forDevTools();
1700
- if (me) {
1701
- sendToPanel({
1702
- msg: "room::sync::partial",
1703
- roomId: room.id,
1704
- me
1705
- });
1599
+ function set(callback) {
1600
+ const newState = callback(state);
1601
+ if (state === newState) {
1602
+ return;
1603
+ }
1604
+ state = newState;
1605
+ for (const subscriber of subscribers) {
1606
+ subscriber(state);
1607
+ }
1706
1608
  }
1707
- }
1708
- function partialSyncOthers(room) {
1709
- const others = room[kInternal].getOthers_forDevTools();
1710
- if (others) {
1711
- sendToPanel({
1712
- msg: "room::sync::partial",
1713
- roomId: room.id,
1714
- others
1715
- });
1609
+ function subscribe(callback) {
1610
+ subscribers.add(callback);
1611
+ callback(state);
1612
+ return () => {
1613
+ subscribers.delete(callback);
1614
+ };
1716
1615
  }
1616
+ return {
1617
+ get,
1618
+ set,
1619
+ subscribe
1620
+ };
1717
1621
  }
1718
- function fullSync(room) {
1719
- const root = room.getStorageSnapshot();
1720
- const me = room[kInternal].getSelf_forDevTools();
1721
- const others = room[kInternal].getOthers_forDevTools();
1722
- room.fetchYDoc("");
1723
- sendToPanel({
1724
- msg: "room::sync::full",
1725
- roomId: room.id,
1726
- status: room.getStatus(),
1727
- storage: _nullishCoalesce(_optionalChain([root, 'optionalAccess', _41 => _41.toTreeNode, 'call', _42 => _42("root"), 'access', _43 => _43.payload]), () => ( null)),
1728
- me,
1729
- others
1622
+
1623
+ // src/store.ts
1624
+ function createClientStore() {
1625
+ const store = createStore({
1626
+ threads: {},
1627
+ queries: {},
1628
+ optimisticUpdates: [],
1629
+ inboxNotifications: {},
1630
+ notificationSettings: {}
1730
1631
  });
1731
- }
1732
- var roomChannelListeners = /* @__PURE__ */ new Map();
1733
- function stopRoomChannelListener(roomId) {
1734
- const listener = roomChannelListeners.get(roomId);
1735
- roomChannelListeners.delete(roomId);
1736
- if (listener) {
1737
- listener();
1738
- }
1739
- }
1740
- function linkDevTools(roomId, room) {
1741
- if (process.env.NODE_ENV === "production" || typeof window === "undefined") {
1742
- return;
1743
- }
1744
- sendToPanel({ msg: "room::available", roomId, clientVersion: VERSION });
1745
- stopRoomChannelListener(roomId);
1746
- roomChannelListeners.set(
1747
- roomId,
1748
- // Returns the unsubscribe callback, that we store in the
1749
- // roomChannelListeners registry
1750
- onMessageFromPanel.subscribe((msg) => {
1751
- switch (msg.msg) {
1752
- case "room::subscribe": {
1753
- if (msg.roomId === roomId) {
1754
- startSyncStream(room);
1755
- }
1756
- break;
1757
- }
1758
- case "room::unsubscribe": {
1759
- if (msg.roomId === roomId) {
1760
- stopSyncStream(roomId);
1632
+ const optimisticUpdatesEventSource = makeEventSource();
1633
+ return {
1634
+ ...store,
1635
+ deleteThread(threadId) {
1636
+ store.set((state) => {
1637
+ return {
1638
+ ...state,
1639
+ threads: deleteKeyImmutable(state.threads, threadId),
1640
+ inboxNotifications: Object.fromEntries(
1641
+ Object.entries(state.inboxNotifications).filter(
1642
+ ([_id, notification]) => notification.kind === "thread" && notification.threadId === threadId
1643
+ )
1644
+ )
1645
+ };
1646
+ });
1647
+ },
1648
+ updateThreadAndNotification(thread, inboxNotification) {
1649
+ store.set((state) => {
1650
+ const existingThread = state.threads[thread.id];
1651
+ return {
1652
+ ...state,
1653
+ threads: existingThread === void 0 || compareThreads(thread, existingThread) === 1 ? { ...state.threads, [thread.id]: thread } : state.threads,
1654
+ inboxNotifications: inboxNotification === void 0 ? state.inboxNotifications : {
1655
+ ...state.inboxNotifications,
1656
+ [inboxNotification.id]: inboxNotification
1761
1657
  }
1762
- break;
1763
- }
1764
- }
1765
- })
1766
- );
1658
+ };
1659
+ });
1660
+ },
1661
+ updateThreadsAndNotifications(threads, inboxNotifications, deletedThreads, deletedInboxNotifications, queryKey) {
1662
+ store.set((state) => ({
1663
+ ...state,
1664
+ threads: applyThreadUpdates(state.threads, {
1665
+ newThreads: threads,
1666
+ deletedThreads
1667
+ }),
1668
+ inboxNotifications: applyNotificationsUpdates(
1669
+ state.inboxNotifications,
1670
+ {
1671
+ newInboxNotifications: inboxNotifications,
1672
+ deletedNotifications: deletedInboxNotifications
1673
+ }
1674
+ ),
1675
+ queries: queryKey !== void 0 ? {
1676
+ ...state.queries,
1677
+ [queryKey]: {
1678
+ isLoading: false
1679
+ }
1680
+ } : state.queries
1681
+ }));
1682
+ },
1683
+ updateRoomInboxNotificationSettings(roomId, settings, queryKey) {
1684
+ store.set((state) => ({
1685
+ ...state,
1686
+ notificationSettings: {
1687
+ ...state.notificationSettings,
1688
+ [roomId]: settings
1689
+ },
1690
+ queries: {
1691
+ ...state.queries,
1692
+ [queryKey]: {
1693
+ isLoading: false
1694
+ }
1695
+ }
1696
+ }));
1697
+ },
1698
+ pushOptimisticUpdate(optimisticUpdate) {
1699
+ optimisticUpdatesEventSource.notify(optimisticUpdate);
1700
+ store.set((state) => ({
1701
+ ...state,
1702
+ optimisticUpdates: [...state.optimisticUpdates, optimisticUpdate]
1703
+ }));
1704
+ },
1705
+ setQueryState(queryKey, queryState) {
1706
+ store.set((state) => ({
1707
+ ...state,
1708
+ queries: {
1709
+ ...state.queries,
1710
+ [queryKey]: queryState
1711
+ }
1712
+ }));
1713
+ },
1714
+ optimisticUpdatesEventSource
1715
+ };
1767
1716
  }
1768
- function unlinkDevTools(roomId) {
1769
- if (process.env.NODE_ENV === "production" || typeof window === "undefined") {
1770
- return;
1717
+ function deleteKeyImmutable(record, key) {
1718
+ if (Object.prototype.hasOwnProperty.call(record, key)) {
1719
+ const { [key]: _toDelete, ...rest } = record;
1720
+ return rest;
1771
1721
  }
1772
- stopSyncStream(roomId);
1773
- stopRoomChannelListener(roomId);
1774
- sendToPanel({
1775
- msg: "room::unavailable",
1776
- roomId
1777
- });
1722
+ return record;
1778
1723
  }
1779
-
1780
- // src/lib/stringify.ts
1781
- function stringify(object, ...args) {
1782
- if (typeof object !== "object" || object === null || Array.isArray(object)) {
1783
- return JSON.stringify(object, ...args);
1724
+ function compareThreads(thread1, thread2) {
1725
+ if (thread1.updatedAt && thread2.updatedAt) {
1726
+ return thread1.updatedAt > thread2.updatedAt ? 1 : thread1.updatedAt < thread2.updatedAt ? -1 : 0;
1727
+ } else if (thread1.updatedAt || thread2.updatedAt) {
1728
+ return thread1.updatedAt ? 1 : -1;
1784
1729
  }
1785
- const sortedObject = Object.keys(object).sort().reduce(
1786
- (sortedObject2, key) => {
1787
- sortedObject2[key] = object[key];
1788
- return sortedObject2;
1730
+ if (thread1.createdAt > thread2.createdAt) {
1731
+ return 1;
1732
+ } else if (thread1.createdAt < thread2.createdAt) {
1733
+ return -1;
1734
+ }
1735
+ return 0;
1736
+ }
1737
+ function applyOptimisticUpdates(state) {
1738
+ const result = {
1739
+ threads: {
1740
+ ...state.threads
1789
1741
  },
1790
- {}
1742
+ inboxNotifications: {
1743
+ ...state.inboxNotifications
1744
+ },
1745
+ notificationSettings: {
1746
+ ...state.notificationSettings
1747
+ }
1748
+ };
1749
+ for (const optimisticUpdate of state.optimisticUpdates) {
1750
+ switch (optimisticUpdate.type) {
1751
+ case "create-thread": {
1752
+ result.threads[optimisticUpdate.thread.id] = optimisticUpdate.thread;
1753
+ break;
1754
+ }
1755
+ case "edit-thread-metadata": {
1756
+ const thread = result.threads[optimisticUpdate.threadId];
1757
+ if (thread === void 0) {
1758
+ break;
1759
+ }
1760
+ if (thread.deletedAt !== void 0) {
1761
+ break;
1762
+ }
1763
+ if (thread.updatedAt !== void 0 && thread.updatedAt > optimisticUpdate.updatedAt) {
1764
+ break;
1765
+ }
1766
+ result.threads[thread.id] = {
1767
+ ...thread,
1768
+ updatedAt: optimisticUpdate.updatedAt,
1769
+ metadata: {
1770
+ ...thread.metadata,
1771
+ ...optimisticUpdate.metadata
1772
+ }
1773
+ };
1774
+ break;
1775
+ }
1776
+ case "create-comment": {
1777
+ const thread = result.threads[optimisticUpdate.comment.threadId];
1778
+ if (thread === void 0) {
1779
+ break;
1780
+ }
1781
+ result.threads[thread.id] = upsertComment(
1782
+ thread,
1783
+ optimisticUpdate.comment
1784
+ );
1785
+ const inboxNotification = Object.values(result.inboxNotifications).find(
1786
+ (notification) => notification.kind === "thread" && notification.threadId === thread.id
1787
+ );
1788
+ if (inboxNotification === void 0) {
1789
+ break;
1790
+ }
1791
+ result.inboxNotifications[inboxNotification.id] = {
1792
+ ...inboxNotification,
1793
+ notifiedAt: optimisticUpdate.comment.createdAt,
1794
+ readAt: optimisticUpdate.comment.createdAt
1795
+ };
1796
+ break;
1797
+ }
1798
+ case "edit-comment": {
1799
+ const thread = result.threads[optimisticUpdate.comment.threadId];
1800
+ if (thread === void 0) {
1801
+ break;
1802
+ }
1803
+ result.threads[thread.id] = upsertComment(
1804
+ thread,
1805
+ optimisticUpdate.comment
1806
+ );
1807
+ break;
1808
+ }
1809
+ case "delete-comment": {
1810
+ const thread = result.threads[optimisticUpdate.threadId];
1811
+ if (thread === void 0) {
1812
+ break;
1813
+ }
1814
+ result.threads[thread.id] = deleteComment(
1815
+ thread,
1816
+ optimisticUpdate.commentId,
1817
+ optimisticUpdate.deletedAt
1818
+ );
1819
+ break;
1820
+ }
1821
+ case "add-reaction": {
1822
+ const thread = result.threads[optimisticUpdate.threadId];
1823
+ if (thread === void 0) {
1824
+ break;
1825
+ }
1826
+ result.threads[thread.id] = addReaction(
1827
+ thread,
1828
+ optimisticUpdate.commentId,
1829
+ optimisticUpdate.reaction
1830
+ );
1831
+ break;
1832
+ }
1833
+ case "remove-reaction": {
1834
+ const thread = result.threads[optimisticUpdate.threadId];
1835
+ if (thread === void 0) {
1836
+ break;
1837
+ }
1838
+ result.threads[thread.id] = removeReaction(
1839
+ thread,
1840
+ optimisticUpdate.commentId,
1841
+ optimisticUpdate.emoji,
1842
+ optimisticUpdate.userId,
1843
+ optimisticUpdate.removedAt
1844
+ );
1845
+ break;
1846
+ }
1847
+ case "mark-inbox-notification-as-read": {
1848
+ result.inboxNotifications[optimisticUpdate.inboxNotificationId] = {
1849
+ ...state.inboxNotifications[optimisticUpdate.inboxNotificationId],
1850
+ readAt: optimisticUpdate.readAt
1851
+ };
1852
+ break;
1853
+ }
1854
+ case "mark-inbox-notifications-as-read": {
1855
+ for (const id in result.inboxNotifications) {
1856
+ result.inboxNotifications[id] = {
1857
+ ...result.inboxNotifications[id],
1858
+ readAt: optimisticUpdate.readAt
1859
+ };
1860
+ }
1861
+ break;
1862
+ }
1863
+ case "update-notification-settings": {
1864
+ result.notificationSettings[optimisticUpdate.roomId] = {
1865
+ ...result.notificationSettings[optimisticUpdate.roomId],
1866
+ ...optimisticUpdate.settings
1867
+ };
1868
+ }
1869
+ }
1870
+ }
1871
+ return result;
1872
+ }
1873
+ function applyThreadUpdates(existingThreads, updates) {
1874
+ const updatedThreads = { ...existingThreads };
1875
+ updates.newThreads.forEach((thread) => {
1876
+ const existingThread = updatedThreads[thread.id];
1877
+ if (existingThread) {
1878
+ const result = compareThreads(existingThread, thread);
1879
+ if (result === 1)
1880
+ return;
1881
+ }
1882
+ updatedThreads[thread.id] = thread;
1883
+ });
1884
+ updates.deletedThreads.forEach(({ id, deletedAt }) => {
1885
+ const existingThread = updatedThreads[id];
1886
+ if (existingThread === void 0)
1887
+ return;
1888
+ existingThread.deletedAt = deletedAt;
1889
+ existingThread.updatedAt = deletedAt;
1890
+ existingThread.comments = [];
1891
+ });
1892
+ return updatedThreads;
1893
+ }
1894
+ function applyNotificationsUpdates(existingInboxNotifications, updates) {
1895
+ const updatedInboxNotifications = { ...existingInboxNotifications };
1896
+ updates.newInboxNotifications.forEach((notification) => {
1897
+ const existingNotification = updatedInboxNotifications[notification.id];
1898
+ if (existingNotification) {
1899
+ const result = compareInboxNotifications(
1900
+ existingNotification,
1901
+ notification
1902
+ );
1903
+ if (result === 1)
1904
+ return;
1905
+ }
1906
+ updatedInboxNotifications[notification.id] = notification;
1907
+ });
1908
+ updates.deletedNotifications.forEach(
1909
+ ({ id }) => delete updatedInboxNotifications[id]
1791
1910
  );
1792
- return JSON.stringify(sortedObject, ...args);
1911
+ return updatedInboxNotifications;
1793
1912
  }
1794
-
1795
- // src/lib/batch.ts
1796
- var DEFAULT_SIZE = 50;
1797
- var DEFAULT_DELAY = 100;
1798
- var noop = () => {
1799
- };
1800
- var BatchCall = class {
1801
- constructor(args) {
1802
- this.resolve = noop;
1803
- this.reject = noop;
1804
- this.promise = new Promise(noop);
1805
- this.args = args;
1913
+ function compareInboxNotifications(inboxNotificationA, inboxNotificationB) {
1914
+ if (inboxNotificationA.notifiedAt > inboxNotificationB.notifiedAt) {
1915
+ return 1;
1916
+ } else if (inboxNotificationA.notifiedAt < inboxNotificationB.notifiedAt) {
1917
+ return -1;
1806
1918
  }
1807
- };
1808
- var Batch = class {
1809
- constructor(callback, options) {
1810
- this.queue = [];
1811
- this.error = false;
1812
- this.callback = callback;
1813
- this.size = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _44 => _44.size]), () => ( DEFAULT_SIZE));
1814
- this.delay = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _45 => _45.delay]), () => ( DEFAULT_DELAY));
1919
+ if (inboxNotificationA.readAt && inboxNotificationB.readAt) {
1920
+ return inboxNotificationA.readAt > inboxNotificationB.readAt ? 1 : inboxNotificationA.readAt < inboxNotificationB.readAt ? -1 : 0;
1921
+ } else if (inboxNotificationA.readAt || inboxNotificationB.readAt) {
1922
+ return inboxNotificationA.readAt ? 1 : -1;
1815
1923
  }
1816
- clearDelayTimeout() {
1817
- if (this.delayTimeoutId !== void 0) {
1818
- clearTimeout(this.delayTimeoutId);
1819
- this.delayTimeoutId = void 0;
1820
- }
1924
+ return 0;
1925
+ }
1926
+ function upsertComment(thread, comment) {
1927
+ if (thread.deletedAt !== void 0) {
1928
+ return thread;
1821
1929
  }
1822
- schedule() {
1823
- if (this.queue.length === this.size) {
1824
- void this.flush();
1825
- } else if (this.queue.length === 1) {
1826
- this.clearDelayTimeout();
1827
- this.delayTimeoutId = setTimeout(() => void this.flush(), this.delay);
1828
- }
1930
+ if (comment.threadId !== thread.id) {
1931
+ warn(
1932
+ `Comment ${comment.id} does not belong to thread ${thread.id}`
1933
+ );
1934
+ return thread;
1829
1935
  }
1830
- async flush() {
1831
- if (this.queue.length === 0) {
1832
- return;
1833
- }
1834
- const calls = this.queue.splice(0);
1835
- const args = calls.map((call) => call.args);
1836
- try {
1837
- const results = await this.callback(args);
1838
- this.error = false;
1839
- calls.forEach((call, index) => {
1840
- const result = _optionalChain([results, 'optionalAccess', _46 => _46[index]]);
1841
- if (!Array.isArray(results)) {
1842
- call.reject(new Error("Callback must return an array."));
1843
- } else if (calls.length !== results.length) {
1844
- call.reject(
1845
- new Error(
1846
- `Callback must return an array of the same length as the number of provided items. Expected ${calls.length}, but got ${results.length}.`
1847
- )
1848
- );
1849
- } else if (result instanceof Error) {
1850
- call.reject(result);
1851
- } else {
1852
- call.resolve(result);
1853
- }
1854
- });
1855
- } catch (error3) {
1856
- this.error = true;
1857
- calls.forEach((call) => {
1858
- call.reject(error3);
1859
- });
1860
- }
1936
+ const existingComment = thread.comments.find(
1937
+ (existingComment2) => existingComment2.id === comment.id
1938
+ );
1939
+ if (existingComment === void 0) {
1940
+ const updatedAt = new Date(
1941
+ Math.max(_optionalChain([thread, 'access', _38 => _38.updatedAt, 'optionalAccess', _39 => _39.getTime, 'call', _40 => _40()]) || 0, comment.createdAt.getTime())
1942
+ );
1943
+ const updatedThread = {
1944
+ ...thread,
1945
+ updatedAt,
1946
+ comments: [...thread.comments, comment]
1947
+ };
1948
+ return updatedThread;
1861
1949
  }
1862
- get(...args) {
1863
- const existingCall = this.queue.find(
1864
- (call2) => stringify(call2.args) === stringify(args)
1950
+ if (existingComment.deletedAt !== void 0) {
1951
+ return thread;
1952
+ }
1953
+ if (existingComment.editedAt === void 0 || comment.editedAt === void 0 || existingComment.editedAt <= comment.editedAt) {
1954
+ const updatedComments = thread.comments.map(
1955
+ (existingComment2) => existingComment2.id === comment.id ? comment : existingComment2
1865
1956
  );
1866
- if (existingCall) {
1867
- return existingCall.promise;
1868
- }
1869
- const call = new BatchCall(args);
1870
- call.promise = new Promise((resolve, reject) => {
1871
- call.resolve = resolve;
1872
- call.reject = reject;
1873
- });
1874
- this.queue.push(call);
1875
- this.schedule();
1876
- return call.promise;
1957
+ const updatedThread = {
1958
+ ...thread,
1959
+ updatedAt: new Date(
1960
+ Math.max(
1961
+ _optionalChain([thread, 'access', _41 => _41.updatedAt, 'optionalAccess', _42 => _42.getTime, 'call', _43 => _43()]) || 0,
1962
+ _optionalChain([comment, 'access', _44 => _44.editedAt, 'optionalAccess', _45 => _45.getTime, 'call', _46 => _46()]) || comment.createdAt.getTime()
1963
+ )
1964
+ ),
1965
+ comments: updatedComments
1966
+ };
1967
+ return updatedThread;
1877
1968
  }
1878
- clear() {
1879
- this.queue = [];
1880
- this.error = false;
1881
- this.clearDelayTimeout();
1969
+ return thread;
1970
+ }
1971
+ function deleteComment(thread, commentId, deletedAt) {
1972
+ if (thread.deletedAt !== void 0) {
1973
+ return thread;
1882
1974
  }
1883
- };
1884
- function createBatchStore(callback, options) {
1885
- const batch = new Batch(callback, options);
1886
- const cache = /* @__PURE__ */ new Map();
1887
- const eventSource2 = makeEventSource();
1888
- function getCacheKey(args) {
1889
- return stringify(args);
1975
+ const existingComment = thread.comments.find(
1976
+ (comment) => comment.id === commentId
1977
+ );
1978
+ if (existingComment === void 0) {
1979
+ return thread;
1890
1980
  }
1891
- function setStateAndNotify(cacheKey, state) {
1892
- if (state) {
1893
- cache.set(cacheKey, state);
1894
- } else {
1895
- cache.delete(cacheKey);
1896
- }
1897
- eventSource2.notify(state);
1981
+ if (existingComment.deletedAt !== void 0) {
1982
+ return thread;
1898
1983
  }
1899
- async function get(...args) {
1900
- const cacheKey = getCacheKey(args);
1901
- if (cache.has(cacheKey)) {
1902
- return;
1903
- }
1904
- try {
1905
- setStateAndNotify(cacheKey, { isLoading: true });
1906
- const result = await batch.get(...args);
1907
- setStateAndNotify(cacheKey, { isLoading: false, data: result });
1908
- } catch (error3) {
1909
- setStateAndNotify(cacheKey, {
1910
- isLoading: false,
1911
- error: error3
1912
- });
1913
- }
1984
+ const updatedComments = thread.comments.map(
1985
+ (comment) => comment.id === commentId ? {
1986
+ ...comment,
1987
+ deletedAt,
1988
+ body: void 0
1989
+ } : comment
1990
+ );
1991
+ if (!updatedComments.some((comment) => comment.deletedAt === void 0)) {
1992
+ return {
1993
+ ...thread,
1994
+ deletedAt,
1995
+ updatedAt: deletedAt,
1996
+ comments: []
1997
+ };
1998
+ }
1999
+ return {
2000
+ ...thread,
2001
+ updatedAt: deletedAt,
2002
+ comments: updatedComments
2003
+ };
2004
+ }
2005
+ function addReaction(thread, commentId, reaction) {
2006
+ if (thread.deletedAt !== void 0) {
2007
+ return thread;
2008
+ }
2009
+ const existingComment = thread.comments.find(
2010
+ (comment) => comment.id === commentId
2011
+ );
2012
+ if (existingComment === void 0) {
2013
+ return thread;
1914
2014
  }
1915
- function getState(...args) {
1916
- const cacheKey = getCacheKey(args);
1917
- return cache.get(cacheKey);
2015
+ if (existingComment.deletedAt !== void 0) {
2016
+ return thread;
1918
2017
  }
2018
+ const updatedComments = thread.comments.map(
2019
+ (comment) => comment.id === commentId ? {
2020
+ ...comment,
2021
+ reactions: upsertReaction(comment.reactions, reaction)
2022
+ } : comment
2023
+ );
1919
2024
  return {
1920
- ...eventSource2,
1921
- get,
1922
- getState
2025
+ ...thread,
2026
+ updatedAt: new Date(
2027
+ Math.max(reaction.createdAt.getTime(), _optionalChain([thread, 'access', _47 => _47.updatedAt, 'optionalAccess', _48 => _48.getTime, 'call', _49 => _49()]) || 0)
2028
+ ),
2029
+ comments: updatedComments
1923
2030
  };
1924
2031
  }
1925
-
1926
- // src/lib/create-store.ts
1927
- function createStore(initialState) {
1928
- let state = initialState;
1929
- const subscribers = /* @__PURE__ */ new Set();
1930
- function get() {
1931
- return state;
2032
+ function removeReaction(thread, commentId, emoji, userId, removedAt) {
2033
+ if (thread.deletedAt !== void 0) {
2034
+ return thread;
1932
2035
  }
1933
- function set(callback) {
1934
- const newState = callback(state);
1935
- if (state === newState) {
1936
- return;
1937
- }
1938
- state = newState;
1939
- for (const subscriber of subscribers) {
1940
- subscriber(state);
1941
- }
2036
+ const existingComment = thread.comments.find(
2037
+ (comment) => comment.id === commentId
2038
+ );
2039
+ if (existingComment === void 0) {
2040
+ return thread;
1942
2041
  }
1943
- function subscribe(callback) {
1944
- subscribers.add(callback);
1945
- callback(state);
1946
- return () => {
1947
- subscribers.delete(callback);
1948
- };
2042
+ if (existingComment.deletedAt !== void 0) {
2043
+ return thread;
1949
2044
  }
2045
+ const updatedComments = thread.comments.map(
2046
+ (comment) => comment.id === commentId ? {
2047
+ ...comment,
2048
+ reactions: comment.reactions.map(
2049
+ (reaction) => reaction.emoji === emoji ? {
2050
+ ...reaction,
2051
+ users: reaction.users.filter((user) => user.id !== userId)
2052
+ } : reaction
2053
+ ).filter((reaction) => reaction.users.length > 0)
2054
+ // Remove reactions with no users left
2055
+ } : comment
2056
+ );
1950
2057
  return {
1951
- get,
1952
- set,
1953
- subscribe
2058
+ ...thread,
2059
+ updatedAt: new Date(
2060
+ Math.max(removedAt.getTime(), _optionalChain([thread, 'access', _50 => _50.updatedAt, 'optionalAccess', _51 => _51.getTime, 'call', _52 => _52()]) || 0)
2061
+ ),
2062
+ comments: updatedComments
1954
2063
  };
1955
2064
  }
1956
-
1957
- // src/lib/deprecation.ts
1958
- var _emittedDeprecationWarnings = /* @__PURE__ */ new Set();
1959
- function deprecate(message, key = message) {
1960
- if (process.env.NODE_ENV !== "production") {
1961
- if (!_emittedDeprecationWarnings.has(key)) {
1962
- _emittedDeprecationWarnings.add(key);
1963
- errorWithTitle("Deprecation warning", message);
1964
- }
2065
+ function upsertReaction(reactions, reaction) {
2066
+ const existingReaction = reactions.find(
2067
+ (existingReaction2) => existingReaction2.emoji === reaction.emoji
2068
+ );
2069
+ if (existingReaction === void 0) {
2070
+ return [
2071
+ ...reactions,
2072
+ {
2073
+ emoji: reaction.emoji,
2074
+ createdAt: reaction.createdAt,
2075
+ users: [{ id: reaction.userId }]
2076
+ }
2077
+ ];
1965
2078
  }
1966
- }
1967
- function deprecateIf(condition, message, key = message) {
1968
- if (process.env.NODE_ENV !== "production") {
1969
- if (condition) {
1970
- deprecate(message, key);
1971
- }
2079
+ if (existingReaction.users.some((user) => user.id === reaction.userId) === false) {
2080
+ return reactions.map(
2081
+ (existingReaction2) => existingReaction2.emoji === reaction.emoji ? {
2082
+ ...existingReaction2,
2083
+ users: [...existingReaction2.users, { id: reaction.userId }]
2084
+ } : existingReaction2
2085
+ );
1972
2086
  }
2087
+ return reactions;
1973
2088
  }
1974
- function throwUsageError(message) {
1975
- if (process.env.NODE_ENV !== "production") {
1976
- const usageError = new Error(message);
1977
- usageError.name = "Usage error";
1978
- errorWithTitle("Usage error", message);
1979
- throw usageError;
1980
- }
2089
+
2090
+ // src/comments/lib/select-notification-settings.ts
2091
+ function selectNotificationSettings(roomId, state) {
2092
+ const { notificationSettings } = applyOptimisticUpdates(state);
2093
+ return nn(notificationSettings[roomId]);
1981
2094
  }
1982
- function errorIf(condition, message) {
1983
- if (process.env.NODE_ENV !== "production") {
1984
- if (condition) {
1985
- throwUsageError(message);
1986
- }
1987
- }
2095
+
2096
+ // src/comments/lib/selected-inbox-notifications.ts
2097
+ function selectedInboxNotifications(state) {
2098
+ const result = applyOptimisticUpdates(state);
2099
+ return Object.values(result.inboxNotifications).sort(
2100
+ // Sort so that the most recent notifications are first
2101
+ (a, b) => b.notifiedAt.getTime() - a.notifiedAt.getTime()
2102
+ );
1988
2103
  }
1989
2104
 
1990
2105
  // src/convert-plain-data.ts
@@ -2035,6 +2150,18 @@ function convertToCommentUserReaction(data) {
2035
2150
  function convertToInboxNotificationData(data) {
2036
2151
  const notifiedAt = new Date(data.notifiedAt);
2037
2152
  const readAt = data.readAt ? new Date(data.readAt) : null;
2153
+ if ("activities" in data) {
2154
+ const activities = data.activities.map((activity) => ({
2155
+ ...activity,
2156
+ createdAt: new Date(activity.createdAt)
2157
+ }));
2158
+ return {
2159
+ ...data,
2160
+ notifiedAt,
2161
+ readAt,
2162
+ activities
2163
+ };
2164
+ }
2038
2165
  return {
2039
2166
  ...data,
2040
2167
  notifiedAt,
@@ -2048,142 +2175,11 @@ function convertToThreadDeleteInfo(data) {
2048
2175
  deletedAt
2049
2176
  };
2050
2177
  }
2051
- function convertToInboxNotificationDeleteInfo(data) {
2052
- const deletedAt = new Date(data.deletedAt);
2053
- return {
2054
- ...data,
2055
- deletedAt
2056
- };
2057
- }
2058
-
2059
- // src/lib/url.ts
2060
- function toURLSearchParams(params) {
2061
- const result = new URLSearchParams();
2062
- for (const [key, value] of Object.entries(params)) {
2063
- if (value !== void 0 && value !== null) {
2064
- result.set(key, value.toString());
2065
- }
2066
- }
2067
- return result;
2068
- }
2069
- function urljoin(baseUrl, path, params) {
2070
- const url = new URL(path, baseUrl);
2071
- if (params !== void 0) {
2072
- url.search = (params instanceof URLSearchParams ? params : toURLSearchParams(params)).toString();
2073
- }
2074
- return url.toString();
2075
- }
2076
-
2077
- // src/notifications.ts
2078
- var MARK_INBOX_NOTIFICATIONS_AS_READ_BATCH_DELAY = 50;
2079
- function createNotificationsApi({
2080
- baseUrl,
2081
- authManager,
2082
- currentUserIdStore,
2083
- fetcher
2084
- }) {
2085
- async function fetchJson(endpoint, options, params) {
2086
- const authValue = await authManager.getAuthValue({
2087
- requestedScope: "comments:read"
2088
- });
2089
- if (authValue.type === "secret" && authValue.token.parsed.k === "acc" /* ACCESS_TOKEN */) {
2090
- const userId = authValue.token.parsed.uid;
2091
- currentUserIdStore.set(() => userId);
2092
- }
2093
- const url = urljoin(baseUrl, `/v2/c${endpoint}`, params);
2094
- const response = await fetcher(url.toString(), {
2095
- ...options,
2096
- headers: {
2097
- ..._optionalChain([options, 'optionalAccess', _47 => _47.headers]),
2098
- Authorization: `Bearer ${getAuthBearerHeaderFromAuthValue(authValue)}`
2099
- }
2100
- });
2101
- if (!response.ok) {
2102
- if (response.status >= 400 && response.status < 600) {
2103
- let error3;
2104
- try {
2105
- const errorBody = await response.json();
2106
- error3 = new NotificationsApiError(
2107
- errorBody.message,
2108
- response.status,
2109
- errorBody
2110
- );
2111
- } catch (e3) {
2112
- error3 = new NotificationsApiError(
2113
- response.statusText,
2114
- response.status
2115
- );
2116
- }
2117
- throw error3;
2118
- }
2119
- }
2120
- let body;
2121
- try {
2122
- body = await response.json();
2123
- } catch (e4) {
2124
- body = {};
2125
- }
2126
- return body;
2127
- }
2128
- async function getInboxNotifications(options) {
2129
- const json = await fetchJson("/inbox-notifications", void 0, {
2130
- limit: _optionalChain([options, 'optionalAccess', _48 => _48.limit]),
2131
- since: _optionalChain([options, 'optionalAccess', _49 => _49.since, 'optionalAccess', _50 => _50.toISOString, 'call', _51 => _51()])
2132
- });
2133
- return {
2134
- threads: json.threads.map((thread) => convertToThreadData(thread)),
2135
- inboxNotifications: json.inboxNotifications.map(
2136
- (notification) => convertToInboxNotificationData(notification)
2137
- ),
2138
- deletedThreads: json.deletedThreads.map(
2139
- (info) => convertToThreadDeleteInfo(info)
2140
- ),
2141
- deletedInboxNotifications: json.deletedInboxNotifications.map(
2142
- (info) => convertToInboxNotificationDeleteInfo(info)
2143
- ),
2144
- meta: {
2145
- requestedAt: new Date(json.meta.requestedAt)
2146
- }
2147
- };
2148
- }
2149
- async function getUnreadInboxNotificationsCount() {
2150
- const { count } = await fetchJson("/inbox-notifications/count");
2151
- return count;
2152
- }
2153
- async function markAllInboxNotificationsAsRead() {
2154
- await fetchJson("/inbox-notifications/read", {
2155
- method: "POST",
2156
- headers: {
2157
- "Content-Type": "application/json"
2158
- },
2159
- body: JSON.stringify({ inboxNotificationIds: "all" })
2160
- });
2161
- }
2162
- async function markInboxNotificationsAsRead(inboxNotificationIds) {
2163
- await fetchJson("/inbox-notifications/read", {
2164
- method: "POST",
2165
- headers: {
2166
- "Content-Type": "application/json"
2167
- },
2168
- body: JSON.stringify({ inboxNotificationIds })
2169
- });
2170
- }
2171
- const batchedMarkInboxNotificationsAsRead = new Batch(
2172
- async (batchedInboxNotificationIds) => {
2173
- const inboxNotificationIds = batchedInboxNotificationIds.flat();
2174
- await markInboxNotificationsAsRead(inboxNotificationIds);
2175
- return inboxNotificationIds;
2176
- },
2177
- { delay: MARK_INBOX_NOTIFICATIONS_AS_READ_BATCH_DELAY }
2178
- );
2179
- async function markInboxNotificationAsRead(inboxNotificationId) {
2180
- await batchedMarkInboxNotificationsAsRead.get(inboxNotificationId);
2181
- }
2178
+ function convertToInboxNotificationDeleteInfo(data) {
2179
+ const deletedAt = new Date(data.deletedAt);
2182
2180
  return {
2183
- getInboxNotifications,
2184
- getUnreadInboxNotificationsCount,
2185
- markAllInboxNotificationsAsRead,
2186
- markInboxNotificationAsRead
2181
+ ...data,
2182
+ deletedAt
2187
2183
  };
2188
2184
  }
2189
2185
 
@@ -2441,13 +2437,13 @@ var AbstractCrdt = class {
2441
2437
  }
2442
2438
  }
2443
2439
  /** @internal */
2444
- _attach(id, pool) {
2440
+ _attach(id, pool2) {
2445
2441
  if (this.__id || this.__pool) {
2446
2442
  throw new Error("Cannot attach node: already attached");
2447
2443
  }
2448
- pool.addNode(id, crdtAsLiveNode(this));
2444
+ pool2.addNode(id, crdtAsLiveNode(this));
2449
2445
  this.__id = id;
2450
- this.__pool = pool;
2446
+ this.__pool = pool2;
2451
2447
  }
2452
2448
  /** @internal */
2453
2449
  _detach() {
@@ -2526,7 +2522,7 @@ function isChildCrdt(crdt) {
2526
2522
  }
2527
2523
 
2528
2524
  // src/lib/nanoid.ts
2529
- function nanoid(length = 7) {
2525
+ function nanoid2(length = 7) {
2530
2526
  const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789,./;[]~!@#$%&*()_+=-";
2531
2527
  const len = alphabet.length;
2532
2528
  return Array.from(
@@ -2545,13 +2541,13 @@ var LiveRegister = class _LiveRegister extends AbstractCrdt {
2545
2541
  return this._data;
2546
2542
  }
2547
2543
  /** @internal */
2548
- static _deserialize([id, item], _parentToChildren, pool) {
2544
+ static _deserialize([id, item], _parentToChildren, pool2) {
2549
2545
  const register = new _LiveRegister(item.data);
2550
- register._attach(id, pool);
2546
+ register._attach(id, pool2);
2551
2547
  return register;
2552
2548
  }
2553
2549
  /** @internal */
2554
- _toOps(parentId, parentKey, pool) {
2550
+ _toOps(parentId, parentKey, pool2) {
2555
2551
  if (this._id === void 0) {
2556
2552
  throw new Error(
2557
2553
  "Cannot serialize register if parentId or parentKey is undefined"
@@ -2560,7 +2556,7 @@ var LiveRegister = class _LiveRegister extends AbstractCrdt {
2560
2556
  return [
2561
2557
  {
2562
2558
  type: 8 /* CREATE_REGISTER */,
2563
- opId: _optionalChain([pool, 'optionalAccess', _52 => _52.generateOpId, 'call', _53 => _53()]),
2559
+ opId: _optionalChain([pool2, 'optionalAccess', _53 => _53.generateOpId, 'call', _54 => _54()]),
2564
2560
  id: this._id,
2565
2561
  parentId,
2566
2562
  parentKey,
@@ -2596,7 +2592,7 @@ var LiveRegister = class _LiveRegister extends AbstractCrdt {
2596
2592
  _toTreeNode(key) {
2597
2593
  return {
2598
2594
  type: "Json",
2599
- id: _nullishCoalesce(this._id, () => ( nanoid())),
2595
+ id: _nullishCoalesce(this._id, () => ( nanoid2())),
2600
2596
  key,
2601
2597
  payload: this._data
2602
2598
  };
@@ -2632,15 +2628,15 @@ var LiveList = class _LiveList extends AbstractCrdt {
2632
2628
  }
2633
2629
  }
2634
2630
  /** @internal */
2635
- static _deserialize([id], parentToChildren, pool) {
2631
+ static _deserialize([id], parentToChildren, pool2) {
2636
2632
  const list = new _LiveList();
2637
- list._attach(id, pool);
2633
+ list._attach(id, pool2);
2638
2634
  const children = parentToChildren.get(id);
2639
2635
  if (children === void 0) {
2640
2636
  return list;
2641
2637
  }
2642
2638
  for (const [id2, crdt] of children) {
2643
- const child = deserialize([id2, crdt], parentToChildren, pool);
2639
+ const child = deserialize([id2, crdt], parentToChildren, pool2);
2644
2640
  child._setParentLink(list, crdt.parentKey);
2645
2641
  list._insertAndSort(child);
2646
2642
  }
@@ -2655,14 +2651,14 @@ var LiveList = class _LiveList extends AbstractCrdt {
2655
2651
  * This is quite unintuitive and should disappear as soon as
2656
2652
  * we introduce an explicit LiveList.Set operation
2657
2653
  */
2658
- _toOps(parentId, parentKey, pool) {
2654
+ _toOps(parentId, parentKey, pool2) {
2659
2655
  if (this._id === void 0) {
2660
2656
  throw new Error("Cannot serialize item is not attached");
2661
2657
  }
2662
2658
  const ops = [];
2663
2659
  const op = {
2664
2660
  id: this._id,
2665
- opId: _optionalChain([pool, 'optionalAccess', _54 => _54.generateOpId, 'call', _55 => _55()]),
2661
+ opId: _optionalChain([pool2, 'optionalAccess', _55 => _55.generateOpId, 'call', _56 => _56()]),
2666
2662
  type: 2 /* CREATE_LIST */,
2667
2663
  parentId,
2668
2664
  parentKey
@@ -2671,7 +2667,7 @@ var LiveList = class _LiveList extends AbstractCrdt {
2671
2667
  for (const item of this._items) {
2672
2668
  const parentKey2 = item._getParentKeyOrThrow();
2673
2669
  const childOps = HACK_addIntentAndDeletedIdToOperation(
2674
- item._toOps(this._id, parentKey2, pool),
2670
+ item._toOps(this._id, parentKey2, pool2),
2675
2671
  void 0
2676
2672
  );
2677
2673
  const childOpId = childOps[0].opId;
@@ -2703,10 +2699,10 @@ var LiveList = class _LiveList extends AbstractCrdt {
2703
2699
  );
2704
2700
  }
2705
2701
  /** @internal */
2706
- _attach(id, pool) {
2707
- super._attach(id, pool);
2702
+ _attach(id, pool2) {
2703
+ super._attach(id, pool2);
2708
2704
  for (const item of this._items) {
2709
- item._attach(pool.generateId(), pool);
2705
+ item._attach(pool2.generateId(), pool2);
2710
2706
  }
2711
2707
  }
2712
2708
  /** @internal */
@@ -2939,7 +2935,7 @@ var LiveList = class _LiveList extends AbstractCrdt {
2939
2935
  _applyInsertUndoRedo(op) {
2940
2936
  const { id, parentKey: key } = op;
2941
2937
  const child = creationOpToLiveNode(op);
2942
- if (_optionalChain([this, 'access', _56 => _56._pool, 'optionalAccess', _57 => _57.getNode, 'call', _58 => _58(id)]) !== void 0) {
2938
+ if (_optionalChain([this, 'access', _57 => _57._pool, 'optionalAccess', _58 => _58.getNode, 'call', _59 => _59(id)]) !== void 0) {
2943
2939
  return { modified: false };
2944
2940
  }
2945
2941
  child._attach(id, nn(this._pool));
@@ -2947,8 +2943,8 @@ var LiveList = class _LiveList extends AbstractCrdt {
2947
2943
  const existingItemIndex = this._indexOfPosition(key);
2948
2944
  let newKey = key;
2949
2945
  if (existingItemIndex !== -1) {
2950
- const before2 = _optionalChain([this, 'access', _59 => _59._items, 'access', _60 => _60[existingItemIndex], 'optionalAccess', _61 => _61._parentPos]);
2951
- const after2 = _optionalChain([this, 'access', _62 => _62._items, 'access', _63 => _63[existingItemIndex + 1], 'optionalAccess', _64 => _64._parentPos]);
2946
+ const before2 = _optionalChain([this, 'access', _60 => _60._items, 'access', _61 => _61[existingItemIndex], 'optionalAccess', _62 => _62._parentPos]);
2947
+ const after2 = _optionalChain([this, 'access', _63 => _63._items, 'access', _64 => _64[existingItemIndex + 1], 'optionalAccess', _65 => _65._parentPos]);
2952
2948
  newKey = makePosition(before2, after2);
2953
2949
  child._setParentLink(this, newKey);
2954
2950
  }
@@ -2963,7 +2959,7 @@ var LiveList = class _LiveList extends AbstractCrdt {
2963
2959
  _applySetUndoRedo(op) {
2964
2960
  const { id, parentKey: key } = op;
2965
2961
  const child = creationOpToLiveNode(op);
2966
- if (_optionalChain([this, 'access', _65 => _65._pool, 'optionalAccess', _66 => _66.getNode, 'call', _67 => _67(id)]) !== void 0) {
2962
+ if (_optionalChain([this, 'access', _66 => _66._pool, 'optionalAccess', _67 => _67.getNode, 'call', _68 => _68(id)]) !== void 0) {
2967
2963
  return { modified: false };
2968
2964
  }
2969
2965
  this._unacknowledgedSets.set(key, nn(op.opId));
@@ -3085,7 +3081,7 @@ var LiveList = class _LiveList extends AbstractCrdt {
3085
3081
  } else {
3086
3082
  this._items[existingItemIndex]._setParentLink(
3087
3083
  this,
3088
- makePosition(newKey, _optionalChain([this, 'access', _68 => _68._items, 'access', _69 => _69[existingItemIndex + 1], 'optionalAccess', _70 => _70._parentPos]))
3084
+ makePosition(newKey, _optionalChain([this, 'access', _69 => _69._items, 'access', _70 => _70[existingItemIndex + 1], 'optionalAccess', _71 => _71._parentPos]))
3089
3085
  );
3090
3086
  const previousIndex = this._items.indexOf(child);
3091
3087
  child._setParentLink(this, newKey);
@@ -3111,7 +3107,7 @@ var LiveList = class _LiveList extends AbstractCrdt {
3111
3107
  if (existingItemIndex !== -1) {
3112
3108
  this._items[existingItemIndex]._setParentLink(
3113
3109
  this,
3114
- makePosition(newKey, _optionalChain([this, 'access', _71 => _71._items, 'access', _72 => _72[existingItemIndex + 1], 'optionalAccess', _73 => _73._parentPos]))
3110
+ makePosition(newKey, _optionalChain([this, 'access', _72 => _72._items, 'access', _73 => _73[existingItemIndex + 1], 'optionalAccess', _74 => _74._parentPos]))
3115
3111
  );
3116
3112
  }
3117
3113
  child._setParentLink(this, newKey);
@@ -3130,7 +3126,7 @@ var LiveList = class _LiveList extends AbstractCrdt {
3130
3126
  if (existingItemIndex !== -1) {
3131
3127
  this._items[existingItemIndex]._setParentLink(
3132
3128
  this,
3133
- makePosition(newKey, _optionalChain([this, 'access', _74 => _74._items, 'access', _75 => _75[existingItemIndex + 1], 'optionalAccess', _76 => _76._parentPos]))
3129
+ makePosition(newKey, _optionalChain([this, 'access', _75 => _75._items, 'access', _76 => _76[existingItemIndex + 1], 'optionalAccess', _77 => _77._parentPos]))
3134
3130
  );
3135
3131
  }
3136
3132
  child._setParentLink(this, newKey);
@@ -3158,7 +3154,7 @@ var LiveList = class _LiveList extends AbstractCrdt {
3158
3154
  if (existingItemIndex !== -1) {
3159
3155
  this._items[existingItemIndex]._setParentLink(
3160
3156
  this,
3161
- makePosition(newKey, _optionalChain([this, 'access', _77 => _77._items, 'access', _78 => _78[existingItemIndex + 1], 'optionalAccess', _79 => _79._parentPos]))
3157
+ makePosition(newKey, _optionalChain([this, 'access', _78 => _78._items, 'access', _79 => _79[existingItemIndex + 1], 'optionalAccess', _80 => _80._parentPos]))
3162
3158
  );
3163
3159
  }
3164
3160
  child._setParentLink(this, newKey);
@@ -3216,7 +3212,7 @@ var LiveList = class _LiveList extends AbstractCrdt {
3216
3212
  * @param element The element to add to the end of the LiveList.
3217
3213
  */
3218
3214
  push(element) {
3219
- _optionalChain([this, 'access', _80 => _80._pool, 'optionalAccess', _81 => _81.assertStorageIsWritable, 'call', _82 => _82()]);
3215
+ _optionalChain([this, 'access', _81 => _81._pool, 'optionalAccess', _82 => _82.assertStorageIsWritable, 'call', _83 => _83()]);
3220
3216
  return this.insert(element, this.length);
3221
3217
  }
3222
3218
  /**
@@ -3225,7 +3221,7 @@ var LiveList = class _LiveList extends AbstractCrdt {
3225
3221
  * @param index The index at which you want to insert the element.
3226
3222
  */
3227
3223
  insert(element, index) {
3228
- _optionalChain([this, 'access', _83 => _83._pool, 'optionalAccess', _84 => _84.assertStorageIsWritable, 'call', _85 => _85()]);
3224
+ _optionalChain([this, 'access', _84 => _84._pool, 'optionalAccess', _85 => _85.assertStorageIsWritable, 'call', _86 => _86()]);
3229
3225
  if (index < 0 || index > this._items.length) {
3230
3226
  throw new Error(
3231
3227
  `Cannot insert list item at index "${index}". index should be between 0 and ${this._items.length}`
@@ -3255,7 +3251,7 @@ var LiveList = class _LiveList extends AbstractCrdt {
3255
3251
  * @param targetIndex The index where the element should be after moving.
3256
3252
  */
3257
3253
  move(index, targetIndex) {
3258
- _optionalChain([this, 'access', _86 => _86._pool, 'optionalAccess', _87 => _87.assertStorageIsWritable, 'call', _88 => _88()]);
3254
+ _optionalChain([this, 'access', _87 => _87._pool, 'optionalAccess', _88 => _88.assertStorageIsWritable, 'call', _89 => _89()]);
3259
3255
  if (targetIndex < 0) {
3260
3256
  throw new Error("targetIndex cannot be less than 0");
3261
3257
  }
@@ -3313,7 +3309,7 @@ var LiveList = class _LiveList extends AbstractCrdt {
3313
3309
  * @param index The index of the element to delete
3314
3310
  */
3315
3311
  delete(index) {
3316
- _optionalChain([this, 'access', _89 => _89._pool, 'optionalAccess', _90 => _90.assertStorageIsWritable, 'call', _91 => _91()]);
3312
+ _optionalChain([this, 'access', _90 => _90._pool, 'optionalAccess', _91 => _91.assertStorageIsWritable, 'call', _92 => _92()]);
3317
3313
  if (index < 0 || index >= this._items.length) {
3318
3314
  throw new Error(
3319
3315
  `Cannot delete list item at index "${index}". index should be between 0 and ${this._items.length - 1}`
@@ -3346,7 +3342,7 @@ var LiveList = class _LiveList extends AbstractCrdt {
3346
3342
  }
3347
3343
  }
3348
3344
  clear() {
3349
- _optionalChain([this, 'access', _92 => _92._pool, 'optionalAccess', _93 => _93.assertStorageIsWritable, 'call', _94 => _94()]);
3345
+ _optionalChain([this, 'access', _93 => _93._pool, 'optionalAccess', _94 => _94.assertStorageIsWritable, 'call', _95 => _95()]);
3350
3346
  if (this._pool) {
3351
3347
  const ops = [];
3352
3348
  const reverseOps = [];
@@ -3380,7 +3376,7 @@ var LiveList = class _LiveList extends AbstractCrdt {
3380
3376
  }
3381
3377
  }
3382
3378
  set(index, item) {
3383
- _optionalChain([this, 'access', _95 => _95._pool, 'optionalAccess', _96 => _96.assertStorageIsWritable, 'call', _97 => _97()]);
3379
+ _optionalChain([this, 'access', _96 => _96._pool, 'optionalAccess', _97 => _97.assertStorageIsWritable, 'call', _98 => _98()]);
3384
3380
  if (index < 0 || index >= this._items.length) {
3385
3381
  throw new Error(
3386
3382
  `Cannot set list item at index "${index}". index should be between 0 and ${this._items.length - 1}`
@@ -3528,7 +3524,7 @@ var LiveList = class _LiveList extends AbstractCrdt {
3528
3524
  _shiftItemPosition(index, key) {
3529
3525
  const shiftedPosition = makePosition(
3530
3526
  key,
3531
- this._items.length > index + 1 ? _optionalChain([this, 'access', _98 => _98._items, 'access', _99 => _99[index + 1], 'optionalAccess', _100 => _100._parentPos]) : void 0
3527
+ this._items.length > index + 1 ? _optionalChain([this, 'access', _99 => _99._items, 'access', _100 => _100[index + 1], 'optionalAccess', _101 => _101._parentPos]) : void 0
3532
3528
  );
3533
3529
  this._items[index]._setParentLink(this, shiftedPosition);
3534
3530
  }
@@ -3536,7 +3532,7 @@ var LiveList = class _LiveList extends AbstractCrdt {
3536
3532
  _toTreeNode(key) {
3537
3533
  return {
3538
3534
  type: "LiveList",
3539
- id: _nullishCoalesce(this._id, () => ( nanoid())),
3535
+ id: _nullishCoalesce(this._id, () => ( nanoid2())),
3540
3536
  key,
3541
3537
  payload: this._items.map(
3542
3538
  (item, index) => item.toTreeNode(index.toString())
@@ -3650,36 +3646,36 @@ var LiveMap = class _LiveMap extends AbstractCrdt {
3650
3646
  /**
3651
3647
  * @internal
3652
3648
  */
3653
- _toOps(parentId, parentKey, pool) {
3649
+ _toOps(parentId, parentKey, pool2) {
3654
3650
  if (this._id === void 0) {
3655
3651
  throw new Error("Cannot serialize item is not attached");
3656
3652
  }
3657
3653
  const ops = [];
3658
3654
  const op = {
3659
3655
  id: this._id,
3660
- opId: _optionalChain([pool, 'optionalAccess', _101 => _101.generateOpId, 'call', _102 => _102()]),
3656
+ opId: _optionalChain([pool2, 'optionalAccess', _102 => _102.generateOpId, 'call', _103 => _103()]),
3661
3657
  type: 7 /* CREATE_MAP */,
3662
3658
  parentId,
3663
3659
  parentKey
3664
3660
  };
3665
3661
  ops.push(op);
3666
3662
  for (const [key, value] of this._map) {
3667
- ops.push(...value._toOps(this._id, key, pool));
3663
+ ops.push(...value._toOps(this._id, key, pool2));
3668
3664
  }
3669
3665
  return ops;
3670
3666
  }
3671
3667
  /**
3672
3668
  * @internal
3673
3669
  */
3674
- static _deserialize([id, _item], parentToChildren, pool) {
3670
+ static _deserialize([id, _item], parentToChildren, pool2) {
3675
3671
  const map = new _LiveMap();
3676
- map._attach(id, pool);
3672
+ map._attach(id, pool2);
3677
3673
  const children = parentToChildren.get(id);
3678
3674
  if (children === void 0) {
3679
3675
  return map;
3680
3676
  }
3681
3677
  for (const [id2, crdt] of children) {
3682
- const child = deserialize([id2, crdt], parentToChildren, pool);
3678
+ const child = deserialize([id2, crdt], parentToChildren, pool2);
3683
3679
  child._setParentLink(map, crdt.parentKey);
3684
3680
  map._map.set(crdt.parentKey, child);
3685
3681
  map.invalidate();
@@ -3689,11 +3685,11 @@ var LiveMap = class _LiveMap extends AbstractCrdt {
3689
3685
  /**
3690
3686
  * @internal
3691
3687
  */
3692
- _attach(id, pool) {
3693
- super._attach(id, pool);
3688
+ _attach(id, pool2) {
3689
+ super._attach(id, pool2);
3694
3690
  for (const [_key, value] of this._map) {
3695
3691
  if (isLiveNode(value)) {
3696
- value._attach(pool.generateId(), pool);
3692
+ value._attach(pool2.generateId(), pool2);
3697
3693
  }
3698
3694
  }
3699
3695
  }
@@ -3804,7 +3800,7 @@ var LiveMap = class _LiveMap extends AbstractCrdt {
3804
3800
  * @param value The value of the element to add. Should be serializable to JSON.
3805
3801
  */
3806
3802
  set(key, value) {
3807
- _optionalChain([this, 'access', _103 => _103._pool, 'optionalAccess', _104 => _104.assertStorageIsWritable, 'call', _105 => _105()]);
3803
+ _optionalChain([this, 'access', _104 => _104._pool, 'optionalAccess', _105 => _105.assertStorageIsWritable, 'call', _106 => _106()]);
3808
3804
  const oldValue = this._map.get(key);
3809
3805
  if (oldValue) {
3810
3806
  oldValue._detach();
@@ -3850,7 +3846,7 @@ var LiveMap = class _LiveMap extends AbstractCrdt {
3850
3846
  * @returns true if an element existed and has been removed, or false if the element does not exist.
3851
3847
  */
3852
3848
  delete(key) {
3853
- _optionalChain([this, 'access', _106 => _106._pool, 'optionalAccess', _107 => _107.assertStorageIsWritable, 'call', _108 => _108()]);
3849
+ _optionalChain([this, 'access', _107 => _107._pool, 'optionalAccess', _108 => _108.assertStorageIsWritable, 'call', _109 => _109()]);
3854
3850
  const item = this._map.get(key);
3855
3851
  if (item === void 0) {
3856
3852
  return false;
@@ -3953,7 +3949,7 @@ var LiveMap = class _LiveMap extends AbstractCrdt {
3953
3949
  _toTreeNode(key) {
3954
3950
  return {
3955
3951
  type: "LiveMap",
3956
- id: _nullishCoalesce(this._id, () => ( nanoid())),
3952
+ id: _nullishCoalesce(this._id, () => ( nanoid2())),
3957
3953
  key,
3958
3954
  payload: Array.from(this._map.entries()).map(
3959
3955
  ([key2, val]) => val.toTreeNode(key2)
@@ -4015,20 +4011,20 @@ var LiveObject = class _LiveObject extends AbstractCrdt {
4015
4011
  return [root, parentToChildren];
4016
4012
  }
4017
4013
  /** @internal */
4018
- static _fromItems(items, pool) {
4014
+ static _fromItems(items, pool2) {
4019
4015
  const [root, parentToChildren] = _LiveObject._buildRootAndParentToChildren(items);
4020
4016
  return _LiveObject._deserialize(
4021
4017
  root,
4022
4018
  parentToChildren,
4023
- pool
4019
+ pool2
4024
4020
  );
4025
4021
  }
4026
4022
  /** @internal */
4027
- _toOps(parentId, parentKey, pool) {
4023
+ _toOps(parentId, parentKey, pool2) {
4028
4024
  if (this._id === void 0) {
4029
4025
  throw new Error("Cannot serialize item is not attached");
4030
4026
  }
4031
- const opId = _optionalChain([pool, 'optionalAccess', _109 => _109.generateOpId, 'call', _110 => _110()]);
4027
+ const opId = _optionalChain([pool2, 'optionalAccess', _110 => _110.generateOpId, 'call', _111 => _111()]);
4032
4028
  const ops = [];
4033
4029
  const op = {
4034
4030
  type: 4 /* CREATE_OBJECT */,
@@ -4041,7 +4037,7 @@ var LiveObject = class _LiveObject extends AbstractCrdt {
4041
4037
  ops.push(op);
4042
4038
  for (const [key, value] of this._map) {
4043
4039
  if (isLiveNode(value)) {
4044
- ops.push(...value._toOps(this._id, key, pool));
4040
+ ops.push(...value._toOps(this._id, key, pool2));
4045
4041
  } else {
4046
4042
  op.data[key] = value;
4047
4043
  }
@@ -4049,19 +4045,19 @@ var LiveObject = class _LiveObject extends AbstractCrdt {
4049
4045
  return ops;
4050
4046
  }
4051
4047
  /** @internal */
4052
- static _deserialize([id, item], parentToChildren, pool) {
4048
+ static _deserialize([id, item], parentToChildren, pool2) {
4053
4049
  const liveObj = new _LiveObject(item.data);
4054
- liveObj._attach(id, pool);
4055
- return this._deserializeChildren(liveObj, parentToChildren, pool);
4050
+ liveObj._attach(id, pool2);
4051
+ return this._deserializeChildren(liveObj, parentToChildren, pool2);
4056
4052
  }
4057
4053
  /** @internal */
4058
- static _deserializeChildren(liveObj, parentToChildren, pool) {
4054
+ static _deserializeChildren(liveObj, parentToChildren, pool2) {
4059
4055
  const children = parentToChildren.get(nn(liveObj._id));
4060
4056
  if (children === void 0) {
4061
4057
  return liveObj;
4062
4058
  }
4063
4059
  for (const [id, crdt] of children) {
4064
- const child = deserializeToLson([id, crdt], parentToChildren, pool);
4060
+ const child = deserializeToLson([id, crdt], parentToChildren, pool2);
4065
4061
  if (isLiveStructure(child)) {
4066
4062
  child._setParentLink(liveObj, crdt.parentKey);
4067
4063
  }
@@ -4071,11 +4067,11 @@ var LiveObject = class _LiveObject extends AbstractCrdt {
4071
4067
  return liveObj;
4072
4068
  }
4073
4069
  /** @internal */
4074
- _attach(id, pool) {
4075
- super._attach(id, pool);
4070
+ _attach(id, pool2) {
4071
+ super._attach(id, pool2);
4076
4072
  for (const [_key, value] of this._map) {
4077
4073
  if (isLiveNode(value)) {
4078
- value._attach(pool.generateId(), pool);
4074
+ value._attach(pool2.generateId(), pool2);
4079
4075
  }
4080
4076
  }
4081
4077
  }
@@ -4306,7 +4302,7 @@ var LiveObject = class _LiveObject extends AbstractCrdt {
4306
4302
  * @param value The value of the property to add
4307
4303
  */
4308
4304
  set(key, value) {
4309
- _optionalChain([this, 'access', _111 => _111._pool, 'optionalAccess', _112 => _112.assertStorageIsWritable, 'call', _113 => _113()]);
4305
+ _optionalChain([this, 'access', _112 => _112._pool, 'optionalAccess', _113 => _113.assertStorageIsWritable, 'call', _114 => _114()]);
4310
4306
  this.update({ [key]: value });
4311
4307
  }
4312
4308
  /**
@@ -4321,7 +4317,7 @@ var LiveObject = class _LiveObject extends AbstractCrdt {
4321
4317
  * @param key The key of the property to delete
4322
4318
  */
4323
4319
  delete(key) {
4324
- _optionalChain([this, 'access', _114 => _114._pool, 'optionalAccess', _115 => _115.assertStorageIsWritable, 'call', _116 => _116()]);
4320
+ _optionalChain([this, 'access', _115 => _115._pool, 'optionalAccess', _116 => _116.assertStorageIsWritable, 'call', _117 => _117()]);
4325
4321
  const keyAsString = key;
4326
4322
  const oldValue = this._map.get(keyAsString);
4327
4323
  if (oldValue === void 0) {
@@ -4374,7 +4370,7 @@ var LiveObject = class _LiveObject extends AbstractCrdt {
4374
4370
  * @param patch The object used to overrides properties
4375
4371
  */
4376
4372
  update(patch) {
4377
- _optionalChain([this, 'access', _117 => _117._pool, 'optionalAccess', _118 => _118.assertStorageIsWritable, 'call', _119 => _119()]);
4373
+ _optionalChain([this, 'access', _118 => _118._pool, 'optionalAccess', _119 => _119.assertStorageIsWritable, 'call', _120 => _120()]);
4378
4374
  if (this._pool === void 0 || this._id === void 0) {
4379
4375
  for (const key in patch) {
4380
4376
  const newValue = patch[key];
@@ -4464,7 +4460,7 @@ var LiveObject = class _LiveObject extends AbstractCrdt {
4464
4460
  }
4465
4461
  /** @internal */
4466
4462
  _toTreeNode(key) {
4467
- const nodeId = _nullishCoalesce(this._id, () => ( nanoid()));
4463
+ const nodeId = _nullishCoalesce(this._id, () => ( nanoid2()));
4468
4464
  return {
4469
4465
  type: "LiveObject",
4470
4466
  id: nodeId,
@@ -4521,35 +4517,35 @@ function isSameNodeOrChildOf(node, parent) {
4521
4517
  }
4522
4518
  return false;
4523
4519
  }
4524
- function deserialize([id, crdt], parentToChildren, pool) {
4520
+ function deserialize([id, crdt], parentToChildren, pool2) {
4525
4521
  switch (crdt.type) {
4526
4522
  case 0 /* OBJECT */: {
4527
- return LiveObject._deserialize([id, crdt], parentToChildren, pool);
4523
+ return LiveObject._deserialize([id, crdt], parentToChildren, pool2);
4528
4524
  }
4529
4525
  case 1 /* LIST */: {
4530
- return LiveList._deserialize([id, crdt], parentToChildren, pool);
4526
+ return LiveList._deserialize([id, crdt], parentToChildren, pool2);
4531
4527
  }
4532
4528
  case 2 /* MAP */: {
4533
- return LiveMap._deserialize([id, crdt], parentToChildren, pool);
4529
+ return LiveMap._deserialize([id, crdt], parentToChildren, pool2);
4534
4530
  }
4535
4531
  case 3 /* REGISTER */: {
4536
- return LiveRegister._deserialize([id, crdt], parentToChildren, pool);
4532
+ return LiveRegister._deserialize([id, crdt], parentToChildren, pool2);
4537
4533
  }
4538
4534
  default: {
4539
4535
  throw new Error("Unexpected CRDT type");
4540
4536
  }
4541
4537
  }
4542
4538
  }
4543
- function deserializeToLson([id, crdt], parentToChildren, pool) {
4539
+ function deserializeToLson([id, crdt], parentToChildren, pool2) {
4544
4540
  switch (crdt.type) {
4545
4541
  case 0 /* OBJECT */: {
4546
- return LiveObject._deserialize([id, crdt], parentToChildren, pool);
4542
+ return LiveObject._deserialize([id, crdt], parentToChildren, pool2);
4547
4543
  }
4548
4544
  case 1 /* LIST */: {
4549
- return LiveList._deserialize([id, crdt], parentToChildren, pool);
4545
+ return LiveList._deserialize([id, crdt], parentToChildren, pool2);
4550
4546
  }
4551
4547
  case 2 /* MAP */: {
4552
- return LiveMap._deserialize([id, crdt], parentToChildren, pool);
4548
+ return LiveMap._deserialize([id, crdt], parentToChildren, pool2);
4553
4549
  }
4554
4550
  case 3 /* REGISTER */: {
4555
4551
  return crdt.data;
@@ -4747,6 +4743,155 @@ function findNonSerializableValue(value, path = "") {
4747
4743
  return false;
4748
4744
  }
4749
4745
 
4746
+ // src/internal.ts
4747
+ var kInternal = Symbol();
4748
+
4749
+ // src/lib/stringify.ts
4750
+ function stringify(object, ...args) {
4751
+ if (typeof object !== "object" || object === null || Array.isArray(object)) {
4752
+ return JSON.stringify(object, ...args);
4753
+ }
4754
+ const sortedObject = Object.keys(object).sort().reduce(
4755
+ (sortedObject2, key) => {
4756
+ sortedObject2[key] = object[key];
4757
+ return sortedObject2;
4758
+ },
4759
+ {}
4760
+ );
4761
+ return JSON.stringify(sortedObject, ...args);
4762
+ }
4763
+
4764
+ // src/lib/batch.ts
4765
+ var DEFAULT_SIZE = 50;
4766
+ var DEFAULT_DELAY = 100;
4767
+ var noop = () => {
4768
+ };
4769
+ var BatchCall = class {
4770
+ constructor(args) {
4771
+ this.resolve = noop;
4772
+ this.reject = noop;
4773
+ this.promise = new Promise(noop);
4774
+ this.args = args;
4775
+ }
4776
+ };
4777
+ var Batch = class {
4778
+ constructor(callback, options) {
4779
+ this.queue = [];
4780
+ this.error = false;
4781
+ this.callback = callback;
4782
+ this.size = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _121 => _121.size]), () => ( DEFAULT_SIZE));
4783
+ this.delay = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _122 => _122.delay]), () => ( DEFAULT_DELAY));
4784
+ }
4785
+ clearDelayTimeout() {
4786
+ if (this.delayTimeoutId !== void 0) {
4787
+ clearTimeout(this.delayTimeoutId);
4788
+ this.delayTimeoutId = void 0;
4789
+ }
4790
+ }
4791
+ schedule() {
4792
+ if (this.queue.length === this.size) {
4793
+ void this.flush();
4794
+ } else if (this.queue.length === 1) {
4795
+ this.clearDelayTimeout();
4796
+ this.delayTimeoutId = setTimeout(() => void this.flush(), this.delay);
4797
+ }
4798
+ }
4799
+ async flush() {
4800
+ if (this.queue.length === 0) {
4801
+ return;
4802
+ }
4803
+ const calls = this.queue.splice(0);
4804
+ const args = calls.map((call) => call.args);
4805
+ try {
4806
+ const results = await this.callback(args);
4807
+ this.error = false;
4808
+ calls.forEach((call, index) => {
4809
+ const result = _optionalChain([results, 'optionalAccess', _123 => _123[index]]);
4810
+ if (!Array.isArray(results)) {
4811
+ call.reject(new Error("Callback must return an array."));
4812
+ } else if (calls.length !== results.length) {
4813
+ call.reject(
4814
+ new Error(
4815
+ `Callback must return an array of the same length as the number of provided items. Expected ${calls.length}, but got ${results.length}.`
4816
+ )
4817
+ );
4818
+ } else if (result instanceof Error) {
4819
+ call.reject(result);
4820
+ } else {
4821
+ call.resolve(result);
4822
+ }
4823
+ });
4824
+ } catch (error3) {
4825
+ this.error = true;
4826
+ calls.forEach((call) => {
4827
+ call.reject(error3);
4828
+ });
4829
+ }
4830
+ }
4831
+ get(...args) {
4832
+ const existingCall = this.queue.find(
4833
+ (call2) => stringify(call2.args) === stringify(args)
4834
+ );
4835
+ if (existingCall) {
4836
+ return existingCall.promise;
4837
+ }
4838
+ const call = new BatchCall(args);
4839
+ call.promise = new Promise((resolve, reject) => {
4840
+ call.resolve = resolve;
4841
+ call.reject = reject;
4842
+ });
4843
+ this.queue.push(call);
4844
+ this.schedule();
4845
+ return call.promise;
4846
+ }
4847
+ clear() {
4848
+ this.queue = [];
4849
+ this.error = false;
4850
+ this.clearDelayTimeout();
4851
+ }
4852
+ };
4853
+ function createBatchStore(callback, options) {
4854
+ const batch = new Batch(callback, options);
4855
+ const cache = /* @__PURE__ */ new Map();
4856
+ const eventSource2 = makeEventSource();
4857
+ function getCacheKey(args) {
4858
+ return stringify(args);
4859
+ }
4860
+ function setStateAndNotify(cacheKey, state) {
4861
+ if (state) {
4862
+ cache.set(cacheKey, state);
4863
+ } else {
4864
+ cache.delete(cacheKey);
4865
+ }
4866
+ eventSource2.notify(state);
4867
+ }
4868
+ async function get(...args) {
4869
+ const cacheKey = getCacheKey(args);
4870
+ if (cache.has(cacheKey)) {
4871
+ return;
4872
+ }
4873
+ try {
4874
+ setStateAndNotify(cacheKey, { isLoading: true });
4875
+ const result = await batch.get(...args);
4876
+ setStateAndNotify(cacheKey, { isLoading: false, data: result });
4877
+ } catch (error3) {
4878
+ setStateAndNotify(cacheKey, {
4879
+ isLoading: false,
4880
+ error: error3
4881
+ });
4882
+ }
4883
+ }
4884
+ function getState(...args) {
4885
+ const cacheKey = getCacheKey(args);
4886
+ return cache.get(cacheKey);
4887
+ }
4888
+ return {
4889
+ ...eventSource2,
4890
+ get,
4891
+ getState
4892
+ };
4893
+ }
4894
+
4750
4895
  // src/lib/debug.ts
4751
4896
  function captureStackTrace(msg, traceRoot) {
4752
4897
  const errorLike = { name: msg };
@@ -4768,6 +4913,133 @@ function isJsonObject(data) {
4768
4913
  return !isJsonScalar(data) && !isJsonArray(data);
4769
4914
  }
4770
4915
 
4916
+ // src/lib/objectToQuery.ts
4917
+ var identifierRegex = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
4918
+ function objectToQuery(obj) {
4919
+ let filterList = [];
4920
+ const entries2 = Object.entries(obj);
4921
+ const keyValuePairs = [];
4922
+ const keyValuePairsWithOperator = [];
4923
+ const indexedKeys = [];
4924
+ entries2.forEach(([key, value]) => {
4925
+ if (!identifierRegex.test(key)) {
4926
+ throw new Error("Key must only contain letters, numbers, _");
4927
+ }
4928
+ if (isSimpleValue(value)) {
4929
+ keyValuePairs.push([key, value]);
4930
+ } else if (isValueWithOperator(value)) {
4931
+ keyValuePairsWithOperator.push([key, value]);
4932
+ } else if (typeof value === "object" && !("startsWith" in value)) {
4933
+ indexedKeys.push([key, value]);
4934
+ }
4935
+ });
4936
+ filterList = [
4937
+ ...getFiltersFromKeyValuePairs(keyValuePairs),
4938
+ ...getFiltersFromKeyValuePairsWithOperator(keyValuePairsWithOperator)
4939
+ ];
4940
+ indexedKeys.forEach(([key, value]) => {
4941
+ const nestedEntries = Object.entries(value);
4942
+ const nKeyValuePairs = [];
4943
+ const nKeyValuePairsWithOperator = [];
4944
+ nestedEntries.forEach(([nestedKey, nestedValue]) => {
4945
+ if (isStringEmpty(nestedKey)) {
4946
+ throw new Error("Key cannot be empty");
4947
+ }
4948
+ if (isSimpleValue(nestedValue)) {
4949
+ nKeyValuePairs.push([formatFilterKey(key, nestedKey), nestedValue]);
4950
+ } else if (isValueWithOperator(nestedValue)) {
4951
+ nKeyValuePairsWithOperator.push([
4952
+ formatFilterKey(key, nestedKey),
4953
+ nestedValue
4954
+ ]);
4955
+ }
4956
+ });
4957
+ filterList = [
4958
+ ...filterList,
4959
+ ...getFiltersFromKeyValuePairs(nKeyValuePairs),
4960
+ ...getFiltersFromKeyValuePairsWithOperator(nKeyValuePairsWithOperator)
4961
+ ];
4962
+ });
4963
+ return filterList.map(
4964
+ ({ key, operator, value }) => formatFilter(key, operator, formatFilterValue(value))
4965
+ ).join(" AND ");
4966
+ }
4967
+ var getFiltersFromKeyValuePairs = (keyValuePairs) => {
4968
+ const filters = [];
4969
+ keyValuePairs.forEach(([key, value]) => {
4970
+ filters.push({
4971
+ key,
4972
+ operator: ":",
4973
+ value
4974
+ });
4975
+ });
4976
+ return filters;
4977
+ };
4978
+ var getFiltersFromKeyValuePairsWithOperator = (keyValuePairsWithOperator) => {
4979
+ const filters = [];
4980
+ keyValuePairsWithOperator.forEach(([key, value]) => {
4981
+ if ("startsWith" in value && typeof value.startsWith === "string") {
4982
+ filters.push({
4983
+ key,
4984
+ operator: "^",
4985
+ value: value.startsWith
4986
+ });
4987
+ }
4988
+ });
4989
+ return filters;
4990
+ };
4991
+ var isSimpleValue = (value) => {
4992
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
4993
+ return true;
4994
+ }
4995
+ return false;
4996
+ };
4997
+ var isValueWithOperator = (value) => {
4998
+ if (typeof value === "object" && value !== null && "startsWith" in value) {
4999
+ return true;
5000
+ }
5001
+ return false;
5002
+ };
5003
+ var formatFilter = (key, operator, value) => {
5004
+ return `${key}${operator}${value}`;
5005
+ };
5006
+ var formatFilterKey = (key, nestedKey) => {
5007
+ if (nestedKey) {
5008
+ return `${key}[${JSON.stringify(nestedKey)}]`;
5009
+ }
5010
+ return key;
5011
+ };
5012
+ var formatFilterValue = (value) => {
5013
+ if (typeof value === "string") {
5014
+ if (isStringEmpty(value)) {
5015
+ throw new Error("Value cannot be empty");
5016
+ }
5017
+ return JSON.stringify(value);
5018
+ }
5019
+ return value.toString();
5020
+ };
5021
+ var isStringEmpty = (value) => {
5022
+ return !value || value.toString().trim() === "";
5023
+ };
5024
+
5025
+ // src/lib/url.ts
5026
+ function toURLSearchParams(params) {
5027
+ const result = new URLSearchParams();
5028
+ for (const [key, value] of Object.entries(params)) {
5029
+ if (value !== void 0 && value !== null) {
5030
+ result.set(key, value.toString());
5031
+ }
5032
+ }
5033
+ return result;
5034
+ }
5035
+ function urljoin(baseUrl, path, params) {
5036
+ const url = new URL(path, baseUrl);
5037
+ if (params !== void 0) {
5038
+ url.search = (params instanceof URLSearchParams ? params : toURLSearchParams(params)).toString();
5039
+ }
5040
+ return url.toString();
5041
+ }
5042
+
4771
5043
  // src/protocol/ClientMsg.ts
4772
5044
  var ClientMsgCode = /* @__PURE__ */ ((ClientMsgCode2) => {
4773
5045
  ClientMsgCode2[ClientMsgCode2["UPDATE_PRESENCE"] = 100] = "UPDATE_PRESENCE";
@@ -5018,15 +5290,15 @@ function installBackgroundTabSpy() {
5018
5290
  const doc = typeof document !== "undefined" ? document : void 0;
5019
5291
  const inBackgroundSince = { current: null };
5020
5292
  function onVisibilityChange() {
5021
- if (_optionalChain([doc, 'optionalAccess', _120 => _120.visibilityState]) === "hidden") {
5293
+ if (_optionalChain([doc, 'optionalAccess', _124 => _124.visibilityState]) === "hidden") {
5022
5294
  inBackgroundSince.current = _nullishCoalesce(inBackgroundSince.current, () => ( Date.now()));
5023
5295
  } else {
5024
5296
  inBackgroundSince.current = null;
5025
5297
  }
5026
5298
  }
5027
- _optionalChain([doc, 'optionalAccess', _121 => _121.addEventListener, 'call', _122 => _122("visibilitychange", onVisibilityChange)]);
5299
+ _optionalChain([doc, 'optionalAccess', _125 => _125.addEventListener, 'call', _126 => _126("visibilitychange", onVisibilityChange)]);
5028
5300
  const unsub = () => {
5029
- _optionalChain([doc, 'optionalAccess', _123 => _123.removeEventListener, 'call', _124 => _124("visibilitychange", onVisibilityChange)]);
5301
+ _optionalChain([doc, 'optionalAccess', _127 => _127.removeEventListener, 'call', _128 => _128("visibilitychange", onVisibilityChange)]);
5030
5302
  };
5031
5303
  return [inBackgroundSince, unsub];
5032
5304
  }
@@ -5055,7 +5327,7 @@ function createCommentsApi(roomId, getAuthValue, fetchClientApi) {
5055
5327
  response.status,
5056
5328
  errorBody
5057
5329
  );
5058
- } catch (e5) {
5330
+ } catch (e3) {
5059
5331
  error3 = new CommentsApiError(response.statusText, response.status);
5060
5332
  }
5061
5333
  throw error3;
@@ -5064,25 +5336,26 @@ function createCommentsApi(roomId, getAuthValue, fetchClientApi) {
5064
5336
  let body;
5065
5337
  try {
5066
5338
  body = await response.json();
5067
- } catch (e6) {
5339
+ } catch (e4) {
5068
5340
  body = {};
5069
5341
  }
5070
5342
  return body;
5071
5343
  }
5072
5344
  async function getThreads(options) {
5345
+ let query;
5346
+ if (_optionalChain([options, 'optionalAccess', _129 => _129.query])) {
5347
+ query = objectToQuery(options.query);
5348
+ }
5073
5349
  const response = await fetchCommentsApi(
5074
- "/threads/search",
5350
+ "/threads",
5075
5351
  {
5076
- since: _optionalChain([options, 'optionalAccess', _125 => _125.since, 'optionalAccess', _126 => _126.toISOString, 'call', _127 => _127()])
5352
+ since: _optionalChain([options, 'optionalAccess', _130 => _130.since, 'optionalAccess', _131 => _131.toISOString, 'call', _132 => _132()]),
5353
+ query
5077
5354
  },
5078
5355
  {
5079
- body: JSON.stringify({
5080
- ..._optionalChain([options, 'optionalAccess', _128 => _128.query, 'optionalAccess', _129 => _129.metadata]) && { metadata: options.query.metadata }
5081
- }),
5082
5356
  headers: {
5083
5357
  "Content-Type": "application/json"
5084
- },
5085
- method: "POST"
5358
+ }
5086
5359
  }
5087
5360
  );
5088
5361
  if (response.ok) {
@@ -5138,23 +5411,20 @@ function createCommentsApi(roomId, getAuthValue, fetchClientApi) {
5138
5411
  commentId,
5139
5412
  threadId
5140
5413
  }) {
5141
- const thread = await fetchJson(
5142
- "/threads",
5143
- {
5144
- method: "POST",
5145
- headers: {
5146
- "Content-Type": "application/json"
5414
+ const thread = await fetchJson("/threads", {
5415
+ method: "POST",
5416
+ headers: {
5417
+ "Content-Type": "application/json"
5418
+ },
5419
+ body: JSON.stringify({
5420
+ id: threadId,
5421
+ comment: {
5422
+ id: commentId,
5423
+ body
5147
5424
  },
5148
- body: JSON.stringify({
5149
- id: threadId,
5150
- comment: {
5151
- id: commentId,
5152
- body
5153
- },
5154
- metadata
5155
- })
5156
- }
5157
- );
5425
+ metadata
5426
+ })
5427
+ });
5158
5428
  return convertToThreadData(thread);
5159
5429
  }
5160
5430
  async function editThreadMetadata({
@@ -5271,7 +5541,7 @@ function createCommentsApi(roomId, getAuthValue, fetchClientApi) {
5271
5541
  removeReaction: removeReaction2
5272
5542
  };
5273
5543
  }
5274
- var MARK_INBOX_NOTIFICATIONS_AS_READ_BATCH_DELAY2 = 50;
5544
+ var MARK_INBOX_NOTIFICATIONS_AS_READ_BATCH_DELAY = 50;
5275
5545
  function createRoom(options, config) {
5276
5546
  const initialPresence = typeof options.initialPresence === "function" ? options.initialPresence(config.roomId) : options.initialPresence;
5277
5547
  const initialStorage = typeof options.initialStorage === "function" ? options.initialStorage(config.roomId) : options.initialStorage;
@@ -5416,7 +5686,7 @@ function createRoom(options, config) {
5416
5686
  eventHub.error.notify(err);
5417
5687
  });
5418
5688
  });
5419
- const pool = {
5689
+ const pool2 = {
5420
5690
  roomId: config.roomId,
5421
5691
  getNode: (id) => context.nodes.get(id),
5422
5692
  addNode: (id, node) => void context.nodes.set(id, node),
@@ -5459,7 +5729,7 @@ function createRoom(options, config) {
5459
5729
  }
5460
5730
  },
5461
5731
  assertStorageIsWritable: () => {
5462
- const scopes = _optionalChain([context, 'access', _130 => _130.dynamicSessionInfo, 'access', _131 => _131.current, 'optionalAccess', _132 => _132.scopes]);
5732
+ const scopes = _optionalChain([context, 'access', _133 => _133.dynamicSessionInfo, 'access', _134 => _134.current, 'optionalAccess', _135 => _135.scopes]);
5463
5733
  if (scopes === void 0) {
5464
5734
  return;
5465
5735
  }
@@ -5495,12 +5765,12 @@ function createRoom(options, config) {
5495
5765
  `/v2/c/rooms/${encodeURIComponent(roomId)}${endpoint}`,
5496
5766
  params
5497
5767
  );
5498
- const fetcher = _optionalChain([config, 'access', _133 => _133.polyfills, 'optionalAccess', _134 => _134.fetch]) || /* istanbul ignore next */
5768
+ const fetcher = _optionalChain([config, 'access', _136 => _136.polyfills, 'optionalAccess', _137 => _137.fetch]) || /* istanbul ignore next */
5499
5769
  fetch;
5500
5770
  return await fetcher(url, {
5501
5771
  ...options2,
5502
5772
  headers: {
5503
- ..._optionalChain([options2, 'optionalAccess', _135 => _135.headers]),
5773
+ ..._optionalChain([options2, 'optionalAccess', _138 => _138.headers]),
5504
5774
  Authorization: `Bearer ${getAuthBearerHeaderFromAuthValue(authValue)}`
5505
5775
  }
5506
5776
  });
@@ -5511,23 +5781,62 @@ function createRoom(options, config) {
5511
5781
  headers: {
5512
5782
  "Content-Type": "application/json"
5513
5783
  }
5514
- });
5784
+ });
5785
+ }
5786
+ async function httpPostToRoom(endpoint, body) {
5787
+ if (!managedSocket.authValue) {
5788
+ throw new Error("Not authorized");
5789
+ }
5790
+ return fetchClientApi(config.roomId, endpoint, managedSocket.authValue, {
5791
+ method: "POST",
5792
+ headers: {
5793
+ "Content-Type": "application/json"
5794
+ },
5795
+ body: JSON.stringify(body)
5796
+ });
5797
+ }
5798
+ async function createTextMention(userId, mentionId) {
5799
+ if (!managedSocket.authValue) {
5800
+ throw new Error("Not authorized");
5801
+ }
5802
+ return fetchClientApi(
5803
+ config.roomId,
5804
+ "/text-mentions",
5805
+ managedSocket.authValue,
5806
+ {
5807
+ method: "POST",
5808
+ headers: {
5809
+ "Content-Type": "application/json"
5810
+ },
5811
+ body: JSON.stringify({
5812
+ userId,
5813
+ mentionId
5814
+ })
5815
+ }
5816
+ );
5515
5817
  }
5516
- async function httpPostToRoom(endpoint, body) {
5818
+ async function deleteTextMention(mentionId) {
5517
5819
  if (!managedSocket.authValue) {
5518
5820
  throw new Error("Not authorized");
5519
5821
  }
5520
- return fetchClientApi(config.roomId, endpoint, managedSocket.authValue, {
5521
- method: "POST",
5522
- headers: {
5523
- "Content-Type": "application/json"
5524
- },
5525
- body: JSON.stringify(body)
5822
+ return fetchClientApi(
5823
+ config.roomId,
5824
+ `/text-mentions/${mentionId}`,
5825
+ managedSocket.authValue,
5826
+ {
5827
+ method: "DELETE"
5828
+ }
5829
+ );
5830
+ }
5831
+ async function reportTextEditor(type, rootKey) {
5832
+ return httpPostToRoom("/text-metadata", {
5833
+ type,
5834
+ rootKey
5526
5835
  });
5527
5836
  }
5528
5837
  function sendMessages(messages) {
5529
5838
  const serializedPayload = JSON.stringify(messages);
5530
- const nonce = _optionalChain([context, 'access', _136 => _136.dynamicSessionInfo, 'access', _137 => _137.current, 'optionalAccess', _138 => _138.nonce]);
5839
+ const nonce = _optionalChain([context, 'access', _139 => _139.dynamicSessionInfo, 'access', _140 => _140.current, 'optionalAccess', _141 => _141.nonce]);
5531
5840
  if (config.unstable_fallbackToHTTP && nonce) {
5532
5841
  const size = new TextEncoder().encode(serializedPayload).length;
5533
5842
  if (size > MAX_SOCKET_MESSAGE_SIZE) {
@@ -5589,7 +5898,7 @@ function createRoom(options, config) {
5589
5898
  if (context.root !== void 0) {
5590
5899
  updateRoot(message.items, batchedUpdatesWrapper);
5591
5900
  } else {
5592
- context.root = LiveObject._fromItems(message.items, pool);
5901
+ context.root = LiveObject._fromItems(message.items, pool2);
5593
5902
  }
5594
5903
  const stackSizeBefore = context.undoStack.length;
5595
5904
  for (const key in context.initialStorage) {
@@ -5664,7 +5973,7 @@ function createRoom(options, config) {
5664
5973
  const createdNodeIds = /* @__PURE__ */ new Set();
5665
5974
  const ops = rawOps.map((op) => {
5666
5975
  if (op.type !== "presence" && !op.opId) {
5667
- return { ...op, opId: pool.generateOpId() };
5976
+ return { ...op, opId: pool2.generateOpId() };
5668
5977
  } else {
5669
5978
  return op;
5670
5979
  }
@@ -5789,7 +6098,7 @@ function createRoom(options, config) {
5789
6098
  }
5790
6099
  context.myPresence.patch(patch);
5791
6100
  if (context.activeBatch) {
5792
- if (_optionalChain([options2, 'optionalAccess', _139 => _139.addToHistory])) {
6101
+ if (_optionalChain([options2, 'optionalAccess', _142 => _142.addToHistory])) {
5793
6102
  context.activeBatch.reverseOps.unshift({
5794
6103
  type: "presence",
5795
6104
  data: oldValues
@@ -5799,7 +6108,7 @@ function createRoom(options, config) {
5799
6108
  } else {
5800
6109
  flushNowOrSoon();
5801
6110
  batchUpdates(() => {
5802
- if (_optionalChain([options2, 'optionalAccess', _140 => _140.addToHistory])) {
6111
+ if (_optionalChain([options2, 'optionalAccess', _143 => _143.addToHistory])) {
5803
6112
  addToUndoStack(
5804
6113
  [{ type: "presence", data: oldValues }],
5805
6114
  doNotBatchUpdates
@@ -5997,7 +6306,7 @@ function createRoom(options, config) {
5997
6306
  if (process.env.NODE_ENV !== "production") {
5998
6307
  const traces = /* @__PURE__ */ new Set();
5999
6308
  for (const opId of message.opIds) {
6000
- const trace = _optionalChain([context, 'access', _141 => _141.opStackTraces, 'optionalAccess', _142 => _142.get, 'call', _143 => _143(opId)]);
6309
+ const trace = _optionalChain([context, 'access', _144 => _144.opStackTraces, 'optionalAccess', _145 => _145.get, 'call', _146 => _146(opId)]);
6001
6310
  if (trace) {
6002
6311
  traces.add(trace);
6003
6312
  }
@@ -6129,7 +6438,7 @@ ${Array.from(traces).join("\n\n")}`
6129
6438
  const unacknowledgedOps = new Map(context.unacknowledgedOps);
6130
6439
  createOrUpdateRootFromMessage(message, doNotBatchUpdates);
6131
6440
  applyAndSendOps(unacknowledgedOps, doNotBatchUpdates);
6132
- _optionalChain([_resolveStoragePromise, 'optionalCall', _144 => _144()]);
6441
+ _optionalChain([_resolveStoragePromise, 'optionalCall', _147 => _147()]);
6133
6442
  notifyStorageStatus();
6134
6443
  eventHub.storageDidLoad.notify();
6135
6444
  }
@@ -6346,7 +6655,7 @@ ${Array.from(traces).join("\n\n")}`
6346
6655
  response.status,
6347
6656
  errorBody
6348
6657
  );
6349
- } catch (e7) {
6658
+ } catch (e5) {
6350
6659
  error3 = new NotificationsApiError(
6351
6660
  response.statusText,
6352
6661
  response.status
@@ -6358,7 +6667,7 @@ ${Array.from(traces).join("\n\n")}`
6358
6667
  let body;
6359
6668
  try {
6360
6669
  body = await response.json();
6361
- } catch (e8) {
6670
+ } catch (e6) {
6362
6671
  body = {};
6363
6672
  }
6364
6673
  return body;
@@ -6395,7 +6704,7 @@ ${Array.from(traces).join("\n\n")}`
6395
6704
  await markInboxNotificationsAsRead(inboxNotificationIds);
6396
6705
  return inboxNotificationIds;
6397
6706
  },
6398
- { delay: MARK_INBOX_NOTIFICATIONS_AS_READ_BATCH_DELAY2 }
6707
+ { delay: MARK_INBOX_NOTIFICATIONS_AS_READ_BATCH_DELAY }
6399
6708
  );
6400
6709
  async function markInboxNotificationAsRead(inboxNotificationId) {
6401
6710
  await batchedMarkInboxNotificationsAsRead.get(inboxNotificationId);
@@ -6404,7 +6713,7 @@ ${Array.from(traces).join("\n\n")}`
6404
6713
  {
6405
6714
  [kInternal]: {
6406
6715
  get presenceBuffer() {
6407
- return deepClone(_nullishCoalesce(_optionalChain([context, 'access', _145 => _145.buffer, 'access', _146 => _146.presenceUpdates, 'optionalAccess', _147 => _147.data]), () => ( null)));
6716
+ return deepClone(_nullishCoalesce(_optionalChain([context, 'access', _148 => _148.buffer, 'access', _149 => _149.presenceUpdates, 'optionalAccess', _150 => _150.data]), () => ( null)));
6408
6717
  },
6409
6718
  // prettier-ignore
6410
6719
  get undoStack() {
@@ -6415,6 +6724,12 @@ ${Array.from(traces).join("\n\n")}`
6415
6724
  return context.nodes.size;
6416
6725
  },
6417
6726
  // prettier-ignore
6727
+ // send metadata when using a text editor
6728
+ reportTextEditor,
6729
+ // create a text mention when using a text editor
6730
+ createTextMention,
6731
+ // delete a text mention when using a text editor
6732
+ deleteTextMention,
6418
6733
  // Support for the Liveblocks browser extension
6419
6734
  getSelf_forDevTools: () => selfAsTreeNode.current,
6420
6735
  getOthers_forDevTools: () => others_forDevTools.current,
@@ -6553,7 +6868,7 @@ function makeClassicSubscribeFn(events) {
6553
6868
  }
6554
6869
  if (isLiveNode(first)) {
6555
6870
  const node = first;
6556
- if (_optionalChain([options, 'optionalAccess', _148 => _148.isDeep])) {
6871
+ if (_optionalChain([options, 'optionalAccess', _151 => _151.isDeep])) {
6557
6872
  const storageCallback = second;
6558
6873
  return subscribeToLiveStructureDeeply(node, storageCallback);
6559
6874
  } else {
@@ -6599,469 +6914,405 @@ function makeCreateSocketDelegateForRoom(roomId, baseUrl, WebSocketPolyfill) {
6599
6914
  };
6600
6915
  }
6601
6916
 
6602
- // src/store.ts
6603
- function createClientStore() {
6604
- const store = createStore({
6605
- threads: {},
6606
- queries: {},
6607
- optimisticUpdates: [],
6608
- inboxNotifications: {},
6609
- notificationSettings: {}
6610
- });
6611
- return {
6612
- ...store,
6613
- deleteThread(threadId) {
6614
- store.set((state) => {
6615
- return {
6616
- ...state,
6617
- threads: deleteKeyImmutable(state.threads, threadId),
6618
- inboxNotifications: Object.fromEntries(
6619
- Object.entries(state.inboxNotifications).filter(
6620
- ([_id, notification]) => notification.threadId !== threadId
6621
- )
6622
- )
6623
- };
6624
- });
6625
- },
6626
- updateThreadAndNotification(thread, inboxNotification) {
6627
- store.set((state) => {
6628
- const existingThread = state.threads[thread.id];
6629
- return {
6630
- ...state,
6631
- threads: existingThread === void 0 || compareThreads(thread, existingThread) === 1 ? { ...state.threads, [thread.id]: thread } : state.threads,
6632
- inboxNotifications: inboxNotification === void 0 ? state.inboxNotifications : {
6633
- ...state.inboxNotifications,
6634
- [inboxNotification.id]: inboxNotification
6635
- }
6636
- };
6637
- });
6638
- },
6639
- updateThreadsAndNotifications(threads, inboxNotifications, deletedThreads, deletedInboxNotifications, queryKey) {
6640
- store.set((state) => ({
6641
- ...state,
6642
- threads: applyThreadUpdates(state.threads, {
6643
- newThreads: threads,
6644
- deletedThreads
6645
- }),
6646
- inboxNotifications: applyNotificationsUpdates(
6647
- state.inboxNotifications,
6648
- {
6649
- newInboxNotifications: inboxNotifications,
6650
- deletedNotifications: deletedInboxNotifications
6651
- }
6652
- ),
6653
- queries: queryKey !== void 0 ? {
6654
- ...state.queries,
6655
- [queryKey]: {
6656
- isLoading: false
6657
- }
6658
- } : state.queries
6659
- }));
6660
- },
6661
- updateRoomInboxNotificationSettings(roomId, settings, queryKey) {
6662
- store.set((state) => ({
6663
- ...state,
6664
- notificationSettings: {
6665
- ...state.notificationSettings,
6666
- [roomId]: settings
6667
- },
6668
- queries: {
6669
- ...state.queries,
6670
- [queryKey]: {
6671
- isLoading: false
6917
+ // src/comments/lib/selected-threads.ts
6918
+ function selectedThreads(roomId, state, options) {
6919
+ const result = applyOptimisticUpdates(state);
6920
+ const threads = Object.values(result.threads).filter(
6921
+ (thread) => {
6922
+ if (thread.roomId !== roomId)
6923
+ return false;
6924
+ if (thread.deletedAt !== void 0) {
6925
+ return false;
6926
+ }
6927
+ const query = options.query;
6928
+ if (!query)
6929
+ return true;
6930
+ for (const key in query.metadata) {
6931
+ const metadataValue = thread.metadata[key];
6932
+ const filterValue = query.metadata[key];
6933
+ if (assertFilterIsStartsWithOperator(filterValue) && assertMetadataValueIsString(metadataValue)) {
6934
+ if (metadataValue.startsWith(filterValue.startsWith)) {
6935
+ return true;
6672
6936
  }
6673
6937
  }
6674
- }));
6675
- },
6676
- pushOptimisticUpdate(optimisticUpdate) {
6677
- store.set((state) => ({
6678
- ...state,
6679
- optimisticUpdates: [...state.optimisticUpdates, optimisticUpdate]
6680
- }));
6681
- },
6682
- setQueryState(queryKey, queryState) {
6683
- store.set((state) => ({
6684
- ...state,
6685
- queries: {
6686
- ...state.queries,
6687
- [queryKey]: queryState
6938
+ if (metadataValue !== filterValue) {
6939
+ return false;
6688
6940
  }
6689
- }));
6941
+ }
6942
+ return true;
6690
6943
  }
6691
- };
6692
- }
6693
- function deleteKeyImmutable(record, key) {
6694
- if (Object.prototype.hasOwnProperty.call(record, key)) {
6695
- const { [key]: _toDelete, ...rest } = record;
6696
- return rest;
6697
- }
6698
- return record;
6944
+ );
6945
+ return threads.sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime());
6699
6946
  }
6700
- function compareThreads(thread1, thread2) {
6701
- if (thread1.updatedAt && thread2.updatedAt) {
6702
- return thread1.updatedAt > thread2.updatedAt ? 1 : thread1.updatedAt < thread2.updatedAt ? -1 : 0;
6703
- } else if (thread1.updatedAt || thread2.updatedAt) {
6704
- return thread1.updatedAt ? 1 : -1;
6705
- }
6706
- if (thread1.createdAt > thread2.createdAt) {
6707
- return 1;
6708
- } else if (thread1.createdAt < thread2.createdAt) {
6709
- return -1;
6947
+ var assertFilterIsStartsWithOperator = (filter) => {
6948
+ if (typeof filter === "object" && typeof filter.startsWith === "string") {
6949
+ return true;
6950
+ } else {
6951
+ return false;
6710
6952
  }
6711
- return 0;
6712
- }
6713
- function applyOptimisticUpdates(state) {
6714
- const result = {
6715
- threads: {
6716
- ...state.threads
6717
- },
6718
- inboxNotifications: {
6719
- ...state.inboxNotifications
6720
- },
6721
- notificationSettings: {
6722
- ...state.notificationSettings
6723
- }
6724
- };
6725
- for (const optimisticUpdate of state.optimisticUpdates) {
6726
- switch (optimisticUpdate.type) {
6727
- case "create-thread": {
6728
- result.threads[optimisticUpdate.thread.id] = optimisticUpdate.thread;
6729
- break;
6730
- }
6731
- case "edit-thread-metadata": {
6732
- const thread = result.threads[optimisticUpdate.threadId];
6733
- if (thread === void 0) {
6734
- break;
6735
- }
6736
- if (thread.deletedAt !== void 0) {
6737
- break;
6738
- }
6739
- if (thread.updatedAt !== void 0 && thread.updatedAt > optimisticUpdate.updatedAt) {
6740
- break;
6741
- }
6742
- result.threads[thread.id] = {
6743
- ...thread,
6744
- updatedAt: optimisticUpdate.updatedAt,
6745
- metadata: {
6746
- ...thread.metadata,
6747
- ...optimisticUpdate.metadata
6748
- }
6749
- };
6750
- break;
6751
- }
6752
- case "create-comment": {
6753
- const thread = result.threads[optimisticUpdate.comment.threadId];
6754
- if (thread === void 0) {
6755
- break;
6756
- }
6757
- result.threads[thread.id] = upsertComment(
6758
- thread,
6759
- optimisticUpdate.comment
6760
- );
6761
- const inboxNotification = Object.values(result.inboxNotifications).find(
6762
- (notification) => notification.threadId === thread.id
6763
- );
6764
- if (inboxNotification === void 0) {
6765
- break;
6766
- }
6767
- result.inboxNotifications[inboxNotification.id] = {
6768
- ...inboxNotification,
6769
- notifiedAt: optimisticUpdate.comment.createdAt,
6770
- readAt: optimisticUpdate.comment.createdAt
6771
- };
6772
- break;
6773
- }
6774
- case "edit-comment": {
6775
- const thread = result.threads[optimisticUpdate.comment.threadId];
6776
- if (thread === void 0) {
6777
- break;
6778
- }
6779
- result.threads[thread.id] = upsertComment(
6780
- thread,
6781
- optimisticUpdate.comment
6782
- );
6783
- break;
6784
- }
6785
- case "delete-comment": {
6786
- const thread = result.threads[optimisticUpdate.threadId];
6787
- if (thread === void 0) {
6788
- break;
6789
- }
6790
- result.threads[thread.id] = deleteComment(
6791
- thread,
6792
- optimisticUpdate.commentId,
6793
- optimisticUpdate.deletedAt
6794
- );
6795
- break;
6796
- }
6797
- case "add-reaction": {
6798
- const thread = result.threads[optimisticUpdate.threadId];
6799
- if (thread === void 0) {
6800
- break;
6801
- }
6802
- result.threads[thread.id] = addReaction(
6803
- thread,
6804
- optimisticUpdate.commentId,
6805
- optimisticUpdate.reaction
6806
- );
6807
- break;
6808
- }
6809
- case "remove-reaction": {
6810
- const thread = result.threads[optimisticUpdate.threadId];
6811
- if (thread === void 0) {
6812
- break;
6813
- }
6814
- result.threads[thread.id] = removeReaction(
6815
- thread,
6816
- optimisticUpdate.commentId,
6817
- optimisticUpdate.emoji,
6818
- optimisticUpdate.userId,
6819
- optimisticUpdate.removedAt
6820
- );
6821
- break;
6822
- }
6823
- case "mark-inbox-notification-as-read": {
6824
- result.inboxNotifications[optimisticUpdate.inboxNotificationId] = {
6825
- ...state.inboxNotifications[optimisticUpdate.inboxNotificationId],
6826
- readAt: optimisticUpdate.readAt
6827
- };
6828
- break;
6829
- }
6830
- case "mark-inbox-notifications-as-read": {
6831
- for (const id in result.inboxNotifications) {
6832
- result.inboxNotifications[id] = {
6833
- ...result.inboxNotifications[id],
6834
- readAt: optimisticUpdate.readAt
6835
- };
6953
+ };
6954
+ var assertMetadataValueIsString = (value) => {
6955
+ return typeof value === "string";
6956
+ };
6957
+
6958
+ // src/constants.ts
6959
+ var DEFAULT_BASE_URL = "https://api.liveblocks.io";
6960
+
6961
+ // src/devtools/bridge.ts
6962
+ var _bridgeActive = false;
6963
+ function activateBridge(allowed) {
6964
+ _bridgeActive = allowed;
6965
+ }
6966
+ function sendToPanel(message, options) {
6967
+ if (process.env.NODE_ENV === "production" || typeof window === "undefined") {
6968
+ return;
6969
+ }
6970
+ const fullMsg = {
6971
+ ...message,
6972
+ source: "liveblocks-devtools-client"
6973
+ };
6974
+ if (!(_optionalChain([options, 'optionalAccess', _152 => _152.force]) || _bridgeActive)) {
6975
+ return;
6976
+ }
6977
+ window.postMessage(fullMsg, "*");
6978
+ }
6979
+ var eventSource = makeEventSource();
6980
+ if (process.env.NODE_ENV !== "production" && typeof window !== "undefined") {
6981
+ window.addEventListener("message", (event) => {
6982
+ if (event.source === window && _optionalChain([event, 'access', _153 => _153.data, 'optionalAccess', _154 => _154.source]) === "liveblocks-devtools-panel") {
6983
+ eventSource.notify(event.data);
6984
+ } else {
6985
+ }
6986
+ });
6987
+ }
6988
+ var onMessageFromPanel = eventSource.observable;
6989
+
6990
+ // src/devtools/index.ts
6991
+ var VERSION = PKG_VERSION || "dev";
6992
+ var _devtoolsSetupHasRun = false;
6993
+ function setupDevTools(getAllRooms) {
6994
+ if (process.env.NODE_ENV === "production" || typeof window === "undefined") {
6995
+ return;
6996
+ }
6997
+ if (_devtoolsSetupHasRun) {
6998
+ return;
6999
+ }
7000
+ _devtoolsSetupHasRun = true;
7001
+ onMessageFromPanel.subscribe((msg) => {
7002
+ switch (msg.msg) {
7003
+ case "connect": {
7004
+ activateBridge(true);
7005
+ for (const roomId of getAllRooms()) {
7006
+ sendToPanel({
7007
+ msg: "room::available",
7008
+ roomId,
7009
+ clientVersion: VERSION
7010
+ });
6836
7011
  }
6837
7012
  break;
6838
7013
  }
6839
- case "update-notification-settings": {
6840
- result.notificationSettings[optimisticUpdate.roomId] = {
6841
- ...result.notificationSettings[optimisticUpdate.roomId],
6842
- ...optimisticUpdate.settings
6843
- };
6844
- }
6845
7014
  }
7015
+ });
7016
+ sendToPanel({ msg: "wake-up-devtools" }, { force: true });
7017
+ }
7018
+ var unsubsByRoomId = /* @__PURE__ */ new Map();
7019
+ function stopSyncStream(roomId) {
7020
+ const unsubs = _nullishCoalesce(unsubsByRoomId.get(roomId), () => ( []));
7021
+ unsubsByRoomId.delete(roomId);
7022
+ for (const unsub of unsubs) {
7023
+ unsub();
6846
7024
  }
6847
- return result;
6848
7025
  }
6849
- function applyThreadUpdates(existingThreads, updates) {
6850
- const updatedThreads = { ...existingThreads };
6851
- updates.newThreads.forEach((thread) => {
6852
- const existingThread = updatedThreads[thread.id];
6853
- if (existingThread) {
6854
- const result = compareThreads(existingThread, thread);
6855
- if (result === 1)
6856
- return;
6857
- }
6858
- updatedThreads[thread.id] = thread;
6859
- });
6860
- updates.deletedThreads.forEach(({ id, deletedAt }) => {
6861
- const existingThread = updatedThreads[id];
6862
- if (existingThread === void 0)
6863
- return;
6864
- existingThread.deletedAt = deletedAt;
6865
- existingThread.updatedAt = deletedAt;
6866
- existingThread.comments = [];
7026
+ function startSyncStream(room) {
7027
+ stopSyncStream(room.id);
7028
+ fullSync(room);
7029
+ unsubsByRoomId.set(room.id, [
7030
+ // When the connection status changes
7031
+ room.events.status.subscribe(() => partialSyncConnection(room)),
7032
+ // When storage initializes, send the update
7033
+ room.events.storageDidLoad.subscribeOnce(() => partialSyncStorage(room)),
7034
+ // Any time storage updates, send the new storage root
7035
+ room.events.storage.subscribe(() => partialSyncStorage(room)),
7036
+ // Any time "me" or "others" updates, send the new values accordingly
7037
+ room.events.self.subscribe(() => partialSyncMe(room)),
7038
+ room.events.others.subscribe(() => partialSyncOthers(room)),
7039
+ // Any time ydoc is updated, forward the update
7040
+ room.events.ydoc.subscribe((update) => syncYdocUpdate(room, update)),
7041
+ // Any time a custom room event is received, forward it
7042
+ room.events.customEvent.subscribe(
7043
+ (eventData) => forwardEvent(room, eventData)
7044
+ )
7045
+ ]);
7046
+ }
7047
+ function syncYdocUpdate(room, update) {
7048
+ sendToPanel({
7049
+ msg: "room::sync::ydoc",
7050
+ roomId: room.id,
7051
+ update
6867
7052
  });
6868
- return updatedThreads;
6869
7053
  }
6870
- function applyNotificationsUpdates(existingInboxNotifications, updates) {
6871
- const updatedInboxNotifications = { ...existingInboxNotifications };
6872
- updates.newInboxNotifications.forEach((notification) => {
6873
- const existingNotification = updatedInboxNotifications[notification.id];
6874
- if (existingNotification) {
6875
- const result = compareInboxNotifications(
6876
- existingNotification,
6877
- notification
6878
- );
6879
- if (result === 1)
6880
- return;
7054
+ var loadedAt = Date.now();
7055
+ var eventCounter = 0;
7056
+ function nextEventId() {
7057
+ return `event-${loadedAt}-${eventCounter++}`;
7058
+ }
7059
+ function forwardEvent(room, eventData) {
7060
+ sendToPanel({
7061
+ msg: "room::events::custom-event",
7062
+ roomId: room.id,
7063
+ event: {
7064
+ type: "CustomEvent",
7065
+ id: nextEventId(),
7066
+ key: "Event",
7067
+ connectionId: eventData.connectionId,
7068
+ payload: eventData.event
6881
7069
  }
6882
- updatedInboxNotifications[notification.id] = notification;
6883
7070
  });
6884
- updates.deletedNotifications.forEach(
6885
- ({ id }) => delete updatedInboxNotifications[id]
6886
- );
6887
- return updatedInboxNotifications;
6888
7071
  }
6889
- function compareInboxNotifications(inboxNotificationA, inboxNotificationB) {
6890
- if (inboxNotificationA.notifiedAt > inboxNotificationB.notifiedAt) {
6891
- return 1;
6892
- } else if (inboxNotificationA.notifiedAt < inboxNotificationB.notifiedAt) {
6893
- return -1;
7072
+ function partialSyncConnection(room) {
7073
+ sendToPanel({
7074
+ msg: "room::sync::partial",
7075
+ roomId: room.id,
7076
+ status: room.getStatus()
7077
+ });
7078
+ }
7079
+ function partialSyncStorage(room) {
7080
+ const root = room.getStorageSnapshot();
7081
+ if (root) {
7082
+ sendToPanel({
7083
+ msg: "room::sync::partial",
7084
+ roomId: room.id,
7085
+ storage: root.toTreeNode("root").payload
7086
+ });
6894
7087
  }
6895
- if (inboxNotificationA.readAt && inboxNotificationB.readAt) {
6896
- return inboxNotificationA.readAt > inboxNotificationB.readAt ? 1 : inboxNotificationA.readAt < inboxNotificationB.readAt ? -1 : 0;
6897
- } else if (inboxNotificationA.readAt || inboxNotificationB.readAt) {
6898
- return inboxNotificationA.readAt ? 1 : -1;
7088
+ }
7089
+ function partialSyncMe(room) {
7090
+ const me = room[kInternal].getSelf_forDevTools();
7091
+ if (me) {
7092
+ sendToPanel({
7093
+ msg: "room::sync::partial",
7094
+ roomId: room.id,
7095
+ me
7096
+ });
6899
7097
  }
6900
- return 0;
6901
7098
  }
6902
- function upsertComment(thread, comment) {
6903
- if (thread.deletedAt !== void 0) {
6904
- return thread;
7099
+ function partialSyncOthers(room) {
7100
+ const others = room[kInternal].getOthers_forDevTools();
7101
+ if (others) {
7102
+ sendToPanel({
7103
+ msg: "room::sync::partial",
7104
+ roomId: room.id,
7105
+ others
7106
+ });
6905
7107
  }
6906
- if (comment.threadId !== thread.id) {
6907
- warn(
6908
- `Comment ${comment.id} does not belong to thread ${thread.id}`
6909
- );
6910
- return thread;
7108
+ }
7109
+ function fullSync(room) {
7110
+ const root = room.getStorageSnapshot();
7111
+ const me = room[kInternal].getSelf_forDevTools();
7112
+ const others = room[kInternal].getOthers_forDevTools();
7113
+ room.fetchYDoc("");
7114
+ sendToPanel({
7115
+ msg: "room::sync::full",
7116
+ roomId: room.id,
7117
+ status: room.getStatus(),
7118
+ storage: _nullishCoalesce(_optionalChain([root, 'optionalAccess', _155 => _155.toTreeNode, 'call', _156 => _156("root"), 'access', _157 => _157.payload]), () => ( null)),
7119
+ me,
7120
+ others
7121
+ });
7122
+ }
7123
+ var roomChannelListeners = /* @__PURE__ */ new Map();
7124
+ function stopRoomChannelListener(roomId) {
7125
+ const listener = roomChannelListeners.get(roomId);
7126
+ roomChannelListeners.delete(roomId);
7127
+ if (listener) {
7128
+ listener();
6911
7129
  }
6912
- const existingComment = thread.comments.find(
6913
- (existingComment2) => existingComment2.id === comment.id
7130
+ }
7131
+ function linkDevTools(roomId, room) {
7132
+ if (process.env.NODE_ENV === "production" || typeof window === "undefined") {
7133
+ return;
7134
+ }
7135
+ sendToPanel({ msg: "room::available", roomId, clientVersion: VERSION });
7136
+ stopRoomChannelListener(roomId);
7137
+ roomChannelListeners.set(
7138
+ roomId,
7139
+ // Returns the unsubscribe callback, that we store in the
7140
+ // roomChannelListeners registry
7141
+ onMessageFromPanel.subscribe((msg) => {
7142
+ switch (msg.msg) {
7143
+ case "room::subscribe": {
7144
+ if (msg.roomId === roomId) {
7145
+ startSyncStream(room);
7146
+ }
7147
+ break;
7148
+ }
7149
+ case "room::unsubscribe": {
7150
+ if (msg.roomId === roomId) {
7151
+ stopSyncStream(roomId);
7152
+ }
7153
+ break;
7154
+ }
7155
+ }
7156
+ })
6914
7157
  );
6915
- if (existingComment === void 0) {
6916
- const updatedAt = new Date(
6917
- Math.max(_optionalChain([thread, 'access', _149 => _149.updatedAt, 'optionalAccess', _150 => _150.getTime, 'call', _151 => _151()]) || 0, comment.createdAt.getTime())
6918
- );
6919
- const updatedThread = {
6920
- ...thread,
6921
- updatedAt,
6922
- comments: [...thread.comments, comment]
6923
- };
6924
- return updatedThread;
7158
+ }
7159
+ function unlinkDevTools(roomId) {
7160
+ if (process.env.NODE_ENV === "production" || typeof window === "undefined") {
7161
+ return;
6925
7162
  }
6926
- if (existingComment.deletedAt !== void 0) {
6927
- return thread;
7163
+ stopSyncStream(roomId);
7164
+ stopRoomChannelListener(roomId);
7165
+ sendToPanel({
7166
+ msg: "room::unavailable",
7167
+ roomId
7168
+ });
7169
+ }
7170
+
7171
+ // src/lib/deprecation.ts
7172
+ var _emittedDeprecationWarnings = /* @__PURE__ */ new Set();
7173
+ function deprecate(message, key = message) {
7174
+ if (process.env.NODE_ENV !== "production") {
7175
+ if (!_emittedDeprecationWarnings.has(key)) {
7176
+ _emittedDeprecationWarnings.add(key);
7177
+ errorWithTitle("Deprecation warning", message);
7178
+ }
6928
7179
  }
6929
- if (existingComment.editedAt === void 0 || comment.editedAt === void 0 || existingComment.editedAt <= comment.editedAt) {
6930
- const updatedComments = thread.comments.map(
6931
- (existingComment2) => existingComment2.id === comment.id ? comment : existingComment2
6932
- );
6933
- const updatedThread = {
6934
- ...thread,
6935
- updatedAt: new Date(
6936
- Math.max(
6937
- _optionalChain([thread, 'access', _152 => _152.updatedAt, 'optionalAccess', _153 => _153.getTime, 'call', _154 => _154()]) || 0,
6938
- _optionalChain([comment, 'access', _155 => _155.editedAt, 'optionalAccess', _156 => _156.getTime, 'call', _157 => _157()]) || comment.createdAt.getTime()
6939
- )
6940
- ),
6941
- comments: updatedComments
6942
- };
6943
- return updatedThread;
7180
+ }
7181
+ function deprecateIf(condition, message, key = message) {
7182
+ if (process.env.NODE_ENV !== "production") {
7183
+ if (condition) {
7184
+ deprecate(message, key);
7185
+ }
6944
7186
  }
6945
- return thread;
6946
7187
  }
6947
- function deleteComment(thread, commentId, deletedAt) {
6948
- if (thread.deletedAt !== void 0) {
6949
- return thread;
7188
+ function throwUsageError(message) {
7189
+ if (process.env.NODE_ENV !== "production") {
7190
+ const usageError = new Error(message);
7191
+ usageError.name = "Usage error";
7192
+ errorWithTitle("Usage error", message);
7193
+ throw usageError;
6950
7194
  }
6951
- const existingComment = thread.comments.find(
6952
- (comment) => comment.id === commentId
6953
- );
6954
- if (existingComment === void 0) {
6955
- return thread;
7195
+ }
7196
+ function errorIf(condition, message) {
7197
+ if (process.env.NODE_ENV !== "production") {
7198
+ if (condition) {
7199
+ throwUsageError(message);
7200
+ }
6956
7201
  }
6957
- if (existingComment.deletedAt !== void 0) {
6958
- return thread;
7202
+ }
7203
+
7204
+ // src/notifications.ts
7205
+ var MARK_INBOX_NOTIFICATIONS_AS_READ_BATCH_DELAY2 = 50;
7206
+ function createNotificationsApi({
7207
+ baseUrl,
7208
+ authManager,
7209
+ currentUserIdStore,
7210
+ fetcher
7211
+ }) {
7212
+ async function fetchJson(endpoint, options, params) {
7213
+ const authValue = await authManager.getAuthValue({
7214
+ requestedScope: "comments:read"
7215
+ });
7216
+ if (authValue.type === "secret" && authValue.token.parsed.k === "acc" /* ACCESS_TOKEN */) {
7217
+ const userId = authValue.token.parsed.uid;
7218
+ currentUserIdStore.set(() => userId);
7219
+ }
7220
+ const url = urljoin(baseUrl, `/v2/c${endpoint}`, params);
7221
+ const response = await fetcher(url.toString(), {
7222
+ ...options,
7223
+ headers: {
7224
+ ..._optionalChain([options, 'optionalAccess', _158 => _158.headers]),
7225
+ Authorization: `Bearer ${getAuthBearerHeaderFromAuthValue(authValue)}`
7226
+ }
7227
+ });
7228
+ if (!response.ok) {
7229
+ if (response.status >= 400 && response.status < 600) {
7230
+ let error3;
7231
+ try {
7232
+ const errorBody = await response.json();
7233
+ error3 = new NotificationsApiError(
7234
+ errorBody.message,
7235
+ response.status,
7236
+ errorBody
7237
+ );
7238
+ } catch (e7) {
7239
+ error3 = new NotificationsApiError(
7240
+ response.statusText,
7241
+ response.status
7242
+ );
7243
+ }
7244
+ throw error3;
7245
+ }
7246
+ }
7247
+ let body;
7248
+ try {
7249
+ body = await response.json();
7250
+ } catch (e8) {
7251
+ body = {};
7252
+ }
7253
+ return body;
6959
7254
  }
6960
- const updatedComments = thread.comments.map(
6961
- (comment) => comment.id === commentId ? {
6962
- ...comment,
6963
- deletedAt,
6964
- body: void 0
6965
- } : comment
6966
- );
6967
- if (!updatedComments.some((comment) => comment.deletedAt === void 0)) {
7255
+ async function getInboxNotifications(options) {
7256
+ const json = await fetchJson("/inbox-notifications", void 0, {
7257
+ limit: _optionalChain([options, 'optionalAccess', _159 => _159.limit]),
7258
+ since: _optionalChain([options, 'optionalAccess', _160 => _160.since, 'optionalAccess', _161 => _161.toISOString, 'call', _162 => _162()])
7259
+ });
6968
7260
  return {
6969
- ...thread,
6970
- deletedAt,
6971
- updatedAt: deletedAt,
6972
- comments: []
7261
+ threads: json.threads.map((thread) => convertToThreadData(thread)),
7262
+ inboxNotifications: json.inboxNotifications.map(
7263
+ (notification) => convertToInboxNotificationData(notification)
7264
+ ),
7265
+ deletedThreads: json.deletedThreads.map(
7266
+ (info) => convertToThreadDeleteInfo(info)
7267
+ ),
7268
+ deletedInboxNotifications: json.deletedInboxNotifications.map(
7269
+ (info) => convertToInboxNotificationDeleteInfo(info)
7270
+ ),
7271
+ meta: {
7272
+ requestedAt: new Date(json.meta.requestedAt)
7273
+ }
6973
7274
  };
6974
7275
  }
6975
- return {
6976
- ...thread,
6977
- updatedAt: deletedAt,
6978
- comments: updatedComments
6979
- };
6980
- }
6981
- function addReaction(thread, commentId, reaction) {
6982
- if (thread.deletedAt !== void 0) {
6983
- return thread;
6984
- }
6985
- const existingComment = thread.comments.find(
6986
- (comment) => comment.id === commentId
6987
- );
6988
- if (existingComment === void 0) {
6989
- return thread;
7276
+ async function getUnreadInboxNotificationsCount() {
7277
+ const { count } = await fetchJson("/inbox-notifications/count");
7278
+ return count;
6990
7279
  }
6991
- if (existingComment.deletedAt !== void 0) {
6992
- return thread;
7280
+ async function markAllInboxNotificationsAsRead() {
7281
+ await fetchJson("/inbox-notifications/read", {
7282
+ method: "POST",
7283
+ headers: {
7284
+ "Content-Type": "application/json"
7285
+ },
7286
+ body: JSON.stringify({ inboxNotificationIds: "all" })
7287
+ });
6993
7288
  }
6994
- const updatedComments = thread.comments.map(
6995
- (comment) => comment.id === commentId ? {
6996
- ...comment,
6997
- reactions: upsertReaction(comment.reactions, reaction)
6998
- } : comment
6999
- );
7000
- return {
7001
- ...thread,
7002
- updatedAt: new Date(
7003
- Math.max(reaction.createdAt.getTime(), _optionalChain([thread, 'access', _158 => _158.updatedAt, 'optionalAccess', _159 => _159.getTime, 'call', _160 => _160()]) || 0)
7004
- ),
7005
- comments: updatedComments
7006
- };
7007
- }
7008
- function removeReaction(thread, commentId, emoji, userId, removedAt) {
7009
- if (thread.deletedAt !== void 0) {
7010
- return thread;
7289
+ async function markInboxNotificationsAsRead(inboxNotificationIds) {
7290
+ await fetchJson("/inbox-notifications/read", {
7291
+ method: "POST",
7292
+ headers: {
7293
+ "Content-Type": "application/json"
7294
+ },
7295
+ body: JSON.stringify({ inboxNotificationIds })
7296
+ });
7011
7297
  }
7012
- const existingComment = thread.comments.find(
7013
- (comment) => comment.id === commentId
7298
+ const batchedMarkInboxNotificationsAsRead = new Batch(
7299
+ async (batchedInboxNotificationIds) => {
7300
+ const inboxNotificationIds = batchedInboxNotificationIds.flat();
7301
+ await markInboxNotificationsAsRead(inboxNotificationIds);
7302
+ return inboxNotificationIds;
7303
+ },
7304
+ { delay: MARK_INBOX_NOTIFICATIONS_AS_READ_BATCH_DELAY2 }
7014
7305
  );
7015
- if (existingComment === void 0) {
7016
- return thread;
7017
- }
7018
- if (existingComment.deletedAt !== void 0) {
7019
- return thread;
7306
+ async function markInboxNotificationAsRead(inboxNotificationId) {
7307
+ await batchedMarkInboxNotificationsAsRead.get(inboxNotificationId);
7020
7308
  }
7021
- const updatedComments = thread.comments.map(
7022
- (comment) => comment.id === commentId ? {
7023
- ...comment,
7024
- reactions: comment.reactions.map(
7025
- (reaction) => reaction.emoji === emoji ? {
7026
- ...reaction,
7027
- users: reaction.users.filter((user) => user.id !== userId)
7028
- } : reaction
7029
- ).filter((reaction) => reaction.users.length > 0)
7030
- // Remove reactions with no users left
7031
- } : comment
7032
- );
7033
7309
  return {
7034
- ...thread,
7035
- updatedAt: new Date(
7036
- Math.max(removedAt.getTime(), _optionalChain([thread, 'access', _161 => _161.updatedAt, 'optionalAccess', _162 => _162.getTime, 'call', _163 => _163()]) || 0)
7037
- ),
7038
- comments: updatedComments
7310
+ getInboxNotifications,
7311
+ getUnreadInboxNotificationsCount,
7312
+ markAllInboxNotificationsAsRead,
7313
+ markInboxNotificationAsRead
7039
7314
  };
7040
7315
  }
7041
- function upsertReaction(reactions, reaction) {
7042
- const existingReaction = reactions.find(
7043
- (existingReaction2) => existingReaction2.emoji === reaction.emoji
7044
- );
7045
- if (existingReaction === void 0) {
7046
- return [
7047
- ...reactions,
7048
- {
7049
- emoji: reaction.emoji,
7050
- createdAt: reaction.createdAt,
7051
- users: [{ id: reaction.userId }]
7052
- }
7053
- ];
7054
- }
7055
- if (existingReaction.users.some((user) => user.id === reaction.userId) === false) {
7056
- return reactions.map(
7057
- (existingReaction2) => existingReaction2.emoji === reaction.emoji ? {
7058
- ...existingReaction2,
7059
- users: [...existingReaction2.users, { id: reaction.userId }]
7060
- } : existingReaction2
7061
- );
7062
- }
7063
- return reactions;
7064
- }
7065
7316
 
7066
7317
  // src/client.ts
7067
7318
  var MIN_THROTTLE = 16;
@@ -7148,12 +7399,12 @@ function createClient(options) {
7148
7399
  createSocket: makeCreateSocketDelegateForRoom(
7149
7400
  roomId,
7150
7401
  baseUrl,
7151
- _optionalChain([clientOptions, 'access', _164 => _164.polyfills, 'optionalAccess', _165 => _165.WebSocket])
7402
+ _optionalChain([clientOptions, 'access', _163 => _163.polyfills, 'optionalAccess', _164 => _164.WebSocket])
7152
7403
  ),
7153
7404
  authenticate: makeAuthDelegateForRoom(roomId, authManager)
7154
7405
  })),
7155
7406
  enableDebugLogging: clientOptions.enableDebugLogging,
7156
- unstable_batchedUpdates: _optionalChain([options2, 'optionalAccess', _166 => _166.unstable_batchedUpdates]),
7407
+ unstable_batchedUpdates: _optionalChain([options2, 'optionalAccess', _165 => _165.unstable_batchedUpdates]),
7157
7408
  baseUrl,
7158
7409
  unstable_fallbackToHTTP: !!clientOptions.unstable_fallbackToHTTP,
7159
7410
  unstable_streamData: !!clientOptions.unstable_streamData
@@ -7169,7 +7420,7 @@ function createClient(options) {
7169
7420
  const shouldConnect = _nullishCoalesce(_nullishCoalesce(options2.autoConnect, () => ( options2.shouldInitiallyConnect)), () => ( true));
7170
7421
  if (shouldConnect) {
7171
7422
  if (typeof atob === "undefined") {
7172
- if (_optionalChain([clientOptions, 'access', _167 => _167.polyfills, 'optionalAccess', _168 => _168.atob]) === void 0) {
7423
+ if (_optionalChain([clientOptions, 'access', _166 => _166.polyfills, 'optionalAccess', _167 => _167.atob]) === void 0) {
7173
7424
  throw new Error(
7174
7425
  "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"
7175
7426
  );
@@ -7185,11 +7436,11 @@ function createClient(options) {
7185
7436
  return room;
7186
7437
  }
7187
7438
  function getRoom(roomId) {
7188
- const room = _optionalChain([roomsById, 'access', _169 => _169.get, 'call', _170 => _170(roomId), 'optionalAccess', _171 => _171.room]);
7439
+ const room = _optionalChain([roomsById, 'access', _168 => _168.get, 'call', _169 => _169(roomId), 'optionalAccess', _170 => _170.room]);
7189
7440
  return room ? room : null;
7190
7441
  }
7191
7442
  function forceLeave(roomId) {
7192
- const unsubs = _nullishCoalesce(_optionalChain([roomsById, 'access', _172 => _172.get, 'call', _173 => _173(roomId), 'optionalAccess', _174 => _174.unsubs]), () => ( /* @__PURE__ */ new Set()));
7443
+ const unsubs = _nullishCoalesce(_optionalChain([roomsById, 'access', _171 => _171.get, 'call', _172 => _172(roomId), 'optionalAccess', _173 => _173.unsubs]), () => ( /* @__PURE__ */ new Set()));
7193
7444
  for (const unsub of unsubs) {
7194
7445
  unsub();
7195
7446
  }
@@ -7210,7 +7461,7 @@ function createClient(options) {
7210
7461
  markInboxNotificationAsRead
7211
7462
  } = createNotificationsApi({
7212
7463
  baseUrl,
7213
- fetcher: _optionalChain([clientOptions, 'access', _175 => _175.polyfills, 'optionalAccess', _176 => _176.fetch]) || /* istanbul ignore next */
7464
+ fetcher: _optionalChain([clientOptions, 'access', _174 => _174.polyfills, 'optionalAccess', _175 => _175.fetch]) || /* istanbul ignore next */
7214
7465
  fetch,
7215
7466
  authManager,
7216
7467
  currentUserIdStore
@@ -7224,7 +7475,7 @@ function createClient(options) {
7224
7475
  const usersStore = createBatchStore(
7225
7476
  async (batchedUserIds) => {
7226
7477
  const userIds = batchedUserIds.flat();
7227
- const users = await _optionalChain([resolveUsers, 'optionalCall', _177 => _177({ userIds })]);
7478
+ const users = await _optionalChain([resolveUsers, 'optionalCall', _176 => _176({ userIds })]);
7228
7479
  warnIfNoResolveUsers();
7229
7480
  return _nullishCoalesce(users, () => ( userIds.map(() => void 0)));
7230
7481
  },
@@ -7238,7 +7489,7 @@ function createClient(options) {
7238
7489
  const roomsInfoStore = createBatchStore(
7239
7490
  async (batchedRoomIds) => {
7240
7491
  const roomIds = batchedRoomIds.flat();
7241
- const roomsInfo = await _optionalChain([resolveRoomsInfo, 'optionalCall', _178 => _178({ roomIds })]);
7492
+ const roomsInfo = await _optionalChain([resolveRoomsInfo, 'optionalCall', _177 => _177({ roomIds })]);
7242
7493
  warnIfNoResolveRoomsInfo();
7243
7494
  return _nullishCoalesce(roomsInfo, () => ( roomIds.map(() => void 0)));
7244
7495
  },
@@ -7261,6 +7512,14 @@ function createClient(options) {
7261
7512
  markAllInboxNotificationsAsRead,
7262
7513
  markInboxNotificationAsRead
7263
7514
  },
7515
+ comments: {
7516
+ createThreadId,
7517
+ createCommentId,
7518
+ createInboxNotificationId,
7519
+ selectedThreads,
7520
+ selectedInboxNotifications,
7521
+ selectNotificationSettings
7522
+ },
7264
7523
  currentUserIdStore,
7265
7524
  resolveMentionSuggestions: clientOptions.resolveMentionSuggestions,
7266
7525
  cacheStore,
@@ -7355,7 +7614,7 @@ var commentBodyElementsTypes = {
7355
7614
  mention: "inline"
7356
7615
  };
7357
7616
  function traverseCommentBody(body, elementOrVisitor, possiblyVisitor) {
7358
- if (!body || !_optionalChain([body, 'optionalAccess', _179 => _179.content])) {
7617
+ if (!body || !_optionalChain([body, 'optionalAccess', _178 => _178.content])) {
7359
7618
  return;
7360
7619
  }
7361
7620
  const element = typeof elementOrVisitor === "string" ? elementOrVisitor : void 0;
@@ -7365,13 +7624,13 @@ function traverseCommentBody(body, elementOrVisitor, possiblyVisitor) {
7365
7624
  for (const block of body.content) {
7366
7625
  if (type === "all" || type === "block") {
7367
7626
  if (guard(block)) {
7368
- _optionalChain([visitor, 'optionalCall', _180 => _180(block)]);
7627
+ _optionalChain([visitor, 'optionalCall', _179 => _179(block)]);
7369
7628
  }
7370
7629
  }
7371
7630
  if (type === "all" || type === "inline") {
7372
7631
  for (const inline of block.children) {
7373
7632
  if (guard(inline)) {
7374
- _optionalChain([visitor, 'optionalCall', _181 => _181(inline)]);
7633
+ _optionalChain([visitor, 'optionalCall', _180 => _180(inline)]);
7375
7634
  }
7376
7635
  }
7377
7636
  }
@@ -7396,7 +7655,7 @@ async function resolveUsersInCommentBody(body, resolveUsers) {
7396
7655
  userIds
7397
7656
  });
7398
7657
  for (const [index, userId] of userIds.entries()) {
7399
- const user = _optionalChain([users, 'optionalAccess', _182 => _182[index]]);
7658
+ const user = _optionalChain([users, 'optionalAccess', _181 => _181[index]]);
7400
7659
  if (user) {
7401
7660
  resolvedUsers.set(userId, user);
7402
7661
  }
@@ -7519,7 +7778,7 @@ var stringifyCommentBodyPlainElements = {
7519
7778
  text: ({ element }) => element.text,
7520
7779
  link: ({ element }) => element.url,
7521
7780
  mention: ({ element, user }) => {
7522
- return `@${_nullishCoalesce(_optionalChain([user, 'optionalAccess', _183 => _183.name]), () => ( element.id))}`;
7781
+ return `@${_nullishCoalesce(_optionalChain([user, 'optionalAccess', _182 => _182.name]), () => ( element.id))}`;
7523
7782
  }
7524
7783
  };
7525
7784
  var stringifyCommentBodyHtmlElements = {
@@ -7549,7 +7808,7 @@ var stringifyCommentBodyHtmlElements = {
7549
7808
  return html`<a href="${href}" target="_blank" rel="noopener noreferrer">${element.url}</a>`;
7550
7809
  },
7551
7810
  mention: ({ element, user }) => {
7552
- return html`<span data-mention>@${_nullishCoalesce(_optionalChain([user, 'optionalAccess', _184 => _184.name]), () => ( element.id))}</span>`;
7811
+ return html`<span data-mention>@${_nullishCoalesce(_optionalChain([user, 'optionalAccess', _183 => _183.name]), () => ( element.id))}</span>`;
7553
7812
  }
7554
7813
  };
7555
7814
  var stringifyCommentBodyMarkdownElements = {
@@ -7579,19 +7838,19 @@ var stringifyCommentBodyMarkdownElements = {
7579
7838
  return markdown`[${element.url}](${href})`;
7580
7839
  },
7581
7840
  mention: ({ element, user }) => {
7582
- return markdown`@${_nullishCoalesce(_optionalChain([user, 'optionalAccess', _185 => _185.name]), () => ( element.id))}`;
7841
+ return markdown`@${_nullishCoalesce(_optionalChain([user, 'optionalAccess', _184 => _184.name]), () => ( element.id))}`;
7583
7842
  }
7584
7843
  };
7585
7844
  async function stringifyCommentBody(body, options) {
7586
- const format = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _186 => _186.format]), () => ( "plain"));
7587
- const separator = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _187 => _187.separator]), () => ( (format === "markdown" ? "\n\n" : "\n")));
7845
+ const format = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _185 => _185.format]), () => ( "plain"));
7846
+ const separator = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _186 => _186.separator]), () => ( (format === "markdown" ? "\n\n" : "\n")));
7588
7847
  const elements = {
7589
7848
  ...format === "html" ? stringifyCommentBodyHtmlElements : format === "markdown" ? stringifyCommentBodyMarkdownElements : stringifyCommentBodyPlainElements,
7590
- ..._optionalChain([options, 'optionalAccess', _188 => _188.elements])
7849
+ ..._optionalChain([options, 'optionalAccess', _187 => _187.elements])
7591
7850
  };
7592
7851
  const resolvedUsers = await resolveUsersInCommentBody(
7593
7852
  body,
7594
- _optionalChain([options, 'optionalAccess', _189 => _189.resolveUsers])
7853
+ _optionalChain([options, 'optionalAccess', _188 => _188.resolveUsers])
7595
7854
  );
7596
7855
  const blocks = body.content.flatMap((block, blockIndex) => {
7597
7856
  switch (block.type) {
@@ -7866,12 +8125,12 @@ function legacy_patchImmutableNode(state, path, update) {
7866
8125
  }
7867
8126
  const newState = Object.assign({}, state);
7868
8127
  for (const key in update.updates) {
7869
- if (_optionalChain([update, 'access', _190 => _190.updates, 'access', _191 => _191[key], 'optionalAccess', _192 => _192.type]) === "update") {
8128
+ if (_optionalChain([update, 'access', _189 => _189.updates, 'access', _190 => _190[key], 'optionalAccess', _191 => _191.type]) === "update") {
7870
8129
  const val = update.node.get(key);
7871
8130
  if (val !== void 0) {
7872
8131
  newState[key] = lsonToJson(val);
7873
8132
  }
7874
- } else if (_optionalChain([update, 'access', _193 => _193.updates, 'access', _194 => _194[key], 'optionalAccess', _195 => _195.type]) === "delete") {
8133
+ } else if (_optionalChain([update, 'access', _192 => _192.updates, 'access', _193 => _193[key], 'optionalAccess', _194 => _194.type]) === "delete") {
7875
8134
  delete newState[key];
7876
8135
  }
7877
8136
  }
@@ -7932,12 +8191,12 @@ function legacy_patchImmutableNode(state, path, update) {
7932
8191
  }
7933
8192
  const newState = Object.assign({}, state);
7934
8193
  for (const key in update.updates) {
7935
- if (_optionalChain([update, 'access', _196 => _196.updates, 'access', _197 => _197[key], 'optionalAccess', _198 => _198.type]) === "update") {
8194
+ if (_optionalChain([update, 'access', _195 => _195.updates, 'access', _196 => _196[key], 'optionalAccess', _197 => _197.type]) === "update") {
7936
8195
  const value = update.node.get(key);
7937
8196
  if (value !== void 0) {
7938
8197
  newState[key] = lsonToJson(value);
7939
8198
  }
7940
- } else if (_optionalChain([update, 'access', _199 => _199.updates, 'access', _200 => _200[key], 'optionalAccess', _201 => _201.type]) === "delete") {
8199
+ } else if (_optionalChain([update, 'access', _198 => _198.updates, 'access', _199 => _199[key], 'optionalAccess', _200 => _200.type]) === "delete") {
7941
8200
  delete newState[key];
7942
8201
  }
7943
8202
  }
@@ -8155,5 +8414,7 @@ detectDupes(PKG_NAME, PKG_VERSION, PKG_FORMAT);
8155
8414
 
8156
8415
 
8157
8416
 
8158
- exports.ClientMsgCode = ClientMsgCode; exports.CommentsApiError = CommentsApiError; exports.CrdtType = CrdtType; exports.LiveList = LiveList; exports.LiveMap = LiveMap; exports.LiveObject = LiveObject; exports.NotificationsApiError = NotificationsApiError; exports.OpCode = OpCode; exports.ServerMsgCode = ServerMsgCode; exports.WebsocketCloseCodes = WebsocketCloseCodes; exports.ackOp = ackOp; exports.addReaction = addReaction; exports.applyOptimisticUpdates = applyOptimisticUpdates; exports.asPos = asPos; exports.assert = assert; exports.assertNever = assertNever; exports.b64decode = b64decode; exports.cloneLson = cloneLson; exports.console = fancy_console_exports; exports.convertToCommentData = convertToCommentData; exports.convertToCommentUserReaction = convertToCommentUserReaction; exports.convertToThreadData = convertToThreadData; exports.createClient = createClient; exports.deleteComment = deleteComment; exports.deprecate = deprecate; exports.deprecateIf = deprecateIf; exports.detectDupes = detectDupes; exports.errorIf = errorIf; exports.freeze = freeze; exports.getMentionedIdsFromCommentBody = getMentionedIdsFromCommentBody; exports.isChildCrdt = isChildCrdt; exports.isJsonArray = isJsonArray; exports.isJsonObject = isJsonObject; exports.isJsonScalar = isJsonScalar; exports.isLiveNode = isLiveNode; exports.isPlainObject = isPlainObject; exports.isRootCrdt = isRootCrdt; exports.kInternal = kInternal; exports.legacy_patchImmutableObject = legacy_patchImmutableObject; exports.lsonToJson = lsonToJson; exports.makeEventSource = makeEventSource; exports.makePoller = makePoller; exports.makePosition = makePosition; exports.nn = nn; exports.patchLiveObjectKey = patchLiveObjectKey; exports.raise = raise; exports.removeReaction = removeReaction; exports.shallow = shallow; exports.stringify = stringify; exports.stringifyCommentBody = stringifyCommentBody; exports.throwUsageError = throwUsageError; exports.toPlainLson = toPlainLson; exports.tryParseJson = tryParseJson; exports.upsertComment = upsertComment; exports.withTimeout = withTimeout;
8417
+
8418
+
8419
+ exports.ClientMsgCode = ClientMsgCode; exports.CommentsApiError = CommentsApiError; exports.CrdtType = CrdtType; exports.LiveList = LiveList; exports.LiveMap = LiveMap; exports.LiveObject = LiveObject; exports.NotificationsApiError = NotificationsApiError; exports.OpCode = OpCode; exports.ServerMsgCode = ServerMsgCode; exports.WebsocketCloseCodes = WebsocketCloseCodes; exports.ackOp = ackOp; exports.addReaction = addReaction; exports.applyOptimisticUpdates = applyOptimisticUpdates; exports.asPos = asPos; exports.assert = assert; exports.assertNever = assertNever; exports.b64decode = b64decode; exports.cloneLson = cloneLson; exports.console = fancy_console_exports; exports.convertToCommentData = convertToCommentData; exports.convertToCommentUserReaction = convertToCommentUserReaction; exports.convertToInboxNotificationData = convertToInboxNotificationData; exports.convertToThreadData = convertToThreadData; exports.createClient = createClient; exports.deleteComment = deleteComment; exports.deprecate = deprecate; exports.deprecateIf = deprecateIf; exports.detectDupes = detectDupes; exports.errorIf = errorIf; exports.freeze = freeze; exports.getMentionedIdsFromCommentBody = getMentionedIdsFromCommentBody; exports.isChildCrdt = isChildCrdt; exports.isJsonArray = isJsonArray; exports.isJsonObject = isJsonObject; exports.isJsonScalar = isJsonScalar; exports.isLiveNode = isLiveNode; exports.isPlainObject = isPlainObject; exports.isRootCrdt = isRootCrdt; exports.kInternal = kInternal; exports.legacy_patchImmutableObject = legacy_patchImmutableObject; exports.lsonToJson = lsonToJson; exports.makeEventSource = makeEventSource; exports.makePoller = makePoller; exports.makePosition = makePosition; exports.nn = nn; exports.objectToQuery = objectToQuery; exports.patchLiveObjectKey = patchLiveObjectKey; exports.raise = raise; exports.removeReaction = removeReaction; exports.shallow = shallow; exports.stringify = stringify; exports.stringifyCommentBody = stringifyCommentBody; exports.throwUsageError = throwUsageError; exports.toPlainLson = toPlainLson; exports.tryParseJson = tryParseJson; exports.upsertComment = upsertComment; exports.withTimeout = withTimeout;
8159
8420
  //# sourceMappingURL=index.js.map