@legendapp/state 2.0.0-next.13 → 2.0.0-next.15

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.
@@ -0,0 +1,669 @@
1
+ 'use strict';
2
+
3
+ var state = require('@legendapp/state');
4
+ var persist = require('@legendapp/state/persist');
5
+ var auth = require('firebase/auth');
6
+ var database = require('firebase/database');
7
+
8
+ const { symbolDelete } = state.internal;
9
+ const { observablePersistConfiguration } = persist.internal;
10
+ function clone(obj) {
11
+ return obj === undefined || obj === null ? obj : JSON.parse(JSON.stringify(obj));
12
+ }
13
+ function getDateModifiedKey(dateModifiedKey) {
14
+ return dateModifiedKey || observablePersistConfiguration.dateModifiedKey || '@';
15
+ }
16
+ const symbolSaveValue = Symbol('___obsSaveValue');
17
+ class ObservablePersistFirebaseBase {
18
+ constructor(fns) {
19
+ var _a;
20
+ this._batch = {};
21
+ this._pathsLoadStatus = state.observable({});
22
+ this.listenErrors = new Map();
23
+ this.saveStates = new Map();
24
+ this.fns = fns;
25
+ this.user = state.observablePrimitive();
26
+ this.SaveTimeout = (_a = observablePersistConfiguration === null || observablePersistConfiguration === void 0 ? void 0 : observablePersistConfiguration.saveTimeout) !== null && _a !== void 0 ? _a : 500;
27
+ this.fns.onAuthStateChanged((user) => {
28
+ this.user.set(user === null || user === void 0 ? void 0 : user.uid);
29
+ });
30
+ }
31
+ async get(params) {
32
+ const { obs, options } = params;
33
+ const { remote } = options;
34
+ if (!remote || !remote.firebase) {
35
+ // If the plugin is set globally but it has no firebase options this plugin can't do anything
36
+ return;
37
+ }
38
+ const { requireAuth } = remote;
39
+ let { waitForLoad } = remote;
40
+ if (requireAuth) {
41
+ await state.whenReady(this.user);
42
+ }
43
+ if (waitForLoad) {
44
+ if (state.isObservable(waitForLoad)) {
45
+ waitForLoad = state.whenReady(waitForLoad);
46
+ }
47
+ await waitForLoad;
48
+ }
49
+ const saveState = {
50
+ pendingSaveResults: new Map(),
51
+ pendingSaves: new Map(),
52
+ numSavesPending: 0,
53
+ };
54
+ this.saveStates.set(obs, saveState);
55
+ const { queryByModified } = options.remote.firebase;
56
+ const onLoadParams = {
57
+ waiting: 0,
58
+ onLoad: () => {
59
+ onLoadParams.waiting--;
60
+ if (onLoadParams.waiting === 0) {
61
+ params.onLoad();
62
+ }
63
+ },
64
+ };
65
+ if (state.isObject(queryByModified)) {
66
+ // TODO: Track which paths were handled and then afterwards listen to the non-handled ones
67
+ // without modified
68
+ this.iterateListen(obs, params, saveState, [], [], queryByModified, onLoadParams);
69
+ }
70
+ else {
71
+ const dateModified = queryByModified === true ? params.dateModified : undefined;
72
+ this._listen(obs, params, saveState, [], [], queryByModified, dateModified, onLoadParams);
73
+ }
74
+ }
75
+ iterateListen(obs, params, saveState, path, pathTypes, queryByModified, onLoadParams) {
76
+ const { options } = params;
77
+ const { ignoreKeys } = options.remote.firebase;
78
+ Object.keys(obs).forEach((key) => {
79
+ if (!ignoreKeys || !ignoreKeys.includes(key)) {
80
+ const o = obs[key];
81
+ const q = queryByModified[key] || queryByModified['*'];
82
+ const pathChild = path.concat(key);
83
+ const pathTypesChild = pathTypes.concat(state.isArray(o.peek()) ? 'array' : 'object');
84
+ let dateModified = undefined;
85
+ if (state.isObject(q)) {
86
+ this.iterateListen(o, params, saveState, pathChild, pathTypesChild, q, onLoadParams);
87
+ }
88
+ else {
89
+ if (q === true || q === '*') {
90
+ dateModified = params.dateModified;
91
+ }
92
+ this._listen(o, params, saveState, pathChild, pathTypesChild, queryByModified, dateModified, onLoadParams);
93
+ }
94
+ }
95
+ });
96
+ }
97
+ retryListens() {
98
+ // If a listen failed but save succeeded, the save should have fixed
99
+ // the permission problem so try again
100
+ this.listenErrors.forEach((listenError) => {
101
+ const { params, path, pathTypes, dateModified, queryByModified, unsubscribes, saveState, onLoadParams } = listenError;
102
+ listenError.retry++;
103
+ if (listenError.retry < 10) {
104
+ unsubscribes.forEach((cb) => cb());
105
+ this._listen(params.obs, params, saveState, path, pathTypes, queryByModified, dateModified, onLoadParams);
106
+ }
107
+ else {
108
+ this.listenErrors.delete(listenError);
109
+ }
110
+ });
111
+ }
112
+ async _listen(obs, params, saveState, path, pathTypes, queryByModified, dateModified, onLoadParams) {
113
+ const { options } = params;
114
+ const { once, fieldTransforms, onLoadError, allowSaveIfError, firebase } = options.remote;
115
+ const { syncPath, dateModifiedKey: dateModifiedKeyOption } = firebase;
116
+ let didError = false;
117
+ const dateModifiedKey = getDateModifiedKey(dateModifiedKeyOption);
118
+ const originalPath = path;
119
+ if (fieldTransforms && path.length) {
120
+ path = persist.transformPath(path, pathTypes, fieldTransforms);
121
+ }
122
+ const pathFirebase = syncPath(this.fns.getCurrentUser()) + path.join('/');
123
+ const status$ = this._pathsLoadStatus[pathFirebase].set({
124
+ startedLoading: false,
125
+ isLoaded: false,
126
+ canSave: false,
127
+ });
128
+ let refPath = this.fns.ref(pathFirebase);
129
+ if (dateModified && !isNaN(dateModified)) {
130
+ refPath = this.fns.orderByChild(refPath, dateModifiedKey, dateModified + 1);
131
+ }
132
+ const unsubscribes = [];
133
+ const _onError = (err) => {
134
+ if (!didError) {
135
+ didError = true;
136
+ const existing = this.listenErrors.get(obs);
137
+ if (existing) {
138
+ existing.retry++;
139
+ }
140
+ else {
141
+ this.listenErrors.set(obs, {
142
+ params,
143
+ path: originalPath,
144
+ pathTypes,
145
+ dateModified,
146
+ queryByModified,
147
+ unsubscribes,
148
+ retry: 0,
149
+ saveState,
150
+ onLoadParams,
151
+ });
152
+ params.state.remoteError.set(err);
153
+ onLoadError === null || onLoadError === void 0 ? void 0 : onLoadError(err);
154
+ if (allowSaveIfError) {
155
+ status$.canSave.set(true);
156
+ }
157
+ }
158
+ }
159
+ };
160
+ if (!once) {
161
+ const localState = { changes: {} };
162
+ const cb = this._onChange.bind(this, path, pathTypes, pathFirebase, dateModifiedKey, dateModifiedKeyOption, params, localState, saveState);
163
+ unsubscribes.push(this.fns.onChildAdded(refPath, cb));
164
+ unsubscribes.push(this.fns.onChildChanged(refPath, cb));
165
+ }
166
+ onLoadParams.waiting++;
167
+ unsubscribes.push(this.fns.once(refPath, this._onceValue.bind(this, path, pathTypes, pathFirebase, dateModifiedKey, dateModifiedKeyOption, queryByModified, onLoadParams.onLoad, params), _onError));
168
+ }
169
+ _updatePendingSave(path, value, pending) {
170
+ if (path.length === 0) {
171
+ pending[symbolSaveValue] = value;
172
+ }
173
+ else if (pending[symbolSaveValue]) {
174
+ pending[symbolSaveValue] = state.mergeIntoObservable(pending[symbolSaveValue], value);
175
+ }
176
+ else {
177
+ const p = path[0];
178
+ const v = value[p];
179
+ const pendingChild = pending[p];
180
+ // If already have a save info here then don't need to go deeper on the path. Just overwrite the value.
181
+ if (pendingChild && pendingChild[symbolSaveValue] !== undefined) {
182
+ const pendingSaveValue = pendingChild[symbolSaveValue];
183
+ pendingChild[symbolSaveValue] =
184
+ state.isArray(pendingSaveValue) || state.isObject(pendingSaveValue)
185
+ ? state.mergeIntoObservable(pendingSaveValue, v)
186
+ : v;
187
+ }
188
+ else {
189
+ // 1. If nothing here
190
+ // 2. If other strings here
191
+ if (!pending[p]) {
192
+ pending[p] = {};
193
+ }
194
+ if (path.length > 1) {
195
+ this._updatePendingSave(path.slice(1), v, pending[p]);
196
+ }
197
+ else {
198
+ pending[p] = { [symbolSaveValue]: v };
199
+ }
200
+ }
201
+ }
202
+ }
203
+ async set({ options, path, valueAtPath, pathTypes, obs }) {
204
+ const { remote } = options;
205
+ // If the plugin is set globally but it has no firebase options this plugin can't do anything
206
+ if (!remote || !remote.firebase) {
207
+ return;
208
+ }
209
+ const { requireAuth, waitForSave, saveTimeout, log } = remote;
210
+ if (requireAuth) {
211
+ await state.whenReady(this.user);
212
+ }
213
+ if (valueAtPath === undefined) {
214
+ valueAtPath = null;
215
+ }
216
+ const value = state.constructObjectWithPath(path, clone(valueAtPath), pathTypes);
217
+ const pathCloned = path.slice();
218
+ const syncPath = options.remote.firebase.syncPath(this.fns.getCurrentUser());
219
+ log === null || log === void 0 ? void 0 : log('Saving', value);
220
+ const status$ = this._pathsLoadStatus[syncPath];
221
+ if (!status$.canSave.peek()) {
222
+ // Wait for load
223
+ await state.when(status$.canSave);
224
+ }
225
+ if (waitForSave) {
226
+ await (state.isObservable(waitForSave)
227
+ ? state.whenReady(waitForSave)
228
+ : state.isFunction(waitForSave)
229
+ ? waitForSave(value, pathCloned)
230
+ : waitForSave);
231
+ }
232
+ const saveState = this.saveStates.get(obs);
233
+ const { pendingSaveResults, pendingSaves } = saveState;
234
+ if (!pendingSaves.has(syncPath)) {
235
+ pendingSaves.set(syncPath, { options, saves: {} });
236
+ pendingSaveResults.set(syncPath, { saved: [] });
237
+ }
238
+ const pending = pendingSaves.get(syncPath).saves;
239
+ this._updatePendingSave(pathCloned, value, pending);
240
+ if (!saveState.eventSaved) {
241
+ saveState.eventSaved = state.observablePrimitive();
242
+ }
243
+ // Keep the current eventSaved. This will get reassigned once the timeout activates.
244
+ const eventSaved = saveState.eventSaved;
245
+ const timeout = saveTimeout !== null && saveTimeout !== void 0 ? saveTimeout : this.SaveTimeout;
246
+ if (timeout) {
247
+ if (saveState.timeout) {
248
+ clearTimeout(saveState.timeout);
249
+ }
250
+ saveState.timeout = setTimeout(this._onTimeoutSave.bind(this, saveState), timeout);
251
+ }
252
+ else {
253
+ this._onTimeoutSave(saveState);
254
+ }
255
+ const savedOrError = await state.when(eventSaved);
256
+ if (savedOrError === true) {
257
+ this.retryListens();
258
+ const saveResults = pendingSaveResults.get(syncPath);
259
+ log === null || log === void 0 ? void 0 : log('saved', { value, saves: saveResults === null || saveResults === void 0 ? void 0 : saveResults.saved });
260
+ if (saveResults) {
261
+ const { saved } = saveResults;
262
+ if (saved === null || saved === void 0 ? void 0 : saved.length) {
263
+ // Only want to return from saved one time
264
+ if (saveState.numSavesPending === 0) {
265
+ pendingSaveResults.delete(syncPath);
266
+ }
267
+ else {
268
+ saveResults.saved = [];
269
+ }
270
+ let maxModified = 0;
271
+ // Compile a changes object of all the dateModified
272
+ const changes = {};
273
+ for (let i = 0; i < saved.length; i++) {
274
+ const { dateModified, path, dateModifiedKeyOption, dateModifiedKey, value } = saved[i];
275
+ if (dateModified) {
276
+ maxModified = Math.max(dateModified, maxModified);
277
+ if (dateModifiedKeyOption) {
278
+ const deconstructed = state.deconstructObjectWithPath(path, value);
279
+ // Don't resurrect deleted items
280
+ if (deconstructed !== symbolDelete) {
281
+ Object.assign(changes, state.constructObjectWithPath(path, {
282
+ [dateModifiedKey]: dateModified,
283
+ }, pathTypes));
284
+ }
285
+ }
286
+ }
287
+ }
288
+ return {
289
+ changes,
290
+ dateModified: maxModified || undefined,
291
+ };
292
+ }
293
+ }
294
+ }
295
+ else {
296
+ throw savedOrError;
297
+ }
298
+ return {};
299
+ }
300
+ _constructBatch(options, batch, basePath, saves, ...path) {
301
+ const { fieldTransforms, firebase } = options.remote;
302
+ const { dateModifiedKey: dateModifiedKeyOption } = firebase;
303
+ const dateModifiedKey = getDateModifiedKey(dateModifiedKeyOption);
304
+ let valSave = saves[symbolSaveValue];
305
+ if (valSave !== undefined) {
306
+ let queryByModified = options.remote.firebase.queryByModified;
307
+ if (queryByModified) {
308
+ if (queryByModified !== true && fieldTransforms) {
309
+ queryByModified = persist.transformObject(queryByModified, fieldTransforms);
310
+ }
311
+ valSave = this.insertDatesToSave(batch, queryByModified, dateModifiedKey, basePath, path, valSave);
312
+ }
313
+ const pathThis = basePath + path.join('/');
314
+ if (pathThis && !batch[pathThis]) {
315
+ batch[pathThis] = valSave;
316
+ }
317
+ }
318
+ else {
319
+ Object.keys(saves).forEach((key) => {
320
+ this._constructBatch(options, batch, basePath, saves[key], ...path, key);
321
+ });
322
+ }
323
+ }
324
+ _constructBatchesForSave(pendingSaves) {
325
+ const batches = [];
326
+ pendingSaves.forEach(({ options, saves }) => {
327
+ const basePath = options.remote.firebase.syncPath(this.fns.getCurrentUser());
328
+ const batch = {};
329
+ this._constructBatch(options, batch, basePath, saves);
330
+ batches.push(batch);
331
+ });
332
+ return batches;
333
+ }
334
+ async _onTimeoutSave(saveState) {
335
+ const { pendingSaves, eventSaved } = saveState;
336
+ saveState.timeout = undefined;
337
+ saveState.eventSaved = undefined;
338
+ saveState.numSavesPending++;
339
+ if (pendingSaves.size > 0) {
340
+ const batches = JSON.parse(JSON.stringify(this._constructBatchesForSave(pendingSaves)));
341
+ saveState.savingSaves = pendingSaves;
342
+ // Clear the pendingSaves so that the next batch starts from scratch
343
+ saveState.pendingSaves = new Map();
344
+ if (batches.length > 0) {
345
+ const promises = [];
346
+ for (let i = 0; i < batches.length; i++) {
347
+ const batch = batches[i];
348
+ promises.push(this._saveBatch(batch));
349
+ }
350
+ const results = await Promise.all(promises);
351
+ const errors = results.filter((result) => result.error);
352
+ if (errors.length === 0) {
353
+ saveState.numSavesPending--;
354
+ eventSaved === null || eventSaved === void 0 ? void 0 : eventSaved.set(true);
355
+ }
356
+ else {
357
+ eventSaved === null || eventSaved === void 0 ? void 0 : eventSaved.set(errors[0].error);
358
+ }
359
+ }
360
+ }
361
+ }
362
+ async _saveBatch(batch) {
363
+ const length = JSON.stringify(batch).length;
364
+ let error = undefined;
365
+ // Firebase has a maximum limit of 16MB per save so we constrain our saves to
366
+ // less than 12 to be safe
367
+ if (length > 12e6) {
368
+ const parts = splitLargeObject(batch, 6e6);
369
+ let didSave = true;
370
+ // TODO: Option for logging
371
+ for (let i = 0; i < parts.length; i++) {
372
+ const ret = await this._saveBatch(parts[i]);
373
+ if (ret.error) {
374
+ error = ret.error;
375
+ }
376
+ else {
377
+ didSave = didSave && ret.didSave;
378
+ }
379
+ }
380
+ return error ? { error } : { didSave };
381
+ }
382
+ else {
383
+ for (let i = 0; i < 3; i++) {
384
+ try {
385
+ await this.fns.update(batch);
386
+ return { didSave: true };
387
+ }
388
+ catch (err) {
389
+ error = err;
390
+ await new Promise((resolve) => setTimeout(resolve, 500));
391
+ }
392
+ }
393
+ return { error };
394
+ }
395
+ }
396
+ _convertFBTimestamps(obj, dateModifiedKey, dateModifiedKeyOption) {
397
+ let value = obj;
398
+ // Database value can be either { @: number, _: object } or { @: number, ...rest }
399
+ // where @ is the dateModifiedKey
400
+ let dateModified = value[dateModifiedKey];
401
+ if (dateModified) {
402
+ // If user doesn't request a dateModifiedKey then delete it
403
+ if (value._ !== undefined) {
404
+ value = value._;
405
+ }
406
+ else if (dateModified && Object.keys(value).length < 2) {
407
+ value = symbolDelete;
408
+ }
409
+ if (!dateModifiedKeyOption) {
410
+ delete value[dateModifiedKey];
411
+ }
412
+ }
413
+ if (state.isObject(value)) {
414
+ Object.keys(value).forEach((k) => {
415
+ const val = value[k];
416
+ if (val !== undefined) {
417
+ if (state.isObject(val) || state.isArray(val)) {
418
+ const { value: valueChild, dateModified: dateModifiedChild } = this._convertFBTimestamps(val, dateModifiedKey, dateModifiedKeyOption);
419
+ if (dateModifiedChild) {
420
+ dateModified = Math.max(dateModified || 0, dateModifiedChild);
421
+ }
422
+ if (valueChild !== val) {
423
+ value[k] = valueChild;
424
+ }
425
+ }
426
+ }
427
+ });
428
+ }
429
+ return { value, dateModified };
430
+ }
431
+ async _onceValue(path, pathTypes, pathFirebase, dateModifiedKey, dateModifiedKeyOption, queryByModified, onLoad, params, snapshot) {
432
+ const { onChange } = params;
433
+ const outerValue = snapshot.val();
434
+ // If this path previously errored, clear the error state
435
+ const obs = params.obs;
436
+ params.state.remoteError.delete();
437
+ this.listenErrors.delete(obs);
438
+ const status$ = this._pathsLoadStatus[pathFirebase];
439
+ status$.startedLoading.set(true);
440
+ if (outerValue && state.isObject(outerValue)) {
441
+ let value;
442
+ let dateModified;
443
+ if (queryByModified) {
444
+ const converted = this._convertFBTimestamps(outerValue, dateModifiedKey, dateModifiedKeyOption);
445
+ value = converted.value;
446
+ dateModified = converted.dateModified;
447
+ }
448
+ else {
449
+ value = outerValue;
450
+ }
451
+ value = state.constructObjectWithPath(path, value, pathTypes);
452
+ const onChangePromise = onChange({
453
+ value,
454
+ path,
455
+ pathTypes,
456
+ mode: queryByModified ? 'assign' : 'set',
457
+ dateModified,
458
+ });
459
+ if (onChangePromise) {
460
+ await onChangePromise;
461
+ }
462
+ }
463
+ onLoad();
464
+ status$.assign({
465
+ canSave: true,
466
+ isLoaded: true,
467
+ });
468
+ }
469
+ async _onChange(path, pathTypes, pathFirebase, dateModifiedKey, dateModifiedKeyOption, params, localState, saveState, snapshot) {
470
+ const status$ = this._pathsLoadStatus[pathFirebase];
471
+ const { isLoaded, startedLoading } = status$.peek();
472
+ if (!isLoaded) {
473
+ // If onceValue has not been called yet, then skip onChange because it will come later
474
+ if (!startedLoading)
475
+ return;
476
+ // Wait for load
477
+ await state.when(status$.isLoaded);
478
+ }
479
+ const { onChange, state: state$1 } = params;
480
+ // Skip changes if disabled
481
+ if (state$1.isEnabledRemote.peek() === false)
482
+ return;
483
+ const key = snapshot.key;
484
+ const val = snapshot.val();
485
+ if (val) {
486
+ // eslint-disable-next-line prefer-const
487
+ let { value, dateModified } = this._convertFBTimestamps(val, dateModifiedKey, dateModifiedKeyOption);
488
+ const pathChild = path.concat(key);
489
+ const constructed = state.constructObjectWithPath(pathChild, value, pathTypes);
490
+ if (!this.addValuesToPendingSaves(pathFirebase, constructed, pathChild, dateModified, dateModifiedKey, dateModifiedKeyOption, saveState, onChange)) {
491
+ localState.changes = state.setAtPath(localState.changes, pathChild, pathTypes, value);
492
+ // Debounce many child changes into a single onChange
493
+ clearTimeout(localState.timeout);
494
+ localState.timeout = setTimeout(() => {
495
+ const changes = localState.changes;
496
+ localState.changes = {};
497
+ onChange({ value: changes, path, pathTypes, mode: 'assign', dateModified });
498
+ }, 300);
499
+ }
500
+ }
501
+ }
502
+ insertDateToObject(value, dateModifiedKey) {
503
+ const timestamp = this.fns.serverTimestamp();
504
+ if (state.isObject(value)) {
505
+ return Object.assign(value, {
506
+ [dateModifiedKey]: timestamp,
507
+ });
508
+ }
509
+ else {
510
+ return {
511
+ [dateModifiedKey]: timestamp,
512
+ _: value,
513
+ };
514
+ }
515
+ }
516
+ insertDatesToSaveObject(batch, queryByModified, dateModifiedKey, path, value) {
517
+ if (queryByModified === true) {
518
+ value = this.insertDateToObject(value, dateModifiedKey);
519
+ }
520
+ else if (state.isObject(value)) {
521
+ Object.keys(value).forEach((key) => {
522
+ value[key] = this.insertDatesToSaveObject(batch, queryByModified[key], dateModifiedKey, path + '/' + key, value[key]);
523
+ });
524
+ }
525
+ return value;
526
+ }
527
+ insertDatesToSave(batch, queryByModified, dateModifiedKey, basePath, path, value) {
528
+ let o = queryByModified;
529
+ for (let i = 0; i < path.length; i++) {
530
+ if (o === true) {
531
+ const pathThis = basePath + path.slice(0, i + 1).join('/');
532
+ if (i === path.length - 1) {
533
+ if (!state.isObject(value)) {
534
+ return this.insertDateToObject(value, dateModifiedKey);
535
+ }
536
+ else {
537
+ if (state.isObject(value)) {
538
+ value[dateModifiedKey] = this.fns.serverTimestamp();
539
+ }
540
+ else {
541
+ batch[pathThis + '/' + dateModifiedKey] = this.fns.serverTimestamp();
542
+ }
543
+ }
544
+ }
545
+ else {
546
+ batch[pathThis + '/' + dateModifiedKey] = this.fns.serverTimestamp();
547
+ }
548
+ return value;
549
+ }
550
+ else if (state.isObject(o)) {
551
+ o = o[path[i]];
552
+ }
553
+ }
554
+ if (o === true && state.isObject(value)) {
555
+ Object.keys(value).forEach((key) => {
556
+ this.insertDatesToSaveObject(batch, o, dateModifiedKey, basePath + path.join('/') + '/' + key, value[key]);
557
+ });
558
+ }
559
+ else if (o !== undefined) {
560
+ this.insertDatesToSaveObject(batch, o, dateModifiedKey, basePath + path.join('/'), value);
561
+ }
562
+ return value;
563
+ }
564
+ addValuesToPendingSaves(syncPath, value, pathChild, dateModified, dateModifiedKey, dateModifiedKeyOption, saveState, onChange) {
565
+ const { pendingSaveResults, savingSaves } = saveState;
566
+ let found = false;
567
+ const pathArr = syncPath.split('/');
568
+ for (let i = pathArr.length - 1; !found && i >= 0; i--) {
569
+ const p = pathArr[i];
570
+ if (p === '')
571
+ continue;
572
+ const path = pathArr.slice(0, i + 1).join('/') + '/';
573
+ // Look for this saved key in the currently saving saves.
574
+ // If it's being saved locally this must be the remote onChange
575
+ // coming in for this save.
576
+ if (pendingSaveResults.has(path) && (savingSaves === null || savingSaves === void 0 ? void 0 : savingSaves.has(path))) {
577
+ found = true;
578
+ if (pathChild.length > 0) {
579
+ const savingSave = savingSaves.get(path);
580
+ const save = savingSave.saves[pathChild[0]];
581
+ if (!save) {
582
+ found = false;
583
+ }
584
+ }
585
+ if (found) {
586
+ const pending = pendingSaveResults.get(path);
587
+ pending.saved.push({
588
+ value,
589
+ dateModified,
590
+ path: pathChild,
591
+ dateModifiedKey,
592
+ dateModifiedKeyOption,
593
+ onChange,
594
+ });
595
+ }
596
+ }
597
+ value = { [p]: value };
598
+ }
599
+ return found;
600
+ }
601
+ }
602
+ function splitLargeObject(obj, limit) {
603
+ const parts = [{}];
604
+ let sizeCount = 0;
605
+ function estimateSize(value) {
606
+ return ('' + value).length + 2; // Convert to string and account for quotes in JSON.
607
+ }
608
+ function recursiveSplit(innerObj, path = []) {
609
+ for (const key in innerObj) {
610
+ if (!state.hasOwnProperty.call(innerObj, key)) {
611
+ continue;
612
+ }
613
+ const newPath = [...path, key];
614
+ const keySize = key.length + 4; // Account for quotes and colon in JSON.
615
+ const val = innerObj[key];
616
+ let itemSize = 0;
617
+ if (val && typeof val === 'object') {
618
+ itemSize = JSON.stringify(val).length;
619
+ }
620
+ else {
621
+ itemSize = estimateSize(val);
622
+ }
623
+ if (val && typeof val === 'object' && itemSize > limit) {
624
+ recursiveSplit(val, newPath);
625
+ }
626
+ else {
627
+ // Check if the size of the current item exceeds the limit
628
+ if (sizeCount > 0 && sizeCount + keySize + itemSize > limit) {
629
+ parts.push({});
630
+ sizeCount = 0;
631
+ }
632
+ const pathKey = newPath.join('/');
633
+ parts[parts.length - 1][pathKey] = val;
634
+ sizeCount += keySize + itemSize;
635
+ }
636
+ }
637
+ }
638
+ recursiveSplit(obj);
639
+ return parts;
640
+ }
641
+ class ObservablePersistFirebase extends ObservablePersistFirebaseBase {
642
+ constructor() {
643
+ super({
644
+ getCurrentUser: () => { var _a; return (_a = auth.getAuth().currentUser) === null || _a === void 0 ? void 0 : _a.uid; },
645
+ ref: (path) => database.ref(database.getDatabase(), path),
646
+ orderByChild: (ref, child, start) => database.query(ref, database.orderByChild(child), database.startAt(start)),
647
+ update: (object) => database.update(database.ref(database.getDatabase()), object),
648
+ once: (ref, callback, callbackError) => {
649
+ let unsubscribe;
650
+ const cb = (snap) => {
651
+ if (unsubscribe) {
652
+ unsubscribe();
653
+ unsubscribe = undefined;
654
+ }
655
+ callback(snap);
656
+ };
657
+ unsubscribe = database.onValue(ref, cb, callbackError);
658
+ return unsubscribe;
659
+ },
660
+ onChildAdded: database.onChildAdded,
661
+ onChildChanged: database.onChildChanged,
662
+ serverTimestamp: database.serverTimestamp,
663
+ onAuthStateChanged: (cb) => auth.getAuth().onAuthStateChanged(cb),
664
+ });
665
+ }
666
+ }
667
+
668
+ exports.ObservablePersistFirebase = ObservablePersistFirebase;
669
+ //# sourceMappingURL=firebase.js.map