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