@liveblocks/core 1.1.0 → 1.1.1-dual2

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.d.ts CHANGED
@@ -669,31 +669,6 @@ declare type Delegates<T extends BaseAuthResult> = {
669
669
  createSocket: (token: T) => IWebSocketInstance;
670
670
  };
671
671
 
672
- declare type AppOnlyAuthToken = {
673
- appId: string;
674
- roomId?: never;
675
- scopes: string[];
676
- };
677
- declare type RoomAuthToken = {
678
- appId: string;
679
- roomId: string;
680
- scopes: string[];
681
- actor: number;
682
- maxConnectionsPerRoom?: number;
683
- info?: Json;
684
- groupIds?: string[];
685
- } & ({
686
- id: string;
687
- anonymousId?: never;
688
- } | {
689
- id?: never;
690
- anonymousId: string;
691
- });
692
- declare type AuthToken = AppOnlyAuthToken | RoomAuthToken;
693
- declare function isAppOnlyAuthToken(data: JsonObject): data is AppOnlyAuthToken;
694
- declare function isRoomAuthToken(data: JsonObject): data is RoomAuthToken;
695
- declare function isAuthToken(data: JsonObject): data is AuthToken;
696
-
697
672
  declare type ReadonlyArrayWithLegacyMethods<T> = readonly T[] & {
698
673
  /**
699
674
  * @deprecated Prefer the normal .length property on arrays.
@@ -711,11 +686,11 @@ declare function asArrayWithLegacyMethods<T>(arr: readonly T[]): ReadonlyArrayWi
711
686
  */
712
687
  declare type User<TPresence extends JsonObject, TUserMeta extends BaseUserMeta> = {
713
688
  /**
714
- * The connection id of the user. It is unique and increment at every new connection.
689
+ * The connection ID of the User. It is unique and increment at every new connection.
715
690
  */
716
691
  readonly connectionId: number;
717
692
  /**
718
- * The id of the user that has been set in the authentication endpoint.
693
+ * The ID of the User that has been set in the authentication endpoint.
719
694
  * Useful to get additional information about the connected user.
720
695
  */
721
696
  readonly id: TUserMeta["id"];
@@ -724,7 +699,7 @@ declare type User<TPresence extends JsonObject, TUserMeta extends BaseUserMeta>
724
699
  */
725
700
  readonly info: TUserMeta["info"];
726
701
  /**
727
- * The user presence.
702
+ * The user’s presence data.
728
703
  */
729
704
  readonly presence: TPresence;
730
705
  /**
@@ -1077,6 +1052,17 @@ declare type Room<TPresence extends JsonObject, TStorage extends LsonObject, TUs
1077
1052
  */
1078
1053
  addToHistory: boolean;
1079
1054
  }): void;
1055
+ /**
1056
+ *
1057
+ * Sends Yjs document updates to liveblocks server
1058
+ *
1059
+ * @param {string} data the doc update to send to the server, base64 encoded uint8array
1060
+ */
1061
+ updateYDoc(data: string): void;
1062
+ /**
1063
+ * Sends a request for the current document from liveblocks server
1064
+ */
1065
+ fetchYDoc(stateVector: string): void;
1080
1066
  /**
1081
1067
  * Broadcasts an event to other users in the room. Event broadcasted to the room can be listened with {@link Room.subscribe}("event").
1082
1068
  * @param {any} event the event to broadcast. Should be serializable to JSON
@@ -1134,6 +1120,7 @@ declare type Room<TPresence extends JsonObject, TStorage extends LsonObject, TUs
1134
1120
  */
1135
1121
  readonly storageDidLoad: Observable<void>;
1136
1122
  readonly storageStatus: Observable<StorageStatus>;
1123
+ readonly ydoc: Observable<string>;
1137
1124
  };
1138
1125
  /**
1139
1126
  * Batches modifications made during the given function.
@@ -1456,12 +1443,14 @@ declare enum ClientMsgCode {
1456
1443
  UPDATE_PRESENCE = 100,
1457
1444
  BROADCAST_EVENT = 103,
1458
1445
  FETCH_STORAGE = 200,
1459
- UPDATE_STORAGE = 201
1446
+ UPDATE_STORAGE = 201,
1447
+ FETCH_YDOC = 300,
1448
+ UPDATE_YDOC = 301
1460
1449
  }
1461
1450
  /**
1462
1451
  * Messages that can be sent from the client to the server.
1463
1452
  */
1464
- declare type ClientMsg<TPresence extends JsonObject, TRoomEvent extends Json> = BroadcastEventClientMsg<TRoomEvent> | UpdatePresenceClientMsg<TPresence> | UpdateStorageClientMsg | FetchStorageClientMsg;
1453
+ declare type ClientMsg<TPresence extends JsonObject, TRoomEvent extends Json> = BroadcastEventClientMsg<TRoomEvent> | UpdatePresenceClientMsg<TPresence> | UpdateStorageClientMsg | FetchStorageClientMsg | FetchYDocClientMsg | UpdateYDocClientMsg;
1465
1454
  declare type BroadcastEventClientMsg<TRoomEvent extends Json> = {
1466
1455
  type: ClientMsgCode.BROADCAST_EVENT;
1467
1456
  event: TRoomEvent;
@@ -1499,6 +1488,14 @@ declare type UpdateStorageClientMsg = {
1499
1488
  declare type FetchStorageClientMsg = {
1500
1489
  readonly type: ClientMsgCode.FETCH_STORAGE;
1501
1490
  };
1491
+ declare type FetchYDocClientMsg = {
1492
+ readonly type: ClientMsgCode.FETCH_YDOC;
1493
+ readonly vector: string;
1494
+ };
1495
+ declare type UpdateYDocClientMsg = {
1496
+ readonly type: ClientMsgCode.UPDATE_YDOC;
1497
+ readonly update: string;
1498
+ };
1502
1499
 
1503
1500
  declare type IdTuple<T> = [id: string, value: T];
1504
1501
  declare enum CrdtType {
@@ -1548,12 +1545,13 @@ declare enum ServerMsgCode {
1548
1545
  ROOM_STATE = 104,
1549
1546
  INITIAL_STORAGE_STATE = 200,
1550
1547
  UPDATE_STORAGE = 201,
1551
- REJECT_STORAGE_OP = 299
1548
+ REJECT_STORAGE_OP = 299,
1549
+ UPDATE_YDOC = 300
1552
1550
  }
1553
1551
  /**
1554
1552
  * Messages that can be sent from the server to the client.
1555
1553
  */
1556
- declare type ServerMsg<TPresence extends JsonObject, TUserMeta extends BaseUserMeta, TRoomEvent extends Json> = UpdatePresenceServerMsg<TPresence> | UserJoinServerMsg<TUserMeta> | UserLeftServerMsg | BroadcastedEventServerMsg<TRoomEvent> | RoomStateServerMsg<TUserMeta> | InitialDocumentStateServerMsg | UpdateStorageServerMsg | RejectedStorageOpServerMsg;
1554
+ declare type ServerMsg<TPresence extends JsonObject, TUserMeta extends BaseUserMeta, TRoomEvent extends Json> = UpdatePresenceServerMsg<TPresence> | UserJoinServerMsg<TUserMeta> | UserLeftServerMsg | BroadcastedEventServerMsg<TRoomEvent> | RoomStateServerMsg<TUserMeta> | InitialDocumentStateServerMsg | UpdateStorageServerMsg | RejectedStorageOpServerMsg | YDocUpdate;
1557
1555
  /**
1558
1556
  * Sent by the WebSocket server and broadcasted to all clients to announce that
1559
1557
  * a User updated their presence. For example, when a user moves their cursor.
@@ -1636,6 +1634,14 @@ declare type UserLeftServerMsg = {
1636
1634
  readonly type: ServerMsgCode.USER_LEFT;
1637
1635
  readonly actor: number;
1638
1636
  };
1637
+ /**
1638
+ * Sent by the WebSocket server when the ydoc is updated or when requested based on stateVector passed.
1639
+ * Contains a base64 encoded update
1640
+ */
1641
+ declare type YDocUpdate = {
1642
+ readonly type: ServerMsgCode.UPDATE_YDOC;
1643
+ readonly update: string;
1644
+ };
1639
1645
  /**
1640
1646
  * Sent by the WebSocket server and broadcasted to all clients to announce that
1641
1647
  * a User broadcasted an Event to everyone in the Room.
@@ -1884,4 +1890,4 @@ declare type EnsureJson<T> = [
1884
1890
  [K in keyof T]: EnsureJson<T[K]>;
1885
1891
  };
1886
1892
 
1887
- export { AckOp, AppOnlyAuthToken, AuthToken, BaseAuthResult, BaseUserMeta, BroadcastEventClientMsg, BroadcastOptions, BroadcastedEventServerMsg, Client, ClientMsg, ClientMsgCode, CrdtType, CreateChildOp, CreateListOp, CreateMapOp, CreateObjectOp, CreateOp, CreateRegisterOp, CreateRootObjectOp, Delegates, DeleteCrdtOp, DeleteObjectKeyOp, DevToolsTreeNode as DevTools, protocol as DevToolsMsg, EnsureJson, FetchStorageClientMsg, History, IWebSocket, IWebSocketCloseEvent, IWebSocketEvent, IWebSocketInstance, IWebSocketMessageEvent, IdTuple, Immutable, InitialDocumentStateServerMsg, Json, JsonArray, JsonObject, JsonScalar, LegacyConnectionStatus, LiveList, LiveListUpdate, LiveMap, LiveMapUpdate, LiveNode, LiveObject, LiveObjectUpdate, LiveStructure, LostConnectionEvent, Lson, LsonObject, NodeMap, Op, OpCode, Others, ParentToChildNodeMap, PlainLson, PlainLsonFields, PlainLsonList, PlainLsonMap, PlainLsonObject, RejectedStorageOpServerMsg, Resolve, Room, RoomAuthToken, RoomInitializers, RoomStateServerMsg, SerializedChild, SerializedCrdt, SerializedList, SerializedMap, SerializedObject, SerializedRegister, SerializedRootObject, ServerMsg, ServerMsgCode, SetParentKeyOp, Status, StorageStatus, StorageUpdate, ToImmutable, ToJson, UpdateObjectOp, UpdatePresenceClientMsg, UpdatePresenceServerMsg, UpdateStorageClientMsg, UpdateStorageServerMsg, User, UserJoinServerMsg, UserLeftServerMsg, WebsocketCloseCodes, asArrayWithLegacyMethods, asPos, assert, assertNever, b64decode, createClient, deprecate, deprecateIf, errorIf, freeze, isAppOnlyAuthToken, isAuthToken, isChildCrdt, isJsonArray, isJsonObject, isJsonScalar, isPlainObject, isRoomAuthToken, isRootCrdt, legacy_patchImmutableObject, lsonToJson, makePosition, nn, patchLiveObjectKey, shallow, throwUsageError, toPlainLson, tryParseJson, withTimeout };
1893
+ export { AckOp, BaseAuthResult, BaseUserMeta, BroadcastEventClientMsg, BroadcastOptions, BroadcastedEventServerMsg, Client, ClientMsg, ClientMsgCode, CrdtType, CreateChildOp, CreateListOp, CreateMapOp, CreateObjectOp, CreateOp, CreateRegisterOp, CreateRootObjectOp, Delegates, DeleteCrdtOp, DeleteObjectKeyOp, DevToolsTreeNode as DevTools, protocol as DevToolsMsg, EnsureJson, FetchStorageClientMsg, FetchYDocClientMsg, History, IWebSocket, IWebSocketCloseEvent, IWebSocketEvent, IWebSocketInstance, IWebSocketMessageEvent, IdTuple, Immutable, InitialDocumentStateServerMsg, Json, JsonArray, JsonObject, JsonScalar, LegacyConnectionStatus, LiveList, LiveListUpdate, LiveMap, LiveMapUpdate, LiveNode, LiveObject, LiveObjectUpdate, LiveStructure, LostConnectionEvent, Lson, LsonObject, NodeMap, Op, OpCode, Others, ParentToChildNodeMap, PlainLson, PlainLsonFields, PlainLsonList, PlainLsonMap, PlainLsonObject, RejectedStorageOpServerMsg, Resolve, Room, RoomInitializers, RoomStateServerMsg, SerializedChild, SerializedCrdt, SerializedList, SerializedMap, SerializedObject, SerializedRegister, SerializedRootObject, ServerMsg, ServerMsgCode, SetParentKeyOp, Status, StorageStatus, StorageUpdate, ToImmutable, ToJson, UpdateObjectOp, UpdatePresenceClientMsg, UpdatePresenceServerMsg, UpdateStorageClientMsg, UpdateStorageServerMsg, UpdateYDocClientMsg, User, UserJoinServerMsg, UserLeftServerMsg, WebsocketCloseCodes, asArrayWithLegacyMethods, asPos, assert, assertNever, b64decode, createClient, deprecate, deprecateIf, errorIf, freeze, isChildCrdt, isJsonArray, isJsonObject, isJsonScalar, isPlainObject, isRootCrdt, legacy_patchImmutableObject, lsonToJson, makePosition, nn, patchLiveObjectKey, shallow, throwUsageError, toPlainLson, tryParseJson, withTimeout };
package/dist/index.js CHANGED
@@ -17,18 +17,6 @@ var __spreadValues = (a, b) => {
17
17
  return a;
18
18
  };
19
19
  var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
20
- var __objRest = (source, exclude) => {
21
- var target = {};
22
- for (var prop in source)
23
- if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
24
- target[prop] = source[prop];
25
- if (source != null && __getOwnPropSymbols)
26
- for (var prop of __getOwnPropSymbols(source)) {
27
- if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
28
- target[prop] = source[prop];
29
- }
30
- return target;
31
- };
32
20
  var __async = (__this, __arguments, generator) => {
33
21
  return new Promise((resolve, reject) => {
34
22
  var fulfilled = (value) => {
@@ -157,7 +145,7 @@ var onMessageFromPanel = eventSource.observable;
157
145
  // src/devtools/index.ts
158
146
  var VERSION = true ? (
159
147
  /* istanbul ignore next */
160
- "1.1.0"
148
+ "1.1.1-dual2"
161
149
  ) : "dev";
162
150
  var _devtoolsSetupHasRun = false;
163
151
  function setupDevTools(getAllRooms) {
@@ -472,7 +460,11 @@ var FSM = class {
472
460
  }
473
461
  get currentState() {
474
462
  if (this.currentStateOrNull === null) {
475
- throw new Error("Not started yet");
463
+ if (this.runningState === 0 /* NOT_STARTED_YET */) {
464
+ throw new Error("Not started yet");
465
+ } else {
466
+ throw new Error("Already stopped");
467
+ }
476
468
  }
477
469
  return this.currentStateOrNull;
478
470
  }
@@ -494,10 +486,10 @@ var FSM = class {
494
486
  */
495
487
  stop() {
496
488
  if (this.runningState !== 1 /* STARTED */) {
497
- throw new Error("Cannot stop a state machine that isn't started yet");
489
+ throw new Error("Cannot stop a state machine that hasn't started yet");
498
490
  }
499
- this.runningState = 2 /* STOPPED */;
500
491
  this.exit(null);
492
+ this.runningState = 2 /* STOPPED */;
501
493
  this.currentStateOrNull = null;
502
494
  }
503
495
  constructor(initialContext) {
@@ -665,10 +657,11 @@ var FSM = class {
665
657
  * Exits the current state, and executes any necessary cleanup functions.
666
658
  * Call this before changing the current state to the next state.
667
659
  *
668
- * @param levels Defines how many "levels" of nesting will be exited. For
669
- * example, if you transition from `foo.bar.qux` to `foo.bar.baz`, then
670
- * the level is 1. But if you transition from `foo.bar.qux` to `bla.bla`,
671
- * then the level is 3.
660
+ * @param levels Defines how many "levels" of nesting will be
661
+ * exited. For example, if you transition from `foo.bar.qux` to
662
+ * `foo.bar.baz`, then the level is 1. But if you transition from
663
+ * `foo.bar.qux` to `bla.bla`, then the level is 3.
664
+ * If `null`, it will exit all levels.
672
665
  */
673
666
  exit(levels) {
674
667
  this.eventHub.willExitState.notify(this.currentState);
@@ -707,12 +700,15 @@ var FSM = class {
707
700
  * transition to happen. When that happens, will trigger side effects.
708
701
  */
709
702
  send(event) {
703
+ if (!this.knownEventTypes.has(event.type)) {
704
+ throw new Error(`Invalid event ${JSON.stringify(event.type)}`);
705
+ }
706
+ if (this.runningState === 2 /* STOPPED */) {
707
+ return;
708
+ }
710
709
  const targetFn = this.getTargetFn(event.type);
711
710
  if (targetFn !== void 0) {
712
711
  return this.transition(event, targetFn);
713
- }
714
- if (!this.knownEventTypes.has(event.type)) {
715
- throw new Error(`Invalid event ${JSON.stringify(event.type)}`);
716
712
  } else {
717
713
  this.eventHub.didIgnoreEvent.notify(event);
718
714
  }
@@ -1711,7 +1707,7 @@ function nanoid(length = 7) {
1711
1707
  }
1712
1708
 
1713
1709
  // src/crdts/LiveRegister.ts
1714
- var LiveRegister = class extends AbstractCrdt {
1710
+ var LiveRegister = class _LiveRegister extends AbstractCrdt {
1715
1711
  constructor(data) {
1716
1712
  super();
1717
1713
  this._data = data;
@@ -1721,7 +1717,7 @@ var LiveRegister = class extends AbstractCrdt {
1721
1717
  }
1722
1718
  /** @internal */
1723
1719
  static _deserialize([id, item], _parentToChildren, pool) {
1724
- const register = new LiveRegister(item.data);
1720
+ const register = new _LiveRegister(item.data);
1725
1721
  register._attach(id, pool);
1726
1722
  return register;
1727
1723
  }
@@ -1789,7 +1785,7 @@ function compareNodePosition(itemA, itemB) {
1789
1785
  const posB = itemB._parentPos;
1790
1786
  return posA === posB ? 0 : posA < posB ? -1 : 1;
1791
1787
  }
1792
- var LiveList = class extends AbstractCrdt {
1788
+ var LiveList = class _LiveList extends AbstractCrdt {
1793
1789
  constructor(items = []) {
1794
1790
  super();
1795
1791
  this._items = [];
@@ -1806,7 +1802,7 @@ var LiveList = class extends AbstractCrdt {
1806
1802
  }
1807
1803
  /** @internal */
1808
1804
  static _deserialize([id], parentToChildren, pool) {
1809
- const list = new LiveList();
1805
+ const list = new _LiveList();
1810
1806
  list._attach(id, pool);
1811
1807
  const children = parentToChildren.get(id);
1812
1808
  if (children === void 0) {
@@ -2796,7 +2792,7 @@ var freeze = process.env.NODE_ENV === "production" ? (
2796
2792
  ) : Object.freeze;
2797
2793
 
2798
2794
  // src/crdts/LiveMap.ts
2799
- var LiveMap = class extends AbstractCrdt {
2795
+ var LiveMap = class _LiveMap extends AbstractCrdt {
2800
2796
  constructor(entries2) {
2801
2797
  super();
2802
2798
  this.unacknowledgedSet = /* @__PURE__ */ new Map();
@@ -2837,7 +2833,7 @@ var LiveMap = class extends AbstractCrdt {
2837
2833
  * @internal
2838
2834
  */
2839
2835
  static _deserialize([id, _item], parentToChildren, pool) {
2840
- const map = new LiveMap();
2836
+ const map = new _LiveMap();
2841
2837
  map._attach(id, pool);
2842
2838
  const children = parentToChildren.get(id);
2843
2839
  if (children === void 0) {
@@ -3142,7 +3138,7 @@ var LiveMap = class extends AbstractCrdt {
3142
3138
  };
3143
3139
 
3144
3140
  // src/crdts/LiveObject.ts
3145
- var LiveObject = class extends AbstractCrdt {
3141
+ var LiveObject = class _LiveObject extends AbstractCrdt {
3146
3142
  constructor(obj = {}) {
3147
3143
  super();
3148
3144
  this._propToLastUpdate = /* @__PURE__ */ new Map();
@@ -3180,8 +3176,8 @@ var LiveObject = class extends AbstractCrdt {
3180
3176
  }
3181
3177
  /** @internal */
3182
3178
  static _fromItems(items, pool) {
3183
- const [root, parentToChildren] = LiveObject._buildRootAndParentToChildren(items);
3184
- return LiveObject._deserialize(
3179
+ const [root, parentToChildren] = _LiveObject._buildRootAndParentToChildren(items);
3180
+ return _LiveObject._deserialize(
3185
3181
  root,
3186
3182
  parentToChildren,
3187
3183
  pool
@@ -3217,7 +3213,7 @@ var LiveObject = class extends AbstractCrdt {
3217
3213
  }
3218
3214
  /** @internal */
3219
3215
  static _deserialize([id, item], parentToChildren, pool) {
3220
- const liveObj = new LiveObject(item.data);
3216
+ const liveObj = new _LiveObject(item.data);
3221
3217
  liveObj._attach(id, pool);
3222
3218
  return this._deserializeChildren(liveObj, parentToChildren, pool);
3223
3219
  }
@@ -3924,13 +3920,6 @@ function isJsonObject(data) {
3924
3920
  }
3925
3921
 
3926
3922
  // src/protocol/AuthToken.ts
3927
- function hasJwtMeta(data) {
3928
- if (!isPlainObject(data)) {
3929
- return false;
3930
- }
3931
- const { iat, exp } = data;
3932
- return typeof iat === "number" && typeof exp === "number";
3933
- }
3934
3923
  function isTokenExpired(token) {
3935
3924
  const now = Date.now() / 1e3;
3936
3925
  const valid = now <= token.exp - 300 && now >= token.iat - 300;
@@ -3939,44 +3928,23 @@ function isTokenExpired(token) {
3939
3928
  function isStringList(value) {
3940
3929
  return Array.isArray(value) && value.every((i) => typeof i === "string");
3941
3930
  }
3942
- function isAppOnlyAuthToken(data) {
3943
- return typeof data.appId === "string" && data.roomId === void 0 && isStringList(data.scopes);
3944
- }
3945
- function isRoomAuthToken(data) {
3946
- return typeof data.appId === "string" && typeof data.roomId === "string" && typeof data.actor === "number" && (data.id === void 0 || typeof data.id === "string") && isStringList(data.scopes) && (data.maxConnectionsPerRoom === void 0 || typeof data.maxConnectionsPerRoom === "number");
3947
- }
3948
- function isAuthToken(data) {
3949
- return isAppOnlyAuthToken(data) || isRoomAuthToken(data);
3931
+ function isMinimalTokenPayload(data) {
3932
+ return isPlainObject(data) && typeof data.iat === "number" && typeof data.exp === "number" && typeof data.actor === "number" && (data.id === void 0 || typeof data.id === "string") && isStringList(data.scopes);
3950
3933
  }
3951
- function parseJwtToken(token) {
3952
- const tokenParts = token.split(".");
3934
+ function parseAuthToken(rawTokenString) {
3935
+ const tokenParts = rawTokenString.split(".");
3953
3936
  if (tokenParts.length !== 3) {
3954
3937
  throw new Error("Authentication error: invalid JWT token");
3955
3938
  }
3956
- const data = tryParseJson(b64decode(tokenParts[1]));
3957
- if (data && hasJwtMeta(data)) {
3958
- return data;
3959
- } else {
3960
- throw new Error("Authentication error: missing JWT metadata");
3961
- }
3962
- }
3963
- function parseRoomAuthToken(tokenString) {
3964
- const data = parseJwtToken(tokenString);
3965
- if (!(data && isRoomAuthToken(data))) {
3939
+ const payload = tryParseJson(b64decode(tokenParts[1]));
3940
+ if (!(payload && isMinimalTokenPayload(payload))) {
3966
3941
  throw new Error(
3967
3942
  "Authentication error: we expected a room token but did not get one. Hint: if you are using a callback, ensure the room is passed when creating the token. For more information: https://liveblocks.io/docs/api-reference/liveblocks-client#createClientCallback"
3968
3943
  );
3969
3944
  }
3970
- const _a = data, {
3971
- maxConnections: _legacyField
3972
- } = _a, parsedToken = __objRest(_a, [
3973
- // If this legacy field is found on the token, pretend it wasn't there,
3974
- // to make all internally used token payloads uniform
3975
- "maxConnections"
3976
- ]);
3977
3945
  return {
3978
- raw: tokenString,
3979
- parsed: parsedToken
3946
+ raw: rawTokenString,
3947
+ parsed: payload
3980
3948
  };
3981
3949
  }
3982
3950
 
@@ -3986,6 +3954,8 @@ var ClientMsgCode = /* @__PURE__ */ ((ClientMsgCode2) => {
3986
3954
  ClientMsgCode2[ClientMsgCode2["BROADCAST_EVENT"] = 103] = "BROADCAST_EVENT";
3987
3955
  ClientMsgCode2[ClientMsgCode2["FETCH_STORAGE"] = 200] = "FETCH_STORAGE";
3988
3956
  ClientMsgCode2[ClientMsgCode2["UPDATE_STORAGE"] = 201] = "UPDATE_STORAGE";
3957
+ ClientMsgCode2[ClientMsgCode2["FETCH_YDOC"] = 300] = "FETCH_YDOC";
3958
+ ClientMsgCode2[ClientMsgCode2["UPDATE_YDOC"] = 301] = "UPDATE_YDOC";
3989
3959
  return ClientMsgCode2;
3990
3960
  })(ClientMsgCode || {});
3991
3961
 
@@ -3999,9 +3969,23 @@ var ServerMsgCode = /* @__PURE__ */ ((ServerMsgCode2) => {
3999
3969
  ServerMsgCode2[ServerMsgCode2["INITIAL_STORAGE_STATE"] = 200] = "INITIAL_STORAGE_STATE";
4000
3970
  ServerMsgCode2[ServerMsgCode2["UPDATE_STORAGE"] = 201] = "UPDATE_STORAGE";
4001
3971
  ServerMsgCode2[ServerMsgCode2["REJECT_STORAGE_OP"] = 299] = "REJECT_STORAGE_OP";
3972
+ ServerMsgCode2[ServerMsgCode2["UPDATE_YDOC"] = 300] = "UPDATE_YDOC";
4002
3973
  return ServerMsgCode2;
4003
3974
  })(ServerMsgCode || {});
4004
3975
 
3976
+ // src/lib/LegacyArray.ts
3977
+ function asArrayWithLegacyMethods(arr) {
3978
+ Object.defineProperty(arr, "count", {
3979
+ value: arr.length,
3980
+ enumerable: false
3981
+ });
3982
+ Object.defineProperty(arr, "toArray", {
3983
+ value: () => arr,
3984
+ enumerable: false
3985
+ });
3986
+ return freeze(arr);
3987
+ }
3988
+
4005
3989
  // src/refs/ImmutableRef.ts
4006
3990
  function merge(target, patch) {
4007
3991
  let updated = false;
@@ -4039,42 +4023,6 @@ var ImmutableRef = class {
4039
4023
  }
4040
4024
  };
4041
4025
 
4042
- // src/refs/MeRef.ts
4043
- var MeRef = class extends ImmutableRef {
4044
- constructor(initialPresence) {
4045
- super();
4046
- this._me = freeze(compactObject(initialPresence));
4047
- }
4048
- /** @internal */
4049
- _toImmutable() {
4050
- return this._me;
4051
- }
4052
- /**
4053
- * Patches the current "me" instance.
4054
- */
4055
- patch(patch) {
4056
- const oldMe = this._me;
4057
- const newMe = merge(oldMe, patch);
4058
- if (oldMe !== newMe) {
4059
- this._me = freeze(newMe);
4060
- this.invalidate();
4061
- }
4062
- }
4063
- };
4064
-
4065
- // src/lib/LegacyArray.ts
4066
- function asArrayWithLegacyMethods(arr) {
4067
- Object.defineProperty(arr, "count", {
4068
- value: arr.length,
4069
- enumerable: false
4070
- });
4071
- Object.defineProperty(arr, "toArray", {
4072
- value: () => arr,
4073
- enumerable: false
4074
- });
4075
- return freeze(arr);
4076
- }
4077
-
4078
4026
  // src/refs/OthersRef.ts
4079
4027
  function makeUser(conn, presence) {
4080
4028
  return freeze(compactObject(__spreadProps(__spreadValues({}, conn), { presence })));
@@ -4184,6 +4132,29 @@ var OthersRef = class extends ImmutableRef {
4184
4132
  }
4185
4133
  };
4186
4134
 
4135
+ // src/refs/PatchableRef.ts
4136
+ var PatchableRef = class extends ImmutableRef {
4137
+ constructor(data) {
4138
+ super();
4139
+ this._data = freeze(compactObject(data));
4140
+ }
4141
+ /** @internal */
4142
+ _toImmutable() {
4143
+ return this._data;
4144
+ }
4145
+ /**
4146
+ * Patches the current object.
4147
+ */
4148
+ patch(patch) {
4149
+ const oldMe = this._data;
4150
+ const newMe = merge(oldMe, patch);
4151
+ if (oldMe !== newMe) {
4152
+ this._data = freeze(newMe);
4153
+ this.invalidate();
4154
+ }
4155
+ }
4156
+ };
4157
+
4187
4158
  // src/refs/ValueRef.ts
4188
4159
  var ValueRef = class extends ImmutableRef {
4189
4160
  constructor(initialValue) {
@@ -4266,7 +4237,7 @@ function createRoom(options, config) {
4266
4237
  storageOperations: []
4267
4238
  },
4268
4239
  sessionInfo: new ValueRef(null),
4269
- me: new MeRef(initialPresence),
4240
+ me: new PatchableRef(initialPresence),
4270
4241
  others: new OthersRef(),
4271
4242
  initialStorage,
4272
4243
  idFactory: null,
@@ -4291,9 +4262,10 @@ function createRoom(options, config) {
4291
4262
  const token = (_a2 = managedSocket.token) == null ? void 0 : _a2.parsed;
4292
4263
  if (token !== void 0 && token !== lastToken) {
4293
4264
  context.sessionInfo.set({
4294
- id: token.actor,
4295
4265
  userInfo: token.info,
4296
4266
  userId: token.id,
4267
+ // NOTE: In the future, these fields will get assigned in the connection phase
4268
+ actor: token.actor,
4297
4269
  isReadOnly: isStorageReadOnly(token.scopes)
4298
4270
  });
4299
4271
  lastToken = token;
@@ -4345,7 +4317,7 @@ function createRoom(options, config) {
4345
4317
  __spreadValues({}, context.me.current)
4346
4318
  )
4347
4319
  };
4348
- context.idFactory = makeIdFactory(sessionInfo.id);
4320
+ context.idFactory = makeIdFactory(sessionInfo.actor);
4349
4321
  if (_getStorage$ !== null) {
4350
4322
  refreshStorage({ flush: false });
4351
4323
  }
@@ -4431,7 +4403,8 @@ function createRoom(options, config) {
4431
4403
  storage: makeEventSource(),
4432
4404
  history: makeEventSource(),
4433
4405
  storageDidLoad: makeEventSource(),
4434
- storageStatus: makeEventSource()
4406
+ storageStatus: makeEventSource(),
4407
+ ydoc: makeEventSource()
4435
4408
  };
4436
4409
  function sendMessages(messageOrMessages) {
4437
4410
  var _a2, _b2;
@@ -4461,7 +4434,7 @@ function createRoom(options, config) {
4461
4434
  context.me,
4462
4435
  (info, me) => {
4463
4436
  return info !== null ? {
4464
- connectionId: info.id,
4437
+ connectionId: info.actor,
4465
4438
  id: info.userId,
4466
4439
  info: info.userInfo,
4467
4440
  presence: me,
@@ -4538,7 +4511,7 @@ function createRoom(options, config) {
4538
4511
  function getConnectionId() {
4539
4512
  const info = context.sessionInfo.current;
4540
4513
  if (info) {
4541
- return info.id;
4514
+ return info.actor;
4542
4515
  }
4543
4516
  throw new Error(
4544
4517
  "Internal. Tried to get connection id but connection was never open"
@@ -4852,6 +4825,10 @@ function createRoom(options, config) {
4852
4825
  }
4853
4826
  break;
4854
4827
  }
4828
+ case 300 /* UPDATE_YDOC */: {
4829
+ eventHub.ydoc.notify(message.update);
4830
+ break;
4831
+ }
4855
4832
  case 104 /* ROOM_STATE */: {
4856
4833
  updates.others.push(onRoomStateMessage(message));
4857
4834
  break;
@@ -4970,6 +4947,13 @@ ${Array.from(traces).join("\n\n")}`
4970
4947
  }
4971
4948
  return messages;
4972
4949
  }
4950
+ function updateYDoc(update) {
4951
+ context.buffer.messages.push({
4952
+ type: 301 /* UPDATE_YDOC */,
4953
+ update
4954
+ });
4955
+ flushNowOrSoon();
4956
+ }
4973
4957
  function broadcastEvent(event, options2 = {
4974
4958
  shouldQueueEventIfNotReady: false
4975
4959
  }) {
@@ -5029,6 +5013,13 @@ ${Array.from(traces).join("\n\n")}`
5029
5013
  };
5030
5014
  });
5031
5015
  }
5016
+ function fetchYDoc(vector) {
5017
+ context.buffer.messages.push({
5018
+ type: 300 /* FETCH_YDOC */,
5019
+ vector
5020
+ });
5021
+ flushNowOrSoon();
5022
+ }
5032
5023
  function undo() {
5033
5024
  if (context.activeBatch) {
5034
5025
  throw new Error("undo is not allowed during a batch");
@@ -5150,7 +5141,8 @@ ${Array.from(traces).join("\n\n")}`
5150
5141
  storage: eventHub.storage.observable,
5151
5142
  history: eventHub.history.observable,
5152
5143
  storageDidLoad: eventHub.storageDidLoad.observable,
5153
- storageStatus: eventHub.storageStatus.observable
5144
+ storageStatus: eventHub.storageStatus.observable,
5145
+ ydoc: eventHub.ydoc.observable
5154
5146
  };
5155
5147
  return {
5156
5148
  /* NOTE: Exposing __internal here only to allow testing implementation details in unit tests */
@@ -5185,6 +5177,7 @@ ${Array.from(traces).join("\n\n")}`
5185
5177
  destroy: () => managedSocket.destroy(),
5186
5178
  // Presence
5187
5179
  updatePresence,
5180
+ updateYDoc,
5188
5181
  broadcastEvent,
5189
5182
  // Storage
5190
5183
  batch,
@@ -5196,6 +5189,7 @@ ${Array.from(traces).join("\n\n")}`
5196
5189
  pause: pauseHistory,
5197
5190
  resume: resumeHistory
5198
5191
  },
5192
+ fetchYDoc,
5199
5193
  getStorage,
5200
5194
  getStorageSnapshot,
5201
5195
  getStorageStatus,
@@ -5311,7 +5305,7 @@ function makeCreateSocketDelegateForRoom(liveblocksServer, WebSocketPolyfill) {
5311
5305
  // @ts-ignore (__PACKAGE_VERSION__ will be injected by the build script)
5312
5306
  true ? (
5313
5307
  /* istanbul ignore next */
5314
- "1.1.0"
5308
+ "1.1.1-dual2"
5315
5309
  ) : "dev"}`
5316
5310
  );
5317
5311
  };
@@ -5342,7 +5336,7 @@ function makeAuthDelegateForRoom(roomId, authentication, fetchPolyfill) {
5342
5336
  return fetchAuthEndpoint(fetcher, authentication.url, {
5343
5337
  room: roomId,
5344
5338
  publicApiKey: authentication.publicApiKey
5345
- }).then(({ token }) => parseRoomAuthToken(token));
5339
+ }).then(({ token }) => parseAuthToken(token));
5346
5340
  });
5347
5341
  } else if (authentication.type === "private") {
5348
5342
  return () => __async(this, null, function* () {
@@ -5353,7 +5347,7 @@ function makeAuthDelegateForRoom(roomId, authentication, fetchPolyfill) {
5353
5347
  }
5354
5348
  return fetchAuthEndpoint(fetcher, authentication.url, {
5355
5349
  room: roomId
5356
- }).then(({ token }) => parseRoomAuthToken(token));
5350
+ }).then(({ token }) => parseAuthToken(token));
5357
5351
  });
5358
5352
  } else if (authentication.type === "custom") {
5359
5353
  return () => __async(this, null, function* () {
@@ -5363,7 +5357,7 @@ function makeAuthDelegateForRoom(roomId, authentication, fetchPolyfill) {
5363
5357
  'We expect the authentication callback to return a token, but it does not. Hint: the return value should look like: { token: "..." }'
5364
5358
  );
5365
5359
  }
5366
- return parseRoomAuthToken(response.token);
5360
+ return parseAuthToken(response.token);
5367
5361
  });
5368
5362
  } else {
5369
5363
  throw new Error("Internal error. Unexpected authentication type");
@@ -5964,7 +5958,4 @@ var WebsocketCloseCodes = /* @__PURE__ */ ((WebsocketCloseCodes2) => {
5964
5958
 
5965
5959
 
5966
5960
 
5967
-
5968
-
5969
-
5970
- exports.ClientMsgCode = ClientMsgCode; exports.CrdtType = CrdtType; exports.LiveList = LiveList; exports.LiveMap = LiveMap; exports.LiveObject = LiveObject; exports.OpCode = OpCode; exports.ServerMsgCode = ServerMsgCode; exports.WebsocketCloseCodes = WebsocketCloseCodes; exports.asArrayWithLegacyMethods = asArrayWithLegacyMethods; exports.asPos = asPos; exports.assert = assert; exports.assertNever = assertNever; exports.b64decode = b64decode; exports.createClient = createClient; exports.deprecate = deprecate; exports.deprecateIf = deprecateIf; exports.errorIf = errorIf; exports.freeze = freeze; exports.isAppOnlyAuthToken = isAppOnlyAuthToken; exports.isAuthToken = isAuthToken; exports.isChildCrdt = isChildCrdt; exports.isJsonArray = isJsonArray; exports.isJsonObject = isJsonObject; exports.isJsonScalar = isJsonScalar; exports.isPlainObject = isPlainObject; exports.isRoomAuthToken = isRoomAuthToken; exports.isRootCrdt = isRootCrdt; exports.legacy_patchImmutableObject = legacy_patchImmutableObject; exports.lsonToJson = lsonToJson; exports.makePosition = makePosition; exports.nn = nn; exports.patchLiveObjectKey = patchLiveObjectKey; exports.shallow = shallow; exports.throwUsageError = throwUsageError; exports.tryParseJson = tryParseJson; exports.withTimeout = withTimeout;
5961
+ exports.ClientMsgCode = ClientMsgCode; exports.CrdtType = CrdtType; exports.LiveList = LiveList; exports.LiveMap = LiveMap; exports.LiveObject = LiveObject; exports.OpCode = OpCode; exports.ServerMsgCode = ServerMsgCode; exports.WebsocketCloseCodes = WebsocketCloseCodes; exports.asArrayWithLegacyMethods = asArrayWithLegacyMethods; exports.asPos = asPos; exports.assert = assert; exports.assertNever = assertNever; exports.b64decode = b64decode; exports.createClient = createClient; exports.deprecate = deprecate; exports.deprecateIf = deprecateIf; exports.errorIf = errorIf; exports.freeze = freeze; exports.isChildCrdt = isChildCrdt; exports.isJsonArray = isJsonArray; exports.isJsonObject = isJsonObject; exports.isJsonScalar = isJsonScalar; exports.isPlainObject = isPlainObject; exports.isRootCrdt = isRootCrdt; exports.legacy_patchImmutableObject = legacy_patchImmutableObject; exports.lsonToJson = lsonToJson; exports.makePosition = makePosition; exports.nn = nn; exports.patchLiveObjectKey = patchLiveObjectKey; exports.shallow = shallow; exports.throwUsageError = throwUsageError; exports.tryParseJson = tryParseJson; exports.withTimeout = withTimeout;