firetruss-worker 2.6.0 → 3.0.0

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.
@@ -1,597 +1,527 @@
1
1
  /* globals firebase */
2
2
 
3
- var fireworkers = [];
4
- var apps = {};
3
+ const fireworkers = [];
4
+ const apps = {};
5
5
  // This version is filled in by the build, don't reformat the line.
6
- var VERSION = '2.6.0';
6
+ const VERSION = '3.0.0';
7
7
 
8
8
 
9
- var LocalStorage = function LocalStorage() {
10
- this._items = [];
11
- this._pendingItems = [];
12
- this._initialized = false;
13
- this._flushPending = this.flushPending.bind(this);
14
- };
15
-
16
- var prototypeAccessors = { length: { configurable: true } };
17
-
18
- LocalStorage.prototype.init = function init (items) {
19
- if (!this._initialized) {
20
- this._items = items;
21
- this._initialized = true;
9
+ class LocalStorage {
10
+ constructor() {
11
+ this._items = [];
12
+ this._pendingItems = [];
13
+ this._initialized = false;
14
+ this._flushPending = this.flushPending.bind(this);
22
15
  }
23
- };
24
-
25
- LocalStorage.prototype._update = function _update (item) {
26
- if (!this._pendingItems.length) { Promise.resolve().then(this._flushPending); }
27
- this._pendingItems.push(item);
28
- };
29
16
 
30
- LocalStorage.prototype.flushPending = function flushPending () {
31
- if (!this._pendingItems.length) { return; }
32
- if (!fireworkers.length) {
33
- setTimeout(this._flushPending, 200);
34
- return;
17
+ init(items) {
18
+ if (!this._initialized) {
19
+ this._items = items;
20
+ this._initialized = true;
21
+ }
35
22
  }
36
- fireworkers[0]._send({msg: 'updateLocalStorage', items: this._pendingItems});
37
- this._pendingItems = [];
38
- };
39
23
 
40
- prototypeAccessors.length.get = function () {return this._items.length;};
24
+ _update(item) {
25
+ if (!this._pendingItems.length) Promise.resolve().then(this._flushPending);
26
+ this._pendingItems.push(item);
27
+ }
41
28
 
42
- LocalStorage.prototype.key = function key (n) {
43
- return this._items[n].key;
44
- };
29
+ flushPending() {
30
+ if (!this._pendingItems.length) return;
31
+ if (!fireworkers.length) {
32
+ setTimeout(this._flushPending, 200);
33
+ return;
34
+ }
35
+ fireworkers[0]._send({msg: 'updateLocalStorage', items: this._pendingItems});
36
+ this._pendingItems = [];
37
+ }
45
38
 
46
- LocalStorage.prototype.getItem = function getItem (key) {
47
- for (var i = 0, list = this._items; i < list.length; i += 1) {
48
- var item = list[i];
39
+ get length() {return this._items.length;}
49
40
 
50
- if (item.key === key) { return item.value; }
41
+ key(n) {
42
+ return this._items[n].key;
51
43
  }
52
- return null;
53
- };
54
44
 
55
- LocalStorage.prototype.setItem = function setItem (key, value) {
56
- var targetItem;
57
- for (var i = 0, list = this._items; i < list.length; i += 1) {
58
- var item = list[i];
45
+ getItem(key) {
46
+ for (const item of this._items) {
47
+ if (item.key === key) return item.value;
48
+ }
49
+ return null;
50
+ }
59
51
 
52
+ setItem(key, value) {
53
+ let targetItem;
54
+ for (const item of this._items) {
60
55
  if (item.key === key) {
61
- targetItem = item;
62
- item.value = value;
63
- break;
56
+ targetItem = item;
57
+ item.value = value;
58
+ break;
59
+ }
64
60
  }
61
+ if (!targetItem) {
62
+ targetItem = {key, value};
63
+ this._items.push(targetItem);
64
+ }
65
+ this._update(targetItem);
65
66
  }
66
- if (!targetItem) {
67
- targetItem = {key: key, value: value};
68
- this._items.push(targetItem);
69
- }
70
- this._update(targetItem);
71
- };
72
67
 
73
- LocalStorage.prototype.removeItem = function removeItem (key) {
74
- for (var i = 0; i < this._items.length; i++) {
75
- if (this._items[i].key === key) {
76
- this._items.splice(i, 1);
77
- this._update({key: key, value: null});
78
- break;
68
+ removeItem(key) {
69
+ for (let i = 0; i < this._items.length; i++) {
70
+ if (this._items[i].key === key) {
71
+ this._items.splice(i, 1);
72
+ this._update({key, value: null});
73
+ break;
74
+ }
79
75
  }
80
76
  }
81
- };
82
77
 
83
- LocalStorage.prototype.clear = function clear () {
84
- for (var item in this._items) {
85
- this._update({key: item.key, value: null});
78
+ clear() {
79
+ for (const item in this._items) {
80
+ this._update({key: item.key, value: null});
81
+ }
82
+ this._items = [];
86
83
  }
87
- this._items = [];
88
- };
89
-
90
- Object.defineProperties( LocalStorage.prototype, prototypeAccessors );
84
+ }
91
85
 
92
86
  self.localStorage = new LocalStorage();
93
87
 
94
88
 
95
- var Branch = function Branch() {
96
- this._root = null;
97
- };
98
-
99
- Branch.prototype.set = function set (value) {
100
- this._root = value;
101
- };
89
+ class Branch {
90
+ constructor() {
91
+ this._root = null;
92
+ }
102
93
 
103
- Branch.prototype.diff = function diff (value, pathPrefix) {
104
- var updates = {};
105
- var segments = pathPrefix === '/' ? [''] : pathPrefix.split('/');
106
- if (this._diffRecursively(this._root, value, segments, updates)) {
94
+ set(value) {
107
95
  this._root = value;
108
- updates[pathPrefix] = value;
109
- }
110
- return updates;
111
- };
112
-
113
- Branch.prototype._diffRecursively = function _diffRecursively (oldValue, newValue, segments, updates) {
114
- if (oldValue === undefined) { oldValue = null; }
115
- if (newValue === undefined) { newValue = null; }
116
- if (oldValue === null) { return newValue !== null; }
117
- if (oldValue instanceof Object && newValue instanceof Object) {
118
- var replace = true;
119
- var keysToReplace = [];
120
- for (var childKey in newValue) {
121
- if (!newValue.hasOwnProperty(childKey)) { continue; }
122
- var replaceChild = this._diffRecursively(
123
- oldValue[childKey], newValue[childKey], segments.concat(childKey), updates);
124
- if (replaceChild) {
125
- keysToReplace.push(childKey);
126
- } else {
127
- replace = false;
96
+ }
97
+
98
+ diff(value, pathPrefix) {
99
+ const updates = {};
100
+ const segments = pathPrefix === '/' ? [''] : pathPrefix.split('/');
101
+ if (this._diffRecursively(this._root, value, segments, updates)) {
102
+ this._root = value;
103
+ updates[pathPrefix] = value;
104
+ }
105
+ return updates;
106
+ }
107
+
108
+ _diffRecursively(oldValue, newValue, segments, updates) {
109
+ if (oldValue === undefined) oldValue = null;
110
+ if (newValue === undefined) newValue = null;
111
+ if (oldValue === null) return newValue !== null;
112
+ if (oldValue instanceof Object && newValue instanceof Object) {
113
+ let replace = true;
114
+ const keysToReplace = [];
115
+ for (const childKey in newValue) {
116
+ if (!newValue.hasOwnProperty(childKey)) continue;
117
+ const replaceChild = this._diffRecursively(
118
+ oldValue[childKey], newValue[childKey], segments.concat(childKey), updates);
119
+ if (replaceChild) {
120
+ keysToReplace.push(childKey);
121
+ } else {
122
+ replace = false;
123
+ }
128
124
  }
125
+ if (replace) return true;
126
+ for (const childKey in oldValue) {
127
+ if (!oldValue.hasOwnProperty(childKey) || newValue.hasOwnProperty(childKey)) continue;
128
+ updates[segments.concat(childKey).join('/')] = null;
129
+ delete oldValue[childKey];
130
+ }
131
+ for (const childKey of keysToReplace) {
132
+ updates[segments.concat(childKey).join('/')] = newValue[childKey];
133
+ oldValue[childKey] = newValue[childKey];
134
+ }
135
+ } else {
136
+ return newValue !== oldValue;
129
137
  }
130
- if (replace) { return true; }
131
- for (var childKey$1 in oldValue) {
132
- if (!oldValue.hasOwnProperty(childKey$1) || newValue.hasOwnProperty(childKey$1)) { continue; }
133
- updates[segments.concat(childKey$1).join('/')] = null;
134
- delete oldValue[childKey$1];
138
+ }
139
+ }
140
+
141
+
142
+ class Fireworker {
143
+ constructor(port) {
144
+ this._port = port;
145
+ this._lastWriteSerial = 0;
146
+ this._app = undefined;
147
+ this._cachedAuth = undefined;
148
+ this._cachedDatabase = undefined;
149
+ this._lastJsonUser = undefined;
150
+ this._configError = Fireworker._staticConfigError;
151
+ this._callbacks = {};
152
+ this._messages = [];
153
+ this._flushMessageQueue = this._flushMessageQueue.bind(this);
154
+ port.onmessage = this._receive.bind(this);
155
+ }
156
+
157
+ get _auth() {
158
+ if (this._cachedAuth) return this._cachedAuth;
159
+ if (!this._app) throw new Error('Must provide Firebase configuration data first');
160
+ return this._cachedAuth = this._app.auth();
161
+ }
162
+
163
+ get _database() {
164
+ if (this._cachedDatabase) return this._cachedDatabase;
165
+ if (!this._app) throw new Error('Must provide Firebase configuration data first');
166
+ if (Fireworker._databaseWrapperCallback) {
167
+ this._cachedDatabase = Fireworker._databaseWrapperCallback(this._app.database());
168
+ } else {
169
+ this._cachedDatabase = this._app.database();
135
170
  }
136
- for (var i = 0, list = keysToReplace; i < list.length; i += 1) {
137
- var childKey$2 = list[i];
171
+ return this._cachedDatabase;
172
+ }
173
+
174
+ init({storage, config}) {
175
+ if (storage) self.localStorage.init(storage);
176
+ if (config) {
177
+ try {
178
+ this._app = apps[config.databaseURL];
179
+ if (!this._app) {
180
+ this._app = apps[config.databaseURL] = firebase.initializeApp(config, config.databaseURL);
181
+ // If the API key looks invalid then assume that we're running against Cinderbase rather
182
+ // than Firebase and override the configuration appropriately.
183
+ if (config.apiKey && config.apiKey.length < 20) {
184
+ this._app.database().INTERNAL.forceWebSockets();
185
+ this._app.auth().useEmulator(config.databaseURL, {disableWarnings: true});
186
+ }
187
+ }
188
+ this._app.database();
189
+ this._app.auth();
190
+ this._configError = Fireworker._staticConfigError;
191
+ } catch (e) {
192
+ this._configError = e;
193
+ throw e;
194
+ }
195
+ } else if (this._configError) {
196
+ throw this._configError;
197
+ }
198
+ return {
199
+ exposedFunctionNames: Object.keys(Fireworker._exposed),
200
+ version: VERSION,
201
+ firebaseSdkVersion: firebase.SDK_VERSION
202
+ };
203
+ }
138
204
 
139
- updates[segments.concat(childKey$2).join('/')] = newValue[childKey$2];
140
- oldValue[childKey$2] = newValue[childKey$2];
205
+ destroy() {
206
+ for (const key in this._callbacks) {
207
+ const callback = this._callbacks[key];
208
+ if (callback.cancel) callback.cancel();
141
209
  }
142
- } else {
143
- return newValue !== oldValue;
144
- }
145
- };
146
-
147
-
148
- var Fireworker = function Fireworker(port) {
149
- this._port = port;
150
- this._lastWriteSerial = 0;
151
- this._app = undefined;
152
- this._cachedAuth = undefined;
153
- this._cachedDatabase = undefined;
154
- this._lastJsonUser = undefined;
155
- this._configError = Fireworker._staticConfigError;
156
- this._callbacks = {};
157
- this._messages = [];
158
- this._flushMessageQueue = this._flushMessageQueue.bind(this);
159
- port.onmessage = this._receive.bind(this);
160
- };
161
-
162
- var prototypeAccessors$1 = { _auth: { configurable: true },_database: { configurable: true } };
163
-
164
- prototypeAccessors$1._auth.get = function () {
165
- if (this._cachedAuth) { return this._cachedAuth; }
166
- if (!this._app) { throw new Error('Must provide Firebase configuration data first'); }
167
- return this._cachedAuth = this._app.auth();
168
- };
169
-
170
- prototypeAccessors$1._database.get = function () {
171
- if (this._cachedDatabase) { return this._cachedDatabase; }
172
- if (!this._app) { throw new Error('Must provide Firebase configuration data first'); }
173
- if (Fireworker._databaseWrapperCallback) {
174
- this._cachedDatabase = Fireworker._databaseWrapperCallback(this._app.database());
175
- } else {
176
- this._cachedDatabase = this._app.database();
210
+ this._callbacks = {};
211
+ this._port.onmessage = null;
212
+ this._messages = [];
213
+ const k = fireworkers.indexOf(this);
214
+ if (k >= 0) fireworkers[k] = null;
177
215
  }
178
- return this._cachedDatabase;
179
- };
180
216
 
181
- Fireworker.prototype.init = function init (ref) {
182
- var storage = ref.storage;
183
- var config = ref.config;
217
+ enableFirebaseLogging({value}) {
218
+ firebase.database.enableLogging(value);
219
+ }
220
+
221
+ ping() {
222
+ // Noop, placeholder for legacy Firetruss clients.
223
+ }
224
+
225
+ bounceConnection() {
226
+ this._database.goOffline();
227
+ this._database.goOnline();
228
+ }
229
+
230
+ _receive(event) {
231
+ Fireworker._firstMessageReceived = true;
232
+ for (const message of event.data) this._receiveMessage(message);
233
+ }
184
234
 
185
- if (storage) { self.localStorage.init(storage); }
186
- if (config) {
235
+ _receiveMessage(message) {
236
+ let promise;
187
237
  try {
188
- this._app = apps[config.databaseURL];
189
- if (!this._app) {
190
- this._app = apps[config.databaseURL] = firebase.initializeApp(config, config.databaseURL);
191
- // If the API key looks invalid then assume that we're running against Cinderbase rather
192
- // than Firebase and override the configuration appropriately.
193
- if (config.apiKey && config.apiKey.length < 20) {
194
- this._app.database().INTERNAL.forceWebSockets();
195
- this._app.auth().useEmulator(config.databaseURL, {disableWarnings: true});
196
- }
238
+ const fn = this[message.msg];
239
+ if (typeof fn !== 'function') throw new Error('Unknown message: ' + message.msg);
240
+ if (message.writeSerial) {
241
+ this._lastWriteSerial = Math.max(this._lastWriteSerial, message.writeSerial);
197
242
  }
198
- this._app.database();
199
- this._app.auth();
200
- this._configError = Fireworker._staticConfigError;
243
+ promise = Promise.resolve(fn.call(this, message));
201
244
  } catch (e) {
202
- this._configError = e;
203
- throw e;
245
+ e.immediateFailure = true;
246
+ promise = Promise.reject(e);
204
247
  }
205
- } else if (this._configError) {
206
- throw this._configError;
207
- }
208
- return {
209
- exposedFunctionNames: Object.keys(Fireworker._exposed),
210
- version: VERSION,
211
- firebaseSdkVersion: firebase.SDK_VERSION
212
- };
213
- };
214
-
215
- Fireworker.prototype.destroy = function destroy () {
216
- for (var key in this._callbacks) {
217
- var callback = this._callbacks[key];
218
- if (callback.cancel) { callback.cancel(); }
219
- }
220
- this._callbacks = {};
221
- this._port.onmessage = null;
222
- this._messages = [];
223
- var k = fireworkers.indexOf(this);
224
- if (k >= 0) { fireworkers[k] = null; }
225
- };
226
-
227
- Fireworker.prototype.enableFirebaseLogging = function enableFirebaseLogging (ref) {
228
- var value = ref.value;
229
-
230
- firebase.database.enableLogging(value);
231
- };
232
-
233
- Fireworker.prototype.ping = function ping () {
234
- // Noop, placeholder for legacy Firetruss clients.
235
- };
236
-
237
- Fireworker.prototype.bounceConnection = function bounceConnection () {
238
- this._database.goOffline();
239
- this._database.goOnline();
240
- };
241
-
242
- Fireworker.prototype._receive = function _receive (event) {
243
- Fireworker._firstMessageReceived = true;
244
- for (var i = 0, list = event.data; i < list.length; i += 1) {
245
- var message = list[i];
246
-
247
- this._receiveMessage(message);
248
+ if (!message.oneWay) {
249
+ promise.then(result => {
250
+ this._send({msg: 'resolve', id: message.id, result});
251
+ }, error => {
252
+ this._send({msg: 'reject', id: message.id, error: errorToJson(error)});
253
+ });
248
254
  }
249
- };
255
+ }
256
+
257
+ _send(message) {
258
+ if (!this._messages.length) Promise.resolve().then(this._flushMessageQueue);
259
+ this._messages.push(message);
260
+ }
250
261
 
251
- Fireworker.prototype._receiveMessage = function _receiveMessage (message) {
252
- var this$1 = this;
262
+ _flushMessageQueue() {
263
+ this._port.postMessage(this._messages);
264
+ this._messages = [];
265
+ }
253
266
 
254
- var promise;
255
- try {
256
- var fn = this[message.msg];
257
- if (typeof fn !== 'function') { throw new Error('Unknown message: ' + message.msg); }
258
- if (message.writeSerial) {
259
- this._lastWriteSerial = Math.max(this._lastWriteSerial, message.writeSerial);
267
+ call({name, args}) {
268
+ try {
269
+ return Promise.resolve(Fireworker._exposed[name].apply(null, args));
270
+ } catch (e) {
271
+ return Promise.reject(e);
260
272
  }
261
- promise = Promise.resolve(fn.call(this, message));
262
- } catch (e) {
263
- e.immediateFailure = true;
264
- promise = Promise.reject(e);
265
- }
266
- if (!message.oneWay) {
267
- promise.then(function (result) {
268
- this$1._send({msg: 'resolve', id: message.id, result: result});
269
- }, function (error) {
270
- this$1._send({msg: 'reject', id: message.id, error: errorToJson(error)});
271
- });
272
273
  }
273
- };
274
274
 
275
- Fireworker.prototype._send = function _send (message) {
276
- if (!this._messages.length) { Promise.resolve().then(this._flushMessageQueue); }
277
- this._messages.push(message);
278
- };
275
+ authWithCustomToken({url, authToken}) {
276
+ return this._auth.signInWithCustomToken(authToken)
277
+ .then(result => userToJson(result.user));
278
+ }
279
279
 
280
- Fireworker.prototype._flushMessageQueue = function _flushMessageQueue () {
281
- this._port.postMessage(this._messages);
282
- this._messages = [];
283
- };
280
+ authAnonymously({url}) {
281
+ return this._auth.signInAnonymously()
282
+ .then(result => userToJson(result.user));
283
+ }
284
284
 
285
- Fireworker.prototype.call = function call (ref) {
286
- var name = ref.name;
287
- var args = ref.args;
285
+ unauth({url}) {
286
+ return this._auth.signOut().catch(e => {
287
+ // We can ignore the error if the user is signed out anyway, but make sure to notify all
288
+ // authCallbacks otherwise we end up in a bogus state!
289
+ if (this._auth.currentUser === null) {
290
+ for (const callbackId in this._callbacks) {
291
+ if (!this._callbacks.hasOwnProperty(callbackId)) continue;
292
+ const callback = this._callbacks[callbackId];
293
+ if (callback.auth) callback(null);
294
+ }
295
+ } else {
296
+ return Promise.reject(e);
297
+ }
298
+ });
299
+ }
288
300
 
289
- try {
290
- return Promise.resolve(Fireworker._exposed[name].apply(null, args));
291
- } catch (e) {
292
- return Promise.reject(e);
301
+ onAuth({url, callbackId}) {
302
+ const authCallback = this._callbacks[callbackId] = this._onAuthCallback.bind(this, callbackId);
303
+ authCallback.auth = true;
304
+ authCallback.cancel = this._auth.onIdTokenChanged(authCallback);
293
305
  }
294
- };
295
306
 
296
- Fireworker.prototype.authWithCustomToken = function authWithCustomToken (ref) {
297
- var url = ref.url;
298
- var authToken = ref.authToken;
307
+ _onAuthCallback(callbackId, user) {
308
+ userToJson(user).then(jsonUser => {
309
+ if (areEqualValues(this._lastJsonUser, jsonUser)) return;
310
+ this._lastJsonUser = jsonUser;
311
+ this._send({msg: 'callback', id: callbackId, args: [jsonUser]});
312
+ });
313
+ }
299
314
 
300
- return this._auth.signInWithCustomToken(authToken)
301
- .then(function (result) { return userToJson(result.user); });
302
- };
315
+ set({url, value}) {
316
+ return this._createRef(url).set(value);
317
+ }
303
318
 
304
- Fireworker.prototype.authAnonymously = function authAnonymously (ref) {
305
- var url = ref.url;
319
+ update({url, value}) {
320
+ return this._createRef(url).update(value);
321
+ }
306
322
 
307
- return this._auth.signInAnonymously()
308
- .then(function (result) { return userToJson(result.user); });
309
- };
323
+ once({url}) {
324
+ return this._createRef(url).once('value').then(snapshot => this._snapshotToJson(snapshot));
325
+ }
310
326
 
311
- Fireworker.prototype.unauth = function unauth (ref) {
312
- var this$1 = this;
313
- var url = ref.url;
327
+ on({listenerKey, url, spec, eventType, callbackId, options}) {
328
+ options = options || {};
329
+ if (options.sync) options.branch = new Branch();
330
+ options.cancel = this.off.bind(this, {listenerKey, url, spec, eventType, callbackId});
331
+ const snapshotCallback = this._callbacks[callbackId] =
332
+ this._onSnapshotCallback.bind(this, callbackId, options);
333
+ snapshotCallback.listenerKey = listenerKey;
334
+ snapshotCallback.eventType = eventType;
335
+ snapshotCallback.cancel = options.cancel;
336
+ const cancelCallback = this._onCancelCallback.bind(this, callbackId);
337
+ this._createRef(url, spec).on(eventType, snapshotCallback, cancelCallback);
338
+ }
314
339
 
315
- return this._auth.signOut().catch(function (e) {
316
- // We can ignore the error if the user is signed out anyway, but make sure to notify all
317
- // authCallbacks otherwise we end up in a bogus state!
318
- if (this$1._auth.currentUser === null) {
319
- for (var callbackId in this$1._callbacks) {
320
- if (!this$1._callbacks.hasOwnProperty(callbackId)) { continue; }
321
- var callback = this$1._callbacks[callbackId];
322
- if (callback.auth) { callback(null); }
323
- }
340
+ off({listenerKey, url, spec, eventType, callbackId}) {
341
+ let snapshotCallback;
342
+ if (callbackId) {
343
+ // Callback IDs will not be reused across on() calls, so it's safe to just delete it.
344
+ snapshotCallback = this._callbacks[callbackId];
345
+ delete this._callbacks[callbackId];
324
346
  } else {
325
- return Promise.reject(e);
347
+ for (const key of Object.keys(this._callbacks)) {
348
+ if (!this._callbacks.hasOwnProperty(key)) continue;
349
+ const callback = this._callbacks[key];
350
+ if (callback.listenerKey === listenerKey &&
351
+ (!eventType || callback.eventType === eventType)) {
352
+ delete this._callbacks[key];
353
+ }
354
+ }
326
355
  }
327
- });
328
- };
329
-
330
- Fireworker.prototype.onAuth = function onAuth (ref) {
331
- var url = ref.url;
332
- var callbackId = ref.callbackId;
333
-
334
- var authCallback = this._callbacks[callbackId] = this._onAuthCallback.bind(this, callbackId);
335
- authCallback.auth = true;
336
- authCallback.cancel = this._auth.onIdTokenChanged(authCallback);
337
- };
338
-
339
- Fireworker.prototype._onAuthCallback = function _onAuthCallback (callbackId, user) {
340
- var this$1 = this;
341
-
342
- userToJson(user).then(function (jsonUser) {
343
- if (areEqualValues(this$1._lastJsonUser, jsonUser)) { return; }
344
- this$1._lastJsonUser = jsonUser;
345
- this$1._send({msg: 'callback', id: callbackId, args: [jsonUser]});
346
- });
347
- };
348
-
349
- Fireworker.prototype.set = function set (ref) {
350
- var url = ref.url;
351
- var value = ref.value;
352
-
353
- return this._createRef(url).set(value);
354
- };
355
-
356
- Fireworker.prototype.update = function update (ref) {
357
- var url = ref.url;
358
- var value = ref.value;
359
-
360
- return this._createRef(url).update(value);
361
- };
362
-
363
- Fireworker.prototype.once = function once (ref) {
364
- var this$1 = this;
365
- var url = ref.url;
366
-
367
- return this._createRef(url).once('value').then(function (snapshot) { return this$1._snapshotToJson(snapshot); });
368
- };
369
-
370
- Fireworker.prototype.on = function on (ref) {
371
- var listenerKey = ref.listenerKey;
372
- var url = ref.url;
373
- var spec = ref.spec;
374
- var eventType = ref.eventType;
375
- var callbackId = ref.callbackId;
376
- var options = ref.options;
377
-
378
- options = options || {};
379
- if (options.sync) { options.branch = new Branch(); }
380
- options.cancel = this.off.bind(this, {listenerKey: listenerKey, url: url, spec: spec, eventType: eventType, callbackId: callbackId});
381
- var snapshotCallback = this._callbacks[callbackId] =
382
- this._onSnapshotCallback.bind(this, callbackId, options);
383
- snapshotCallback.listenerKey = listenerKey;
384
- snapshotCallback.eventType = eventType;
385
- snapshotCallback.cancel = options.cancel;
386
- var cancelCallback = this._onCancelCallback.bind(this, callbackId);
387
- this._createRef(url, spec).on(eventType, snapshotCallback, cancelCallback);
388
- };
389
-
390
- Fireworker.prototype.off = function off (ref) {
391
- var listenerKey = ref.listenerKey;
392
- var url = ref.url;
393
- var spec = ref.spec;
394
- var eventType = ref.eventType;
395
- var callbackId = ref.callbackId;
396
-
397
- var snapshotCallback;
398
- if (callbackId) {
399
- // Callback IDs will not be reused across on() calls, so it's safe to just delete it.
400
- snapshotCallback = this._callbacks[callbackId];
401
- delete this._callbacks[callbackId];
402
- } else {
403
- for (var i = 0, list = Object.keys(this._callbacks); i < list.length; i += 1) {
404
- var key = list[i];
405
-
406
- if (!this._callbacks.hasOwnProperty(key)) { continue; }
407
- var callback = this._callbacks[key];
408
- if (callback.listenerKey === listenerKey &&
409
- (!eventType || callback.eventType === eventType)) {
410
- delete this._callbacks[key];
356
+ this._createRef(url, spec).off(eventType, snapshotCallback);
357
+ }
358
+
359
+ _onSnapshotCallback(callbackId, options, snapshot) {
360
+ if (options.sync && options.rest) {
361
+ const path = decodeURIComponent(
362
+ snapshot.ref.toString().replace(/.*?:\/\/[^/]*/, '').replace(/\/$/, ''));
363
+ let value;
364
+ try {
365
+ value = normalizeFirebaseValue(snapshot.val());
366
+ } catch (e) {
367
+ options.cancel();
368
+ this._onCancelCallback(callbackId, e);
369
+ return;
370
+ }
371
+ const updates = options.branch.diff(value, path);
372
+ for (const childPath in updates) {
373
+ if (!updates.hasOwnProperty(childPath)) continue;
374
+ this._send({
375
+ msg: 'callback', id: callbackId,
376
+ args: [null, {
377
+ path: childPath, value: updates[childPath], writeSerial: this._lastWriteSerial
378
+ }]
379
+ });
380
+ }
381
+ } else {
382
+ try {
383
+ const snapshotJson = this._snapshotToJson(snapshot);
384
+ if (options.sync) options.branch.set(snapshotJson.value);
385
+ this._send({msg: 'callback', id: callbackId, args: [null, snapshotJson]});
386
+ options.rest = true;
387
+ } catch (e) {
388
+ options.cancel();
389
+ this._onCancelCallback(callbackId, e);
411
390
  }
412
391
  }
413
392
  }
414
- this._createRef(url, spec).off(eventType, snapshotCallback);
415
- };
416
393
 
417
- Fireworker.prototype._onSnapshotCallback = function _onSnapshotCallback (callbackId, options, snapshot) {
418
- if (options.sync && options.rest) {
419
- var path = decodeURIComponent(
420
- snapshot.ref.toString().replace(/.*?:\/\/[^/]*/, '').replace(/\/$/, ''));
421
- var value;
422
- try {
423
- value = normalizeFirebaseValue(snapshot.val());
424
- } catch (e) {
425
- options.cancel();
426
- this._onCancelCallback(callbackId, e);
427
- return;
428
- }
429
- var updates = options.branch.diff(value, path);
430
- for (var childPath in updates) {
431
- if (!updates.hasOwnProperty(childPath)) { continue; }
432
- this._send({
433
- msg: 'callback', id: callbackId,
434
- args: [null, {
435
- path: childPath, value: updates[childPath], writeSerial: this._lastWriteSerial
436
- }]
437
- });
438
- }
439
- } else {
440
- try {
441
- var snapshotJson = this._snapshotToJson(snapshot);
442
- if (options.sync) { options.branch.set(snapshotJson.value); }
443
- this._send({msg: 'callback', id: callbackId, args: [null, snapshotJson]});
444
- options.rest = true;
445
- } catch (e$1) {
446
- options.cancel();
447
- this._onCancelCallback(callbackId, e$1);
448
- }
449
- }
450
- };
451
-
452
- Fireworker.prototype._onCancelCallback = function _onCancelCallback (callbackId, error) {
453
- delete this._callbacks[callbackId];
454
- this._send({msg: 'callback', id: callbackId, args: [errorToJson(error)]});
455
- };
456
-
457
- Fireworker.prototype.transaction = function transaction (ref$1) {
458
- var this$1 = this;
459
- var url = ref$1.url;
460
- var oldValue = ref$1.oldValue;
461
- var relativeUpdates = ref$1.relativeUpdates;
462
-
463
- var transactionPath = decodeURIComponent(url.replace(/.*?:\/\/[^/]*/, '').replace(/\/$/, ''));
464
- var ref = this._createRef(url);
465
- var branch = new Branch();
466
- var stale, committedValue;
467
-
468
- return ref.transaction(function (value) {
469
- committedValue = undefined;
470
- value = normalizeFirebaseValue(value);
471
- stale = !areEqualNormalFirebaseValues(value, oldValue);
472
- if (stale) { value = oldValue; }
473
- if (relativeUpdates) {
474
- for (var relativePath in relativeUpdates) {
475
- if (!relativeUpdates.hasOwnProperty(relativePath)) { continue; }
476
- if (relativePath) {
477
- var segments = relativePath.split('/');
478
- if (value === undefined || value === null) { value = {}; }
479
- var object = value;
480
- for (var i = 0; i < segments.length - 1; i++) {
481
- var key = segments[i];
482
- var child = object[key];
483
- if (child === undefined || child === null) { child = object[key] = {}; }
484
- object = child;
394
+ _onCancelCallback(callbackId, error) {
395
+ delete this._callbacks[callbackId];
396
+ this._send({msg: 'callback', id: callbackId, args: [errorToJson(error)]});
397
+ }
398
+
399
+ transaction({url, oldValue, relativeUpdates}) {
400
+ const transactionPath = decodeURIComponent(url.replace(/.*?:\/\/[^/]*/, '').replace(/\/$/, ''));
401
+ const ref = this._createRef(url);
402
+ const branch = new Branch();
403
+ let stale, committedValue;
404
+
405
+ return ref.transaction(value => {
406
+ committedValue = undefined;
407
+ value = normalizeFirebaseValue(value);
408
+ stale = !areEqualNormalFirebaseValues(value, oldValue);
409
+ if (stale) value = oldValue;
410
+ if (relativeUpdates) {
411
+ for (const relativePath in relativeUpdates) {
412
+ if (!relativeUpdates.hasOwnProperty(relativePath)) continue;
413
+ if (relativePath) {
414
+ const segments = relativePath.split('/');
415
+ if (value === undefined || value === null) value = {};
416
+ let object = value;
417
+ for (let i = 0; i < segments.length - 1; i++) {
418
+ const key = segments[i];
419
+ let child = object[key];
420
+ if (child === undefined || child === null) child = object[key] = {};
421
+ object = child;
422
+ }
423
+ object[segments[segments.length - 1]] = relativeUpdates[relativePath];
424
+ } else {
425
+ value = relativeUpdates[relativePath];
485
426
  }
486
- object[segments[segments.length - 1]] = relativeUpdates[relativePath];
487
- } else {
488
- value = relativeUpdates[relativePath];
489
427
  }
490
428
  }
491
- }
492
- branch.set(value);
493
- if (!stale) {
494
- committedValue = value;
495
- return value;
496
- }
497
- }).then(function (result) {
498
- var snapshots = [];
499
- var updates = branch.diff(normalizeFirebaseValue(result.snapshot.val()), transactionPath);
500
- for (var path in updates) {
501
- if (!updates.hasOwnProperty(path)) { continue; }
502
- snapshots.push({
503
- path: path, value: updates[path], writeSerial: result.writeSerial || this$1._lastWriteSerial
504
- });
505
- }
506
- return {committed: !stale, snapshots: snapshots};
507
- }, function (error) {
508
- if (error.message === 'set' || error.message === 'disconnect') {
509
- return ref.once('value').then(function (snapshot) {
510
- return {committed: false, snapshots: [snapshot], writeSerial: this$1._lastWriteSerial};
511
- });
512
- }
513
- error.committedValue = committedValue;
514
- return Promise.reject(error);
515
- });
516
- };
517
-
518
- Fireworker.prototype._snapshotToJson = function _snapshotToJson (snapshot) {
519
- var path =
520
- decodeURIComponent(snapshot.ref.toString().replace(/.*?:\/\/[^/]*/, '').replace(/\/$/, ''));
521
- return {
522
- path: path, value: normalizeFirebaseValue(snapshot.val()), writeSerial: this._lastWriteSerial
523
- };
524
- };
525
-
526
- Fireworker.prototype.onDisconnect = function onDisconnect (ref) {
527
- var url = ref.url;
528
- var method = ref.method;
529
- var value = ref.value;
530
-
531
- var onDisconnect = this._createRef(url).onDisconnect();
532
- return onDisconnect[method](value);
533
- };
534
-
535
- Fireworker.prototype._createRef = function _createRef (url, spec) {
536
- if (!this._app) { throw new Error('Must provide Firebase configuration data first'); }
537
- try {
538
- var ref = this._database.refFromURL(url);
539
- if (spec) {
540
- switch (spec.by) {
541
- case '$key': ref = ref.orderByKey(); break;
542
- case '$value': ref = ref.orderByValue(); break;
543
- default: ref = ref.orderByChild(spec.by); break;
429
+ branch.set(value);
430
+ if (!stale) {
431
+ committedValue = value;
432
+ return value;
544
433
  }
545
- if (spec.at !== undefined) { ref = ref.equalTo(spec.at); }
546
- else if (spec.from !== undefined) { ref = ref.startAt(spec.from); }
547
- else if (spec.to !== undefined) { ref = ref.endAt(spec.to); }
548
- if (spec.first !== undefined) { ref = ref.limitToFirst(spec.first); }
549
- else if (spec.last !== undefined) { ref = ref.limitToLast(spec.last); }
550
- }
551
- return ref;
552
- } catch (e) {
553
- e.extra = {url: url, spec: spec};
554
- throw e;
434
+ }).then(result => {
435
+ const snapshots = [];
436
+ const updates = branch.diff(normalizeFirebaseValue(result.snapshot.val()), transactionPath);
437
+ for (const path in updates) {
438
+ if (!updates.hasOwnProperty(path)) continue;
439
+ snapshots.push({
440
+ path, value: updates[path], writeSerial: result.writeSerial || this._lastWriteSerial
441
+ });
442
+ }
443
+ return {committed: !stale, snapshots};
444
+ }, error => {
445
+ if (error.message === 'set' || error.message === 'disconnect') {
446
+ return ref.once('value').then(snapshot => {
447
+ return {committed: false, snapshots: [snapshot], writeSerial: this._lastWriteSerial};
448
+ });
449
+ }
450
+ error.committedValue = committedValue;
451
+ return Promise.reject(error);
452
+ });
555
453
  }
556
- };
557
454
 
558
- Fireworker.expose = function expose (fn, name) {
559
- name = name || fn.name;
560
- if (!name) {
561
- Fireworker._signalStaticConfigError(
562
- new Error(("Cannot expose a function with no name: " + fn)));
563
- }
564
- if (Fireworker._exposed.hasOwnProperty(name)) {
565
- Fireworker._signalStaticConfigError(new Error(("Function " + name + "() already exposed")));
566
- }
567
- if (Fireworker._firstMessageReceived) {
568
- Fireworker._signalStaticConfigError(new Error('Too late to expose function, worker in use'));
455
+ _snapshotToJson(snapshot) {
456
+ const path =
457
+ decodeURIComponent(snapshot.ref.toString().replace(/.*?:\/\/[^/]*/, '').replace(/\/$/, ''));
458
+ return {
459
+ path, value: normalizeFirebaseValue(snapshot.val()), writeSerial: this._lastWriteSerial
460
+ };
569
461
  }
570
- Fireworker._exposed[name] = fn;
571
- };
572
462
 
573
- Fireworker.setDatabaseWrapperCallback = function setDatabaseWrapperCallback (fn) {
574
- if (Fireworker._databaseWrapperCallback) {
575
- Fireworker._signalStaticConfigError(new Error('Database wrapper callback already set'));
463
+ onDisconnect({url, method, value}) {
464
+ const onDisconnect = this._createRef(url).onDisconnect();
465
+ return onDisconnect[method](value);
576
466
  }
577
- if (Fireworker._firstMessageReceived) {
578
- Fireworker._signalStaticConfigError(
579
- new Error('Too late to set database wrapper callback, worker in use'));
467
+
468
+ _createRef(url, spec) {
469
+ if (!this._app) throw new Error('Must provide Firebase configuration data first');
470
+ try {
471
+ let ref = this._database.refFromURL(url);
472
+ if (spec) {
473
+ switch (spec.by) {
474
+ case '$key': ref = ref.orderByKey(); break;
475
+ case '$value': ref = ref.orderByValue(); break;
476
+ default: ref = ref.orderByChild(spec.by); break;
477
+ }
478
+ if (spec.at !== undefined) ref = ref.equalTo(spec.at);
479
+ else if (spec.from !== undefined) ref = ref.startAt(spec.from);
480
+ else if (spec.to !== undefined) ref = ref.endAt(spec.to);
481
+ if (spec.first !== undefined) ref = ref.limitToFirst(spec.first);
482
+ else if (spec.last !== undefined) ref = ref.limitToLast(spec.last);
483
+ }
484
+ return ref;
485
+ } catch (e) {
486
+ e.extra = {url, spec};
487
+ throw e;
488
+ }
580
489
  }
581
- Fireworker._databaseWrapperCallback = fn;
582
- };
583
490
 
584
- Fireworker._signalStaticConfigError = function _signalStaticConfigError (error) {
585
- if (!Fireworker._staticConfigError) { Fireworker._staticConfigError = error; }
586
- for (var i = 0, list = fireworkers; i < list.length; i += 1) {
587
- var fireworker = list[i];
491
+ static expose(fn, name) {
492
+ name = name || fn.name;
493
+ if (!name) {
494
+ Fireworker._signalStaticConfigError(
495
+ new Error(`Cannot expose a function with no name: ${fn}`));
496
+ }
497
+ if (Fireworker._exposed.hasOwnProperty(name)) {
498
+ Fireworker._signalStaticConfigError(new Error(`Function ${name}() already exposed`));
499
+ }
500
+ if (Fireworker._firstMessageReceived) {
501
+ Fireworker._signalStaticConfigError(new Error('Too late to expose function, worker in use'));
502
+ }
503
+ Fireworker._exposed[name] = fn;
504
+ }
588
505
 
589
- if (fireworker && !fireworker._configError) { fireworker._configError = error; }
506
+ static setDatabaseWrapperCallback(fn) {
507
+ if (Fireworker._databaseWrapperCallback) {
508
+ Fireworker._signalStaticConfigError(new Error('Database wrapper callback already set'));
509
+ }
510
+ if (Fireworker._firstMessageReceived) {
511
+ Fireworker._signalStaticConfigError(
512
+ new Error('Too late to set database wrapper callback, worker in use'));
513
+ }
514
+ Fireworker._databaseWrapperCallback = fn;
590
515
  }
591
- throw error;
592
- };
593
516
 
594
- Object.defineProperties( Fireworker.prototype, prototypeAccessors$1 );
517
+ static _signalStaticConfigError(error) {
518
+ if (!Fireworker._staticConfigError) Fireworker._staticConfigError = error;
519
+ for (const fireworker of fireworkers) {
520
+ if (fireworker && !fireworker._configError) fireworker._configError = error;
521
+ }
522
+ throw error;
523
+ }
524
+ }
595
525
 
596
526
  Fireworker._exposed = {};
597
527
  Fireworker._firstMessageReceived = false;
@@ -599,11 +529,9 @@ Fireworker._databaseWrapperCallback = undefined;
599
529
  Fireworker._staticConfigError = undefined;
600
530
 
601
531
  function errorToJson(error) {
602
- var json = {name: error.name, message: error.message};
603
- var propertyNames = Object.getOwnPropertyNames(error);
604
- for (var i = 0, list = propertyNames; i < list.length; i += 1) {
605
- var propertyName = list[i];
606
-
532
+ const json = {name: error.name, message: error.message};
533
+ const propertyNames = Object.getOwnPropertyNames(error);
534
+ for (const propertyName of propertyNames) {
607
535
  json[propertyName] = error[propertyName];
608
536
  }
609
537
  return json;
@@ -611,27 +539,27 @@ function errorToJson(error) {
611
539
 
612
540
  function normalizeFirebaseValue(value) {
613
541
  if (Array.isArray(value)) {
614
- var normalValue = {};
615
- for (var i = 0; i < value.length; i++) {
616
- var item = value[i];
617
- if (item === undefined || item === null) { continue; }
542
+ const normalValue = {};
543
+ for (let i = 0; i < value.length; i++) {
544
+ const item = value[i];
545
+ if (item === undefined || item === null) continue;
618
546
  normalValue[i] = normalizeFirebaseValue(item);
619
547
  }
620
548
  return normalValue;
621
549
  }
622
550
  if (value instanceof Object) {
623
- for (var key in value) {
624
- if (value.hasOwnProperty(key)) { value[key] = normalizeFirebaseValue(value[key]); }
551
+ for (const key in value) {
552
+ if (value.hasOwnProperty(key)) value[key] = normalizeFirebaseValue(value[key]);
625
553
  }
626
554
  }
627
555
  return value;
628
556
  }
629
557
 
630
558
  function userToJson(user) {
631
- if (!user) { return Promise.resolve(user); }
632
- var json = user.toJSON();
559
+ if (!user) return Promise.resolve(user);
560
+ const json = user.toJSON();
633
561
  delete json.stsTokenManager;
634
- return user.getIdTokenResult().then(function (result) {
562
+ return user.getIdTokenResult().then(result => {
635
563
  delete result.claims.exp;
636
564
  delete result.claims.iat;
637
565
  json.claims = result.claims;
@@ -641,37 +569,37 @@ function userToJson(user) {
641
569
 
642
570
 
643
571
  function areEqualNormalFirebaseValues(a, b) {
644
- if (a === b) { return true; }
645
- if ((a === null || a === undefined) && (b === null || b === undefined)) { return true; }
646
- if (a === null || b === null) { return false; }
647
- if (!(typeof a === 'object' && typeof b === 'object')) { return false; }
648
- for (var key in a) {
649
- if (!a.hasOwnProperty(key) || !b.hasOwnProperty(key)) { return false; }
650
- if (!areEqualNormalFirebaseValues(a[key], b[key])) { return false; }
572
+ if (a === b) return true;
573
+ if ((a === null || a === undefined) && (b === null || b === undefined)) return true;
574
+ if (a === null || b === null) return false;
575
+ if (!(typeof a === 'object' && typeof b === 'object')) return false;
576
+ for (const key in a) {
577
+ if (!a.hasOwnProperty(key) || !b.hasOwnProperty(key)) return false;
578
+ if (!areEqualNormalFirebaseValues(a[key], b[key])) return false;
651
579
  }
652
- for (var key$1 in b) {
653
- if (!a.hasOwnProperty(key$1) || !b.hasOwnProperty(key$1)) { return false; }
580
+ for (const key in b) {
581
+ if (!a.hasOwnProperty(key) || !b.hasOwnProperty(key)) return false;
654
582
  }
655
583
  return true;
656
584
  }
657
585
 
658
586
  function areEqualValues(a, b) {
659
- if (a === b) { return true; }
660
- if (a === null && b === null || a === undefined && b === undefined) { return true; }
661
- if (a === null || b === null || a === undefined || b === undefined) { return false; }
662
- if (!(typeof a === 'object' && typeof b === 'object')) { return false; }
663
- for (var key in a) {
664
- if (!a.hasOwnProperty(key) || !b.hasOwnProperty(key)) { return false; }
665
- if (!areEqualValues(a[key], b[key])) { return false; }
587
+ if (a === b) return true;
588
+ if (a === null && b === null || a === undefined && b === undefined) return true;
589
+ if (a === null || b === null || a === undefined || b === undefined) return false;
590
+ if (!(typeof a === 'object' && typeof b === 'object')) return false;
591
+ for (const key in a) {
592
+ if (!a.hasOwnProperty(key) || !b.hasOwnProperty(key)) return false;
593
+ if (!areEqualValues(a[key], b[key])) return false;
666
594
  }
667
- for (var key$1 in b) {
668
- if (!a.hasOwnProperty(key$1) || !b.hasOwnProperty(key$1)) { return false; }
595
+ for (const key in b) {
596
+ if (!a.hasOwnProperty(key) || !b.hasOwnProperty(key)) return false;
669
597
  }
670
598
  if (Array.isArray(a) || Array.isArray(b)) {
671
- if (!Array.isArray(a) || !Array.isArray(b)) { return false; }
672
- if (a.length !== b.length) { return false; }
673
- for (var i = 0; i < a.length; i++) {
674
- if (!areEqualValues(a[i], b[i])) { return false; }
599
+ if (!Array.isArray(a) || !Array.isArray(b)) return false;
600
+ if (a.length !== b.length) return false;
601
+ for (let i = 0; i < a.length; i++) {
602
+ if (!areEqualValues(a[i], b[i])) return false;
675
603
  }
676
604
  }
677
605
  return true;
@@ -691,6 +619,6 @@ function acceptConnections() {
691
619
  self.window = self;
692
620
  acceptConnections();
693
621
 
694
- export default Fireworker;
622
+ export { Fireworker as default };
695
623
 
696
624
  //# sourceMappingURL=worker.es2015.js.map