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