@liveblocks/client 0.16.15 → 0.17.0-test1

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.
Files changed (10) hide show
  1. package/index.d.ts +26 -7
  2. package/index.js +1230 -830
  3. package/index.mjs +1030 -782
  4. package/internal.d.ts +271 -251
  5. package/internal.js +314 -168
  6. package/internal.mjs +265 -130
  7. package/package.json +15 -10
  8. package/shared.d.ts +973 -628
  9. package/shared.js +2568 -1331
  10. package/shared.mjs +1989 -1210
package/index.js CHANGED
@@ -1,857 +1,1257 @@
1
1
  "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: !0
5
- });
6
-
7
- var LiveObject = require("./shared.js"), _excluded = [ "_hasReceivedInitialPresence" ], BACKOFF_RETRY_DELAYS = [ 250, 500, 1e3, 2e3, 4e3, 8e3, 1e4 ], BACKOFF_RETRY_DELAYS_SLOW = [ 2e3, 3e4, 6e4, 3e5 ];
8
-
9
- function isValidRoomEventType(value) {
10
- return "my-presence" === value || "others" === value || "event" === value || "error" === value || "connection" === value;
11
- }
12
-
2
+ Object.defineProperty(exports, "__esModule", { value: !0 });
3
+ var Json = require("./shared.js"),
4
+ _excluded = ["_hasReceivedInitialPresence"],
5
+ BACKOFF_RETRY_DELAYS = [250, 500, 1e3, 2e3, 4e3, 8e3, 1e4],
6
+ BACKOFF_RETRY_DELAYS_SLOW = [2e3, 3e4, 6e4, 3e5];
13
7
  function makeOthers(userMap) {
14
- var _ref, users = Object.values(userMap).map((function(user) {
15
- return user._hasReceivedInitialPresence, LiveObject._objectWithoutPropertiesLoose(user, _excluded);
16
- }));
17
- return (_ref = {
18
- get count() {
19
- return users.length;
20
- }
21
- })[Symbol.iterator] = function() {
22
- return users[Symbol.iterator]();
23
- }, _ref.map = function(callback) {
24
- return users.map(callback);
25
- }, _ref.toArray = function() {
26
- return users;
27
- }, _ref;
8
+ var _ref,
9
+ users = Object.values(userMap).map(function (user) {
10
+ return (
11
+ user._hasReceivedInitialPresence,
12
+ Json._objectWithoutPropertiesLoose(user, _excluded)
13
+ );
14
+ });
15
+ return (
16
+ ((_ref = {
17
+ get count() {
18
+ return users.length;
19
+ },
20
+ })[Symbol.iterator] = function () {
21
+ return users[Symbol.iterator]();
22
+ }),
23
+ (_ref.map = function (callback) {
24
+ return users.map(callback);
25
+ }),
26
+ (_ref.toArray = function () {
27
+ return users;
28
+ }),
29
+ _ref
30
+ );
28
31
  }
29
-
30
32
  function makeStateMachine(state, context, mockedEffects) {
31
- var effects = mockedEffects || {
32
- authenticate: function(auth, createWebSocket) {
33
- var token = state.token;
34
- if (!token || !LiveObject.isTokenValid(token)) return auth(context.roomId).then((function(_ref2) {
35
- var token = _ref2.token;
36
- "authenticating" === state.connection.state && (authenticationSuccess(parseToken(token), createWebSocket(token)),
37
- state.token = token);
38
- })).catch((function(er) {
39
- return function(error) {
40
- "production" !== process.env.NODE_ENV && console.error("Call to authentication endpoint failed", error);
41
- state.token = null, updateConnection({
42
- state: "unavailable"
43
- }), state.numberOfRetry++, state.timeoutHandles.reconnect = effects.scheduleReconnect(getRetryDelay());
44
- }(er);
45
- }));
46
- authenticationSuccess(parseToken(token), createWebSocket(token));
47
- },
48
- send: function(messageOrMessages) {
49
- if (null == state.socket) throw new Error("Can't send message if socket is null");
50
- state.socket.send(JSON.stringify(messageOrMessages));
51
- },
52
- delayFlush: function(delay) {
53
- return setTimeout(tryFlushing, delay);
54
- },
55
- startHeartbeatInterval: function() {
56
- return setInterval(heartbeat, 3e4);
57
- },
58
- schedulePongTimeout: function() {
59
- return setTimeout(pongTimeout, 2e3);
60
- },
61
- scheduleReconnect: function(delay) {
62
- return setTimeout(connect, delay);
63
- }
64
- };
65
- function genericSubscribe(callback) {
66
- return state.listeners.storage.push(callback), function() {
67
- return LiveObject.remove(state.listeners.storage, callback);
33
+ var effects = mockedEffects || {
34
+ authenticate: function (auth, createWebSocket) {
35
+ var rawToken = state.token,
36
+ parsedToken = null !== rawToken && Json.parseRoomAuthToken(rawToken);
37
+ if (!parsedToken || Json.isTokenExpired(parsedToken))
38
+ return auth(context.roomId)
39
+ .then(function (_ref2) {
40
+ var token = _ref2.token;
41
+ "authenticating" === state.connection.state &&
42
+ (authenticationSuccess(
43
+ Json.parseRoomAuthToken(token),
44
+ createWebSocket(token)
45
+ ),
46
+ (state.token = token));
47
+ })
48
+ .catch(function (er) {
49
+ return (function (error) {
50
+ "production" !== process.env.NODE_ENV &&
51
+ console.error("Call to authentication endpoint failed", error);
52
+ (state.token = null),
53
+ updateConnection({ state: "unavailable" }),
54
+ state.numberOfRetry++,
55
+ (state.timeoutHandles.reconnect = effects.scheduleReconnect(
56
+ getRetryDelay()
57
+ ));
58
+ })(er instanceof Error ? er : new Error(String(er)));
59
+ });
60
+ authenticationSuccess(parsedToken, createWebSocket(rawToken));
61
+ },
62
+ send: function (messageOrMessages) {
63
+ if (null == state.socket)
64
+ throw new Error("Can't send message if socket is null");
65
+ state.socket.send(JSON.stringify(messageOrMessages));
66
+ },
67
+ delayFlush: function (delay) {
68
+ return setTimeout(tryFlushing, delay);
69
+ },
70
+ startHeartbeatInterval: function () {
71
+ return setInterval(heartbeat, 3e4);
72
+ },
73
+ schedulePongTimeout: function () {
74
+ return setTimeout(pongTimeout, 2e3);
75
+ },
76
+ scheduleReconnect: function (delay) {
77
+ return setTimeout(connect, delay);
78
+ },
68
79
  };
69
- }
70
- function createOrUpdateRootFromMessage(message) {
71
- if (0 === message.items.length) throw new Error("Internal error: cannot load storage without items");
72
- var items, _buildRootAndParentTo, root, parentToChildren;
73
- for (var _key in state.root ? function(items) {
74
- if (!state.root) return;
75
- var currentItems = new Map;
76
- state.items.forEach((function(liveCrdt, id) {
77
- currentItems.set(id, liveCrdt._toSerializedCrdt());
78
- })), notify(apply(LiveObject.getTreesDiffOperations(currentItems, new Map(items)), !1).updates);
79
- }(message.items) : state.root = (items = message.items, _buildRootAndParentTo = function(items) {
80
- for (var _step2, parentToChildren = new Map, root = null, _iterator2 = LiveObject._createForOfIteratorHelperLoose(items); !(_step2 = _iterator2()).done; ) {
81
- var _step2$value = _step2.value, id = _step2$value[0], crdt = _step2$value[1];
82
- if (LiveObject.isRootCrdt(crdt)) root = [ id, crdt ]; else {
83
- var tuple = [ id, crdt ], children = parentToChildren.get(crdt.parentId);
84
- null != children ? children.push(tuple) : parentToChildren.set(crdt.parentId, [ tuple ]);
85
- }
86
- }
87
- if (null == root) throw new Error("Root can't be null");
88
- return [ root, parentToChildren ];
89
- }(items), root = _buildRootAndParentTo[0], parentToChildren = _buildRootAndParentTo[1],
90
- LiveObject.LiveObject._deserialize(root, parentToChildren, {
91
- getItem: getItem,
92
- addItem: addItem,
93
- deleteItem: deleteItem,
94
- generateId: generateId,
95
- generateOpId: generateOpId,
96
- dispatch: storageDispatch,
97
- roomId: context.roomId
98
- })), state.defaultStorageRoot) null == state.root.get(_key) && state.root.set(_key, state.defaultStorageRoot[_key]);
99
- }
100
- function addItem(id, item) {
101
- state.items.set(id, item);
102
- }
103
- function deleteItem(id) {
104
- state.items.delete(id);
105
- }
106
- function getItem(id) {
107
- return state.items.get(id);
108
- }
109
- function addToUndoStack(historyItem) {
110
- var _state$pausedHistory;
111
- (state.undoStack.length >= 50 && state.undoStack.shift(), state.isHistoryPaused) ? (_state$pausedHistory = state.pausedHistory).unshift.apply(_state$pausedHistory, historyItem) : state.undoStack.push(historyItem);
112
- }
113
- function storageDispatch(ops, reverse, storageUpdates) {
114
- var _state$batch$ops, _state$batch$reverseO;
115
- state.isBatching ? ((_state$batch$ops = state.batch.ops).push.apply(_state$batch$ops, ops),
116
- storageUpdates.forEach((function(value, key) {
117
- state.batch.updates.storageUpdates.set(key, LiveObject.mergeStorageUpdates(state.batch.updates.storageUpdates.get(key), value));
118
- })), (_state$batch$reverseO = state.batch.reverseOps).push.apply(_state$batch$reverseO, reverse)) : (addToUndoStack(reverse),
119
- state.redoStack = [], dispatch(ops), notify({
120
- storageUpdates: storageUpdates
121
- }));
122
- }
123
- function notify(_ref3) {
124
- var _ref3$storageUpdates = _ref3.storageUpdates, storageUpdates = void 0 === _ref3$storageUpdates ? new Map : _ref3$storageUpdates, _ref3$presence = _ref3.presence, presence = void 0 !== _ref3$presence && _ref3$presence, _ref3$others = _ref3.others, otherEvents = void 0 === _ref3$others ? [] : _ref3$others;
125
- if (otherEvents.length > 0) {
126
- state.others = makeOthers(state.users);
127
- for (var _step3, _iterator3 = LiveObject._createForOfIteratorHelperLoose(otherEvents); !(_step3 = _iterator3()).done; ) for (var _step4, _event = _step3.value, _iterator4 = LiveObject._createForOfIteratorHelperLoose(state.listeners.others); !(_step4 = _iterator4()).done; ) {
128
- (0, _step4.value)(state.others, _event);
129
- }
130
- }
131
- if (presence) for (var _step5, _iterator5 = LiveObject._createForOfIteratorHelperLoose(state.listeners["my-presence"]); !(_step5 = _iterator5()).done; ) {
132
- (0, _step5.value)(state.me);
133
- }
134
- if (storageUpdates.size > 0) for (var _step6, _iterator6 = LiveObject._createForOfIteratorHelperLoose(state.listeners.storage); !(_step6 = _iterator6()).done; ) {
135
- (0, _step6.value)(Array.from(storageUpdates.values()));
136
- }
137
- }
138
- function getConnectionId() {
139
- if ("open" === state.connection.state || "connecting" === state.connection.state) return state.connection.id;
140
- if (null !== state.lastConnectionId) return state.lastConnectionId;
141
- throw new Error("Internal. Tried to get connection id but connection was never open");
142
- }
143
- function generateId() {
144
- return getConnectionId() + ":" + state.clock++;
145
- }
146
- function generateOpId() {
147
- return getConnectionId() + ":" + state.opClock++;
148
- }
149
- function apply(item, isLocal) {
150
- for (var _step7, result = {
151
- reverse: [],
152
- updates: {
153
- storageUpdates: new Map,
154
- presence: !1
155
- }
156
- }, createdNodeIds = new Set, _iterator7 = LiveObject._createForOfIteratorHelperLoose(item); !(_step7 = _iterator7()).done; ) {
157
- var op = _step7.value;
158
- if ("presence" === op.type) {
159
- var reverse = {
160
- type: "presence",
161
- data: {}
162
- };
163
- for (var _key2 in op.data) reverse.data[_key2] = state.me[_key2];
164
- if (state.me = LiveObject._extends({}, state.me, op.data), null == state.buffer.presence) state.buffer.presence = op.data; else for (var _key3 in op.data) state.buffer.presence[_key3] = op.data[_key3];
165
- result.reverse.unshift(reverse), result.updates.presence = !0;
166
- } else {
167
- isLocal && !op.opId && (op.opId = generateOpId());
168
- var applyOpResult = applyOp(op, isLocal);
169
- if (applyOpResult.modified) {
170
- var _applyOpResult$modifi, _result$reverse, parentId = null == (_applyOpResult$modifi = applyOpResult.modified.node._parent) ? void 0 : _applyOpResult$modifi._id;
171
- if (!createdNodeIds.has(parentId)) result.updates.storageUpdates.set(applyOpResult.modified.node._id, LiveObject.mergeStorageUpdates(result.updates.storageUpdates.get(applyOpResult.modified.node._id), applyOpResult.modified)),
172
- (_result$reverse = result.reverse).unshift.apply(_result$reverse, applyOpResult.reverse);
173
- op.type !== LiveObject.OpCode.CREATE_LIST && op.type !== LiveObject.OpCode.CREATE_MAP && op.type !== LiveObject.OpCode.CREATE_OBJECT || createdNodeIds.add(applyOpResult.modified.node._id);
174
- }
175
- }
176
- }
177
- return result;
178
- }
179
- function applyOp(op, isLocal) {
180
- switch (op.opId && state.offlineOperations.delete(op.opId), op.type) {
181
- case LiveObject.OpCode.DELETE_OBJECT_KEY:
182
- case LiveObject.OpCode.UPDATE_OBJECT:
183
- case LiveObject.OpCode.DELETE_CRDT:
184
- var item = state.items.get(op.id);
185
- return null == item ? {
186
- modified: !1
187
- } : item._apply(op, isLocal);
80
+ function genericSubscribe(callback) {
81
+ return (
82
+ state.listeners.storage.push(callback),
83
+ function () {
84
+ return Json.remove(state.listeners.storage, callback);
85
+ }
86
+ );
87
+ }
88
+ function createOrUpdateRootFromMessage(message) {
89
+ if (0 === message.items.length)
90
+ throw new Error("Internal error: cannot load storage without items");
91
+ var items, _buildRootAndParentTo, root, parentToChildren;
92
+ for (var _key in (state.root
93
+ ? (function (items) {
94
+ if (!state.root) return;
95
+ var currentItems = new Map();
96
+ state.items.forEach(function (liveCrdt, id) {
97
+ currentItems.set(id, liveCrdt._toSerializedCrdt());
98
+ }),
99
+ notify(
100
+ apply(
101
+ Json.getTreesDiffOperations(currentItems, new Map(items)),
102
+ !1
103
+ ).updates
104
+ );
105
+ })(message.items)
106
+ : (state.root =
107
+ ((items = message.items),
108
+ (_buildRootAndParentTo = (function (items) {
109
+ for (
110
+ var _step2,
111
+ parentToChildren = new Map(),
112
+ root = null,
113
+ _iterator2 = Json._createForOfIteratorHelperLoose(items);
114
+ !(_step2 = _iterator2()).done;
188
115
 
189
- case LiveObject.OpCode.SET_PARENT_KEY:
190
- var _item = state.items.get(op.id);
191
- if (null == _item) return {
192
- modified: !1
193
- };
194
- if (_item._parent instanceof LiveObject.LiveList) {
195
- var previousKey = _item._parentKey;
196
- return previousKey === op.parentKey ? {
197
- modified: !1
198
- } : _item._parent._setChildKey(op.parentKey, _item, previousKey);
199
- }
200
- return {
201
- modified: !1
202
- };
116
+ ) {
117
+ var _step2$value = _step2.value,
118
+ id = _step2$value[0],
119
+ crdt = _step2$value[1];
120
+ if (Json.isRootCrdt(crdt)) root = [id, crdt];
121
+ else {
122
+ var tuple = [id, crdt],
123
+ children = parentToChildren.get(crdt.parentId);
124
+ null != children
125
+ ? children.push(tuple)
126
+ : parentToChildren.set(crdt.parentId, [tuple]);
127
+ }
128
+ }
129
+ if (null == root) throw new Error("Root can't be null");
130
+ return [root, parentToChildren];
131
+ })(items)),
132
+ (root = _buildRootAndParentTo[0]),
133
+ (parentToChildren = _buildRootAndParentTo[1]),
134
+ Json.LiveObject._deserialize(root, parentToChildren, {
135
+ getItem: getItem,
136
+ addItem: addItem,
137
+ deleteItem: deleteItem,
138
+ generateId: generateId,
139
+ generateOpId: generateOpId,
140
+ dispatch: storageDispatch,
141
+ roomId: context.roomId,
142
+ }))),
143
+ state.defaultStorageRoot))
144
+ null == state.root.get(_key) &&
145
+ state.root.set(_key, state.defaultStorageRoot[_key]);
146
+ }
147
+ function addItem(id, liveItem) {
148
+ state.items.set(id, liveItem);
149
+ }
150
+ function deleteItem(id) {
151
+ state.items.delete(id);
152
+ }
153
+ function getItem(id) {
154
+ return state.items.get(id);
155
+ }
156
+ function addToUndoStack(historyItem) {
157
+ var _state$pausedHistory;
158
+ (state.undoStack.length >= 50 && state.undoStack.shift(),
159
+ state.isHistoryPaused)
160
+ ? (_state$pausedHistory = state.pausedHistory).unshift.apply(
161
+ _state$pausedHistory,
162
+ historyItem
163
+ )
164
+ : state.undoStack.push(historyItem);
165
+ }
166
+ function storageDispatch(ops, reverse, storageUpdates) {
167
+ var _state$batch$ops, _state$batch$reverseO;
168
+ state.isBatching
169
+ ? ((_state$batch$ops = state.batch.ops).push.apply(_state$batch$ops, ops),
170
+ storageUpdates.forEach(function (value, key) {
171
+ state.batch.updates.storageUpdates.set(
172
+ key,
173
+ Json.mergeStorageUpdates(
174
+ state.batch.updates.storageUpdates.get(key),
175
+ value
176
+ )
177
+ );
178
+ }),
179
+ (_state$batch$reverseO = state.batch.reverseOps).push.apply(
180
+ _state$batch$reverseO,
181
+ reverse
182
+ ))
183
+ : (addToUndoStack(reverse),
184
+ (state.redoStack = []),
185
+ dispatch(ops),
186
+ notify({ storageUpdates: storageUpdates }));
187
+ }
188
+ function notify(_ref3) {
189
+ var _ref3$storageUpdates = _ref3.storageUpdates,
190
+ storageUpdates =
191
+ void 0 === _ref3$storageUpdates ? new Map() : _ref3$storageUpdates,
192
+ _ref3$presence = _ref3.presence,
193
+ presence = void 0 !== _ref3$presence && _ref3$presence,
194
+ _ref3$others = _ref3.others,
195
+ otherEvents = void 0 === _ref3$others ? [] : _ref3$others;
196
+ if (otherEvents.length > 0) {
197
+ state.others = makeOthers(state.users);
198
+ for (
199
+ var _step3,
200
+ _iterator3 = Json._createForOfIteratorHelperLoose(otherEvents);
201
+ !(_step3 = _iterator3()).done;
203
202
 
204
- case LiveObject.OpCode.CREATE_OBJECT:
205
- case LiveObject.OpCode.CREATE_LIST:
206
- case LiveObject.OpCode.CREATE_MAP:
207
- case LiveObject.OpCode.CREATE_REGISTER:
208
- var parent = state.items.get(op.parentId);
209
- return null == parent ? {
210
- modified: !1
211
- } : parent._attachChild(op, isLocal);
212
- }
213
- }
214
- function connect() {
215
- if ("closed" !== state.connection.state && "unavailable" !== state.connection.state) return null;
216
- var auth = function(authentication, fetchPolyfill) {
217
- if ("public" === authentication.type) {
218
- if ("undefined" == typeof window && null == fetchPolyfill) throw new Error("To use Liveblocks client in a non-dom environment with a publicApiKey, you need to provide a fetch polyfill.");
219
- return function(room) {
220
- return fetchAuthEndpoint(fetchPolyfill || fetch, authentication.url, {
221
- room: room,
222
- publicApiKey: authentication.publicApiKey
223
- });
224
- };
225
- }
226
- if ("private" === authentication.type) {
227
- if ("undefined" == typeof window && null == fetchPolyfill) throw new Error("To use Liveblocks client in a non-dom environment with a url as auth endpoint, you need to provide a fetch polyfill.");
228
- return function(room) {
229
- return fetchAuthEndpoint(fetchPolyfill || fetch, authentication.url, {
230
- room: room
231
- });
232
- };
233
- }
234
- if ("custom" === authentication.type) return authentication.callback;
235
- throw new Error("Internal error. Unexpected authentication type");
236
- }(context.authentication, context.fetchPolyfill), createWebSocket = function(liveblocksServer, WebSocketPolyfill) {
237
- if ("undefined" == typeof window && null == WebSocketPolyfill) throw new Error("To use Liveblocks client in a non-dom environment, you need to provide a WebSocket polyfill.");
238
- var ws = WebSocketPolyfill || WebSocket;
239
- return function(token) {
240
- return new ws(liveblocksServer + "/?token=" + token);
241
- };
242
- }(context.liveblocksServer, context.WebSocketPolyfill);
243
- updateConnection({
244
- state: "authenticating"
245
- }), effects.authenticate(auth, createWebSocket);
246
- }
247
- function authenticationSuccess(token, socket) {
248
- var connectionId, count;
249
- socket.addEventListener("message", onMessage), socket.addEventListener("open", onOpen),
250
- socket.addEventListener("close", onClose), socket.addEventListener("error", onError),
251
- updateConnection({
252
- state: "connecting",
253
- id: token.actor,
254
- userInfo: token.info,
255
- userId: token.id
256
- }), state.idFactory = (connectionId = token.actor, count = 0, function() {
257
- return connectionId + ":" + count++;
258
- }), state.socket = socket;
259
- }
260
- function onUpdatePresenceMessage(message) {
261
- var user = state.users[message.actor];
262
- if (void 0 !== message.targetActor || null == user || user._hasReceivedInitialPresence) return state.users[message.actor] = null == user ? {
263
- connectionId: message.actor,
264
- presence: message.data,
265
- _hasReceivedInitialPresence: !0
266
- } : {
267
- id: user.id,
268
- info: user.info,
269
- connectionId: message.actor,
270
- presence: LiveObject._extends({}, user.presence, message.data),
271
- _hasReceivedInitialPresence: !0
272
- }, {
273
- type: "update",
274
- updates: message.data,
275
- user: state.users[message.actor]
276
- };
277
- }
278
- function onUserLeftMessage(message) {
279
- var userLeftMessage = message, user = state.users[userLeftMessage.actor];
280
- return user ? (delete state.users[userLeftMessage.actor], {
281
- type: "leave",
282
- user: user
283
- }) : null;
284
- }
285
- function onRoomStateMessage(message) {
286
- var newUsers = {};
287
- for (var _key5 in message.users) {
288
- var _connectionId = Number.parseInt(_key5), user = message.users[_key5];
289
- newUsers[_connectionId] = {
290
- connectionId: _connectionId,
291
- info: user.info,
292
- id: user.id
293
- };
294
- }
295
- return state.users = newUsers, {
296
- type: "reset"
297
- };
298
- }
299
- function onEvent(message) {
300
- for (var _step8, _iterator8 = LiveObject._createForOfIteratorHelperLoose(state.listeners.event); !(_step8 = _iterator8()).done; ) {
301
- (0, _step8.value)({
302
- connectionId: message.actor,
303
- event: message.event
304
- });
305
- }
306
- }
307
- function onUserJoinedMessage(message) {
308
- return state.users[message.actor] = {
309
- connectionId: message.actor,
310
- info: message.info,
311
- id: message.id,
312
- _hasReceivedInitialPresence: !0
313
- }, state.me && (state.buffer.messages.push({
314
- type: LiveObject.ClientMsgCode.UPDATE_PRESENCE,
315
- data: state.me,
316
- targetActor: message.actor
317
- }), tryFlushing()), {
318
- type: "enter",
319
- user: state.users[message.actor]
320
- };
321
- }
322
- function parseServerMessage(data) {
323
- return LiveObject.isJsonObject(data) ? data : null;
324
- }
325
- function onMessage(event) {
326
- if ("pong" !== event.data) {
327
- var text, data, messages = (text = event.data, void 0 === (data = LiveObject.tryParseJson(text)) ? null : LiveObject.isJsonArray(data) ? LiveObject.compact(data.map((function(item) {
328
- return parseServerMessage(item);
329
- }))) : LiveObject.compact([ parseServerMessage(data) ]));
330
- if (null !== messages && 0 !== messages.length) {
331
- for (var _step9, updates = {
332
- storageUpdates: new Map,
333
- others: []
334
- }, _iterator9 = LiveObject._createForOfIteratorHelperLoose(messages); !(_step9 = _iterator9()).done; ) {
335
- var message = _step9.value;
336
- switch (message.type) {
337
- case LiveObject.ServerMsgCode.USER_JOINED:
338
- updates.others.push(onUserJoinedMessage(message));
339
- break;
203
+ )
204
+ for (
205
+ var _step4,
206
+ _event = _step3.value,
207
+ _iterator4 = Json._createForOfIteratorHelperLoose(
208
+ state.listeners.others
209
+ );
210
+ !(_step4 = _iterator4()).done;
340
211
 
341
- case LiveObject.ServerMsgCode.UPDATE_PRESENCE:
342
- var othersPresenceUpdate = onUpdatePresenceMessage(message);
343
- othersPresenceUpdate && updates.others.push(othersPresenceUpdate);
344
- break;
212
+ ) {
213
+ (0, _step4.value)(state.others, _event);
214
+ }
215
+ }
216
+ if (presence)
217
+ for (
218
+ var _step5,
219
+ _iterator5 = Json._createForOfIteratorHelperLoose(
220
+ state.listeners["my-presence"]
221
+ );
222
+ !(_step5 = _iterator5()).done;
345
223
 
346
- case LiveObject.ServerMsgCode.BROADCASTED_EVENT:
347
- onEvent(message);
348
- break;
224
+ ) {
225
+ (0, _step5.value)(state.me);
226
+ }
227
+ if (storageUpdates.size > 0)
228
+ for (
229
+ var _step6,
230
+ _iterator6 = Json._createForOfIteratorHelperLoose(
231
+ state.listeners.storage
232
+ );
233
+ !(_step6 = _iterator6()).done;
349
234
 
350
- case LiveObject.ServerMsgCode.USER_LEFT:
351
- var _event2 = onUserLeftMessage(message);
352
- _event2 && updates.others.push(_event2);
353
- break;
235
+ ) {
236
+ (0, _step6.value)(Array.from(storageUpdates.values()));
237
+ }
238
+ }
239
+ function getConnectionId() {
240
+ if (
241
+ "open" === state.connection.state ||
242
+ "connecting" === state.connection.state
243
+ )
244
+ return state.connection.id;
245
+ if (null !== state.lastConnectionId) return state.lastConnectionId;
246
+ throw new Error(
247
+ "Internal. Tried to get connection id but connection was never open"
248
+ );
249
+ }
250
+ function generateId() {
251
+ return getConnectionId() + ":" + state.clock++;
252
+ }
253
+ function generateOpId() {
254
+ return getConnectionId() + ":" + state.opClock++;
255
+ }
256
+ function apply(item, isLocal) {
257
+ for (
258
+ var _step7,
259
+ result = {
260
+ reverse: [],
261
+ updates: { storageUpdates: new Map(), presence: !1 },
262
+ },
263
+ createdNodeIds = new Set(),
264
+ _iterator7 = Json._createForOfIteratorHelperLoose(item);
265
+ !(_step7 = _iterator7()).done;
354
266
 
355
- case LiveObject.ServerMsgCode.ROOM_STATE:
356
- updates.others.push(onRoomStateMessage(message));
357
- break;
267
+ ) {
268
+ var op = _step7.value;
269
+ if ("presence" === op.type) {
270
+ var reverse = { type: "presence", data: {} };
271
+ for (var _key2 in op.data) reverse.data[_key2] = state.me[_key2];
272
+ if (
273
+ ((state.me = Json._extends({}, state.me, op.data)),
274
+ null == state.buffer.presence)
275
+ )
276
+ state.buffer.presence = op.data;
277
+ else
278
+ for (var _key3 in op.data)
279
+ state.buffer.presence[_key3] = op.data[_key3];
280
+ result.reverse.unshift(reverse), (result.updates.presence = !0);
281
+ } else {
282
+ var source = void 0;
283
+ if ((op.opId || (op.opId = generateOpId()), isLocal))
284
+ source = Json.OpSource.UNDOREDO_RECONNECT;
285
+ else
286
+ source = state.offlineOperations.delete(Json.nn(op.opId))
287
+ ? Json.OpSource.ACK
288
+ : Json.OpSource.REMOTE;
289
+ var applyOpResult = applyOp(op, source);
290
+ if (applyOpResult.modified) {
291
+ var _result$reverse,
292
+ parentId =
293
+ "HasParent" === applyOpResult.modified.node.parent.type
294
+ ? Json.nn(
295
+ applyOpResult.modified.node.parent.node._id,
296
+ "Expected parent node to have an ID"
297
+ )
298
+ : void 0;
299
+ if (!parentId || !createdNodeIds.has(parentId))
300
+ result.updates.storageUpdates.set(
301
+ Json.nn(applyOpResult.modified.node._id),
302
+ Json.mergeStorageUpdates(
303
+ result.updates.storageUpdates.get(
304
+ Json.nn(applyOpResult.modified.node._id)
305
+ ),
306
+ applyOpResult.modified
307
+ )
308
+ ),
309
+ (_result$reverse = result.reverse).unshift.apply(
310
+ _result$reverse,
311
+ applyOpResult.reverse
312
+ );
313
+ (op.type !== Json.OpCode.CREATE_LIST &&
314
+ op.type !== Json.OpCode.CREATE_MAP &&
315
+ op.type !== Json.OpCode.CREATE_OBJECT) ||
316
+ createdNodeIds.add(Json.nn(applyOpResult.modified.node._id));
317
+ }
318
+ }
319
+ }
320
+ return result;
321
+ }
322
+ function applyOp(op, source) {
323
+ switch (op.type) {
324
+ case Json.OpCode.DELETE_OBJECT_KEY:
325
+ case Json.OpCode.UPDATE_OBJECT:
326
+ case Json.OpCode.DELETE_CRDT:
327
+ var item = state.items.get(op.id);
328
+ return null == item
329
+ ? { modified: !1 }
330
+ : item._apply(op, source === Json.OpSource.UNDOREDO_RECONNECT);
331
+ case Json.OpCode.SET_PARENT_KEY:
332
+ var _item = state.items.get(op.id);
333
+ return null == _item
334
+ ? { modified: !1 }
335
+ : "HasParent" === _item.parent.type &&
336
+ Json.isLiveList(_item.parent.node)
337
+ ? _item.parent.node._setChildKey(op.parentKey, _item, source)
338
+ : { modified: !1 };
339
+ case Json.OpCode.CREATE_OBJECT:
340
+ case Json.OpCode.CREATE_LIST:
341
+ case Json.OpCode.CREATE_MAP:
342
+ case Json.OpCode.CREATE_REGISTER:
343
+ if (void 0 === op.parentId) return { modified: !1 };
344
+ var parent = state.items.get(op.parentId);
345
+ return null == parent
346
+ ? { modified: !1 }
347
+ : parent._attachChild(op, source);
348
+ }
349
+ }
350
+ function connect() {
351
+ if (
352
+ "closed" !== state.connection.state &&
353
+ "unavailable" !== state.connection.state
354
+ )
355
+ return null;
356
+ var auth = (function (authentication, fetchPolyfill) {
357
+ if ("public" === authentication.type) {
358
+ if ("undefined" == typeof window && null == fetchPolyfill)
359
+ throw new Error(
360
+ "To use Liveblocks client in a non-dom environment with a publicApiKey, you need to provide a fetch polyfill."
361
+ );
362
+ return function (room) {
363
+ return fetchAuthEndpoint(
364
+ fetchPolyfill || fetch,
365
+ authentication.url,
366
+ { room: room, publicApiKey: authentication.publicApiKey }
367
+ );
368
+ };
369
+ }
370
+ if ("private" === authentication.type) {
371
+ if ("undefined" == typeof window && null == fetchPolyfill)
372
+ throw new Error(
373
+ "To use Liveblocks client in a non-dom environment with a url as auth endpoint, you need to provide a fetch polyfill."
374
+ );
375
+ return function (room) {
376
+ return fetchAuthEndpoint(
377
+ fetchPolyfill || fetch,
378
+ authentication.url,
379
+ { room: room }
380
+ );
381
+ };
382
+ }
383
+ if ("custom" === authentication.type) return authentication.callback;
384
+ throw new Error("Internal error. Unexpected authentication type");
385
+ })(context.authentication, context.fetchPolyfill),
386
+ createWebSocket = (function (liveblocksServer, WebSocketPolyfill) {
387
+ if ("undefined" == typeof window && null == WebSocketPolyfill)
388
+ throw new Error(
389
+ "To use Liveblocks client in a non-dom environment, you need to provide a WebSocket polyfill."
390
+ );
391
+ var ws = WebSocketPolyfill || WebSocket;
392
+ return function (token) {
393
+ return new ws(liveblocksServer + "/?token=" + token);
394
+ };
395
+ })(context.liveblocksServer, context.WebSocketPolyfill);
396
+ updateConnection({ state: "authenticating" }),
397
+ effects.authenticate(auth, createWebSocket);
398
+ }
399
+ function authenticationSuccess(token, socket) {
400
+ var connectionId, count;
401
+ socket.addEventListener("message", onMessage),
402
+ socket.addEventListener("open", onOpen),
403
+ socket.addEventListener("close", onClose),
404
+ socket.addEventListener("error", onError),
405
+ updateConnection({
406
+ state: "connecting",
407
+ id: token.actor,
408
+ userInfo: token.info,
409
+ userId: token.id,
410
+ }),
411
+ (state.idFactory =
412
+ ((connectionId = token.actor),
413
+ (count = 0),
414
+ function () {
415
+ return connectionId + ":" + count++;
416
+ })),
417
+ (state.socket = socket);
418
+ }
419
+ function onUpdatePresenceMessage(message) {
420
+ var user = state.users[message.actor];
421
+ if (
422
+ void 0 !== message.targetActor ||
423
+ null == user ||
424
+ user._hasReceivedInitialPresence
425
+ )
426
+ return (
427
+ (state.users[message.actor] =
428
+ null == user
429
+ ? {
430
+ connectionId: message.actor,
431
+ presence: message.data,
432
+ _hasReceivedInitialPresence: !0,
433
+ }
434
+ : {
435
+ id: user.id,
436
+ info: user.info,
437
+ connectionId: message.actor,
438
+ presence: Json._extends({}, user.presence, message.data),
439
+ _hasReceivedInitialPresence: !0,
440
+ }),
441
+ {
442
+ type: "update",
443
+ updates: message.data,
444
+ user: state.users[message.actor],
445
+ }
446
+ );
447
+ }
448
+ function onUserLeftMessage(message) {
449
+ var userLeftMessage = message,
450
+ user = state.users[userLeftMessage.actor];
451
+ return user
452
+ ? (delete state.users[userLeftMessage.actor],
453
+ { type: "leave", user: user })
454
+ : null;
455
+ }
456
+ function onRoomStateMessage(message) {
457
+ var newUsers = {};
458
+ for (var _key5 in message.users) {
459
+ var _connectionId = Number.parseInt(_key5),
460
+ user = message.users[_key5];
461
+ newUsers[_connectionId] = {
462
+ connectionId: _connectionId,
463
+ info: user.info,
464
+ id: user.id,
465
+ };
466
+ }
467
+ return (state.users = newUsers), { type: "reset" };
468
+ }
469
+ function onEvent(message) {
470
+ for (
471
+ var _step8,
472
+ _iterator8 = Json._createForOfIteratorHelperLoose(
473
+ state.listeners.event
474
+ );
475
+ !(_step8 = _iterator8()).done;
476
+
477
+ ) {
478
+ (0, _step8.value)({ connectionId: message.actor, event: message.event });
479
+ }
480
+ }
481
+ function onUserJoinedMessage(message) {
482
+ return (
483
+ (state.users[message.actor] = {
484
+ connectionId: message.actor,
485
+ info: message.info,
486
+ id: message.id,
487
+ _hasReceivedInitialPresence: !0,
488
+ }),
489
+ state.me &&
490
+ (state.buffer.messages.push({
491
+ type: Json.ClientMsgCode.UPDATE_PRESENCE,
492
+ data: state.me,
493
+ targetActor: message.actor,
494
+ }),
495
+ tryFlushing()),
496
+ { type: "enter", user: state.users[message.actor] }
497
+ );
498
+ }
499
+ function parseServerMessage(data) {
500
+ return Json.isJsonObject(data) ? data : null;
501
+ }
502
+ function onMessage(event) {
503
+ if ("pong" !== event.data) {
504
+ var text,
505
+ data,
506
+ messages =
507
+ ((text = event.data),
508
+ void 0 === (data = Json.tryParseJson(text))
509
+ ? null
510
+ : Json.isJsonArray(data)
511
+ ? Json.compact(
512
+ data.map(function (item) {
513
+ return parseServerMessage(item);
514
+ })
515
+ )
516
+ : Json.compact([parseServerMessage(data)]));
517
+ if (null !== messages && 0 !== messages.length) {
518
+ for (
519
+ var _step9,
520
+ updates = { storageUpdates: new Map(), others: [] },
521
+ _iterator9 = Json._createForOfIteratorHelperLoose(messages);
522
+ !(_step9 = _iterator9()).done;
358
523
 
359
- case LiveObject.ServerMsgCode.INITIAL_STORAGE_STATE:
360
- var offlineOps = new Map(state.offlineOperations);
361
- createOrUpdateRootFromMessage(message), applyAndSendOfflineOps(offlineOps), null == _getInitialStateResolver || _getInitialStateResolver();
362
- break;
524
+ ) {
525
+ var message = _step9.value;
526
+ switch (message.type) {
527
+ case Json.ServerMsgCode.USER_JOINED:
528
+ updates.others.push(onUserJoinedMessage(message));
529
+ break;
530
+ case Json.ServerMsgCode.UPDATE_PRESENCE:
531
+ var othersPresenceUpdate = onUpdatePresenceMessage(message);
532
+ othersPresenceUpdate && updates.others.push(othersPresenceUpdate);
533
+ break;
534
+ case Json.ServerMsgCode.BROADCASTED_EVENT:
535
+ onEvent(message);
536
+ break;
537
+ case Json.ServerMsgCode.USER_LEFT:
538
+ var _event2 = onUserLeftMessage(message);
539
+ _event2 && updates.others.push(_event2);
540
+ break;
541
+ case Json.ServerMsgCode.ROOM_STATE:
542
+ updates.others.push(onRoomStateMessage(message));
543
+ break;
544
+ case Json.ServerMsgCode.INITIAL_STORAGE_STATE:
545
+ var offlineOps = new Map(state.offlineOperations);
546
+ createOrUpdateRootFromMessage(message),
547
+ applyAndSendOfflineOps(offlineOps),
548
+ null == _getInitialStateResolver || _getInitialStateResolver();
549
+ break;
550
+ case Json.ServerMsgCode.UPDATE_STORAGE:
551
+ apply(message.ops, !1).updates.storageUpdates.forEach(function (
552
+ value,
553
+ key
554
+ ) {
555
+ updates.storageUpdates.set(
556
+ key,
557
+ Json.mergeStorageUpdates(
558
+ updates.storageUpdates.get(key),
559
+ value
560
+ )
561
+ );
562
+ });
563
+ }
564
+ }
565
+ notify(updates);
566
+ }
567
+ } else clearTimeout(state.timeoutHandles.pongTimeout);
568
+ }
569
+ function onClose(event) {
570
+ if (
571
+ ((state.socket = null),
572
+ clearTimeout(state.timeoutHandles.pongTimeout),
573
+ clearInterval(state.intervalHandles.heartbeat),
574
+ state.timeoutHandles.flush && clearTimeout(state.timeoutHandles.flush),
575
+ clearTimeout(state.timeoutHandles.reconnect),
576
+ (state.users = {}),
577
+ notify({ others: [{ type: "reset" }] }),
578
+ event.code >= 4e3 && event.code <= 4100)
579
+ ) {
580
+ updateConnection({ state: "failed" });
581
+ for (
582
+ var _step10,
583
+ error = new LiveblocksError(event.reason, event.code),
584
+ _iterator10 = Json._createForOfIteratorHelperLoose(
585
+ state.listeners.error
586
+ );
587
+ !(_step10 = _iterator10()).done;
363
588
 
364
- case LiveObject.ServerMsgCode.UPDATE_STORAGE:
365
- apply(message.ops, !1).updates.storageUpdates.forEach((function(value, key) {
366
- updates.storageUpdates.set(key, LiveObject.mergeStorageUpdates(updates.storageUpdates.get(key), value));
367
- }));
368
- }
589
+ ) {
590
+ (0, _step10.value)(error);
591
+ }
592
+ var _delay = getRetryDelay(!0);
593
+ state.numberOfRetry++,
594
+ "production" !== process.env.NODE_ENV &&
595
+ console.error(
596
+ "Connection to Liveblocks websocket server closed. Reason: " +
597
+ error.message +
598
+ " (code: " +
599
+ error.code +
600
+ "). Retrying in " +
601
+ _delay +
602
+ "ms."
603
+ ),
604
+ updateConnection({ state: "unavailable" }),
605
+ (state.timeoutHandles.reconnect = effects.scheduleReconnect(_delay));
606
+ } else if (event.code === Json.WebsocketCloseCodes.CLOSE_WITHOUT_RETRY)
607
+ updateConnection({ state: "closed" });
608
+ else {
609
+ var _delay2 = getRetryDelay();
610
+ state.numberOfRetry++,
611
+ "production" !== process.env.NODE_ENV &&
612
+ console.warn(
613
+ "Connection to Liveblocks websocket server closed (code: " +
614
+ event.code +
615
+ "). Retrying in " +
616
+ _delay2 +
617
+ "ms."
618
+ ),
619
+ updateConnection({ state: "unavailable" }),
620
+ (state.timeoutHandles.reconnect = effects.scheduleReconnect(_delay2));
369
621
  }
370
- notify(updates);
371
- }
372
- } else clearTimeout(state.timeoutHandles.pongTimeout);
373
- }
374
- function onClose(event) {
375
- if (state.socket = null, clearTimeout(state.timeoutHandles.pongTimeout), clearInterval(state.intervalHandles.heartbeat),
376
- state.timeoutHandles.flush && clearTimeout(state.timeoutHandles.flush), clearTimeout(state.timeoutHandles.reconnect),
377
- state.users = {}, notify({
378
- others: [ {
379
- type: "reset"
380
- } ]
381
- }), event.code >= 4e3 && event.code <= 4100) {
382
- updateConnection({
383
- state: "failed"
384
- });
385
- for (var _step10, error = new LiveblocksError(event.reason, event.code), _iterator10 = LiveObject._createForOfIteratorHelperLoose(state.listeners.error); !(_step10 = _iterator10()).done; ) {
386
- (0, _step10.value)(error);
387
- }
388
- var _delay = getRetryDelay(!0);
389
- state.numberOfRetry++, "production" !== process.env.NODE_ENV && console.error("Connection to Liveblocks websocket server closed. Reason: " + error.message + " (code: " + error.code + "). Retrying in " + _delay + "ms."),
390
- updateConnection({
391
- state: "unavailable"
392
- }), state.timeoutHandles.reconnect = effects.scheduleReconnect(_delay);
393
- } else if (event.code === LiveObject.WebsocketCloseCodes.CLOSE_WITHOUT_RETRY) updateConnection({
394
- state: "closed"
395
- }); else {
396
- var _delay2 = getRetryDelay();
397
- state.numberOfRetry++, "production" !== process.env.NODE_ENV && console.warn("Connection to Liveblocks websocket server closed (code: " + event.code + "). Retrying in " + _delay2 + "ms."),
398
- updateConnection({
399
- state: "unavailable"
400
- }), state.timeoutHandles.reconnect = effects.scheduleReconnect(_delay2);
401
- }
402
- }
403
- function updateConnection(connection) {
404
- state.connection = connection;
405
- for (var _step11, _iterator11 = LiveObject._createForOfIteratorHelperLoose(state.listeners.connection); !(_step11 = _iterator11()).done; ) {
406
- (0, _step11.value)(connection.state);
407
- }
408
- }
409
- function getRetryDelay(slow) {
410
- return void 0 === slow && (slow = !1), slow ? BACKOFF_RETRY_DELAYS_SLOW[state.numberOfRetry < BACKOFF_RETRY_DELAYS_SLOW.length ? state.numberOfRetry : BACKOFF_RETRY_DELAYS_SLOW.length - 1] : BACKOFF_RETRY_DELAYS[state.numberOfRetry < BACKOFF_RETRY_DELAYS.length ? state.numberOfRetry : BACKOFF_RETRY_DELAYS.length - 1];
411
- }
412
- function onError() {}
413
- function onOpen() {
414
- clearInterval(state.intervalHandles.heartbeat), state.intervalHandles.heartbeat = effects.startHeartbeatInterval(),
415
- "connecting" === state.connection.state && (updateConnection(LiveObject._extends({}, state.connection, {
416
- state: "open"
417
- })), state.numberOfRetry = 0, void 0 !== state.lastConnectionId && (state.buffer.presence = state.me,
418
- tryFlushing()), state.lastConnectionId = state.connection.id, state.root && state.buffer.messages.push({
419
- type: LiveObject.ClientMsgCode.FETCH_STORAGE
420
- }), tryFlushing());
421
- }
422
- function heartbeat() {
423
- null != state.socket && (clearTimeout(state.timeoutHandles.pongTimeout), state.timeoutHandles.pongTimeout = effects.schedulePongTimeout(),
424
- state.socket.readyState === state.socket.OPEN && state.socket.send("ping"));
425
- }
426
- function pongTimeout() {
427
- reconnect();
428
- }
429
- function reconnect() {
430
- state.socket && (state.socket.removeEventListener("open", onOpen), state.socket.removeEventListener("message", onMessage),
431
- state.socket.removeEventListener("close", onClose), state.socket.removeEventListener("error", onError),
432
- state.socket.close(), state.socket = null), updateConnection({
433
- state: "unavailable"
434
- }), clearTimeout(state.timeoutHandles.pongTimeout), state.timeoutHandles.flush && clearTimeout(state.timeoutHandles.flush),
435
- clearTimeout(state.timeoutHandles.reconnect), clearInterval(state.intervalHandles.heartbeat),
436
- connect();
437
- }
438
- function applyAndSendOfflineOps(offlineOps) {
439
- if (0 !== offlineOps.size) {
440
- var messages = [], ops = Array.from(offlineOps.values()), result = apply(ops, !0);
441
- messages.push({
442
- type: LiveObject.ClientMsgCode.UPDATE_STORAGE,
443
- ops: ops
444
- }), notify(result.updates), effects.send(messages);
445
- }
446
- }
447
- function tryFlushing() {
448
- var storageOps = state.buffer.storageOperations;
449
- if (storageOps.length > 0 && storageOps.forEach((function(op) {
450
- state.offlineOperations.set(op.opId, op);
451
- })), null != state.socket && state.socket.readyState === state.socket.OPEN) {
452
- var now = Date.now();
453
- if (now - state.lastFlushTime > context.throttleDelay) {
454
- var _messages = function(state) {
455
- var messages = [];
456
- state.buffer.presence && messages.push({
457
- type: LiveObject.ClientMsgCode.UPDATE_PRESENCE,
458
- data: state.buffer.presence
459
- });
460
- for (var _step12, _iterator12 = LiveObject._createForOfIteratorHelperLoose(state.buffer.messages); !(_step12 = _iterator12()).done; ) {
461
- var _event3 = _step12.value;
462
- messages.push(_event3);
463
- }
464
- state.buffer.storageOperations.length > 0 && messages.push({
465
- type: LiveObject.ClientMsgCode.UPDATE_STORAGE,
466
- ops: state.buffer.storageOperations
467
- });
468
- return messages;
469
- }(state);
470
- if (0 === _messages.length) return;
471
- effects.send(_messages), state.buffer = {
472
- messages: [],
473
- storageOperations: [],
474
- presence: null
475
- }, state.lastFlushTime = now;
476
- } else null != state.timeoutHandles.flush && clearTimeout(state.timeoutHandles.flush),
477
- state.timeoutHandles.flush = effects.delayFlush(context.throttleDelay - (now - state.lastFlushTime));
478
- } else state.buffer.storageOperations = [];
479
- }
480
- function getPresence() {
481
- return state.me;
482
- }
483
- function dispatch(ops) {
484
- var _state$buffer$storage;
485
- (_state$buffer$storage = state.buffer.storageOperations).push.apply(_state$buffer$storage, ops),
486
- tryFlushing();
487
- }
488
- var _getInitialStatePromise = null, _getInitialStateResolver = null;
489
- return {
490
- onClose: onClose,
491
- onMessage: onMessage,
492
- authenticationSuccess: authenticationSuccess,
493
- heartbeat: heartbeat,
494
- onNavigatorOnline: function() {
495
- "unavailable" === state.connection.state && reconnect();
496
- },
497
- simulateSocketClose: function() {
498
- state.socket && state.socket.close();
499
- },
500
- simulateSendCloseEvent: function(event) {
501
- state.socket && onClose(event);
502
- },
503
- onVisibilityChange: function(visibilityState) {
504
- "visible" === visibilityState && "open" === state.connection.state && heartbeat();
505
- },
506
- getUndoStack: function() {
507
- return state.undoStack;
508
- },
509
- getItemsCount: function() {
510
- return state.items.size;
511
- },
512
- connect: connect,
513
- disconnect: function() {
514
- state.socket && (state.socket.removeEventListener("open", onOpen), state.socket.removeEventListener("message", onMessage),
515
- state.socket.removeEventListener("close", onClose), state.socket.removeEventListener("error", onError),
516
- state.socket.close(), state.socket = null), updateConnection({
517
- state: "closed"
518
- }), state.timeoutHandles.flush && clearTimeout(state.timeoutHandles.flush), clearTimeout(state.timeoutHandles.reconnect),
519
- clearTimeout(state.timeoutHandles.pongTimeout), clearInterval(state.intervalHandles.heartbeat),
520
- state.users = {}, notify({
521
- others: [ {
522
- type: "reset"
523
- } ]
524
- }), function() {
525
- for (var _key6 in state.listeners) state.listeners[_key6] = [];
526
- }();
527
- },
528
- subscribe: function(firstParam, listener, options) {
529
- if (firstParam instanceof LiveObject.AbstractCrdt) return function(crdt, innerCallback, options) {
530
- return genericSubscribe((function(updates) {
531
- for (var _step, relatedUpdates = [], _iterator = LiveObject._createForOfIteratorHelperLoose(updates); !(_step = _iterator()).done; ) {
532
- var update = _step.value;
533
- null != options && options.isDeep && LiveObject.isSameNodeOrChildOf(update.node, crdt) ? relatedUpdates.push(update) : update.node._id === crdt._id && innerCallback(update.node);
534
- }
535
- null != options && options.isDeep && relatedUpdates.length > 0 && innerCallback(relatedUpdates);
536
- }));
537
- }(firstParam, listener, options);
538
- if ("function" == typeof firstParam) return genericSubscribe(firstParam);
539
- if (!isValidRoomEventType(firstParam)) throw new Error('"' + firstParam + '" is not a valid event name');
540
- return state.listeners[firstParam].push(listener), function() {
541
- var callbacks = state.listeners[firstParam];
542
- LiveObject.remove(callbacks, listener);
543
- };
544
- },
545
- unsubscribe: function(event, callback) {
546
- if (console.warn("unsubscribe is depreacted and will be removed in a future version.\nuse the callback returned by subscribe instead.\nSee v0.13 release notes for more information.\n"),
547
- !isValidRoomEventType(event)) throw new Error('"' + event + '" is not a valid event name');
548
- var callbacks = state.listeners[event];
549
- LiveObject.remove(callbacks, callback);
550
- },
551
- updatePresence: function(overrides, options) {
552
- var oldValues = {};
553
- for (var _key4 in null == state.buffer.presence && (state.buffer.presence = {}),
554
- overrides) state.buffer.presence[_key4] = overrides[_key4], oldValues[_key4] = state.me[_key4];
555
- state.me = LiveObject._extends({}, state.me, overrides), state.isBatching ? (null != options && options.addToHistory && state.batch.reverseOps.push({
556
- type: "presence",
557
- data: oldValues
558
- }), state.batch.updates.presence = !0) : (tryFlushing(), null != options && options.addToHistory && addToUndoStack([ {
559
- type: "presence",
560
- data: oldValues
561
- } ]), notify({
562
- presence: !0
563
- }));
564
- },
565
- broadcastEvent: function(event, options) {
566
- void 0 === options && (options = {
567
- shouldQueueEventIfNotReady: !1
568
- }), null == state.socket && 0 == options.shouldQueueEventIfNotReady || (state.buffer.messages.push({
569
- type: LiveObject.ClientMsgCode.BROADCAST_EVENT,
570
- event: event
571
- }), tryFlushing());
572
- },
573
- batch: function(callback) {
574
- if (state.isBatching) throw new Error("batch should not be called during a batch");
575
- state.isBatching = !0;
576
- try {
577
- callback();
578
- } finally {
579
- state.isBatching = !1, state.batch.reverseOps.length > 0 && addToUndoStack(state.batch.reverseOps),
580
- state.batch.ops.length > 0 && (state.redoStack = []), state.batch.ops.length > 0 && dispatch(state.batch.ops),
581
- notify(state.batch.updates), state.batch = {
582
- ops: [],
583
- reverseOps: [],
584
- updates: {
585
- others: [],
586
- storageUpdates: new Map,
587
- presence: !1
588
- }
589
- }, tryFlushing();
590
- }
591
- },
592
- undo: function() {
593
- if (state.isBatching) throw new Error("undo is not allowed during a batch");
594
- var historyItem = state.undoStack.pop();
595
- if (null != historyItem) {
596
- state.isHistoryPaused = !1;
597
- var result = apply(historyItem, !0);
598
- notify(result.updates), state.redoStack.push(result.reverse);
599
- for (var _step13, _iterator13 = LiveObject._createForOfIteratorHelperLoose(historyItem); !(_step13 = _iterator13()).done; ) {
600
- var op = _step13.value;
601
- "presence" !== op.type && state.buffer.storageOperations.push(op);
622
+ }
623
+ function updateConnection(connection) {
624
+ state.connection = connection;
625
+ for (
626
+ var _step11,
627
+ _iterator11 = Json._createForOfIteratorHelperLoose(
628
+ state.listeners.connection
629
+ );
630
+ !(_step11 = _iterator11()).done;
631
+
632
+ ) {
633
+ (0, _step11.value)(connection.state);
602
634
  }
603
- tryFlushing();
604
- }
605
- },
606
- redo: function() {
607
- if (state.isBatching) throw new Error("redo is not allowed during a batch");
608
- var historyItem = state.redoStack.pop();
609
- if (null != historyItem) {
610
- state.isHistoryPaused = !1;
611
- var result = apply(historyItem, !0);
612
- notify(result.updates), state.undoStack.push(result.reverse);
613
- for (var _step14, _iterator14 = LiveObject._createForOfIteratorHelperLoose(historyItem); !(_step14 = _iterator14()).done; ) {
614
- var op = _step14.value;
615
- "presence" !== op.type && state.buffer.storageOperations.push(op);
635
+ }
636
+ function getRetryDelay(slow) {
637
+ return (
638
+ void 0 === slow && (slow = !1),
639
+ slow
640
+ ? BACKOFF_RETRY_DELAYS_SLOW[
641
+ state.numberOfRetry < BACKOFF_RETRY_DELAYS_SLOW.length
642
+ ? state.numberOfRetry
643
+ : BACKOFF_RETRY_DELAYS_SLOW.length - 1
644
+ ]
645
+ : BACKOFF_RETRY_DELAYS[
646
+ state.numberOfRetry < BACKOFF_RETRY_DELAYS.length
647
+ ? state.numberOfRetry
648
+ : BACKOFF_RETRY_DELAYS.length - 1
649
+ ]
650
+ );
651
+ }
652
+ function onError() {}
653
+ function onOpen() {
654
+ clearInterval(state.intervalHandles.heartbeat),
655
+ (state.intervalHandles.heartbeat = effects.startHeartbeatInterval()),
656
+ "connecting" === state.connection.state &&
657
+ (updateConnection(
658
+ Json._extends({}, state.connection, { state: "open" })
659
+ ),
660
+ (state.numberOfRetry = 0),
661
+ void 0 !== state.lastConnectionId &&
662
+ ((state.buffer.presence = state.me), tryFlushing()),
663
+ (state.lastConnectionId = state.connection.id),
664
+ state.root &&
665
+ state.buffer.messages.push({
666
+ type: Json.ClientMsgCode.FETCH_STORAGE,
667
+ }),
668
+ tryFlushing());
669
+ }
670
+ function heartbeat() {
671
+ null != state.socket &&
672
+ (clearTimeout(state.timeoutHandles.pongTimeout),
673
+ (state.timeoutHandles.pongTimeout = effects.schedulePongTimeout()),
674
+ state.socket.readyState === state.socket.OPEN &&
675
+ state.socket.send("ping"));
676
+ }
677
+ function pongTimeout() {
678
+ reconnect();
679
+ }
680
+ function reconnect() {
681
+ state.socket &&
682
+ (state.socket.removeEventListener("open", onOpen),
683
+ state.socket.removeEventListener("message", onMessage),
684
+ state.socket.removeEventListener("close", onClose),
685
+ state.socket.removeEventListener("error", onError),
686
+ state.socket.close(),
687
+ (state.socket = null)),
688
+ updateConnection({ state: "unavailable" }),
689
+ clearTimeout(state.timeoutHandles.pongTimeout),
690
+ state.timeoutHandles.flush && clearTimeout(state.timeoutHandles.flush),
691
+ clearTimeout(state.timeoutHandles.reconnect),
692
+ clearInterval(state.intervalHandles.heartbeat),
693
+ connect();
694
+ }
695
+ function applyAndSendOfflineOps(offlineOps) {
696
+ if (0 !== offlineOps.size) {
697
+ var messages = [],
698
+ ops = Array.from(offlineOps.values()),
699
+ result = apply(ops, !0);
700
+ messages.push({ type: Json.ClientMsgCode.UPDATE_STORAGE, ops: ops }),
701
+ notify(result.updates),
702
+ effects.send(messages);
616
703
  }
617
- tryFlushing();
618
- }
619
- },
620
- pauseHistory: function() {
621
- state.pausedHistory = [], state.isHistoryPaused = !0;
622
- },
623
- resumeHistory: function() {
624
- state.isHistoryPaused = !1, state.pausedHistory.length > 0 && addToUndoStack(state.pausedHistory),
625
- state.pausedHistory = [];
626
- },
627
- getStorage: function() {
628
- return state.root ? new Promise((function(resolve) {
629
- return resolve({
630
- root: state.root
631
- });
632
- })) : (null == _getInitialStatePromise && (state.buffer.messages.push({
633
- type: LiveObject.ClientMsgCode.FETCH_STORAGE
634
- }), tryFlushing(), _getInitialStatePromise = new Promise((function(resolve) {
635
- return _getInitialStateResolver = resolve;
636
- }))), _getInitialStatePromise.then((function() {
637
- return {
638
- root: state.root
639
- };
640
- })));
641
- },
642
- selectors: {
643
- getConnectionState: function() {
644
- return state.connection.state;
645
- },
646
- getSelf: function() {
647
- return "open" === state.connection.state || "connecting" === state.connection.state ? {
648
- connectionId: state.connection.id,
649
- id: state.connection.userId,
650
- info: state.connection.userInfo,
651
- presence: getPresence()
652
- } : null;
653
- },
654
- getPresence: getPresence,
655
- getOthers: function() {
656
- return state.others;
657
- }
658
- }
659
- };
660
- }
704
+ }
705
+ function tryFlushing() {
706
+ var storageOps = state.buffer.storageOperations;
707
+ if (
708
+ (storageOps.length > 0 &&
709
+ storageOps.forEach(function (op) {
710
+ state.offlineOperations.set(Json.nn(op.opId), op);
711
+ }),
712
+ null != state.socket && state.socket.readyState === state.socket.OPEN)
713
+ ) {
714
+ var now = Date.now();
715
+ if (now - state.lastFlushTime > context.throttleDelay) {
716
+ var _messages = (function (state) {
717
+ var messages = [];
718
+ state.buffer.presence &&
719
+ messages.push({
720
+ type: Json.ClientMsgCode.UPDATE_PRESENCE,
721
+ data: state.buffer.presence,
722
+ });
723
+ for (
724
+ var _step12,
725
+ _iterator12 = Json._createForOfIteratorHelperLoose(
726
+ state.buffer.messages
727
+ );
728
+ !(_step12 = _iterator12()).done;
661
729
 
662
- function createRoom(options, context) {
663
- var _options$initialPrese, _options$initialStora, initialPresence = null != (_options$initialPrese = options.initialPresence) ? _options$initialPrese : options.defaultPresence, initialStorage = null != (_options$initialStora = options.initialStorage) ? _options$initialStora : options.defaultStorageRoot, machine = makeStateMachine(function(initialPresence, initialStorage) {
730
+ ) {
731
+ var _event3 = _step12.value;
732
+ messages.push(_event3);
733
+ }
734
+ state.buffer.storageOperations.length > 0 &&
735
+ messages.push({
736
+ type: Json.ClientMsgCode.UPDATE_STORAGE,
737
+ ops: state.buffer.storageOperations,
738
+ });
739
+ return messages;
740
+ })(state);
741
+ if (0 === _messages.length) return;
742
+ effects.send(_messages),
743
+ (state.buffer = {
744
+ messages: [],
745
+ storageOperations: [],
746
+ presence: null,
747
+ }),
748
+ (state.lastFlushTime = now);
749
+ } else
750
+ null != state.timeoutHandles.flush &&
751
+ clearTimeout(state.timeoutHandles.flush),
752
+ (state.timeoutHandles.flush = effects.delayFlush(
753
+ context.throttleDelay - (now - state.lastFlushTime)
754
+ ));
755
+ } else state.buffer.storageOperations = [];
756
+ }
757
+ function getPresence() {
758
+ return state.me;
759
+ }
760
+ function dispatch(ops) {
761
+ var _state$buffer$storage;
762
+ (_state$buffer$storage = state.buffer.storageOperations).push.apply(
763
+ _state$buffer$storage,
764
+ ops
765
+ ),
766
+ tryFlushing();
767
+ }
768
+ var _getInitialStatePromise = null,
769
+ _getInitialStateResolver = null;
664
770
  return {
665
- connection: {
666
- state: "closed"
667
- },
668
- token: null,
669
- lastConnectionId: null,
670
- socket: null,
671
- listeners: {
672
- event: [],
673
- others: [],
674
- "my-presence": [],
675
- error: [],
676
- connection: [],
677
- storage: []
678
- },
679
- numberOfRetry: 0,
680
- lastFlushTime: 0,
681
- timeoutHandles: {
682
- flush: null,
683
- reconnect: 0,
684
- pongTimeout: 0
685
- },
686
- buffer: {
687
- presence: null == initialPresence ? {} : initialPresence,
688
- messages: [],
689
- storageOperations: []
690
- },
691
- intervalHandles: {
692
- heartbeat: 0
693
- },
694
- me: null == initialPresence ? {} : initialPresence,
695
- users: {},
696
- others: makeOthers({}),
697
- defaultStorageRoot: initialStorage,
698
- idFactory: null,
699
- clock: 0,
700
- opClock: 0,
701
- items: new Map,
702
- root: void 0,
703
- undoStack: [],
704
- redoStack: [],
705
- isHistoryPaused: !1,
706
- pausedHistory: [],
707
- isBatching: !1,
708
- batch: {
709
- ops: [],
710
- updates: {
711
- storageUpdates: new Map,
712
- presence: !1,
713
- others: []
771
+ onClose: onClose,
772
+ onMessage: onMessage,
773
+ authenticationSuccess: authenticationSuccess,
774
+ heartbeat: heartbeat,
775
+ onNavigatorOnline: function () {
776
+ "unavailable" === state.connection.state && reconnect();
714
777
  },
715
- reverseOps: []
716
- },
717
- offlineOperations: new Map
718
- };
719
- }("function" == typeof initialPresence ? initialPresence(context.roomId) : initialPresence, "function" == typeof initialStorage ? initialStorage(context.roomId) : initialStorage), context), room = {
720
- id: context.roomId,
721
- getConnectionState: machine.selectors.getConnectionState,
722
- getSelf: machine.selectors.getSelf,
723
- subscribe: machine.subscribe,
724
- unsubscribe: machine.unsubscribe,
725
- getPresence: machine.selectors.getPresence,
726
- updatePresence: machine.updatePresence,
727
- getOthers: machine.selectors.getOthers,
728
- broadcastEvent: machine.broadcastEvent,
729
- getStorage: machine.getStorage,
730
- batch: machine.batch,
731
- history: {
732
- undo: machine.undo,
733
- redo: machine.redo,
734
- pause: machine.pauseHistory,
735
- resume: machine.resumeHistory
736
- },
737
- internalDevTools: {
738
- closeWebsocket: machine.simulateSocketClose,
739
- sendCloseEvent: machine.simulateSendCloseEvent
740
- }
741
- };
742
- return {
743
- connect: machine.connect,
744
- disconnect: machine.disconnect,
745
- onNavigatorOnline: machine.onNavigatorOnline,
746
- onVisibilityChange: machine.onVisibilityChange,
747
- room: room
748
- };
749
- }
778
+ simulateSocketClose: function () {
779
+ state.socket && (state.socket = null);
780
+ },
781
+ simulateSendCloseEvent: function (event) {
782
+ onClose(event);
783
+ },
784
+ onVisibilityChange: function (visibilityState) {
785
+ "visible" === visibilityState &&
786
+ "open" === state.connection.state &&
787
+ heartbeat();
788
+ },
789
+ getUndoStack: function () {
790
+ return state.undoStack;
791
+ },
792
+ getItemsCount: function () {
793
+ return state.items.size;
794
+ },
795
+ connect: connect,
796
+ disconnect: function () {
797
+ state.socket &&
798
+ (state.socket.removeEventListener("open", onOpen),
799
+ state.socket.removeEventListener("message", onMessage),
800
+ state.socket.removeEventListener("close", onClose),
801
+ state.socket.removeEventListener("error", onError),
802
+ state.socket.close(),
803
+ (state.socket = null)),
804
+ updateConnection({ state: "closed" }),
805
+ state.timeoutHandles.flush && clearTimeout(state.timeoutHandles.flush),
806
+ clearTimeout(state.timeoutHandles.reconnect),
807
+ clearTimeout(state.timeoutHandles.pongTimeout),
808
+ clearInterval(state.intervalHandles.heartbeat),
809
+ (state.users = {}),
810
+ notify({ others: [{ type: "reset" }] }),
811
+ (function () {
812
+ for (var _key6 in state.listeners) state.listeners[_key6] = [];
813
+ })();
814
+ },
815
+ subscribe: function (firstParam, listener, options) {
816
+ if (Json.isLiveNode(firstParam))
817
+ return (function (liveValue, innerCallback, options) {
818
+ return genericSubscribe(function (updates) {
819
+ for (
820
+ var _step,
821
+ relatedUpdates = [],
822
+ _iterator = Json._createForOfIteratorHelperLoose(updates);
823
+ !(_step = _iterator()).done;
824
+
825
+ ) {
826
+ var update = _step.value;
827
+ null != options &&
828
+ options.isDeep &&
829
+ Json.isSameNodeOrChildOf(update.node, liveValue)
830
+ ? relatedUpdates.push(update)
831
+ : update.node._id === liveValue._id &&
832
+ innerCallback(update.node);
833
+ }
834
+ null != options &&
835
+ options.isDeep &&
836
+ relatedUpdates.length > 0 &&
837
+ innerCallback(relatedUpdates);
838
+ });
839
+ })(firstParam, listener, options);
840
+ if ("function" == typeof firstParam) return genericSubscribe(firstParam);
841
+ if (
842
+ "my-presence" !== (value = firstParam) &&
843
+ "others" !== value &&
844
+ "event" !== value &&
845
+ "error" !== value &&
846
+ "connection" !== value
847
+ )
848
+ throw new Error('"' + firstParam + '" is not a valid event name');
849
+ var value;
850
+ return (
851
+ state.listeners[firstParam].push(listener),
852
+ function () {
853
+ var callbacks = state.listeners[firstParam];
854
+ Json.remove(callbacks, listener);
855
+ }
856
+ );
857
+ },
858
+ updatePresence: function (overrides, options) {
859
+ var oldValues = {};
860
+ for (var _key4 in (null == state.buffer.presence &&
861
+ (state.buffer.presence = {}),
862
+ overrides)) {
863
+ var overrideValue = overrides[_key4];
864
+ void 0 !== overrideValue &&
865
+ ((state.buffer.presence[_key4] = overrideValue),
866
+ (oldValues[_key4] = state.me[_key4]));
867
+ }
868
+ (state.me = Json._extends({}, state.me, overrides)),
869
+ state.isBatching
870
+ ? (null != options &&
871
+ options.addToHistory &&
872
+ state.batch.reverseOps.push({
873
+ type: "presence",
874
+ data: oldValues,
875
+ }),
876
+ (state.batch.updates.presence = !0))
877
+ : (tryFlushing(),
878
+ null != options &&
879
+ options.addToHistory &&
880
+ addToUndoStack([{ type: "presence", data: oldValues }]),
881
+ notify({ presence: !0 }));
882
+ },
883
+ broadcastEvent: function (event, options) {
884
+ void 0 === options && (options = { shouldQueueEventIfNotReady: !1 }),
885
+ (null == state.socket && 0 == options.shouldQueueEventIfNotReady) ||
886
+ (state.buffer.messages.push({
887
+ type: Json.ClientMsgCode.BROADCAST_EVENT,
888
+ event: event,
889
+ }),
890
+ tryFlushing());
891
+ },
892
+ batch: function (callback) {
893
+ if (state.isBatching)
894
+ throw new Error("batch should not be called during a batch");
895
+ state.isBatching = !0;
896
+ try {
897
+ callback();
898
+ } finally {
899
+ (state.isBatching = !1),
900
+ state.batch.reverseOps.length > 0 &&
901
+ addToUndoStack(state.batch.reverseOps),
902
+ state.batch.ops.length > 0 && (state.redoStack = []),
903
+ state.batch.ops.length > 0 && dispatch(state.batch.ops),
904
+ notify(state.batch.updates),
905
+ (state.batch = {
906
+ ops: [],
907
+ reverseOps: [],
908
+ updates: { others: [], storageUpdates: new Map(), presence: !1 },
909
+ }),
910
+ tryFlushing();
911
+ }
912
+ },
913
+ undo: function () {
914
+ if (state.isBatching)
915
+ throw new Error("undo is not allowed during a batch");
916
+ var historyItem = state.undoStack.pop();
917
+ if (null != historyItem) {
918
+ state.isHistoryPaused = !1;
919
+ var result = apply(historyItem, !0);
920
+ notify(result.updates), state.redoStack.push(result.reverse);
921
+ for (
922
+ var _step13,
923
+ _iterator13 = Json._createForOfIteratorHelperLoose(historyItem);
924
+ !(_step13 = _iterator13()).done;
750
925
 
751
- var LiveblocksError = function(_Error) {
752
- function LiveblocksError(message, code) {
753
- return _Error.call(this, message) || this;
754
- }
755
- return LiveObject._inheritsLoose(LiveblocksError, _Error), LiveblocksError;
756
- }(LiveObject._wrapNativeSuper(Error));
926
+ ) {
927
+ var op = _step13.value;
928
+ "presence" !== op.type && state.buffer.storageOperations.push(op);
929
+ }
930
+ tryFlushing();
931
+ }
932
+ },
933
+ redo: function () {
934
+ if (state.isBatching)
935
+ throw new Error("redo is not allowed during a batch");
936
+ var historyItem = state.redoStack.pop();
937
+ if (null != historyItem) {
938
+ state.isHistoryPaused = !1;
939
+ var result = apply(historyItem, !0);
940
+ notify(result.updates), state.undoStack.push(result.reverse);
941
+ for (
942
+ var _step14,
943
+ _iterator14 = Json._createForOfIteratorHelperLoose(historyItem);
944
+ !(_step14 = _iterator14()).done;
757
945
 
758
- function parseToken(token) {
759
- var tokenParts = token.split(".");
760
- if (3 !== tokenParts.length) throw new Error("Authentication error. Liveblocks could not parse the response of your authentication endpoint");
761
- var data = LiveObject.tryParseJson(LiveObject.b64decode(tokenParts[1]));
762
- if (void 0 !== data && LiveObject.isJsonObject(data) && "number" == typeof data.actor && (void 0 === data.id || "string" == typeof data.id)) return {
763
- actor: data.actor,
764
- id: data.id,
765
- info: data.info
766
- };
767
- throw new Error("Authentication error. Liveblocks could not parse the response of your authentication endpoint");
946
+ ) {
947
+ var op = _step14.value;
948
+ "presence" !== op.type && state.buffer.storageOperations.push(op);
949
+ }
950
+ tryFlushing();
951
+ }
952
+ },
953
+ pauseHistory: function () {
954
+ (state.pausedHistory = []), (state.isHistoryPaused = !0);
955
+ },
956
+ resumeHistory: function () {
957
+ (state.isHistoryPaused = !1),
958
+ state.pausedHistory.length > 0 && addToUndoStack(state.pausedHistory),
959
+ (state.pausedHistory = []);
960
+ },
961
+ getStorage: function () {
962
+ return state.root
963
+ ? new Promise(function (resolve) {
964
+ return resolve({ root: state.root });
965
+ })
966
+ : (null == _getInitialStatePromise &&
967
+ (state.buffer.messages.push({
968
+ type: Json.ClientMsgCode.FETCH_STORAGE,
969
+ }),
970
+ tryFlushing(),
971
+ (_getInitialStatePromise = new Promise(function (resolve) {
972
+ return (_getInitialStateResolver = resolve);
973
+ }))),
974
+ _getInitialStatePromise.then(function () {
975
+ return { root: Json.nn(state.root) };
976
+ }));
977
+ },
978
+ selectors: {
979
+ getConnectionState: function () {
980
+ return state.connection.state;
981
+ },
982
+ getSelf: function () {
983
+ return "open" === state.connection.state ||
984
+ "connecting" === state.connection.state
985
+ ? {
986
+ connectionId: state.connection.id,
987
+ id: state.connection.userId,
988
+ info: state.connection.userInfo,
989
+ presence: getPresence(),
990
+ }
991
+ : null;
992
+ },
993
+ getPresence: getPresence,
994
+ getOthers: function () {
995
+ return state.others;
996
+ },
997
+ },
998
+ };
768
999
  }
769
-
1000
+ function createRoom(options, context) {
1001
+ var _options$initialPrese,
1002
+ _options$initialStora,
1003
+ initialPresence =
1004
+ null != (_options$initialPrese = options.initialPresence)
1005
+ ? _options$initialPrese
1006
+ : options.defaultPresence,
1007
+ initialStorage =
1008
+ null != (_options$initialStora = options.initialStorage)
1009
+ ? _options$initialStora
1010
+ : options.defaultStorageRoot,
1011
+ machine = makeStateMachine(
1012
+ (function (initialPresence, initialStorage) {
1013
+ return {
1014
+ connection: { state: "closed" },
1015
+ token: null,
1016
+ lastConnectionId: null,
1017
+ socket: null,
1018
+ listeners: {
1019
+ event: [],
1020
+ others: [],
1021
+ "my-presence": [],
1022
+ error: [],
1023
+ connection: [],
1024
+ storage: [],
1025
+ },
1026
+ numberOfRetry: 0,
1027
+ lastFlushTime: 0,
1028
+ timeoutHandles: { flush: null, reconnect: 0, pongTimeout: 0 },
1029
+ buffer: {
1030
+ presence: null == initialPresence ? {} : initialPresence,
1031
+ messages: [],
1032
+ storageOperations: [],
1033
+ },
1034
+ intervalHandles: { heartbeat: 0 },
1035
+ me: null == initialPresence ? {} : initialPresence,
1036
+ users: {},
1037
+ others: makeOthers({}),
1038
+ defaultStorageRoot: initialStorage,
1039
+ idFactory: null,
1040
+ clock: 0,
1041
+ opClock: 0,
1042
+ items: new Map(),
1043
+ root: void 0,
1044
+ undoStack: [],
1045
+ redoStack: [],
1046
+ isHistoryPaused: !1,
1047
+ pausedHistory: [],
1048
+ isBatching: !1,
1049
+ batch: {
1050
+ ops: [],
1051
+ updates: { storageUpdates: new Map(), presence: !1, others: [] },
1052
+ reverseOps: [],
1053
+ },
1054
+ offlineOperations: new Map(),
1055
+ };
1056
+ })(
1057
+ "function" == typeof initialPresence
1058
+ ? initialPresence(context.roomId)
1059
+ : initialPresence,
1060
+ "function" == typeof initialStorage
1061
+ ? initialStorage(context.roomId)
1062
+ : initialStorage
1063
+ ),
1064
+ context
1065
+ ),
1066
+ room = {
1067
+ id: context.roomId,
1068
+ getConnectionState: machine.selectors.getConnectionState,
1069
+ getSelf: machine.selectors.getSelf,
1070
+ subscribe: machine.subscribe,
1071
+ getPresence: machine.selectors.getPresence,
1072
+ updatePresence: machine.updatePresence,
1073
+ getOthers: machine.selectors.getOthers,
1074
+ broadcastEvent: machine.broadcastEvent,
1075
+ getStorage: machine.getStorage,
1076
+ batch: machine.batch,
1077
+ history: {
1078
+ undo: machine.undo,
1079
+ redo: machine.redo,
1080
+ pause: machine.pauseHistory,
1081
+ resume: machine.resumeHistory,
1082
+ },
1083
+ __INTERNAL_DO_NOT_USE: {
1084
+ simulateCloseWebsocket: machine.simulateSocketClose,
1085
+ simulateSendCloseEvent: machine.simulateSendCloseEvent,
1086
+ },
1087
+ };
1088
+ return {
1089
+ connect: machine.connect,
1090
+ disconnect: machine.disconnect,
1091
+ onNavigatorOnline: machine.onNavigatorOnline,
1092
+ onVisibilityChange: machine.onVisibilityChange,
1093
+ room: room,
1094
+ };
1095
+ }
1096
+ var LiveblocksError = (function (_Error) {
1097
+ function LiveblocksError(message, code) {
1098
+ return _Error.call(this, message) || this;
1099
+ }
1100
+ return Json._inheritsLoose(LiveblocksError, _Error), LiveblocksError;
1101
+ })(Json._wrapNativeSuper(Error));
770
1102
  function fetchAuthEndpoint(fetch, endpoint, body) {
771
- return fetch(endpoint, {
772
- method: "POST",
773
- headers: {
774
- "Content-Type": "application/json"
775
- },
776
- body: JSON.stringify(body)
777
- }).then((function(res) {
778
- if (!res.ok) throw new AuthenticationError("Expected a status 200 but got " + res.status + ' when doing a POST request on "' + endpoint + '"');
779
- return res.json().catch((function(er) {
780
- throw new AuthenticationError('Expected a json when doing a POST request on "' + endpoint + '". ' + er);
781
- }));
782
- })).then((function(authResponse) {
783
- if ("string" != typeof authResponse.token) throw new AuthenticationError('Expected a json with a string token when doing a POST request on "' + endpoint + '", but got ' + JSON.stringify(authResponse));
784
- return authResponse;
785
- }));
1103
+ return fetch(endpoint, {
1104
+ method: "POST",
1105
+ headers: { "Content-Type": "application/json" },
1106
+ body: JSON.stringify(body),
1107
+ })
1108
+ .then(function (res) {
1109
+ if (!res.ok)
1110
+ throw new AuthenticationError(
1111
+ "Expected a status 200 but got " +
1112
+ res.status +
1113
+ ' when doing a POST request on "' +
1114
+ endpoint +
1115
+ '"'
1116
+ );
1117
+ return res.json().catch(function (er) {
1118
+ throw new AuthenticationError(
1119
+ 'Expected a JSON response when doing a POST request on "' +
1120
+ endpoint +
1121
+ '". ' +
1122
+ er
1123
+ );
1124
+ });
1125
+ })
1126
+ .then(function (data) {
1127
+ if (!Json.isPlainObject(data) || "string" != typeof data.token)
1128
+ throw new AuthenticationError(
1129
+ 'Expected a JSON response of the form `{ token: "..." }` when doing a POST request on "' +
1130
+ endpoint +
1131
+ '", but got ' +
1132
+ JSON.stringify(data)
1133
+ );
1134
+ return { token: data.token };
1135
+ });
786
1136
  }
787
-
788
- var AuthenticationError = function(_Error2) {
789
- function AuthenticationError(message) {
790
- return _Error2.call(this, message) || this;
791
- }
792
- return LiveObject._inheritsLoose(AuthenticationError, _Error2), AuthenticationError;
793
- }(LiveObject._wrapNativeSuper(Error));
794
-
1137
+ var AuthenticationError = (function (_Error2) {
1138
+ function AuthenticationError(message) {
1139
+ return _Error2.call(this, message) || this;
1140
+ }
1141
+ return Json._inheritsLoose(AuthenticationError, _Error2), AuthenticationError;
1142
+ })(Json._wrapNativeSuper(Error));
795
1143
  function prepareAuthentication(clientOptions) {
796
- if ("string" == typeof clientOptions.publicApiKey) return {
797
- type: "public",
798
- publicApiKey: clientOptions.publicApiKey,
799
- url: clientOptions.publicAuthorizeEndpoint || "https://liveblocks.io/api/public/authorize"
800
- };
801
- if ("string" == typeof clientOptions.authEndpoint) return {
802
- type: "private",
803
- url: clientOptions.authEndpoint
804
- };
805
- if ("function" == typeof clientOptions.authEndpoint) return {
806
- type: "custom",
807
- callback: clientOptions.authEndpoint
808
- };
809
- throw new Error("Invalid Liveblocks client options. For more information: https://liveblocks.io/docs/api-reference/liveblocks-client#createClient");
1144
+ if ("string" == typeof clientOptions.publicApiKey)
1145
+ return {
1146
+ type: "public",
1147
+ publicApiKey: clientOptions.publicApiKey,
1148
+ url:
1149
+ clientOptions.publicAuthorizeEndpoint ||
1150
+ "https://liveblocks.io/api/public/authorize",
1151
+ };
1152
+ if ("string" == typeof clientOptions.authEndpoint)
1153
+ return { type: "private", url: clientOptions.authEndpoint };
1154
+ if ("function" == typeof clientOptions.authEndpoint)
1155
+ return { type: "custom", callback: clientOptions.authEndpoint };
1156
+ throw new Error(
1157
+ "Invalid Liveblocks client options. For more information: https://liveblocks.io/docs/api-reference/liveblocks-client#createClient"
1158
+ );
810
1159
  }
1160
+ (exports.LiveList = Json.LiveList),
1161
+ (exports.LiveMap = Json.LiveMap),
1162
+ (exports.LiveObject = Json.LiveObject),
1163
+ (exports.createClient = function (options) {
1164
+ var clientOptions = options,
1165
+ throttleDelay = (function (options) {
1166
+ if (void 0 === options.throttle) return 100;
1167
+ if (
1168
+ "number" != typeof options.throttle ||
1169
+ options.throttle < 80 ||
1170
+ options.throttle > 1e3
1171
+ )
1172
+ throw new Error("throttle should be a number between 80 and 1000.");
1173
+ return options.throttle;
1174
+ })(options),
1175
+ rooms = new Map();
1176
+ return (
1177
+ "undefined" != typeof window &&
1178
+ void 0 !== window.addEventListener &&
1179
+ window.addEventListener("online", function () {
1180
+ for (
1181
+ var _step, _iterator = Json._createForOfIteratorHelperLoose(rooms);
1182
+ !(_step = _iterator()).done;
1183
+
1184
+ ) {
1185
+ _step.value[1].onNavigatorOnline();
1186
+ }
1187
+ }),
1188
+ "undefined" != typeof document &&
1189
+ document.addEventListener("visibilitychange", function () {
1190
+ for (
1191
+ var _step2,
1192
+ _iterator2 = Json._createForOfIteratorHelperLoose(rooms);
1193
+ !(_step2 = _iterator2()).done;
811
1194
 
812
- exports.LiveList = LiveObject.LiveList, exports.LiveMap = LiveObject.LiveMap, exports.LiveObject = LiveObject.LiveObject,
813
- exports.createClient = function(options) {
814
- var clientOptions = options, throttleDelay = function(options) {
815
- if (void 0 === options.throttle) return 100;
816
- if ("number" != typeof options.throttle || options.throttle < 80 || options.throttle > 1e3) throw new Error("throttle should be a number between 80 and 1000.");
817
- return options.throttle;
818
- }(options), rooms = new Map;
819
- return "undefined" != typeof window && window.addEventListener("online", (function() {
820
- for (var _step, _iterator = LiveObject._createForOfIteratorHelperLoose(rooms); !(_step = _iterator()).done; ) {
821
- _step.value[1].onNavigatorOnline();
822
- }
823
- })), "undefined" != typeof document && document.addEventListener("visibilitychange", (function() {
824
- for (var _step2, _iterator2 = LiveObject._createForOfIteratorHelperLoose(rooms); !(_step2 = _iterator2()).done; ) {
825
- _step2.value[1].onVisibilityChange(document.visibilityState);
826
- }
827
- })), {
828
- getRoom: function(roomId) {
829
- var internalRoom = rooms.get(roomId);
830
- return internalRoom ? internalRoom.room : null;
831
- },
832
- enter: function(roomId, options) {
833
- void 0 === options && (options = {});
834
- var internalRoom = rooms.get(roomId);
835
- return internalRoom || (LiveObject.deprecateIf(options.defaultPresence, "Argument `defaultPresence` will be removed in @liveblocks/client 0.18. Please use `initialPresence` instead. For more info, see https://bit.ly/3Niy5aP", "defaultPresence"),
836
- LiveObject.deprecateIf(options.defaultStorageRoot, "Argument `defaultStorageRoot` will be removed in @liveblocks/client 0.18. Please use `initialStorage` instead. For more info, see https://bit.ly/3Niy5aP", "defaultStorageRoot"),
837
- internalRoom = createRoom({
838
- initialPresence: options.initialPresence,
839
- initialStorage: options.initialStorage,
840
- defaultPresence: options.defaultPresence,
841
- defaultStorageRoot: options.defaultStorageRoot
842
- }, {
843
- roomId: roomId,
844
- throttleDelay: throttleDelay,
845
- WebSocketPolyfill: clientOptions.WebSocketPolyfill,
846
- fetchPolyfill: clientOptions.fetchPolyfill,
847
- liveblocksServer: clientOptions.liveblocksServer || "wss://liveblocks.net/v5",
848
- authentication: prepareAuthentication(clientOptions)
849
- }), rooms.set(roomId, internalRoom), options.DO_NOT_USE_withoutConnecting || internalRoom.connect()),
850
- internalRoom.room;
851
- },
852
- leave: function(roomId) {
853
- var room = rooms.get(roomId);
854
- room && (room.disconnect(), rooms.delete(roomId));
855
- }
856
- };
857
- };
1195
+ ) {
1196
+ _step2.value[1].onVisibilityChange(document.visibilityState);
1197
+ }
1198
+ }),
1199
+ {
1200
+ getRoom: function (roomId) {
1201
+ var internalRoom = rooms.get(roomId);
1202
+ return internalRoom ? internalRoom.room : null;
1203
+ },
1204
+ enter: function (roomId, options) {
1205
+ void 0 === options && (options = {});
1206
+ var internalRoom = rooms.get(roomId);
1207
+ if (internalRoom) return internalRoom.room;
1208
+ if (
1209
+ (Json.errorIf(
1210
+ options.defaultPresence,
1211
+ "Argument `defaultPresence` will be removed in @liveblocks/client 0.18. Please use `initialPresence` instead. For more info, see https://bit.ly/3Niy5aP"
1212
+ ),
1213
+ Json.errorIf(
1214
+ options.defaultStorageRoot,
1215
+ "Argument `defaultStorageRoot` will be removed in @liveblocks/client 0.18. Please use `initialStorage` instead. For more info, see https://bit.ly/3Niy5aP"
1216
+ ),
1217
+ (internalRoom = createRoom(
1218
+ {
1219
+ initialPresence: options.initialPresence,
1220
+ initialStorage: options.initialStorage,
1221
+ defaultPresence: options.defaultPresence,
1222
+ defaultStorageRoot: options.defaultStorageRoot,
1223
+ },
1224
+ {
1225
+ roomId: roomId,
1226
+ throttleDelay: throttleDelay,
1227
+ WebSocketPolyfill: clientOptions.WebSocketPolyfill,
1228
+ fetchPolyfill: clientOptions.fetchPolyfill,
1229
+ liveblocksServer:
1230
+ (null == clientOptions
1231
+ ? void 0
1232
+ : clientOptions.liveblocksServer) ||
1233
+ "wss://liveblocks.net/v6",
1234
+ authentication: prepareAuthentication(clientOptions),
1235
+ }
1236
+ )),
1237
+ rooms.set(roomId, internalRoom),
1238
+ !options.DO_NOT_USE_withoutConnecting)
1239
+ ) {
1240
+ if ("undefined" == typeof atob) {
1241
+ if (null == clientOptions.atobPolyfill)
1242
+ throw new Error(
1243
+ "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"
1244
+ );
1245
+ global.atob = clientOptions.atobPolyfill;
1246
+ }
1247
+ internalRoom.connect();
1248
+ }
1249
+ return internalRoom.room;
1250
+ },
1251
+ leave: function (roomId) {
1252
+ var room = rooms.get(roomId);
1253
+ room && (room.disconnect(), rooms.delete(roomId));
1254
+ },
1255
+ }
1256
+ );
1257
+ });