@legendapp/state 2.2.0-next.7 → 2.2.0-next.71

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 (298) hide show
  1. package/README.md +4 -2
  2. package/babel.js.map +1 -1
  3. package/config/enable$get.d.ts +8 -0
  4. package/config/enable$get.js +24 -0
  5. package/config/enable$get.js.map +1 -0
  6. package/config/enable$get.mjs +21 -0
  7. package/config/enable$get.mjs.map +1 -0
  8. package/config/enableReactComponents.js.map +1 -1
  9. package/config/enableReactComponents.mjs.map +1 -1
  10. package/config/enableReactNativeComponents.js.map +1 -1
  11. package/config/enableReactNativeComponents.mjs.map +1 -1
  12. package/config/enableReactTracking.d.ts +0 -9
  13. package/config/enableReactTracking.js.map +1 -1
  14. package/config/enableReactTracking.mjs.map +1 -1
  15. package/config/enableReactUse.d.ts +1 -1
  16. package/config/enableReactUse.js +1 -0
  17. package/config/enableReactUse.js.map +1 -1
  18. package/config/enableReactUse.mjs +1 -0
  19. package/config/enableReactUse.mjs.map +1 -1
  20. package/config/enable_peek.d.ts +8 -0
  21. package/config/{enableDirectPeek.js → enable_peek.js} +6 -3
  22. package/config/enable_peek.js.map +1 -0
  23. package/config/{enableDirectPeek.mjs → enable_peek.mjs} +5 -3
  24. package/config/enable_peek.mjs.map +1 -0
  25. package/helpers/fetch.d.ts +4 -3
  26. package/helpers/fetch.js.map +1 -1
  27. package/helpers/fetch.mjs.map +1 -1
  28. package/helpers/pageHash.js.map +1 -1
  29. package/helpers/pageHash.mjs.map +1 -1
  30. package/helpers/pageHashParams.js.map +1 -1
  31. package/helpers/pageHashParams.mjs.map +1 -1
  32. package/helpers/time.d.ts +2 -2
  33. package/helpers/time.js.map +1 -1
  34. package/helpers/time.mjs.map +1 -1
  35. package/history.js +2 -2
  36. package/history.js.map +1 -1
  37. package/history.mjs +3 -3
  38. package/history.mjs.map +1 -1
  39. package/index.d.ts +30 -9
  40. package/index.js +877 -661
  41. package/index.js.map +1 -1
  42. package/index.mjs +874 -658
  43. package/index.mjs.map +1 -1
  44. package/package.json +22 -25
  45. package/persist-plugins/async-storage.d.ts +3 -3
  46. package/persist-plugins/async-storage.js +8 -7
  47. package/persist-plugins/async-storage.js.map +1 -1
  48. package/persist-plugins/async-storage.mjs +9 -8
  49. package/persist-plugins/async-storage.mjs.map +1 -1
  50. package/persist-plugins/fetch.js.map +1 -1
  51. package/persist-plugins/fetch.mjs.map +1 -1
  52. package/persist-plugins/firebase.d.ts +1 -1
  53. package/persist-plugins/firebase.js +12 -11
  54. package/persist-plugins/firebase.js.map +1 -1
  55. package/persist-plugins/firebase.mjs +13 -12
  56. package/persist-plugins/firebase.mjs.map +1 -1
  57. package/persist-plugins/indexeddb.d.ts +10 -10
  58. package/persist-plugins/indexeddb.js +2 -2
  59. package/persist-plugins/indexeddb.js.map +1 -1
  60. package/persist-plugins/indexeddb.mjs +2 -2
  61. package/persist-plugins/indexeddb.mjs.map +1 -1
  62. package/persist-plugins/local-storage.d.ts +3 -4
  63. package/persist-plugins/local-storage.js +19 -7
  64. package/persist-plugins/local-storage.js.map +1 -1
  65. package/persist-plugins/local-storage.mjs +20 -9
  66. package/persist-plugins/local-storage.mjs.map +1 -1
  67. package/persist-plugins/mmkv.d.ts +8 -8
  68. package/persist-plugins/mmkv.js +5 -4
  69. package/persist-plugins/mmkv.js.map +1 -1
  70. package/persist-plugins/mmkv.mjs +6 -5
  71. package/persist-plugins/mmkv.mjs.map +1 -1
  72. package/persist-plugins/query.js.map +1 -1
  73. package/persist-plugins/query.mjs.map +1 -1
  74. package/persist.d.ts +2 -14
  75. package/persist.js +1250 -268
  76. package/persist.js.map +1 -1
  77. package/persist.mjs +1250 -269
  78. package/persist.mjs.map +1 -1
  79. package/react-hooks/createObservableHook.js +1 -1
  80. package/react-hooks/createObservableHook.js.map +1 -1
  81. package/react-hooks/createObservableHook.mjs +1 -1
  82. package/react-hooks/createObservableHook.mjs.map +1 -1
  83. package/react-hooks/useFetch.d.ts +4 -3
  84. package/react-hooks/useFetch.js.map +1 -1
  85. package/react-hooks/useFetch.mjs.map +1 -1
  86. package/react-hooks/useHover.js.map +1 -1
  87. package/react-hooks/useHover.mjs.map +1 -1
  88. package/react-hooks/useMeasure.js.map +1 -1
  89. package/react-hooks/useMeasure.mjs.map +1 -1
  90. package/react-hooks/useObservableNextRouter.js.map +1 -1
  91. package/react-hooks/useObservableNextRouter.mjs.map +1 -1
  92. package/react-hooks/useObservableQuery.js.map +1 -1
  93. package/react-hooks/useObservableQuery.mjs.map +1 -1
  94. package/react-hooks/usePersistedObservable.d.ts +5 -3
  95. package/react-hooks/usePersistedObservable.js +5 -2
  96. package/react-hooks/usePersistedObservable.js.map +1 -1
  97. package/react-hooks/usePersistedObservable.mjs +5 -2
  98. package/react-hooks/usePersistedObservable.mjs.map +1 -1
  99. package/react.js +61 -75
  100. package/react.js.map +1 -1
  101. package/react.mjs +61 -75
  102. package/react.mjs.map +1 -1
  103. package/src/ObservableObject.ts +1184 -0
  104. package/src/ObservablePrimitive.ts +62 -0
  105. package/src/babel/index.ts +70 -0
  106. package/src/batching.ts +372 -0
  107. package/src/computed.ts +16 -0
  108. package/src/config/enable$get.ts +30 -0
  109. package/src/config/enableReactComponents.ts +26 -0
  110. package/src/config/enableReactNativeComponents.ts +102 -0
  111. package/src/config/enableReactTracking.ts +60 -0
  112. package/src/config/enableReactUse.ts +23 -0
  113. package/src/config/enable_peek.ts +31 -0
  114. package/src/config.ts +47 -0
  115. package/src/createObservable.ts +46 -0
  116. package/src/event.ts +26 -0
  117. package/src/globals.ts +224 -0
  118. package/src/helpers/fetch.ts +26 -0
  119. package/src/helpers/pageHash.ts +41 -0
  120. package/src/helpers/pageHashParams.ts +55 -0
  121. package/src/helpers/time.ts +30 -0
  122. package/src/helpers.ts +221 -0
  123. package/src/history/trackHistory.ts +29 -0
  124. package/src/is.ts +56 -0
  125. package/src/linked.ts +6 -0
  126. package/src/observable.ts +32 -0
  127. package/src/observableInterfaces.ts +165 -0
  128. package/src/observableTypes.ts +221 -0
  129. package/src/observe.ts +89 -0
  130. package/src/onChange.ts +136 -0
  131. package/src/persist/configureObservablePersistence.ts +7 -0
  132. package/src/persist/fieldTransformer.ts +149 -0
  133. package/src/persist/observablePersistRemoteFunctionsAdapter.ts +39 -0
  134. package/src/persist/persistObservable.ts +1029 -0
  135. package/src/persist-plugins/async-storage.ts +102 -0
  136. package/src/persist-plugins/fetch.ts +33 -0
  137. package/src/persist-plugins/firebase.ts +1050 -0
  138. package/src/persist-plugins/indexeddb.ts +433 -0
  139. package/src/persist-plugins/local-storage.ts +90 -0
  140. package/src/persist-plugins/mmkv.ts +90 -0
  141. package/src/persist-plugins/query.ts +133 -0
  142. package/src/persistTypes.ts +226 -0
  143. package/src/proxy.ts +28 -0
  144. package/src/react/Computed.tsx +7 -0
  145. package/src/react/For.tsx +116 -0
  146. package/src/react/Memo.tsx +4 -0
  147. package/src/react/Reactive.tsx +53 -0
  148. package/src/react/Show.tsx +33 -0
  149. package/src/react/Switch.tsx +43 -0
  150. package/src/react/react-globals.ts +3 -0
  151. package/src/react/{reactInterfaces.d.ts → reactInterfaces.ts} +15 -7
  152. package/src/react/reactive-observer.tsx +210 -0
  153. package/src/react/useComputed.ts +36 -0
  154. package/src/react/useEffectOnce.ts +41 -0
  155. package/src/react/useIsMounted.ts +16 -0
  156. package/src/react/useMount.ts +15 -0
  157. package/src/react/useObservable.ts +24 -0
  158. package/src/react/useObservableReducer.ts +52 -0
  159. package/src/react/useObservableState.ts +30 -0
  160. package/src/react/useObserve.ts +54 -0
  161. package/src/react/useObserveEffect.ts +40 -0
  162. package/src/react/usePauseProvider.tsx +13 -0
  163. package/src/react/useSelector.ts +167 -0
  164. package/src/react/useUnmount.ts +8 -0
  165. package/src/react/useWhen.ts +9 -0
  166. package/src/react-hooks/createObservableHook.ts +53 -0
  167. package/src/react-hooks/useFetch.ts +16 -0
  168. package/src/react-hooks/useHover.ts +40 -0
  169. package/src/react-hooks/useMeasure.ts +48 -0
  170. package/src/react-hooks/useObservableNextRouter.ts +137 -0
  171. package/src/react-hooks/useObservableQuery.ts +205 -0
  172. package/src/react-hooks/usePersistedObservable.ts +24 -0
  173. package/src/retry.ts +69 -0
  174. package/src/setupTracking.ts +26 -0
  175. package/src/sync/activateSyncedNode.ts +146 -0
  176. package/src/sync/configureObservableSync.ts +7 -0
  177. package/src/sync/syncHelpers.ts +15 -0
  178. package/src/sync/syncObservable.ts +989 -0
  179. package/src/sync/syncObservableAdapter.ts +30 -0
  180. package/src/sync/synced.ts +20 -0
  181. package/src/sync-plugins/fetch.ts +42 -0
  182. package/src/syncTypes.ts +163 -0
  183. package/src/trace/traceHelpers.ts +11 -0
  184. package/src/trace/useTraceListeners.ts +34 -0
  185. package/src/trace/useTraceUpdates.ts +24 -0
  186. package/src/trace/useVerifyNotTracking.ts +33 -0
  187. package/src/trace/useVerifyOneRender.ts +10 -0
  188. package/src/trackSelector.ts +52 -0
  189. package/src/tracking.ts +43 -0
  190. package/src/types/babel.d.ts +12 -0
  191. package/src/when.ts +70 -0
  192. package/sync-plugins/fetch.d.ts +11 -0
  193. package/sync-plugins/fetch.js +24 -0
  194. package/sync-plugins/fetch.js.map +1 -0
  195. package/sync-plugins/fetch.mjs +22 -0
  196. package/sync-plugins/fetch.mjs.map +1 -0
  197. package/sync.d.ts +8 -0
  198. package/sync.js +919 -0
  199. package/sync.js.map +1 -0
  200. package/sync.mjs +912 -0
  201. package/sync.mjs.map +1 -0
  202. package/trace.js +13 -10
  203. package/trace.js.map +1 -1
  204. package/trace.mjs +11 -8
  205. package/trace.mjs.map +1 -1
  206. package/types/babel.d.ts +3 -3
  207. package/config/enableDirectAccess.d.ts +0 -7
  208. package/config/enableDirectAccess.js +0 -25
  209. package/config/enableDirectAccess.js.map +0 -1
  210. package/config/enableDirectAccess.mjs +0 -23
  211. package/config/enableDirectAccess.mjs.map +0 -1
  212. package/config/enableDirectPeek.d.ts +0 -7
  213. package/config/enableDirectPeek.js.map +0 -1
  214. package/config/enableDirectPeek.mjs.map +0 -1
  215. package/config/enableReactDirectRender.d.ts +0 -2
  216. package/config/enableReactDirectRender.js +0 -78
  217. package/config/enableReactDirectRender.js.map +0 -1
  218. package/config/enableReactDirectRender.mjs +0 -75
  219. package/config/enableReactDirectRender.mjs.map +0 -1
  220. package/src/ObservableObject.d.ts +0 -14
  221. package/src/ObservablePrimitive.d.ts +0 -7
  222. package/src/babel/index.d.ts +0 -17
  223. package/src/batching.d.ts +0 -6
  224. package/src/computed.d.ts +0 -4
  225. package/src/config/enableDirectAccess.d.ts +0 -7
  226. package/src/config/enableDirectPeek.d.ts +0 -7
  227. package/src/config/enableReactComponents.d.ts +0 -7
  228. package/src/config/enableReactDirectRender.d.ts +0 -2
  229. package/src/config/enableReactNativeComponents.d.ts +0 -20
  230. package/src/config/enableReactTracking.d.ts +0 -15
  231. package/src/config/enableReactUse.d.ts +0 -7
  232. package/src/config.d.ts +0 -8
  233. package/src/createObservable.d.ts +0 -2
  234. package/src/event.d.ts +0 -2
  235. package/src/globals.d.ts +0 -32
  236. package/src/helpers/fetch.d.ts +0 -6
  237. package/src/helpers/pageHash.d.ts +0 -7
  238. package/src/helpers/pageHashParams.d.ts +0 -7
  239. package/src/helpers/time.d.ts +0 -3
  240. package/src/helpers.d.ts +0 -13
  241. package/src/history/trackHistory.d.ts +0 -4
  242. package/src/is.d.ts +0 -10
  243. package/src/observable.d.ts +0 -16
  244. package/src/observableInterfaces.d.ts +0 -456
  245. package/src/observe.d.ts +0 -6
  246. package/src/onChange.d.ts +0 -7
  247. package/src/persist/configureObservablePersistence.d.ts +0 -3
  248. package/src/persist/fieldTransformer.d.ts +0 -8
  249. package/src/persist/observablePersistRemoteFunctionsAdapter.d.ts +0 -2
  250. package/src/persist/persistActivateNode.d.ts +0 -1
  251. package/src/persist/persistHelpers.d.ts +0 -1
  252. package/src/persist/persistObservable.d.ts +0 -25
  253. package/src/persist-plugins/async-storage.d.ts +0 -14
  254. package/src/persist-plugins/fetch.d.ts +0 -10
  255. package/src/persist-plugins/firebase.d.ts +0 -51
  256. package/src/persist-plugins/indexeddb.d.ts +0 -25
  257. package/src/persist-plugins/local-storage.d.ts +0 -21
  258. package/src/persist-plugins/mmkv.d.ts +0 -14
  259. package/src/persist-plugins/query.d.ts +0 -18
  260. package/src/proxy.d.ts +0 -5
  261. package/src/react/Computed.d.ts +0 -5
  262. package/src/react/For.d.ts +0 -15
  263. package/src/react/Memo.d.ts +0 -3
  264. package/src/react/Reactive.d.ts +0 -9
  265. package/src/react/Show.d.ts +0 -18
  266. package/src/react/Switch.d.ts +0 -14
  267. package/src/react/react-globals.d.ts +0 -3
  268. package/src/react/reactive-observer.d.ts +0 -14
  269. package/src/react/useComputed.d.ts +0 -5
  270. package/src/react/useEffectOnce.d.ts +0 -1
  271. package/src/react/useIsMounted.d.ts +0 -2
  272. package/src/react/useMount.d.ts +0 -2
  273. package/src/react/useObservable.d.ts +0 -9
  274. package/src/react/useObservableReducer.d.ts +0 -7
  275. package/src/react/useObservableState.d.ts +0 -2
  276. package/src/react/useObserve.d.ts +0 -4
  277. package/src/react/useObserveEffect.d.ts +0 -4
  278. package/src/react/usePauseProvider.d.ts +0 -8
  279. package/src/react/useSelector.d.ts +0 -3
  280. package/src/react/useUnmount.d.ts +0 -2
  281. package/src/react/useWhen.d.ts +0 -3
  282. package/src/react-hooks/createObservableHook.d.ts +0 -2
  283. package/src/react-hooks/useFetch.d.ts +0 -6
  284. package/src/react-hooks/useHover.d.ts +0 -3
  285. package/src/react-hooks/useMeasure.d.ts +0 -6
  286. package/src/react-hooks/useObservableNextRouter.d.ts +0 -33
  287. package/src/react-hooks/useObservableQuery.d.ts +0 -6
  288. package/src/react-hooks/usePersistedObservable.d.ts +0 -11
  289. package/src/retry.d.ts +0 -9
  290. package/src/setupTracking.d.ts +0 -2
  291. package/src/trace/traceHelpers.d.ts +0 -2
  292. package/src/trace/useTraceListeners.d.ts +0 -1
  293. package/src/trace/useTraceUpdates.d.ts +0 -1
  294. package/src/trace/useVerifyNotTracking.d.ts +0 -1
  295. package/src/trace/useVerifyOneRender.d.ts +0 -1
  296. package/src/trackSelector.d.ts +0 -7
  297. package/src/tracking.d.ts +0 -13
  298. package/src/when.d.ts +0 -3
@@ -0,0 +1,1050 @@
1
+ import {
2
+ Observable,
3
+ ObservablePersistRemoteClass,
4
+ ObservablePersistRemoteGetParams,
5
+ ObservablePersistRemoteSetParams,
6
+ ObservablePrimitive,
7
+ ObservableParam,
8
+ LegacyPersistOptions,
9
+ QueryByModified,
10
+ TypeAtPath,
11
+ batch,
12
+ constructObjectWithPath,
13
+ deconstructObjectWithPath,
14
+ hasOwnProperty,
15
+ internal,
16
+ isArray,
17
+ isFunction,
18
+ isObject,
19
+ mergeIntoObservable,
20
+ observable,
21
+ observablePrimitive,
22
+ setAtPath,
23
+ when,
24
+ whenReady,
25
+ } from '@legendapp/state';
26
+ import { internal as internalPersist, transformObject, transformPath } from '@legendapp/state/persist';
27
+ import { getAuth, type User } from 'firebase/auth';
28
+ import type { DataSnapshot } from 'firebase/database';
29
+ import {
30
+ DatabaseReference,
31
+ Unsubscribe,
32
+ getDatabase,
33
+ onChildAdded,
34
+ onChildChanged,
35
+ onValue,
36
+ orderByChild,
37
+ query,
38
+ ref,
39
+ serverTimestamp,
40
+ startAt,
41
+ update,
42
+ } from 'firebase/database';
43
+ const { symbolDelete, getPathType, clone } = internal;
44
+ const { observablePersistConfiguration } = internalPersist;
45
+
46
+ function getDateModifiedKey(dateModifiedKey: string | undefined) {
47
+ return dateModifiedKey || observablePersistConfiguration.remoteOptions?.dateModifiedKey || '@';
48
+ }
49
+
50
+ interface FirebaseFns {
51
+ isInitialized: () => boolean;
52
+ getCurrentUser: () => string | undefined;
53
+ ref: (path: string) => DatabaseReference;
54
+ orderByChild: (ref: any, child: string, startAt: number) => any;
55
+ once: (query: any, callback: (snapshot: DataSnapshot) => unknown, onError: (error: Error) => void) => () => void;
56
+ onChildAdded: (
57
+ query: any,
58
+ callback: (snapshot: DataSnapshot) => unknown,
59
+ cancelCallback?: (error: Error) => unknown,
60
+ ) => () => void;
61
+ onChildChanged: (
62
+ query: any,
63
+ callback: (snapshot: DataSnapshot) => unknown,
64
+ cancelCallback?: (error: Error) => unknown,
65
+ ) => () => void;
66
+ serverTimestamp: () => any;
67
+ update: (object: object) => Promise<void>;
68
+ onAuthStateChanged: (cb: (user: User | null) => void) => void;
69
+ }
70
+
71
+ type LocalState<T> = { changes: object | T; timeout?: any };
72
+
73
+ const symbolSaveValue = Symbol('___obsSaveValue');
74
+
75
+ interface SaveInfo {
76
+ [symbolSaveValue]: any;
77
+ adjusted?: boolean;
78
+ }
79
+
80
+ type SaveInfoDictionary<T = any> = {
81
+ [K in keyof T]: SaveInfo | SaveInfoDictionary<T[K]>;
82
+ };
83
+
84
+ interface PendingSaves {
85
+ options: LegacyPersistOptions;
86
+ saves: SaveInfoDictionary;
87
+ }
88
+
89
+ interface SaveState {
90
+ timeout?: any;
91
+ pendingSaves: Map<string, PendingSaves>;
92
+ savingSaves?: Map<string, PendingSaves>;
93
+ eventSaved?: ObservablePrimitive<true | Error | undefined>;
94
+ numSavesPending: Observable<number>;
95
+ pendingSaveResults: Map<
96
+ string,
97
+ {
98
+ saved: {
99
+ value: any;
100
+ path: string[];
101
+ pathTypes: TypeAtPath[];
102
+ dateModified: number | undefined;
103
+ dateModifiedKey: string | undefined;
104
+ dateModifiedKeyOption: string | undefined;
105
+ onChange: ObservablePersistRemoteGetParams<any>['onChange'];
106
+ }[];
107
+ }
108
+ >;
109
+ }
110
+
111
+ interface LoadStatus {
112
+ startedLoading: boolean;
113
+ numLoading: number;
114
+ numWaitingCanSave: number;
115
+ }
116
+
117
+ class ObservablePersistFirebaseBase implements ObservablePersistRemoteClass {
118
+ protected _batch: Record<string, any> = {};
119
+ protected fns: FirebaseFns;
120
+ private _pathsLoadStatus = observable<Record<string, LoadStatus>>({});
121
+ private debounceSet;
122
+ private user: Observable<string | undefined | null>;
123
+ private listenErrors: Map<
124
+ any,
125
+ {
126
+ params: ObservablePersistRemoteGetParams<any>;
127
+ path: string[];
128
+ pathTypes: TypeAtPath[];
129
+ dateModified: number | undefined;
130
+ queryByModified: QueryByModified<any> | undefined;
131
+ unsubscribes: (() => void)[];
132
+ retry: number;
133
+ saveState: SaveState;
134
+ onLoadParams: { waiting: number; onLoad: () => void };
135
+ status$: Observable<LoadStatus>;
136
+ }
137
+ > = new Map();
138
+ private saveStates = new Map<ObservableParam<any>, SaveState>();
139
+
140
+ constructor(fns: FirebaseFns) {
141
+ this.fns = fns;
142
+ this.user = observablePrimitive();
143
+ this.debounceSet = observablePersistConfiguration?.remoteOptions?.debounceSet ?? 500;
144
+
145
+ if (this.fns.isInitialized()) {
146
+ this.fns.onAuthStateChanged((user) => {
147
+ this.user.set(user?.uid);
148
+ });
149
+ } else if (
150
+ process.env.NODE_ENV === 'development' &&
151
+ (typeof window !== 'undefined' || (typeof navigator !== 'undefined' && navigator.product === 'ReactNative'))
152
+ ) {
153
+ // Warn only in web or react-native. If running on a server this shouldn't work.
154
+ console.warn('[legend-state] Firebase is not initialized. Remote persistence will not work.');
155
+ }
156
+ }
157
+ public async get<T>(params: ObservablePersistRemoteGetParams<T>) {
158
+ const { obs, options } = params;
159
+ const { remote } = options;
160
+ if (!remote || !remote.firebase) {
161
+ // If the plugin is set globally but it has no firebase options this plugin can't do anything
162
+ return;
163
+ }
164
+ const {
165
+ firebase: { refPath },
166
+ waitForGet,
167
+ } = remote;
168
+
169
+ const { requireAuth, queryByModified } = options.remote!.firebase!;
170
+
171
+ // If requireAuth wait for user to be signed in
172
+ if (requireAuth) {
173
+ await whenReady(this.user);
174
+ }
175
+
176
+ // If waitForGet wait for it
177
+ if (waitForGet) {
178
+ await whenReady(waitForGet);
179
+ }
180
+
181
+ const saveState: SaveState = {
182
+ pendingSaveResults: new Map(),
183
+ pendingSaves: new Map(),
184
+ numSavesPending: observable(0),
185
+ };
186
+ this.saveStates.set(obs, saveState);
187
+
188
+ const pathFirebase = refPath(this.fns.getCurrentUser());
189
+
190
+ const status$ = this._pathsLoadStatus[pathFirebase];
191
+ status$.set({
192
+ startedLoading: false,
193
+ numLoading: 0,
194
+ numWaitingCanSave: 0,
195
+ });
196
+
197
+ const onLoadParams = {
198
+ waiting: 0,
199
+ onLoad: () => {
200
+ onLoadParams.waiting--;
201
+ if (onLoadParams.waiting === 0) {
202
+ params.onGet();
203
+ }
204
+ },
205
+ };
206
+
207
+ if (isObject(queryByModified)) {
208
+ this.iterateListen(obs, params, saveState, [], [], queryByModified, onLoadParams, status$);
209
+ } else {
210
+ const dateModified = queryByModified === true ? params.dateModified! : undefined;
211
+
212
+ this._listen(obs, params, saveState, [], [], queryByModified, dateModified, onLoadParams, status$);
213
+ }
214
+ }
215
+ private iterateListen<T>(
216
+ obs: ObservableParam<any>,
217
+ params: ObservablePersistRemoteGetParams<T>,
218
+ saveState: SaveState,
219
+ path: string[],
220
+ pathTypes: TypeAtPath[],
221
+ queryByModified: QueryByModified<any>,
222
+ onLoadParams: { waiting: number; onLoad: () => void },
223
+ status$: Observable<LoadStatus>,
224
+ ) {
225
+ const { options } = params;
226
+
227
+ const { ignoreKeys } = options.remote!.firebase!;
228
+ Object.keys(obs).forEach((key) => {
229
+ if (!ignoreKeys || !ignoreKeys.includes(key)) {
230
+ const o = (obs as any)[key] as ObservableParam<any>;
231
+ const q =
232
+ queryByModified[key as keyof typeof queryByModified] || (queryByModified as { '*': boolean })['*'];
233
+ const pathChild = path.concat(key);
234
+ const pathTypesChild = pathTypes.concat(getPathType(o.peek()));
235
+ let dateModified: number | undefined = undefined;
236
+
237
+ if (isObject(q)) {
238
+ this.iterateListen(o, params, saveState, pathChild, pathTypesChild, q, onLoadParams, status$);
239
+ } else {
240
+ if (q === true || q === '*') {
241
+ dateModified = params.dateModified!;
242
+ }
243
+
244
+ this._listen(
245
+ o,
246
+ params,
247
+ saveState,
248
+ pathChild,
249
+ pathTypesChild,
250
+ queryByModified,
251
+ dateModified,
252
+ onLoadParams,
253
+ status$,
254
+ );
255
+ }
256
+ }
257
+ });
258
+ }
259
+ private retryListens() {
260
+ // If a listen failed but save succeeded, the save should have fixed
261
+ // the permission problem so try again
262
+ this.listenErrors.forEach((listenError) => {
263
+ const {
264
+ params,
265
+ path,
266
+ pathTypes,
267
+ dateModified,
268
+ queryByModified,
269
+ unsubscribes,
270
+ saveState,
271
+ onLoadParams,
272
+ status$,
273
+ } = listenError;
274
+ listenError.retry++;
275
+ if (listenError.retry < 10) {
276
+ unsubscribes.forEach((cb) => cb());
277
+ this._listen(
278
+ params.obs,
279
+ params,
280
+ saveState,
281
+ path,
282
+ pathTypes,
283
+ queryByModified,
284
+ dateModified,
285
+ onLoadParams,
286
+ status$,
287
+ );
288
+ } else {
289
+ this.listenErrors.delete(listenError);
290
+ }
291
+ });
292
+ }
293
+ private async _listen<T>(
294
+ obs: ObservableParam<any>,
295
+ params: ObservablePersistRemoteGetParams<T>,
296
+ saveState: SaveState,
297
+ path: string[],
298
+ pathTypes: TypeAtPath[],
299
+ queryByModified: QueryByModified<any> | undefined,
300
+ dateModified: number | undefined,
301
+ onLoadParams: { waiting: number; onLoad: () => void },
302
+ status$: Observable<LoadStatus>,
303
+ ) {
304
+ const { options, onError } = params;
305
+ const { fieldTransforms, allowSetIfError, firebase, dateModifiedKey: dateModifiedKeyOption } = options.remote!;
306
+ const { refPath, query, mode } = firebase!;
307
+
308
+ let didError = false;
309
+ const dateModifiedKey = getDateModifiedKey(dateModifiedKeyOption);
310
+
311
+ const originalPath = path;
312
+ if (fieldTransforms && path.length) {
313
+ path = transformPath(path, pathTypes, fieldTransforms);
314
+ }
315
+
316
+ const pathFirebase = refPath(this.fns.getCurrentUser()) + path.join('/');
317
+
318
+ let ref = this.fns.ref(pathFirebase);
319
+ if (query) {
320
+ ref = query(ref) as DatabaseReference;
321
+ }
322
+ if (dateModified && !isNaN(dateModified)) {
323
+ ref = this.fns.orderByChild(ref, dateModifiedKey, dateModified + 1);
324
+ }
325
+
326
+ const unsubscribes: (() => void)[] = [];
327
+
328
+ status$.numLoading.set((v) => v + 1);
329
+ status$.numWaitingCanSave.set((v) => v + 1);
330
+
331
+ const _onError = (err: Error) => {
332
+ if (!didError) {
333
+ didError = true;
334
+ const existing = this.listenErrors.get(obs);
335
+ if (existing) {
336
+ existing.retry++;
337
+ } else {
338
+ this.listenErrors.set(obs, {
339
+ params,
340
+ path: originalPath,
341
+ pathTypes,
342
+ dateModified,
343
+ queryByModified,
344
+ unsubscribes,
345
+ retry: 0,
346
+ saveState,
347
+ onLoadParams,
348
+ status$,
349
+ });
350
+ params.state.error.set(err);
351
+ onError?.(err);
352
+ if (allowSetIfError) {
353
+ status$.numWaitingCanSave.set((v) => v - 1);
354
+ }
355
+ }
356
+ }
357
+ };
358
+
359
+ if (mode !== 'once') {
360
+ const localState: LocalState<T> = { changes: {} as T };
361
+ const cb = this._onChange.bind(
362
+ this,
363
+ path,
364
+ pathTypes,
365
+ pathFirebase,
366
+ dateModifiedKey,
367
+ dateModifiedKeyOption,
368
+ params as ObservablePersistRemoteGetParams<any>,
369
+ localState,
370
+ saveState,
371
+ status$,
372
+ );
373
+ unsubscribes.push(this.fns.onChildAdded(ref, cb));
374
+ unsubscribes.push(this.fns.onChildChanged(ref, cb));
375
+ }
376
+
377
+ onLoadParams.waiting++;
378
+
379
+ unsubscribes.push(
380
+ this.fns.once(
381
+ ref,
382
+ this._onceValue.bind(
383
+ this,
384
+ path,
385
+ pathTypes,
386
+ pathFirebase,
387
+ dateModifiedKey,
388
+ dateModifiedKeyOption,
389
+ queryByModified,
390
+ onLoadParams.onLoad,
391
+ params as ObservablePersistRemoteGetParams<any>,
392
+ status$,
393
+ ),
394
+ _onError,
395
+ ),
396
+ );
397
+ }
398
+ private _updatePendingSave(path: string[], value: object, pending: SaveInfoDictionary) {
399
+ if (path.length === 0) {
400
+ pending[symbolSaveValue as any] = value as any;
401
+ } else if (pending[symbolSaveValue as any]) {
402
+ pending[symbolSaveValue as any] = mergeIntoObservable(pending[symbolSaveValue as any], value);
403
+ } else {
404
+ const p = path[0];
405
+ const v = (value as any)[p];
406
+ const pendingChild = pending[p] as any;
407
+
408
+ // If already have a save info here then don't need to go deeper on the path. Just overwrite the value.
409
+ if (pendingChild && pendingChild[symbolSaveValue] !== undefined) {
410
+ const pendingSaveValue = pendingChild[symbolSaveValue];
411
+ pendingChild[symbolSaveValue] =
412
+ isArray(pendingSaveValue) || isObject(pendingSaveValue)
413
+ ? mergeIntoObservable(pendingSaveValue, v)
414
+ : v;
415
+ } else {
416
+ // 1. If nothing here
417
+ // 2. If other strings here
418
+ if (!pending[p]) {
419
+ pending[p] = {};
420
+ }
421
+ if (path.length > 1) {
422
+ this._updatePendingSave(path.slice(1), v, pending[p] as SaveInfoDictionary);
423
+ } else {
424
+ pending[p] = { [symbolSaveValue]: v };
425
+ }
426
+ }
427
+ }
428
+ }
429
+ public async set<T>({ options, changes, obs }: ObservablePersistRemoteSetParams<T>): Promise<
430
+ | {
431
+ changes?: object;
432
+ dateModified?: number;
433
+ pathStrs?: string[];
434
+ }
435
+ | undefined
436
+ > {
437
+ const { remote } = options;
438
+ // If the plugin is set globally but it has no firebase options this plugin can't do anything
439
+ if (!remote || !remote.firebase) {
440
+ return;
441
+ }
442
+ const { waitForSet, debounceSet: debounceSet, log, firebase } = remote;
443
+
444
+ const { requireAuth, refPath: refPathFn } = firebase;
445
+
446
+ if (requireAuth) {
447
+ await whenReady(this.user);
448
+ }
449
+
450
+ const refPath = refPathFn(this.fns.getCurrentUser());
451
+
452
+ const status$ = this._pathsLoadStatus[refPath];
453
+ if (status$.numWaitingCanSave.peek() > 0) {
454
+ // Wait for all listened paths to load before we can save
455
+ await when(() => status$.numWaitingCanSave.get() < 1);
456
+ }
457
+
458
+ if (waitForSet) {
459
+ const waitFor = isFunction(waitForSet) ? waitForSet({ changes, value: obs.peek() }) : waitForSet;
460
+ if (waitFor) {
461
+ await when(waitFor);
462
+ }
463
+ }
464
+
465
+ const saveState = this.saveStates.get(obs)!;
466
+
467
+ // Don't start a save until all outstanding saves are finished
468
+ await when(() => saveState.numSavesPending.get() === 0);
469
+
470
+ const { pendingSaveResults, pendingSaves } = saveState;
471
+
472
+ if (!pendingSaves.has(refPath)) {
473
+ pendingSaves.set(refPath, { options, saves: {} });
474
+ pendingSaveResults.set(refPath, { saved: [] });
475
+ }
476
+ const pending = pendingSaves.get(refPath)!.saves;
477
+
478
+ log?.('verbose', 'Saving', changes);
479
+
480
+ for (let i = 0; i < changes.length; i++) {
481
+ let { valueAtPath } = changes[i];
482
+ const { pathTypes, path } = changes[i];
483
+ if (valueAtPath === undefined) {
484
+ valueAtPath = null;
485
+ }
486
+
487
+ const value = constructObjectWithPath(path as string[], pathTypes, clone(valueAtPath)) as unknown as T;
488
+ const pathCloned = path.slice() as string[];
489
+
490
+ this._updatePendingSave(pathCloned, value as unknown as object, pending);
491
+ }
492
+
493
+ if (!saveState.eventSaved) {
494
+ saveState.eventSaved = observablePrimitive();
495
+ }
496
+ // Keep the current eventSaved. This will get reassigned once the timeout activates.
497
+ const eventSaved = saveState.eventSaved;
498
+
499
+ const timeout = debounceSet ?? this.debounceSet;
500
+
501
+ if (timeout) {
502
+ if (saveState.timeout) {
503
+ clearTimeout(saveState.timeout);
504
+ }
505
+ saveState.timeout = setTimeout(this._onTimeoutSave.bind(this, saveState), timeout);
506
+ } else {
507
+ this._onTimeoutSave(saveState);
508
+ }
509
+
510
+ const savedOrError = await when(eventSaved);
511
+
512
+ if (savedOrError === true) {
513
+ this.retryListens();
514
+
515
+ const saveResults = pendingSaveResults.get(refPath);
516
+
517
+ if (saveResults) {
518
+ const { saved } = saveResults;
519
+ if (saved?.length) {
520
+ // Only want to return from saved one time
521
+ if (saveState.numSavesPending.get() === 0) {
522
+ pendingSaveResults.delete(refPath);
523
+ } else {
524
+ saveResults.saved = [];
525
+ }
526
+ let maxModified = 0;
527
+
528
+ // Compile a changes object of all the dateModified
529
+ const changesOut = {};
530
+ for (let i = 0; i < saved.length; i++) {
531
+ const { dateModified, path, pathTypes, dateModifiedKeyOption, dateModifiedKey, value } =
532
+ saved[i];
533
+ if (dateModified) {
534
+ maxModified = Math.max(dateModified, maxModified);
535
+ if (dateModifiedKeyOption) {
536
+ const deconstructed = deconstructObjectWithPath(path, pathTypes, value);
537
+ // Don't resurrect deleted items
538
+ if (deconstructed !== (symbolDelete as any)) {
539
+ Object.assign(
540
+ changesOut,
541
+ constructObjectWithPath(path, pathTypes, {
542
+ [dateModifiedKey!]: dateModified,
543
+ }),
544
+ );
545
+ }
546
+ }
547
+ }
548
+ }
549
+
550
+ const ret = {
551
+ changes: changesOut,
552
+ dateModified: maxModified || undefined,
553
+ };
554
+
555
+ log?.('verbose', 'Saved', changes, ret);
556
+
557
+ return ret;
558
+ }
559
+ }
560
+ } else {
561
+ throw savedOrError;
562
+ }
563
+
564
+ return {};
565
+ }
566
+ private _constructBatch(
567
+ options: LegacyPersistOptions,
568
+ batch: Record<string, string | object>,
569
+ basePath: string,
570
+ saves: SaveInfoDictionary,
571
+ ...path: string[]
572
+ ) {
573
+ const { fieldTransforms, dateModifiedKey: dateModifiedKeyOption } = options.remote!;
574
+ const dateModifiedKey = getDateModifiedKey(dateModifiedKeyOption);
575
+
576
+ let valSave = saves[symbolSaveValue as any];
577
+ if (valSave !== undefined) {
578
+ let queryByModified = options.remote!.firebase!.queryByModified;
579
+ if (queryByModified) {
580
+ if (queryByModified !== true && fieldTransforms) {
581
+ queryByModified = transformObject(queryByModified, fieldTransforms);
582
+ }
583
+ valSave = this.insertDatesToSave(batch, queryByModified!, dateModifiedKey, basePath, path, valSave);
584
+ }
585
+
586
+ const pathThis = basePath + path.join('/');
587
+ if (pathThis && !batch[pathThis]) {
588
+ batch[pathThis] = valSave;
589
+ }
590
+ } else {
591
+ Object.keys(saves).forEach((key) => {
592
+ this._constructBatch(options, batch, basePath, saves[key] as any, ...path, key);
593
+ });
594
+ }
595
+ }
596
+ private _constructBatchesForSave(pendingSaves: Map<string, PendingSaves>) {
597
+ const batches: object[] = [];
598
+ pendingSaves.forEach(({ options, saves }) => {
599
+ const basePath = options.remote!.firebase!.refPath(this.fns.getCurrentUser());
600
+ const batch = {};
601
+ this._constructBatch(options, batch, basePath, saves);
602
+ batches.push(batch);
603
+ });
604
+
605
+ return batches;
606
+ }
607
+ private async _onTimeoutSave(saveState: SaveState) {
608
+ const { pendingSaves, eventSaved } = saveState;
609
+
610
+ saveState.timeout = undefined;
611
+ saveState.eventSaved = undefined;
612
+ saveState.numSavesPending.set((v) => v + 1);
613
+
614
+ if (pendingSaves.size > 0) {
615
+ const batches = clone(this._constructBatchesForSave(pendingSaves)) as Record<string, any>[];
616
+
617
+ saveState.savingSaves = pendingSaves;
618
+
619
+ // Clear the pendingSaves so that the next batch starts from scratch
620
+ saveState.pendingSaves = new Map();
621
+
622
+ if (batches.length > 0) {
623
+ const promises: Promise<{ didSave?: boolean; error?: any }>[] = [];
624
+ for (let i = 0; i < batches.length; i++) {
625
+ const batch = batches[i];
626
+ promises.push(this._saveBatch(batch));
627
+ }
628
+
629
+ const results = await Promise.all(promises);
630
+ const errors = results.filter((result) => result.error);
631
+ if (errors.length === 0) {
632
+ saveState.numSavesPending.set((v) => v - 1);
633
+ eventSaved?.set(true);
634
+ } else {
635
+ eventSaved?.set(errors[0].error);
636
+ }
637
+ }
638
+ }
639
+ }
640
+ private async _saveBatch(batch: Record<string, any>): Promise<any> {
641
+ const length = JSON.stringify(batch).length;
642
+
643
+ let error: Error | undefined = undefined;
644
+ // Firebase has a maximum limit of 16MB per save so we constrain our saves to
645
+ // less than 12 to be safe
646
+ if (length > 12e6) {
647
+ const parts = splitLargeObject(batch, 6e6);
648
+ let didSave = true;
649
+
650
+ // TODO: Option for logging
651
+ for (let i = 0; i < parts.length; i++) {
652
+ const ret = await this._saveBatch(parts[i]);
653
+ if (ret.error) {
654
+ error = ret.error;
655
+ } else {
656
+ didSave = didSave && ret.didSave;
657
+ }
658
+ }
659
+ return error ? { error } : { didSave };
660
+ } else {
661
+ for (let i = 0; i < 3; i++) {
662
+ try {
663
+ await this.fns.update(batch);
664
+ return { didSave: true };
665
+ } catch (err) {
666
+ error = err as Error;
667
+
668
+ await new Promise<void>((resolve) => setTimeout(resolve, 500));
669
+ }
670
+ }
671
+
672
+ return { error };
673
+ }
674
+ }
675
+ private _convertFBTimestamps(obj: any, dateModifiedKey: string, dateModifiedKeyOption: string) {
676
+ let value = obj;
677
+ // Database value can be either { @: number, _: object } or { @: number, ...rest }
678
+ // where @ is the dateModifiedKey
679
+ let dateModified = value[dateModifiedKey];
680
+ if (dateModified) {
681
+ // If user doesn't request a dateModifiedKey then delete it
682
+ if (value._ !== undefined) {
683
+ value = value._;
684
+ } else if (dateModified && Object.keys(value).length < 2) {
685
+ value = symbolDelete;
686
+ }
687
+
688
+ if (!dateModifiedKeyOption) {
689
+ delete value[dateModifiedKey];
690
+ }
691
+ }
692
+
693
+ if (isObject(value)) {
694
+ Object.keys(value).forEach((k) => {
695
+ const val = value[k];
696
+ if (val !== undefined) {
697
+ if (isObject(val) || isArray(val)) {
698
+ const { value: valueChild, dateModified: dateModifiedChild } = this._convertFBTimestamps(
699
+ val,
700
+ dateModifiedKey,
701
+ dateModifiedKeyOption,
702
+ );
703
+ if (dateModifiedChild) {
704
+ dateModified = Math.max(dateModified || 0, dateModifiedChild);
705
+ }
706
+ if (valueChild !== val) {
707
+ value[k] = valueChild;
708
+ }
709
+ }
710
+ }
711
+ });
712
+ }
713
+
714
+ return { value, dateModified };
715
+ }
716
+ private async _onceValue<T>(
717
+ path: string[],
718
+ pathTypes: TypeAtPath[],
719
+ pathFirebase: string,
720
+ dateModifiedKey: string | undefined,
721
+ dateModifiedKeyOption: string | undefined,
722
+ queryByModified: QueryByModified<any> | undefined,
723
+ onLoad: () => void,
724
+ params: ObservablePersistRemoteGetParams<T>,
725
+ status$: Observable<LoadStatus>,
726
+ snapshot: DataSnapshot,
727
+ ) {
728
+ const { onChange } = params;
729
+ const outerValue = snapshot.val();
730
+
731
+ // If this path previously errored, clear the error state
732
+ const obs = params.obs;
733
+ params.state.error.delete();
734
+ this.listenErrors.delete(obs);
735
+
736
+ status$.startedLoading.set(true);
737
+ if (outerValue && isObject(outerValue)) {
738
+ let value;
739
+ let dateModified;
740
+ if (queryByModified) {
741
+ const converted = this._convertFBTimestamps(outerValue, dateModifiedKey!, dateModifiedKeyOption!);
742
+ value = converted.value;
743
+ dateModified = converted.dateModified;
744
+ } else {
745
+ value = outerValue;
746
+ }
747
+
748
+ value = constructObjectWithPath(path, pathTypes, value);
749
+
750
+ const onChangePromise = onChange({
751
+ value,
752
+ path,
753
+ pathTypes,
754
+ mode: queryByModified ? 'assign' : 'set',
755
+ dateModified,
756
+ });
757
+ if (onChangePromise) {
758
+ await onChangePromise;
759
+ }
760
+ }
761
+ onLoad();
762
+ batch(() => {
763
+ status$.numLoading.set((v) => v - 1);
764
+ status$.numWaitingCanSave.set((v) => v - 1);
765
+ });
766
+ }
767
+ private async _onChange<T>(
768
+ path: string[],
769
+ pathTypes: TypeAtPath[],
770
+ pathFirebase: string,
771
+ dateModifiedKey: string | undefined,
772
+ dateModifiedKeyOption: string | undefined,
773
+ params: ObservablePersistRemoteGetParams<T>,
774
+ localState: LocalState<T>,
775
+ saveState: SaveState,
776
+ status$: Observable<LoadStatus>,
777
+ snapshot: DataSnapshot,
778
+ ) {
779
+ const { numLoading, startedLoading } = status$.peek();
780
+
781
+ if (numLoading > 0) {
782
+ // If onceValue has not been called yet, then skip onChange because it will come later
783
+ if (!startedLoading) return;
784
+
785
+ // Wait for load
786
+ await when(() => status$.numLoading.get() < 1);
787
+ }
788
+
789
+ const {
790
+ onChange,
791
+ state,
792
+ options: { remote },
793
+ } = params;
794
+
795
+ const { changeTimeout } = remote!;
796
+
797
+ // Skip changes if disabled
798
+ if (state.isEnabledRemote.peek() === false) return;
799
+
800
+ const key = snapshot.key!;
801
+ const val = snapshot.val();
802
+
803
+ if (val) {
804
+ // eslint-disable-next-line prefer-const
805
+ let { value, dateModified } = this._convertFBTimestamps(val, dateModifiedKey!, dateModifiedKeyOption!);
806
+
807
+ const pathChild = path.concat(key);
808
+ const pathTypesChild = pathTypes.concat('object');
809
+ const constructed = constructObjectWithPath(pathChild, pathTypes, value);
810
+
811
+ if (
812
+ !this.addValuesToPendingSaves(
813
+ pathFirebase,
814
+ constructed,
815
+ pathChild,
816
+ pathTypesChild,
817
+ dateModified,
818
+ dateModifiedKey,
819
+ dateModifiedKeyOption,
820
+ saveState,
821
+ onChange,
822
+ )
823
+ ) {
824
+ localState.changes = setAtPath(localState.changes as object, pathChild, pathTypes, value);
825
+
826
+ // Debounce many child changes into a single onChange
827
+ clearTimeout(localState.timeout);
828
+ localState.timeout = setTimeout(() => {
829
+ const changes = localState.changes;
830
+ localState.changes = {};
831
+ onChange({ value: changes as T, path, pathTypes, mode: 'assign', dateModified });
832
+ }, changeTimeout || 300);
833
+ }
834
+ }
835
+ }
836
+ private insertDateToObject(value: any, dateModifiedKey: string) {
837
+ const timestamp = this.fns.serverTimestamp();
838
+ if (isObject(value)) {
839
+ return Object.assign(value, {
840
+ [dateModifiedKey]: timestamp,
841
+ });
842
+ } else {
843
+ return {
844
+ [dateModifiedKey]: timestamp,
845
+ _: value,
846
+ };
847
+ }
848
+ }
849
+ private insertDatesToSaveObject(
850
+ batch: Record<string, string | object>,
851
+ queryByModified: QueryByModified<any>,
852
+ dateModifiedKey: string,
853
+ path: string,
854
+ value: any,
855
+ ): object {
856
+ if (queryByModified === true) {
857
+ value = this.insertDateToObject(value, dateModifiedKey);
858
+ } else if (isObject(value)) {
859
+ Object.keys(value).forEach((key) => {
860
+ value[key] = this.insertDatesToSaveObject(
861
+ batch,
862
+ (queryByModified as any)[key],
863
+ dateModifiedKey,
864
+ path + '/' + key,
865
+ value[key],
866
+ );
867
+ });
868
+ }
869
+ return value;
870
+ }
871
+ private insertDatesToSave(
872
+ batch: Record<string, string | object>,
873
+ queryByModified: QueryByModified<any>,
874
+ dateModifiedKey: string,
875
+ basePath: string,
876
+ path: string[],
877
+ value: any,
878
+ ) {
879
+ let o = queryByModified;
880
+ for (let i = 0; i < path.length; i++) {
881
+ if (o === true) {
882
+ const pathThis = basePath + path.slice(0, i + 1).join('/');
883
+ if (i === path.length - 1) {
884
+ if (!isObject(value)) {
885
+ return this.insertDateToObject(value, dateModifiedKey);
886
+ } else {
887
+ if (isObject(value)) {
888
+ value[dateModifiedKey] = this.fns.serverTimestamp();
889
+ } else {
890
+ batch[pathThis + '/' + dateModifiedKey] = this.fns.serverTimestamp();
891
+ }
892
+ }
893
+ } else {
894
+ batch[pathThis + '/' + dateModifiedKey] = this.fns.serverTimestamp();
895
+ }
896
+ return value;
897
+ } else if (isObject(o)) {
898
+ o = (o as any)[path[i]];
899
+ }
900
+ }
901
+
902
+ if (o === true && isObject(value)) {
903
+ Object.keys(value).forEach((key) => {
904
+ this.insertDatesToSaveObject(
905
+ batch,
906
+ o,
907
+ dateModifiedKey,
908
+ basePath + path.join('/') + '/' + key,
909
+ value[key],
910
+ );
911
+ });
912
+ } else if (o !== undefined) {
913
+ this.insertDatesToSaveObject(batch, o, dateModifiedKey, basePath + path.join('/'), value);
914
+ }
915
+
916
+ return value;
917
+ }
918
+ private addValuesToPendingSaves(
919
+ refPath: string,
920
+ value: object,
921
+ pathChild: string[],
922
+ pathTypesChild: TypeAtPath[],
923
+ dateModified: number | undefined,
924
+ dateModifiedKey: string | undefined,
925
+ dateModifiedKeyOption: string | undefined,
926
+ saveState: SaveState,
927
+ onChange: ObservablePersistRemoteGetParams<any>['onChange'],
928
+ ) {
929
+ const { pendingSaveResults, savingSaves } = saveState;
930
+ let found = false;
931
+ const pathArr = refPath.split('/');
932
+ for (let i = pathArr.length - 1; !found && i >= 0; i--) {
933
+ const p = pathArr[i];
934
+ if (p === '') continue;
935
+
936
+ const path = pathArr.slice(0, i + 1).join('/') + '/';
937
+
938
+ // Look for this saved key in the currently saving saves.
939
+ // If it's being saved locally this must be the remote onChange
940
+ // coming in for this save.
941
+ if (pendingSaveResults.has(path) && savingSaves?.has(path)) {
942
+ found = true;
943
+ if (pathChild.length > 0) {
944
+ const savingSave = savingSaves.get(path)!;
945
+ const save = savingSave.saves[pathChild[0]];
946
+ if (!save) {
947
+ found = false;
948
+ }
949
+ }
950
+
951
+ if (found) {
952
+ const pending = pendingSaveResults.get(path)!;
953
+ pending.saved.push({
954
+ value,
955
+ dateModified,
956
+ path: pathChild,
957
+ pathTypes: pathTypesChild,
958
+ dateModifiedKey,
959
+ dateModifiedKeyOption,
960
+ onChange,
961
+ });
962
+ }
963
+ }
964
+ value = { [p]: value };
965
+ }
966
+ return found;
967
+ }
968
+ }
969
+
970
+ function estimateSize(value: any): number {
971
+ return ('' + value).length + 2; // Convert to string and account for quotes in JSON.
972
+ }
973
+
974
+ function splitLargeObject(obj: Record<string, any>, limit: number): Record<string, any>[] {
975
+ const parts: Record<string, any>[] = [{}];
976
+ let sizeCount = 0;
977
+
978
+ function recursiveSplit(innerObj: Record<string, any>, path: string[] = []) {
979
+ for (const key in innerObj) {
980
+ if (!hasOwnProperty.call(innerObj, key)) {
981
+ continue;
982
+ }
983
+
984
+ const newPath = [...path, key];
985
+ const keySize = key.length + 4; // Account for quotes and colon in JSON.
986
+ const val = innerObj[key];
987
+
988
+ let itemSize = 0;
989
+ if (val && typeof val === 'object') {
990
+ itemSize = JSON.stringify(val).length;
991
+ } else {
992
+ itemSize = estimateSize(val);
993
+ }
994
+
995
+ if (val && typeof val === 'object' && itemSize > limit) {
996
+ recursiveSplit(val, newPath);
997
+ } else {
998
+ // Check if the size of the current item exceeds the limit
999
+ if (sizeCount > 0 && sizeCount + keySize + itemSize > limit) {
1000
+ parts.push({});
1001
+ sizeCount = 0;
1002
+ }
1003
+
1004
+ const pathKey = newPath.join('/');
1005
+ parts[parts.length - 1][pathKey] = val;
1006
+ sizeCount += keySize + itemSize;
1007
+ }
1008
+ }
1009
+ }
1010
+
1011
+ recursiveSplit(obj);
1012
+ return parts;
1013
+ }
1014
+
1015
+ // This is the web version of all the firebase functions. It passes them in as arguments so that it could
1016
+ // support firebase on other platforms.
1017
+ export class ObservablePersistFirebase extends ObservablePersistFirebaseBase {
1018
+ constructor() {
1019
+ super({
1020
+ isInitialized: () => {
1021
+ try {
1022
+ return !!getAuth().app;
1023
+ } catch {
1024
+ return false;
1025
+ }
1026
+ },
1027
+ getCurrentUser: () => getAuth().currentUser?.uid,
1028
+ ref: (path: string) => ref(getDatabase(), path),
1029
+ orderByChild: (ref: DatabaseReference, child: string, start: number) =>
1030
+ query(ref, orderByChild(child), startAt(start)),
1031
+ update: (object: object) => update(ref(getDatabase()), object),
1032
+ once: (ref: DatabaseReference, callback, callbackError) => {
1033
+ let unsubscribe: Unsubscribe | undefined;
1034
+ const cb = (snap: DataSnapshot) => {
1035
+ if (unsubscribe) {
1036
+ unsubscribe();
1037
+ unsubscribe = undefined;
1038
+ }
1039
+ callback(snap);
1040
+ };
1041
+ unsubscribe = onValue(ref, cb, callbackError);
1042
+ return unsubscribe;
1043
+ },
1044
+ onChildAdded,
1045
+ onChildChanged,
1046
+ serverTimestamp,
1047
+ onAuthStateChanged: (cb) => getAuth().onAuthStateChanged(cb),
1048
+ });
1049
+ }
1050
+ }