@legendapp/state 2.2.0-next.8 → 2.2.0-next.80

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 (321) 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 +34 -32
  14. package/config/enableReactTracking.js.map +1 -1
  15. package/config/enableReactTracking.mjs +35 -33
  16. package/config/enableReactTracking.mjs.map +1 -1
  17. package/config/enableReactUse.d.ts +1 -1
  18. package/config/enableReactUse.js +9 -1
  19. package/config/enableReactUse.js.map +1 -1
  20. package/config/enableReactUse.mjs +9 -1
  21. package/config/enableReactUse.mjs.map +1 -1
  22. package/config/enable_peek.d.ts +8 -0
  23. package/config/{enableDirectPeek.js → enable_peek.js} +6 -3
  24. package/config/enable_peek.js.map +1 -0
  25. package/config/{enableDirectPeek.mjs → enable_peek.mjs} +5 -3
  26. package/config/enable_peek.mjs.map +1 -0
  27. package/helpers/fetch.d.ts +4 -3
  28. package/helpers/fetch.js.map +1 -1
  29. package/helpers/fetch.mjs.map +1 -1
  30. package/helpers/pageHash.js.map +1 -1
  31. package/helpers/pageHash.mjs.map +1 -1
  32. package/helpers/pageHashParams.js.map +1 -1
  33. package/helpers/pageHashParams.mjs.map +1 -1
  34. package/helpers/time.d.ts +2 -2
  35. package/helpers/time.js.map +1 -1
  36. package/helpers/time.mjs.map +1 -1
  37. package/history.js +2 -2
  38. package/history.js.map +1 -1
  39. package/history.mjs +3 -3
  40. package/history.mjs.map +1 -1
  41. package/index.d.ts +29 -9
  42. package/index.js +964 -671
  43. package/index.js.map +1 -1
  44. package/index.mjs +959 -668
  45. package/index.mjs.map +1 -1
  46. package/package.json +37 -25
  47. package/persist-plugins/async-storage.d.ts +4 -3
  48. package/persist-plugins/async-storage.js +8 -7
  49. package/persist-plugins/async-storage.js.map +1 -1
  50. package/persist-plugins/async-storage.mjs +9 -8
  51. package/persist-plugins/async-storage.mjs.map +1 -1
  52. package/persist-plugins/fetch.d.ts +1 -1
  53. package/persist-plugins/fetch.js.map +1 -1
  54. package/persist-plugins/fetch.mjs.map +1 -1
  55. package/persist-plugins/firebase.d.ts +2 -2
  56. package/persist-plugins/firebase.js +12 -11
  57. package/persist-plugins/firebase.js.map +1 -1
  58. package/persist-plugins/firebase.mjs +13 -12
  59. package/persist-plugins/firebase.mjs.map +1 -1
  60. package/persist-plugins/indexeddb.d.ts +11 -10
  61. package/persist-plugins/indexeddb.js +2 -2
  62. package/persist-plugins/indexeddb.js.map +1 -1
  63. package/persist-plugins/indexeddb.mjs +2 -2
  64. package/persist-plugins/indexeddb.mjs.map +1 -1
  65. package/persist-plugins/local-storage.d.ts +4 -4
  66. package/persist-plugins/local-storage.js +19 -7
  67. package/persist-plugins/local-storage.js.map +1 -1
  68. package/persist-plugins/local-storage.mjs +20 -9
  69. package/persist-plugins/local-storage.mjs.map +1 -1
  70. package/persist-plugins/mmkv.d.ts +9 -8
  71. package/persist-plugins/mmkv.js +5 -4
  72. package/persist-plugins/mmkv.js.map +1 -1
  73. package/persist-plugins/mmkv.mjs +6 -5
  74. package/persist-plugins/mmkv.mjs.map +1 -1
  75. package/persist-plugins/query.d.ts +1 -1
  76. package/persist-plugins/query.js.map +1 -1
  77. package/persist-plugins/query.mjs.map +1 -1
  78. package/persist.d.ts +2 -14
  79. package/persist.js +1270 -269
  80. package/persist.js.map +1 -1
  81. package/persist.mjs +1270 -270
  82. package/persist.mjs.map +1 -1
  83. package/react-hooks/createObservableHook.js +1 -1
  84. package/react-hooks/createObservableHook.js.map +1 -1
  85. package/react-hooks/createObservableHook.mjs +1 -1
  86. package/react-hooks/createObservableHook.mjs.map +1 -1
  87. package/react-hooks/useFetch.d.ts +4 -3
  88. package/react-hooks/useFetch.js.map +1 -1
  89. package/react-hooks/useFetch.mjs.map +1 -1
  90. package/react-hooks/useHover.js.map +1 -1
  91. package/react-hooks/useHover.mjs.map +1 -1
  92. package/react-hooks/useMeasure.js.map +1 -1
  93. package/react-hooks/useMeasure.mjs.map +1 -1
  94. package/react-hooks/useObservableNextRouter.js.map +1 -1
  95. package/react-hooks/useObservableNextRouter.mjs.map +1 -1
  96. package/react-hooks/useObservableQuery.js.map +1 -1
  97. package/react-hooks/useObservableQuery.mjs.map +1 -1
  98. package/react-hooks/usePersistedObservable.d.ts +6 -3
  99. package/react-hooks/usePersistedObservable.js +5 -2
  100. package/react-hooks/usePersistedObservable.js.map +1 -1
  101. package/react-hooks/usePersistedObservable.mjs +5 -2
  102. package/react-hooks/usePersistedObservable.mjs.map +1 -1
  103. package/react.js +73 -93
  104. package/react.js.map +1 -1
  105. package/react.mjs +73 -93
  106. package/react.mjs.map +1 -1
  107. package/src/ObservableObject.ts +1217 -0
  108. package/src/ObservablePrimitive.ts +62 -0
  109. package/src/babel/index.ts +70 -0
  110. package/src/batching.ts +378 -0
  111. package/src/computed.ts +18 -0
  112. package/src/config/enable$get.ts +30 -0
  113. package/src/config/enableReactComponents.ts +26 -0
  114. package/src/config/enableReactNativeComponents.ts +102 -0
  115. package/src/config/enableReactTracking.ts +62 -0
  116. package/src/config/enableReactUse.ts +32 -0
  117. package/src/config/enable_peek.ts +31 -0
  118. package/src/config.ts +47 -0
  119. package/src/createObservable.ts +46 -0
  120. package/src/event.ts +26 -0
  121. package/src/globals.ts +234 -0
  122. package/src/helpers/fetch.ts +26 -0
  123. package/src/helpers/pageHash.ts +41 -0
  124. package/src/helpers/pageHashParams.ts +55 -0
  125. package/src/helpers/time.ts +30 -0
  126. package/src/helpers.ts +224 -0
  127. package/src/history/trackHistory.ts +29 -0
  128. package/src/history/undoRedo.ts +111 -0
  129. package/src/is.ts +63 -0
  130. package/src/linked.ts +6 -0
  131. package/src/observable.ts +32 -0
  132. package/src/observableInterfaces.ts +148 -0
  133. package/src/observableTypes.ts +226 -0
  134. package/src/observe.ts +89 -0
  135. package/src/onChange.ts +136 -0
  136. package/src/persist/configureObservablePersistence.ts +7 -0
  137. package/src/persist/fieldTransformer.ts +149 -0
  138. package/src/persist/observablePersistRemoteFunctionsAdapter.ts +39 -0
  139. package/src/persist/persistObservable.ts +1031 -0
  140. package/src/persist-plugins/async-storage.ts +102 -0
  141. package/src/persist-plugins/fetch.ts +34 -0
  142. package/src/persist-plugins/firebase.ts +1052 -0
  143. package/src/persist-plugins/indexeddb.ts +432 -0
  144. package/src/persist-plugins/local-storage.ts +91 -0
  145. package/src/persist-plugins/mmkv.ts +91 -0
  146. package/src/persist-plugins/query.ts +129 -0
  147. package/src/proxy.ts +28 -0
  148. package/src/react/Computed.tsx +7 -0
  149. package/src/react/For.tsx +116 -0
  150. package/src/react/Memo.tsx +4 -0
  151. package/src/react/Reactive.tsx +53 -0
  152. package/src/react/Show.tsx +33 -0
  153. package/src/react/Switch.tsx +43 -0
  154. package/src/react/react-globals.ts +3 -0
  155. package/src/react/{reactInterfaces.d.ts → reactInterfaces.ts} +15 -7
  156. package/src/react/reactive-observer.tsx +210 -0
  157. package/src/react/useComputed.ts +36 -0
  158. package/src/react/useEffectOnce.ts +41 -0
  159. package/src/react/useIsMounted.ts +16 -0
  160. package/src/react/useMount.ts +15 -0
  161. package/src/react/useObservable.ts +24 -0
  162. package/src/react/useObservableReducer.ts +52 -0
  163. package/src/react/useObservableState.ts +30 -0
  164. package/src/react/useObserve.ts +54 -0
  165. package/src/react/useObserveEffect.ts +40 -0
  166. package/src/react/usePauseProvider.tsx +13 -0
  167. package/src/react/useSelector.ts +167 -0
  168. package/src/react/useUnmount.ts +8 -0
  169. package/src/react/useWhen.ts +9 -0
  170. package/src/react-hooks/createObservableHook.ts +53 -0
  171. package/src/react-hooks/useFetch.ts +16 -0
  172. package/src/react-hooks/useHover.ts +40 -0
  173. package/src/react-hooks/useMeasure.ts +48 -0
  174. package/src/react-hooks/useObservableNextRouter.ts +137 -0
  175. package/src/react-hooks/useObservableQuery.ts +205 -0
  176. package/src/react-hooks/usePersistedObservable.ts +25 -0
  177. package/src/retry.ts +71 -0
  178. package/src/setupTracking.ts +26 -0
  179. package/src/sync/activateSyncedNode.ts +128 -0
  180. package/src/sync/configureObservableSync.ts +7 -0
  181. package/src/sync/persistTypes.ts +226 -0
  182. package/src/sync/syncHelpers.ts +56 -0
  183. package/src/sync/syncObservable.ts +1040 -0
  184. package/src/sync/syncObservableAdapter.ts +31 -0
  185. package/src/sync/syncTypes.ts +188 -0
  186. package/src/sync/synced.ts +20 -0
  187. package/src/sync-plugins/crud.ts +404 -0
  188. package/src/sync-plugins/fetch.ts +72 -0
  189. package/src/sync-plugins/keel.ts +452 -0
  190. package/src/sync-plugins/supabase.ts +261 -0
  191. package/src/trace/traceHelpers.ts +11 -0
  192. package/src/trace/useTraceListeners.ts +34 -0
  193. package/src/trace/useTraceUpdates.ts +24 -0
  194. package/src/trace/useVerifyNotTracking.ts +33 -0
  195. package/src/trace/useVerifyOneRender.ts +10 -0
  196. package/src/trackSelector.ts +52 -0
  197. package/src/tracking.ts +43 -0
  198. package/src/types/babel.d.ts +12 -0
  199. package/src/when.ts +75 -0
  200. package/sync-plugins/crud.d.ts +41 -0
  201. package/sync-plugins/crud.js +290 -0
  202. package/sync-plugins/crud.js.map +1 -0
  203. package/sync-plugins/crud.mjs +286 -0
  204. package/sync-plugins/crud.mjs.map +1 -0
  205. package/sync-plugins/fetch.d.ts +13 -0
  206. package/sync-plugins/fetch.js +46 -0
  207. package/sync-plugins/fetch.js.map +1 -0
  208. package/sync-plugins/fetch.mjs +44 -0
  209. package/sync-plugins/fetch.mjs.map +1 -0
  210. package/sync-plugins/keel.d.ts +91 -0
  211. package/sync-plugins/keel.js +277 -0
  212. package/sync-plugins/keel.js.map +1 -0
  213. package/sync-plugins/keel.mjs +273 -0
  214. package/sync-plugins/keel.mjs.map +1 -0
  215. package/sync-plugins/supabase.d.ts +36 -0
  216. package/sync-plugins/supabase.js +152 -0
  217. package/sync-plugins/supabase.js.map +1 -0
  218. package/sync-plugins/supabase.mjs +149 -0
  219. package/sync-plugins/supabase.mjs.map +1 -0
  220. package/sync.d.ts +11 -0
  221. package/sync.js +976 -0
  222. package/sync.js.map +1 -0
  223. package/sync.mjs +966 -0
  224. package/sync.mjs.map +1 -0
  225. package/trace.js +13 -10
  226. package/trace.js.map +1 -1
  227. package/trace.mjs +11 -8
  228. package/trace.mjs.map +1 -1
  229. package/types/babel.d.ts +3 -3
  230. package/config/enableDirectAccess.d.ts +0 -7
  231. package/config/enableDirectAccess.js +0 -25
  232. package/config/enableDirectAccess.js.map +0 -1
  233. package/config/enableDirectAccess.mjs +0 -23
  234. package/config/enableDirectAccess.mjs.map +0 -1
  235. package/config/enableDirectPeek.d.ts +0 -7
  236. package/config/enableDirectPeek.js.map +0 -1
  237. package/config/enableDirectPeek.mjs.map +0 -1
  238. package/config/enableReactDirectRender.d.ts +0 -2
  239. package/config/enableReactDirectRender.js +0 -78
  240. package/config/enableReactDirectRender.js.map +0 -1
  241. package/config/enableReactDirectRender.mjs +0 -75
  242. package/config/enableReactDirectRender.mjs.map +0 -1
  243. package/src/ObservableObject.d.ts +0 -14
  244. package/src/ObservablePrimitive.d.ts +0 -7
  245. package/src/babel/index.d.ts +0 -17
  246. package/src/batching.d.ts +0 -6
  247. package/src/computed.d.ts +0 -4
  248. package/src/config/enableDirectAccess.d.ts +0 -7
  249. package/src/config/enableDirectPeek.d.ts +0 -7
  250. package/src/config/enableReactComponents.d.ts +0 -7
  251. package/src/config/enableReactDirectRender.d.ts +0 -2
  252. package/src/config/enableReactNativeComponents.d.ts +0 -20
  253. package/src/config/enableReactTracking.d.ts +0 -15
  254. package/src/config/enableReactUse.d.ts +0 -7
  255. package/src/config.d.ts +0 -8
  256. package/src/createObservable.d.ts +0 -2
  257. package/src/event.d.ts +0 -2
  258. package/src/globals.d.ts +0 -32
  259. package/src/helpers/fetch.d.ts +0 -6
  260. package/src/helpers/pageHash.d.ts +0 -7
  261. package/src/helpers/pageHashParams.d.ts +0 -7
  262. package/src/helpers/time.d.ts +0 -3
  263. package/src/helpers.d.ts +0 -13
  264. package/src/history/trackHistory.d.ts +0 -4
  265. package/src/is.d.ts +0 -10
  266. package/src/observable.d.ts +0 -16
  267. package/src/observableInterfaces.d.ts +0 -458
  268. package/src/observe.d.ts +0 -6
  269. package/src/onChange.d.ts +0 -7
  270. package/src/persist/configureObservablePersistence.d.ts +0 -3
  271. package/src/persist/fieldTransformer.d.ts +0 -8
  272. package/src/persist/observablePersistRemoteFunctionsAdapter.d.ts +0 -2
  273. package/src/persist/persistActivateNode.d.ts +0 -1
  274. package/src/persist/persistHelpers.d.ts +0 -1
  275. package/src/persist/persistObservable.d.ts +0 -25
  276. package/src/persist-plugins/async-storage.d.ts +0 -14
  277. package/src/persist-plugins/fetch.d.ts +0 -10
  278. package/src/persist-plugins/firebase.d.ts +0 -51
  279. package/src/persist-plugins/indexeddb.d.ts +0 -25
  280. package/src/persist-plugins/local-storage.d.ts +0 -21
  281. package/src/persist-plugins/mmkv.d.ts +0 -14
  282. package/src/persist-plugins/query.d.ts +0 -18
  283. package/src/proxy.d.ts +0 -5
  284. package/src/react/Computed.d.ts +0 -5
  285. package/src/react/For.d.ts +0 -15
  286. package/src/react/Memo.d.ts +0 -3
  287. package/src/react/Reactive.d.ts +0 -9
  288. package/src/react/Show.d.ts +0 -18
  289. package/src/react/Switch.d.ts +0 -14
  290. package/src/react/react-globals.d.ts +0 -3
  291. package/src/react/reactive-observer.d.ts +0 -14
  292. package/src/react/useComputed.d.ts +0 -5
  293. package/src/react/useEffectOnce.d.ts +0 -1
  294. package/src/react/useIsMounted.d.ts +0 -2
  295. package/src/react/useMount.d.ts +0 -2
  296. package/src/react/useObservable.d.ts +0 -9
  297. package/src/react/useObservableReducer.d.ts +0 -7
  298. package/src/react/useObservableState.d.ts +0 -2
  299. package/src/react/useObserve.d.ts +0 -4
  300. package/src/react/useObserveEffect.d.ts +0 -4
  301. package/src/react/usePauseProvider.d.ts +0 -8
  302. package/src/react/useSelector.d.ts +0 -3
  303. package/src/react/useUnmount.d.ts +0 -2
  304. package/src/react/useWhen.d.ts +0 -3
  305. package/src/react-hooks/createObservableHook.d.ts +0 -2
  306. package/src/react-hooks/useFetch.d.ts +0 -6
  307. package/src/react-hooks/useHover.d.ts +0 -3
  308. package/src/react-hooks/useMeasure.d.ts +0 -6
  309. package/src/react-hooks/useObservableNextRouter.d.ts +0 -33
  310. package/src/react-hooks/useObservableQuery.d.ts +0 -6
  311. package/src/react-hooks/usePersistedObservable.d.ts +0 -11
  312. package/src/retry.d.ts +0 -9
  313. package/src/setupTracking.d.ts +0 -2
  314. package/src/trace/traceHelpers.d.ts +0 -2
  315. package/src/trace/useTraceListeners.d.ts +0 -1
  316. package/src/trace/useTraceUpdates.d.ts +0 -1
  317. package/src/trace/useVerifyNotTracking.d.ts +0 -1
  318. package/src/trace/useVerifyOneRender.d.ts +0 -1
  319. package/src/trackSelector.d.ts +0 -7
  320. package/src/tracking.d.ts +0 -13
  321. package/src/when.d.ts +0 -3
@@ -0,0 +1,1040 @@
1
+ import type {
2
+ Change,
3
+ ClassConstructor,
4
+ ListenerParams,
5
+ NodeValue,
6
+ Observable,
7
+ ObservableObject,
8
+ ObservableParam,
9
+ TypeAtPath,
10
+ UpdateFnParams,
11
+ } from '@legendapp/state';
12
+ import {
13
+ beginBatch,
14
+ constructObjectWithPath,
15
+ deconstructObjectWithPath,
16
+ endBatch,
17
+ internal,
18
+ isArray,
19
+ isEmpty,
20
+ isFunction,
21
+ isObject,
22
+ isPromise,
23
+ isString,
24
+ mergeIntoObservable,
25
+ observable,
26
+ setAtPath,
27
+ when,
28
+ } from '@legendapp/state';
29
+ import { observableSyncConfiguration } from './configureObservableSync';
30
+ import type { ObservableOnChangeParams } from './persistTypes';
31
+ import { removeNullUndefined } from './syncHelpers';
32
+ import { syncObservableAdapter } from './syncObservableAdapter';
33
+ import type {
34
+ ObservablePersistPlugin,
35
+ ObservableSyncClass,
36
+ ObservableSyncState,
37
+ PersistMetadata,
38
+ PersistOptions,
39
+ SyncTransform,
40
+ SyncTransformMethod,
41
+ Synced,
42
+ SyncedOptions,
43
+ } from './syncTypes';
44
+
45
+ const { createPreviousHandler, clone, getValueAtPath, globalState, symbolLinked, getNode, getNodeValue } = internal;
46
+
47
+ export const mapSyncPlugins: WeakMap<
48
+ ClassConstructor<ObservablePersistPlugin | ObservableSyncClass>,
49
+ {
50
+ plugin: ObservablePersistPlugin | ObservableSyncClass;
51
+ initialized: Observable<boolean>;
52
+ }
53
+ > = new WeakMap();
54
+
55
+ const metadatas = new WeakMap<ObservableParam<any>, PersistMetadata>();
56
+ const promisesLocalSaves = new Set<Promise<void>>();
57
+
58
+ interface LocalState {
59
+ pluginPersist?: ObservablePersistPlugin;
60
+ pluginSync?: ObservableSyncClass;
61
+ pendingChanges?: Record<string, { p: any; v?: any; t: TypeAtPath[] }>;
62
+ numSavesOutstanding?: number;
63
+ pendingSaveResults?: object[];
64
+ isApplyingPending?: boolean;
65
+ timeoutSaveMetadata?: any;
66
+ }
67
+
68
+ interface PreppedChangeLocal {
69
+ queuedChange: QueuedChange;
70
+ changesLocal: ChangeWithPathStr[];
71
+ saveRemote: boolean;
72
+ }
73
+
74
+ interface PreppedChangeRemote {
75
+ queuedChange: QueuedChange;
76
+ changesRemote: ChangeWithPathStr[];
77
+ }
78
+
79
+ type ChangeWithPathStr = Change & { pathStr: string };
80
+ type ChangeWithPathStrAndPrevious = ChangeWithPathStr & { valuePrevious: any };
81
+
82
+ function parseLocalConfig(config: string | PersistOptions | undefined): {
83
+ table: string;
84
+ config: PersistOptions;
85
+ } {
86
+ return config
87
+ ? isString(config)
88
+ ? { table: config, config: { name: config } }
89
+ : { table: config.name, config }
90
+ : ({} as { table: string; config: PersistOptions });
91
+ }
92
+
93
+ function doInOrder<T>(arg1: T | Promise<T>, arg2: (value: T) => void): any {
94
+ return isPromise(arg1) ? arg1.then(arg2) : arg2(arg1);
95
+ }
96
+
97
+ export function onChangeRemote(cb: () => void) {
98
+ endBatch(true);
99
+ // Remote changes should only update local state
100
+ globalState.isLoadingRemote = true;
101
+
102
+ beginBatch();
103
+ cb();
104
+ // Reset isLoadingRemote before ending the batch so it doesn't
105
+ // apply to any side effects
106
+ globalState.isLoadingRemote = false;
107
+ endBatch(true);
108
+ }
109
+
110
+ export function transformSaveData(
111
+ value: any,
112
+ path: string[],
113
+ pathTypes: TypeAtPath[],
114
+ { transform }: { transform?: SyncTransform },
115
+ ): Promise<any> | any {
116
+ if (transform?.save) {
117
+ const constructed = constructObjectWithPath(path, pathTypes, value);
118
+ const saved = transform.save(constructed);
119
+ value = deconstructObjectWithPath(path, pathTypes, saved);
120
+ }
121
+
122
+ return value;
123
+ }
124
+
125
+ export function transformLoadData(
126
+ value: any,
127
+ { transform }: { transform?: SyncTransform },
128
+ doUserTransform: boolean,
129
+ method: SyncTransformMethod,
130
+ ): Promise<any> | any {
131
+ if (doUserTransform && transform?.load) {
132
+ value = transform.load(value, method);
133
+ }
134
+
135
+ return value;
136
+ }
137
+
138
+ async function updateMetadataImmediate<T>(
139
+ obs: ObservableParam<any>,
140
+ localState: LocalState,
141
+ syncState: Observable<ObservableSyncState>,
142
+ syncOptions: SyncedOptions<T>,
143
+ newMetadata: PersistMetadata,
144
+ ) {
145
+ const saves = Array.from(promisesLocalSaves);
146
+ if (saves.length > 0) {
147
+ await Promise.all(saves);
148
+ }
149
+
150
+ const { pluginPersist } = localState;
151
+ const { table, config } = parseLocalConfig(syncOptions?.persist);
152
+
153
+ // Save metadata
154
+ const oldMetadata: PersistMetadata | undefined = metadatas.get(obs);
155
+
156
+ const { lastSync, pending } = newMetadata;
157
+
158
+ const needsUpdate = pending || (lastSync && (!oldMetadata || lastSync !== oldMetadata.lastSync));
159
+
160
+ if (needsUpdate) {
161
+ const metadata = Object.assign({}, oldMetadata, newMetadata);
162
+ metadatas.set(obs, metadata);
163
+ if (pluginPersist) {
164
+ await pluginPersist!.setMetadata(table, metadata, config);
165
+ }
166
+
167
+ if (lastSync) {
168
+ syncState.assign({
169
+ lastSync: lastSync,
170
+ });
171
+ }
172
+ }
173
+ }
174
+
175
+ function updateMetadata<T>(
176
+ obs: ObservableParam<any>,
177
+ localState: LocalState,
178
+ syncState: ObservableObject<ObservableSyncState>,
179
+ syncOptions: SyncedOptions<T>,
180
+ newMetadata: PersistMetadata,
181
+ ) {
182
+ if (localState.timeoutSaveMetadata) {
183
+ clearTimeout(localState.timeoutSaveMetadata);
184
+ }
185
+ localState.timeoutSaveMetadata = setTimeout(
186
+ () => updateMetadataImmediate(obs, localState, syncState, syncOptions as SyncedOptions<T>, newMetadata),
187
+ 0,
188
+ );
189
+ }
190
+
191
+ interface QueuedChange<T = any> {
192
+ inRemoteChange: boolean;
193
+ isApplyingPending: boolean;
194
+ obs: Observable<T>;
195
+ syncState: ObservableObject<ObservableSyncState>;
196
+ localState: LocalState;
197
+ syncOptions: SyncedOptions<T>;
198
+ changes: ListenerParams['changes'];
199
+ valuePrevious?: T;
200
+ getPrevious: () => T;
201
+ }
202
+
203
+ let _queuedChanges: QueuedChange[] = [];
204
+ const _queuedRemoteChanges: Map<SyncedOptions, QueuedChange[]> = new Map();
205
+ const _queuedRemoteChangesTimeouts: Map<SyncedOptions, number> = new Map();
206
+
207
+ function mergeChanges(changes: Change[]) {
208
+ const changesByPath = new Map<string, Change>();
209
+ const changesOut: Change[] = [];
210
+ // TODO: This could be even more robust by going deeper into paths like the firebase plugin's _updatePendingSave
211
+ for (let i = 0; i < changes.length; i++) {
212
+ const change = changes[i];
213
+ const pathStr = change.path.join('/');
214
+ const existing = changesByPath.get(pathStr);
215
+ if (existing) {
216
+ // If setting a value back to what it was, no need to save it
217
+ if (change.valueAtPath === existing.prevAtPath) {
218
+ changesOut.splice(changesOut.indexOf(change), 1);
219
+ } else {
220
+ existing.valueAtPath = change.valueAtPath;
221
+ }
222
+ } else {
223
+ changesByPath.set(pathStr, change);
224
+ changesOut.push(change);
225
+ }
226
+ }
227
+ return changesOut;
228
+ }
229
+
230
+ function mergeQueuedChanges(allChanges: QueuedChange[]) {
231
+ const changesByObsRemote = new Map<Observable, Change[]>();
232
+ const changesByObsLocal = new Map<Observable, Change[]>();
233
+ const previousByObs = new Map<Observable, any>();
234
+ const outRemote: Map<Observable, QueuedChange> = new Map();
235
+ const outLocal: Map<Observable, QueuedChange> = new Map();
236
+
237
+ for (let i = 0; i < allChanges.length; i++) {
238
+ const value = allChanges[i];
239
+ const { obs, changes, inRemoteChange, getPrevious } = value;
240
+ const targetMap = inRemoteChange ? outRemote : outLocal;
241
+ const changesMap = inRemoteChange ? changesByObsRemote : changesByObsLocal;
242
+ const existing = changesMap.get(obs);
243
+ const newChanges = existing ? [...existing, ...changes] : changes;
244
+ const merged = mergeChanges(newChanges);
245
+ changesMap.set(obs, merged);
246
+ value.changes = merged;
247
+ if (!previousByObs.has(obs)) {
248
+ previousByObs.set(obs, getPrevious());
249
+ }
250
+ value.valuePrevious = previousByObs.get(obs);
251
+ targetMap.set(obs, value);
252
+ }
253
+ return Array.from(outRemote.values()).concat(Array.from(outLocal.values()));
254
+ }
255
+
256
+ async function processQueuedChanges() {
257
+ // Get a local copy of the queued changes and clear the global queue
258
+ const queuedChanges = mergeQueuedChanges(_queuedChanges);
259
+ _queuedChanges = [];
260
+
261
+ const pendingSyncOptions = new Set<SyncedOptions>();
262
+ for (let i = 0; i < queuedChanges.length; i++) {
263
+ const change = queuedChanges[i];
264
+ if (!change.inRemoteChange) {
265
+ if (!_queuedRemoteChanges.has(change.syncOptions)) {
266
+ _queuedRemoteChanges.set(change.syncOptions, []);
267
+ }
268
+ pendingSyncOptions.add(change.syncOptions);
269
+ _queuedRemoteChanges.get(change.syncOptions)!.push(change);
270
+ }
271
+ }
272
+
273
+ // Note: Summary of the order of operations these functions:
274
+ // 1. Prepare all changes for saving. This may involve waiting for promises if the user has asynchronous transform.
275
+ // We need to prepare all of the changes in the queue before saving so that the saves happen in the correct order,
276
+ // since some may take longer to transformSaveData than others.
277
+ // 2. Save pending to the metadata table first. If this is the only operation that succeeds, it would try to save
278
+ // the current value again on next load, which isn't too bad.
279
+ // 3. Save local changes to storage. If they never make it to remote, then on the next load they will be pending
280
+ // and attempted again.
281
+ // 4. Wait for remote load or error if allowed
282
+ // 5. Save to remote
283
+ // 6. On successful save, merge changes (if any) back into observable
284
+ // 7. Lastly, update metadata to clear pending and update lastSync. Doing this earlier could potentially cause
285
+ // sync inconsistences so it's very important that this is last.
286
+
287
+ const preppedChangesLocal = await Promise.all(queuedChanges.map(prepChangeLocal));
288
+
289
+ // TODO Clean this up: We only need to prep this now in order to save pending changes, don't need any of the other stuff. Should split that up?
290
+ await Promise.all(queuedChanges.map(prepChangeRemote));
291
+
292
+ await Promise.all(preppedChangesLocal.map(doChangeLocal));
293
+
294
+ for (const options of pendingSyncOptions) {
295
+ const timeout = options.debounceSet ?? observableSyncConfiguration?.debounceSet;
296
+ const timeoutSaveRemote = _queuedRemoteChangesTimeouts.get(options);
297
+ const run = () => processQueuedRemoteChanges(options);
298
+ if (timeout) {
299
+ if (timeoutSaveRemote) {
300
+ clearTimeout(timeoutSaveRemote);
301
+ }
302
+
303
+ _queuedRemoteChangesTimeouts.set(options, setTimeout(run, timeout) as any);
304
+ } else {
305
+ run();
306
+ }
307
+ }
308
+ }
309
+
310
+ async function processQueuedRemoteChanges(syncOptions: SyncedOptions) {
311
+ const arr = _queuedRemoteChanges.get(syncOptions);
312
+ if (arr?.length) {
313
+ const queuedRemoteChanges = mergeQueuedChanges(arr);
314
+ _queuedRemoteChanges.set(syncOptions, []);
315
+
316
+ const preppedChangesRemote = await Promise.all(queuedRemoteChanges.map(prepChangeRemote));
317
+
318
+ preppedChangesRemote.forEach(doChangeRemote);
319
+ }
320
+ }
321
+
322
+ async function prepChangeLocal(queuedChange: QueuedChange): Promise<PreppedChangeLocal | undefined> {
323
+ const { syncState, changes, localState, syncOptions, inRemoteChange, isApplyingPending } = queuedChange;
324
+
325
+ const persist = syncOptions.persist;
326
+ const { pluginSync } = localState;
327
+ const { config: configLocal } = parseLocalConfig(persist);
328
+ const configRemote = syncOptions;
329
+ const saveLocal = persist?.name && !configLocal.readonly && !isApplyingPending && syncState.isPersistEnabled.peek();
330
+ const saveRemote = !!(
331
+ !inRemoteChange &&
332
+ pluginSync?.set &&
333
+ configRemote?.enableSync !== false &&
334
+ syncState.isSyncEnabled.peek()
335
+ );
336
+
337
+ if (saveLocal || saveRemote) {
338
+ if (saveLocal && !syncState.isPersistLoaded.peek()) {
339
+ console.error(
340
+ '[legend-state] WARNING: An observable was changed before being loaded from persist',
341
+ persist,
342
+ );
343
+ return undefined;
344
+ }
345
+ const changesLocal: ChangeWithPathStr[] = [];
346
+ const changesPaths = new Set<string>();
347
+ let promisesTransform: (void | Promise<any>)[] = [];
348
+
349
+ // Reverse order
350
+ for (let i = changes.length - 1; i >= 0; i--) {
351
+ const { path } = changes[i];
352
+
353
+ let found = false;
354
+
355
+ // Optimization to only save the latest update at each path. We might have multiple changes at the same path
356
+ // and we only need the latest value, so it starts from the end of the array, skipping any earlier changes
357
+ // already processed. If a later change modifies a parent of an earlier change (which happens on delete()
358
+ // it should be ignored as it's superseded by the parent modification.
359
+ if (changesPaths.size > 0) {
360
+ for (let u = 0; u < path.length; u++) {
361
+ if (changesPaths.has((u === path.length - 1 ? path : path.slice(0, u + 1)).join('/'))) {
362
+ found = true;
363
+ break;
364
+ }
365
+ }
366
+ }
367
+
368
+ if (!found) {
369
+ const pathStr = path.join('/');
370
+ changesPaths.add(pathStr);
371
+
372
+ const { prevAtPath, valueAtPath, pathTypes } = changes[i];
373
+ if (saveLocal) {
374
+ const promiseTransformLocal = transformSaveData(
375
+ valueAtPath,
376
+ path as string[],
377
+ pathTypes,
378
+ configLocal,
379
+ );
380
+
381
+ promisesTransform.push(
382
+ doInOrder(promiseTransformLocal, (valueTransformed) => {
383
+ // Prepare the local change with the transformed path/value
384
+ changesLocal.push({
385
+ path,
386
+ pathTypes,
387
+ prevAtPath,
388
+ valueAtPath: valueTransformed,
389
+ pathStr,
390
+ });
391
+ }),
392
+ );
393
+ }
394
+ }
395
+ }
396
+
397
+ // If there's any transform promises, wait for them before saving
398
+ promisesTransform = promisesTransform.filter(Boolean);
399
+ if (promisesTransform.length > 0) {
400
+ await Promise.all(promisesTransform);
401
+ }
402
+
403
+ return { queuedChange, changesLocal, saveRemote };
404
+ }
405
+ }
406
+ async function prepChangeRemote(queuedChange: QueuedChange): Promise<PreppedChangeRemote | undefined> {
407
+ const {
408
+ syncState,
409
+ changes,
410
+ localState,
411
+ syncOptions: syncOptions,
412
+ inRemoteChange,
413
+ isApplyingPending,
414
+ valuePrevious,
415
+ } = queuedChange;
416
+
417
+ const persist = syncOptions.persist;
418
+ const { pluginSync } = localState;
419
+ const { config: configLocal } = parseLocalConfig(persist!);
420
+ const configRemote = syncOptions;
421
+ const saveLocal = persist && !configLocal.readonly && !isApplyingPending && syncState.isPersistEnabled.peek();
422
+ const saveRemote =
423
+ !inRemoteChange && pluginSync?.set && configRemote?.enableSync !== false && syncState.isSyncEnabled.peek();
424
+
425
+ if (saveLocal || saveRemote) {
426
+ if (saveLocal && !syncState.isPersistLoaded.peek()) {
427
+ console.error(
428
+ '[legend-state] WARNING: An observable was changed before being loaded from persist',
429
+ persist,
430
+ );
431
+ return undefined;
432
+ }
433
+ const changesRemote: ChangeWithPathStrAndPrevious[] = [];
434
+ const changesPaths = new Set<string>();
435
+ let promisesTransform: (void | Promise<any>)[] = [];
436
+
437
+ // Reverse order
438
+ for (let i = changes.length - 1; i >= 0; i--) {
439
+ const { path } = changes[i];
440
+
441
+ let found = false;
442
+
443
+ // Optimization to only save the latest update at each path. We might have multiple changes at the same path
444
+ // and we only need the latest value, so it starts from the end of the array, skipping any earlier changes
445
+ // already processed. If a later change modifies a parent of an earlier change (which happens on delete()
446
+ // it should be ignored as it's superseded by the parent modification.
447
+ if (changesPaths.size > 0) {
448
+ for (let u = 0; u < path.length; u++) {
449
+ if (changesPaths.has((u === path.length - 1 ? path : path.slice(0, u + 1)).join('/'))) {
450
+ found = true;
451
+ break;
452
+ }
453
+ }
454
+ }
455
+
456
+ if (!found) {
457
+ const pathStr = path.join('/');
458
+ changesPaths.add(pathStr);
459
+
460
+ const { prevAtPath, valueAtPath, pathTypes } = changes[i];
461
+
462
+ if (saveRemote) {
463
+ const promiseTransformRemote = transformSaveData(
464
+ valueAtPath,
465
+ path as string[],
466
+ pathTypes,
467
+ configRemote || {},
468
+ );
469
+
470
+ promisesTransform.push(
471
+ doInOrder(promiseTransformRemote, (valueTransformed) => {
472
+ // Prepare pending changes
473
+ if (!localState.pendingChanges) {
474
+ localState.pendingChanges = {};
475
+ }
476
+
477
+ // First look for existing pending changes at a higher level than this change
478
+ // If they exist then merge this change into it
479
+ let found = false;
480
+ for (let i = 0; !found && i < path.length - 1; i++) {
481
+ const pathParent = path.slice(0, i + 1).join('/');
482
+ if (localState.pendingChanges[pathParent]?.v) {
483
+ found = true;
484
+ const pathChild = path.slice(i + 1);
485
+ const pathTypesChild = pathTypes.slice(i + 1);
486
+ setAtPath(
487
+ localState.pendingChanges[pathParent].v,
488
+ pathChild,
489
+ pathTypesChild,
490
+ valueAtPath,
491
+ );
492
+ }
493
+ }
494
+ if (!found) {
495
+ // If an existing pending change is deeper than this change, just delete it
496
+ // in favor of this wider change
497
+ for (const key in localState.pendingChanges) {
498
+ if (key !== pathStr && key.startsWith(pathStr)) {
499
+ delete localState.pendingChanges[key];
500
+ }
501
+ }
502
+ // The "p" saved in pending should be the previous state before changes,
503
+ // so don't overwrite it if it already exists
504
+ if (!localState.pendingChanges[pathStr]) {
505
+ localState.pendingChanges[pathStr] = { p: prevAtPath ?? null, t: pathTypes };
506
+ }
507
+
508
+ // Pending value is the untransformed value because it gets loaded without transformment
509
+ // and forwarded through to onObsChange where it gets transformed before save
510
+ localState.pendingChanges[pathStr].v = valueAtPath;
511
+ }
512
+
513
+ // Prepare the remote change with the transformed path/value
514
+ changesRemote.push({
515
+ path,
516
+ pathTypes,
517
+ prevAtPath,
518
+ valueAtPath: valueTransformed,
519
+ pathStr,
520
+ valuePrevious,
521
+ });
522
+ }),
523
+ );
524
+ }
525
+ }
526
+ }
527
+
528
+ // If there's any transform promises, wait for them before saving
529
+ promisesTransform = promisesTransform.filter(Boolean);
530
+ if (promisesTransform.length > 0) {
531
+ await Promise.all(promisesTransform);
532
+ }
533
+
534
+ return { queuedChange, changesRemote };
535
+ }
536
+ }
537
+
538
+ async function doChangeLocal(changeInfo: PreppedChangeLocal | undefined) {
539
+ if (!changeInfo) return;
540
+
541
+ const { queuedChange, changesLocal, saveRemote } = changeInfo;
542
+ const { obs, syncState, localState, syncOptions: syncOptions } = queuedChange;
543
+ const { pluginPersist } = localState;
544
+
545
+ const persist = syncOptions.persist;
546
+ const { table, config: configLocal } = parseLocalConfig(persist!);
547
+ const shouldSaveMetadata = persist?.retrySync;
548
+
549
+ if (saveRemote && shouldSaveMetadata) {
550
+ // First save pending changes before saving local or remote
551
+ await updateMetadataImmediate(obs, localState, syncState, syncOptions, {
552
+ pending: localState.pendingChanges,
553
+ });
554
+ }
555
+
556
+ if (changesLocal.length > 0) {
557
+ // Save the changes to local cache before saving to remote. They are already marked as pending so
558
+ // if remote sync fails or the app is closed before remote sync, it will attempt to sync them on the next load.
559
+ let promiseSet = pluginPersist!.set(table, changesLocal, configLocal);
560
+
561
+ if (promiseSet) {
562
+ promiseSet = promiseSet.then(() => {
563
+ promisesLocalSaves.delete(promiseSet as Promise<any>);
564
+ });
565
+ // Keep track of local save promises so that updateMetadata runs only after everything is saved
566
+ promisesLocalSaves.add(promiseSet);
567
+
568
+ // await the local save before proceeding to save remotely
569
+ await promiseSet;
570
+ }
571
+ }
572
+ }
573
+ async function doChangeRemote(changeInfo: PreppedChangeRemote | undefined) {
574
+ if (!changeInfo) return;
575
+
576
+ const { queuedChange, changesRemote } = changeInfo;
577
+ const { obs, syncState, localState, syncOptions, valuePrevious: previous } = queuedChange;
578
+ const { pluginPersist, pluginSync } = localState;
579
+
580
+ const persist = syncOptions.persist;
581
+ const { table, config: configLocal } = parseLocalConfig(persist!);
582
+ const { allowSetIfGetError, onBeforeSet, onSetError, waitForSet, onAfterSet } =
583
+ syncOptions || ({} as SyncedOptions);
584
+ const shouldSaveMetadata = persist?.retrySync;
585
+
586
+ if (changesRemote.length > 0) {
587
+ // Wait for remote to be ready before saving
588
+ await when(() => syncState.isLoaded.get() || (allowSetIfGetError && syncState.error.get()));
589
+
590
+ if (waitForSet) {
591
+ const waitFor = isFunction(waitForSet)
592
+ ? waitForSet({ changes: changesRemote, value: obs.peek() })
593
+ : waitForSet;
594
+ if (waitFor) {
595
+ await when(waitFor);
596
+ }
597
+ }
598
+
599
+ let value = obs.peek();
600
+ const transformSave = syncOptions?.transform?.save;
601
+ if (transformSave) {
602
+ value = transformSave(value);
603
+ }
604
+
605
+ onBeforeSet?.();
606
+
607
+ localState.numSavesOutstanding = (localState.numSavesOutstanding || 0) + 1;
608
+
609
+ let savedPromise = pluginSync!.set!({
610
+ obs,
611
+ syncState: syncState,
612
+ options: syncOptions,
613
+ changes: changesRemote,
614
+ value,
615
+ valuePrevious: previous,
616
+ });
617
+ if (isPromise(savedPromise)) {
618
+ savedPromise = savedPromise.catch((err) => onSetError?.(err));
619
+ }
620
+
621
+ const saved = await savedPromise;
622
+
623
+ localState.numSavesOutstanding--;
624
+
625
+ // If this remote save changed anything then update cache and metadata
626
+ // Because save happens after a timeout and they're batched together, some calls to save will
627
+ // return saved data and others won't, so those can be ignored.
628
+ if (saved) {
629
+ const pathStrs = Array.from(new Set(changesRemote.map((change) => change.pathStr)));
630
+ const { changes, lastSync } = saved;
631
+ if (pathStrs.length > 0) {
632
+ let transformedChanges: object | undefined = undefined;
633
+ const metadata: PersistMetadata = {};
634
+ if (persist) {
635
+ const pendingMetadata = pluginPersist!.getMetadata(table, configLocal)?.pending;
636
+ const pending = localState.pendingChanges;
637
+
638
+ for (let i = 0; i < pathStrs.length; i++) {
639
+ const pathStr = pathStrs[i];
640
+ // Clear pending for this path
641
+ if (pendingMetadata?.[pathStr]) {
642
+ // Remove pending from persisted medata state
643
+ delete pendingMetadata[pathStr];
644
+ metadata.pending = pendingMetadata;
645
+ }
646
+ // Clear pending for this path if not already removed by above
647
+ // pendingMetadata === pending sometimes
648
+ if (pending?.[pathStr]) {
649
+ // Remove pending from local state
650
+ delete pending[pathStr];
651
+ }
652
+ }
653
+
654
+ if (lastSync) {
655
+ metadata.lastSync = lastSync;
656
+ }
657
+ }
658
+
659
+ // Remote can optionally have data that needs to be merged back into the observable,
660
+ // for example Firebase may update dateModified with the server timestamp
661
+ if (changes && !isEmpty(changes)) {
662
+ transformedChanges = transformLoadData(changes, syncOptions, false, 'set');
663
+ }
664
+
665
+ if (localState.numSavesOutstanding > 0) {
666
+ if (transformedChanges) {
667
+ if (!localState.pendingSaveResults) {
668
+ localState.pendingSaveResults = [];
669
+ }
670
+ localState.pendingSaveResults.push(transformedChanges);
671
+ }
672
+ } else {
673
+ let allChanges = [...(localState.pendingSaveResults || []), transformedChanges].filter(
674
+ (v) => v !== undefined,
675
+ );
676
+ if (allChanges.length > 0) {
677
+ if (allChanges.some((change) => isPromise(change))) {
678
+ allChanges = await Promise.all(allChanges);
679
+ }
680
+ onChangeRemote(() => mergeIntoObservable(obs, ...allChanges));
681
+ }
682
+
683
+ if (persist) {
684
+ if (shouldSaveMetadata && !isEmpty(metadata)) {
685
+ updateMetadata(obs, localState, syncState, syncOptions, metadata);
686
+ }
687
+ }
688
+
689
+ localState.pendingSaveResults = [];
690
+ }
691
+ onAfterSet?.();
692
+ }
693
+ }
694
+ }
695
+ }
696
+
697
+ function onObsChange<T>(
698
+ obs: ObservableParam<T>,
699
+ syncState: ObservableObject<ObservableSyncState>,
700
+ localState: LocalState,
701
+ syncOptions: SyncedOptions<T>,
702
+ { changes, loading, remote, getPrevious }: ListenerParams,
703
+ ) {
704
+ if (!loading) {
705
+ const inRemoteChange = remote;
706
+ const isApplyingPending = localState.isApplyingPending;
707
+ // Queue changes in a microtask so that multiple changes within a frame get run together
708
+ _queuedChanges.push({
709
+ obs: obs as Observable<any>,
710
+ syncState,
711
+ localState,
712
+ syncOptions,
713
+ changes,
714
+ inRemoteChange,
715
+ isApplyingPending: isApplyingPending!,
716
+ getPrevious,
717
+ });
718
+ if (_queuedChanges.length === 1) {
719
+ queueMicrotask(processQueuedChanges);
720
+ }
721
+ }
722
+ }
723
+
724
+ async function loadLocal<T>(
725
+ obs: ObservableParam<T>,
726
+ syncOptions: SyncedOptions<any>,
727
+ syncState: ObservableObject<ObservableSyncState>,
728
+ localState: LocalState,
729
+ ) {
730
+ const { persist } = syncOptions;
731
+
732
+ if (persist) {
733
+ const PersistPlugin: ClassConstructor<ObservablePersistPlugin> =
734
+ persist.plugin! || observableSyncConfiguration.persist?.plugin;
735
+ const { table, config } = parseLocalConfig(persist);
736
+ const node = getNode(obs);
737
+
738
+ if (!PersistPlugin) {
739
+ throw new Error('Local persist is not configured');
740
+ }
741
+ // Ensure there's only one instance of the cache plugin
742
+ if (!mapSyncPlugins.has(PersistPlugin)) {
743
+ const persistPlugin = new PersistPlugin();
744
+ const mapValue = { plugin: persistPlugin, initialized: observable(false) };
745
+ mapSyncPlugins.set(PersistPlugin, mapValue);
746
+ if (persistPlugin.initialize) {
747
+ const initializePromise = persistPlugin.initialize?.(observableSyncConfiguration?.persist || {});
748
+ if (isPromise(initializePromise)) {
749
+ await initializePromise;
750
+ }
751
+ }
752
+ mapValue.initialized.set(true);
753
+ }
754
+
755
+ const { plugin, initialized: initialized$ } = mapSyncPlugins.get(PersistPlugin)!;
756
+ const persistPlugin = plugin as ObservablePersistPlugin;
757
+
758
+ localState.pluginPersist = persistPlugin as ObservablePersistPlugin;
759
+
760
+ if (!initialized$.peek()) {
761
+ await when(initialized$);
762
+ }
763
+
764
+ // If cache has an asynchronous load, wait for it
765
+ if (persistPlugin.loadTable) {
766
+ const promise = persistPlugin.loadTable(table, config);
767
+ if (promise) {
768
+ await promise;
769
+ }
770
+ }
771
+
772
+ // Get current value for init
773
+ const prevValue = getNodeValue(node) as object;
774
+
775
+ // Get the value from state
776
+ let value = persistPlugin.getTable(table, prevValue, config);
777
+ const metadata = persistPlugin.getMetadata(table, config);
778
+
779
+ if (metadata) {
780
+ metadatas.set(obs, metadata);
781
+ localState.pendingChanges = metadata.pending;
782
+ syncState.assign({
783
+ lastSync: metadata.lastSync,
784
+ });
785
+ }
786
+
787
+ // Merge the data from local cache into the default state
788
+ if (value !== undefined) {
789
+ const { transform } = config;
790
+
791
+ value = transformLoadData(value, { transform }, true, 'get');
792
+
793
+ if (isPromise(value)) {
794
+ value = await value;
795
+ }
796
+
797
+ // isLoadingLocal prevents saving remotely when two different caches
798
+ // are set on the same observable
799
+ internal.globalState.isLoadingLocal = true;
800
+
801
+ // We want to merge the local data on top of any initial state the object is created with
802
+ if (value === null && (!prevValue || (prevValue as any)[symbolLinked])) {
803
+ obs.set(value);
804
+ } else {
805
+ mergeIntoObservable(obs, value);
806
+ }
807
+
808
+ internal.globalState.isLoadingLocal = false;
809
+ }
810
+
811
+ node.state!.peek().clearPersist = () =>
812
+ Promise.all([
813
+ persistPlugin.deleteTable(table, config),
814
+ persistPlugin.deleteMetadata(table, config),
815
+ ]) as unknown as Promise<void>;
816
+ }
817
+ syncState.isPersistLoaded.set(true);
818
+ }
819
+
820
+ export function syncObservable<T>(
821
+ obs$: ObservableParam<T>,
822
+ syncOptions: SyncedOptions<T>,
823
+ ): Observable<ObservableSyncState>;
824
+ export function syncObservable<T>(obs$: ObservableParam<T>, syncOptions: Synced<T>): Observable<ObservableSyncState>;
825
+ export function syncObservable<T>(
826
+ obs$: ObservableParam<T>,
827
+ syncOptionsOrSynced: SyncedOptions<T> | Synced<T>,
828
+ ): Observable<ObservableSyncState> {
829
+ let syncOptions = syncOptionsOrSynced as SyncedOptions<T>;
830
+ // If it's a synced then get the SyncOptions from it
831
+ if (isFunction(syncOptions)) {
832
+ syncOptions = syncOptions()[symbolLinked];
833
+ }
834
+ const node = getNode(obs$);
835
+
836
+ // Merge remote sync options with global options
837
+ syncOptions = mergeIntoObservable(
838
+ {
839
+ syncMode: 'auto',
840
+ } as SyncedOptions,
841
+ clone(observableSyncConfiguration),
842
+ removeNullUndefined(syncOptions || {}),
843
+ );
844
+ const localState: LocalState = {};
845
+ let sync: () => Promise<void>;
846
+
847
+ const syncState = (node.state = observable<ObservableSyncState>({
848
+ isPersistLoaded: false,
849
+ isLoaded: !syncOptions.get,
850
+ isPersistEnabled: true,
851
+ isSyncEnabled: true,
852
+ clearPersist: undefined as unknown as () => Promise<void>,
853
+ sync: () => Promise.resolve(),
854
+ getPendingChanges: () => localState.pendingChanges,
855
+ }));
856
+
857
+ loadLocal(obs$, syncOptions, syncState, localState);
858
+
859
+ localState.pluginSync = syncObservableAdapter(syncOptions);
860
+
861
+ if (syncOptions.get) {
862
+ let isSynced = false;
863
+ sync = async () => {
864
+ const lastSync = metadatas.get(obs$)?.lastSync;
865
+ const pending = localState.pendingChanges;
866
+ const get = localState.pluginSync!.get?.bind(localState.pluginSync);
867
+
868
+ if (get) {
869
+ const runGet = () => {
870
+ const onChange = async ({ value, mode, lastSync }: UpdateFnParams) => {
871
+ mode = mode || syncOptions.mode || 'set';
872
+ if (value !== undefined) {
873
+ value = transformLoadData(value, syncOptions, true, 'get');
874
+ if (isPromise(value)) {
875
+ value = await (value as Promise<T>);
876
+ }
877
+
878
+ const pending = localState.pendingChanges;
879
+ const currentValue = obs$.peek();
880
+ if (pending) {
881
+ let didChangeMetadata = false;
882
+ Object.keys(pending).forEach((key) => {
883
+ const p = key.split('/').filter((p) => p !== '');
884
+ const { v, t } = pending[key];
885
+
886
+ if (t.length === 0 || !value) {
887
+ if (isObject(value) && isObject(v)) {
888
+ Object.assign(value, v);
889
+ } else {
890
+ value = v;
891
+ }
892
+ } else if ((value as any)[p[0]] !== undefined) {
893
+ const curValue = getValueAtPath(currentValue as object, p);
894
+ const newValue = getValueAtPath(value as object, p);
895
+ if (JSON.stringify(curValue) === JSON.stringify(newValue)) {
896
+ delete pending[key];
897
+ didChangeMetadata = true;
898
+ } else {
899
+ (value as any) = setAtPath(
900
+ value as any,
901
+ p,
902
+ t,
903
+ v,
904
+ 'merge',
905
+ obs$.peek(),
906
+ (path: string[], value: any) => {
907
+ delete pending[key];
908
+ pending[path.join('/')] = {
909
+ p: null,
910
+ v: value,
911
+ t: t.slice(0, path.length),
912
+ };
913
+ },
914
+ );
915
+ }
916
+ }
917
+ });
918
+
919
+ if (didChangeMetadata) {
920
+ updateMetadata(obs$, localState, syncState, syncOptions, {
921
+ pending,
922
+ });
923
+ }
924
+ }
925
+
926
+ onChangeRemote(() => {
927
+ if (mode === 'assign' && isObject(value)) {
928
+ (obs$ as unknown as Observable<object>).assign(value);
929
+ } else if (mode === 'append' && isArray(value)) {
930
+ (obs$ as unknown as Observable<any[]>).push(...value);
931
+ } else if (mode === 'prepend' && isArray(value)) {
932
+ (obs$ as unknown as Observable<any[]>).splice(0, 0, ...value);
933
+ } else if (mode === 'merge') {
934
+ mergeIntoObservable(obs$, value);
935
+ } else {
936
+ obs$.set(value);
937
+ }
938
+ });
939
+ }
940
+ if (lastSync && syncOptions.persist) {
941
+ updateMetadata(obs$, localState, syncState, syncOptions, {
942
+ lastSync,
943
+ });
944
+ }
945
+ };
946
+ get({
947
+ state: syncState,
948
+ obs: obs$,
949
+ options: syncOptions,
950
+ lastSync,
951
+ dateModified: lastSync,
952
+ onError: (error: Error) => {
953
+ syncOptions.onGetError?.(error);
954
+ },
955
+ onGet: () => {
956
+ const isFirstLoad = !node.state!.isLoaded.peek();
957
+ node.state!.assign({
958
+ isLoaded: true,
959
+ error: undefined,
960
+ });
961
+
962
+ if (isFirstLoad && syncOptions.subscribe) {
963
+ syncOptions.subscribe({
964
+ node,
965
+ update: (params: ObservableOnChangeParams) => {
966
+ params.mode ||= syncOptions.mode || 'merge';
967
+ onChange(params);
968
+ },
969
+ refresh: sync,
970
+ });
971
+ }
972
+ },
973
+ onChange,
974
+ });
975
+ };
976
+ runGet();
977
+ } else {
978
+ node.state!.assign({
979
+ isLoaded: true,
980
+ error: undefined,
981
+ });
982
+ }
983
+ if (!isSynced) {
984
+ isSynced = true;
985
+ // Wait for remote to be ready before saving pending
986
+ await when(() => syncState.isLoaded.get() || (syncOptions.allowSetIfGetError && syncState.error.get()));
987
+
988
+ if (pending && !isEmpty(pending)) {
989
+ localState.isApplyingPending = true;
990
+ const keys = Object.keys(pending);
991
+
992
+ // Bundle up all the changes from pending
993
+ const changes: Change[] = [];
994
+ for (let i = 0; i < keys.length; i++) {
995
+ const key = keys[i];
996
+ const path = key.split('/').filter((p) => p !== '');
997
+ const { p, v, t } = pending[key];
998
+ changes.push({ path, valueAtPath: v, prevAtPath: p, pathTypes: t });
999
+ }
1000
+
1001
+ // Send the changes into onObsChange so that they get synced remotely
1002
+ const value = getNodeValue(node);
1003
+ onObsChange(obs$, syncState, localState, syncOptions, {
1004
+ value,
1005
+ loading: false,
1006
+ remote: false,
1007
+ getPrevious: createPreviousHandler(value, changes),
1008
+ changes,
1009
+ });
1010
+ localState.isApplyingPending = false;
1011
+ }
1012
+ }
1013
+ };
1014
+
1015
+ syncState.assign({ sync });
1016
+ }
1017
+
1018
+ // Wait for this node and all parent nodes up the hierarchy to be loaded
1019
+ const onAllPersistLoaded = () => {
1020
+ let parentNode: NodeValue | undefined = node;
1021
+ while (parentNode) {
1022
+ if (parentNode.state?.isPersistLoaded?.get() === false) {
1023
+ return false;
1024
+ }
1025
+ parentNode = parentNode.parent;
1026
+ }
1027
+ return true;
1028
+ };
1029
+ // When all is loaded locally we can start syncing and listening for changes
1030
+ when(onAllPersistLoaded, function (this: any) {
1031
+ // If remote is not manual, then sync() is called automatically
1032
+ if (syncOptions.get && syncOptions.syncMode === 'auto') {
1033
+ sync();
1034
+ }
1035
+
1036
+ obs$.onChange(onObsChange.bind(this, obs$ as any, syncState, localState, syncOptions as SyncedOptions<any>));
1037
+ });
1038
+
1039
+ return syncState;
1040
+ }