react-native-cloud-sync 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (268) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +360 -0
  3. package/app.plugin.js +3 -0
  4. package/ios/CloudSyncError.swift +144 -0
  5. package/ios/CloudSyncImpl.swift +1263 -0
  6. package/ios/RNCloudSync.h +25 -0
  7. package/ios/RNCloudSync.mm +477 -0
  8. package/jest-mock.js +136 -0
  9. package/lib/commonjs/config.js +85 -0
  10. package/lib/commonjs/config.js.map +1 -0
  11. package/lib/commonjs/errors.js +244 -0
  12. package/lib/commonjs/errors.js.map +1 -0
  13. package/lib/commonjs/hooks.js +257 -0
  14. package/lib/commonjs/hooks.js.map +1 -0
  15. package/lib/commonjs/index.js +244 -0
  16. package/lib/commonjs/index.js.map +1 -0
  17. package/lib/commonjs/internal/autoFlush.js +65 -0
  18. package/lib/commonjs/internal/autoFlush.js.map +1 -0
  19. package/lib/commonjs/internal/base64.js +58 -0
  20. package/lib/commonjs/internal/base64.js.map +1 -0
  21. package/lib/commonjs/internal/bytes.js +32 -0
  22. package/lib/commonjs/internal/bytes.js.map +1 -0
  23. package/lib/commonjs/internal/cloudKitRest.js +527 -0
  24. package/lib/commonjs/internal/cloudKitRest.js.map +1 -0
  25. package/lib/commonjs/internal/enums.js +23 -0
  26. package/lib/commonjs/internal/enums.js.map +1 -0
  27. package/lib/commonjs/internal/googleDriveRest.js +624 -0
  28. package/lib/commonjs/internal/googleDriveRest.js.map +1 -0
  29. package/lib/commonjs/internal/keys.js +139 -0
  30. package/lib/commonjs/internal/keys.js.map +1 -0
  31. package/lib/commonjs/internal/logger.js +29 -0
  32. package/lib/commonjs/internal/logger.js.map +1 -0
  33. package/lib/commonjs/internal/nativeModule.js +125 -0
  34. package/lib/commonjs/internal/nativeModule.js.map +1 -0
  35. package/lib/commonjs/internal/timeout.js +72 -0
  36. package/lib/commonjs/internal/timeout.js.map +1 -0
  37. package/lib/commonjs/package.json +1 -0
  38. package/lib/commonjs/providers/cloudKit.js +398 -0
  39. package/lib/commonjs/providers/cloudKit.js.map +1 -0
  40. package/lib/commonjs/providers/cloudKitBackup.js +86 -0
  41. package/lib/commonjs/providers/cloudKitBackup.js.map +1 -0
  42. package/lib/commonjs/providers/cloudKitEncrypted.js +150 -0
  43. package/lib/commonjs/providers/cloudKitEncrypted.js.map +1 -0
  44. package/lib/commonjs/providers/googleDrive.js +219 -0
  45. package/lib/commonjs/providers/googleDrive.js.map +1 -0
  46. package/lib/commonjs/providers/googleDriveFiles.js +68 -0
  47. package/lib/commonjs/providers/googleDriveFiles.js.map +1 -0
  48. package/lib/commonjs/providers/icloudDocuments.js +121 -0
  49. package/lib/commonjs/providers/icloudDocuments.js.map +1 -0
  50. package/lib/commonjs/providers/icloudKV.js +171 -0
  51. package/lib/commonjs/providers/icloudKV.js.map +1 -0
  52. package/lib/commonjs/providers/icloudKV.web.js +42 -0
  53. package/lib/commonjs/providers/icloudKV.web.js.map +1 -0
  54. package/lib/commonjs/providers/memory.js +201 -0
  55. package/lib/commonjs/providers/memory.js.map +1 -0
  56. package/lib/commonjs/resolvers.js +128 -0
  57. package/lib/commonjs/resolvers.js.map +1 -0
  58. package/lib/commonjs/specs/NativeRNCloudSync.js +14 -0
  59. package/lib/commonjs/specs/NativeRNCloudSync.js.map +1 -0
  60. package/lib/commonjs/store.js +1064 -0
  61. package/lib/commonjs/store.js.map +1 -0
  62. package/lib/commonjs/testing.js +32 -0
  63. package/lib/commonjs/testing.js.map +1 -0
  64. package/lib/commonjs/types.js +86 -0
  65. package/lib/commonjs/types.js.map +1 -0
  66. package/lib/module/config.js +72 -0
  67. package/lib/module/config.js.map +1 -0
  68. package/lib/module/errors.js +231 -0
  69. package/lib/module/errors.js.map +1 -0
  70. package/lib/module/hooks.js +250 -0
  71. package/lib/module/hooks.js.map +1 -0
  72. package/lib/module/index.js +46 -0
  73. package/lib/module/index.js.map +1 -0
  74. package/lib/module/internal/autoFlush.js +62 -0
  75. package/lib/module/internal/autoFlush.js.map +1 -0
  76. package/lib/module/internal/base64.js +53 -0
  77. package/lib/module/internal/base64.js.map +1 -0
  78. package/lib/module/internal/bytes.js +28 -0
  79. package/lib/module/internal/bytes.js.map +1 -0
  80. package/lib/module/internal/cloudKitRest.js +518 -0
  81. package/lib/module/internal/cloudKitRest.js.map +1 -0
  82. package/lib/module/internal/enums.js +18 -0
  83. package/lib/module/internal/enums.js.map +1 -0
  84. package/lib/module/internal/googleDriveRest.js +620 -0
  85. package/lib/module/internal/googleDriveRest.js.map +1 -0
  86. package/lib/module/internal/keys.js +134 -0
  87. package/lib/module/internal/keys.js.map +1 -0
  88. package/lib/module/internal/logger.js +23 -0
  89. package/lib/module/internal/logger.js.map +1 -0
  90. package/lib/module/internal/nativeModule.js +117 -0
  91. package/lib/module/internal/nativeModule.js.map +1 -0
  92. package/lib/module/internal/timeout.js +67 -0
  93. package/lib/module/internal/timeout.js.map +1 -0
  94. package/lib/module/package.json +1 -0
  95. package/lib/module/providers/cloudKit.js +392 -0
  96. package/lib/module/providers/cloudKit.js.map +1 -0
  97. package/lib/module/providers/cloudKitBackup.js +82 -0
  98. package/lib/module/providers/cloudKitBackup.js.map +1 -0
  99. package/lib/module/providers/cloudKitEncrypted.js +146 -0
  100. package/lib/module/providers/cloudKitEncrypted.js.map +1 -0
  101. package/lib/module/providers/googleDrive.js +214 -0
  102. package/lib/module/providers/googleDrive.js.map +1 -0
  103. package/lib/module/providers/googleDriveFiles.js +64 -0
  104. package/lib/module/providers/googleDriveFiles.js.map +1 -0
  105. package/lib/module/providers/icloudDocuments.js +117 -0
  106. package/lib/module/providers/icloudDocuments.js.map +1 -0
  107. package/lib/module/providers/icloudKV.js +165 -0
  108. package/lib/module/providers/icloudKV.js.map +1 -0
  109. package/lib/module/providers/icloudKV.web.js +36 -0
  110. package/lib/module/providers/icloudKV.web.js.map +1 -0
  111. package/lib/module/providers/memory.js +197 -0
  112. package/lib/module/providers/memory.js.map +1 -0
  113. package/lib/module/resolvers.js +120 -0
  114. package/lib/module/resolvers.js.map +1 -0
  115. package/lib/module/specs/NativeRNCloudSync.js +12 -0
  116. package/lib/module/specs/NativeRNCloudSync.js.map +1 -0
  117. package/lib/module/store.js +1061 -0
  118. package/lib/module/store.js.map +1 -0
  119. package/lib/module/testing.js +17 -0
  120. package/lib/module/testing.js.map +1 -0
  121. package/lib/module/types.js +82 -0
  122. package/lib/module/types.js.map +1 -0
  123. package/lib/typescript/commonjs/config.d.ts +33 -0
  124. package/lib/typescript/commonjs/config.d.ts.map +1 -0
  125. package/lib/typescript/commonjs/errors.d.ts +140 -0
  126. package/lib/typescript/commonjs/errors.d.ts.map +1 -0
  127. package/lib/typescript/commonjs/hooks.d.ts +109 -0
  128. package/lib/typescript/commonjs/hooks.d.ts.map +1 -0
  129. package/lib/typescript/commonjs/index.d.ts +37 -0
  130. package/lib/typescript/commonjs/index.d.ts.map +1 -0
  131. package/lib/typescript/commonjs/internal/autoFlush.d.ts +45 -0
  132. package/lib/typescript/commonjs/internal/autoFlush.d.ts.map +1 -0
  133. package/lib/typescript/commonjs/internal/base64.d.ts +12 -0
  134. package/lib/typescript/commonjs/internal/base64.d.ts.map +1 -0
  135. package/lib/typescript/commonjs/internal/bytes.d.ts +12 -0
  136. package/lib/typescript/commonjs/internal/bytes.d.ts.map +1 -0
  137. package/lib/typescript/commonjs/internal/cloudKitRest.d.ts +149 -0
  138. package/lib/typescript/commonjs/internal/cloudKitRest.d.ts.map +1 -0
  139. package/lib/typescript/commonjs/internal/enums.d.ts +10 -0
  140. package/lib/typescript/commonjs/internal/enums.d.ts.map +1 -0
  141. package/lib/typescript/commonjs/internal/googleDriveRest.d.ts +232 -0
  142. package/lib/typescript/commonjs/internal/googleDriveRest.d.ts.map +1 -0
  143. package/lib/typescript/commonjs/internal/keys.d.ts +28 -0
  144. package/lib/typescript/commonjs/internal/keys.d.ts.map +1 -0
  145. package/lib/typescript/commonjs/internal/logger.d.ts +10 -0
  146. package/lib/typescript/commonjs/internal/logger.d.ts.map +1 -0
  147. package/lib/typescript/commonjs/internal/nativeModule.d.ts +29 -0
  148. package/lib/typescript/commonjs/internal/nativeModule.d.ts.map +1 -0
  149. package/lib/typescript/commonjs/internal/timeout.d.ts +36 -0
  150. package/lib/typescript/commonjs/internal/timeout.d.ts.map +1 -0
  151. package/lib/typescript/commonjs/package.json +1 -0
  152. package/lib/typescript/commonjs/providers/cloudKit.d.ts +86 -0
  153. package/lib/typescript/commonjs/providers/cloudKit.d.ts.map +1 -0
  154. package/lib/typescript/commonjs/providers/cloudKitBackup.d.ts +65 -0
  155. package/lib/typescript/commonjs/providers/cloudKitBackup.d.ts.map +1 -0
  156. package/lib/typescript/commonjs/providers/cloudKitEncrypted.d.ts +37 -0
  157. package/lib/typescript/commonjs/providers/cloudKitEncrypted.d.ts.map +1 -0
  158. package/lib/typescript/commonjs/providers/googleDrive.d.ts +35 -0
  159. package/lib/typescript/commonjs/providers/googleDrive.d.ts.map +1 -0
  160. package/lib/typescript/commonjs/providers/googleDriveFiles.d.ts +59 -0
  161. package/lib/typescript/commonjs/providers/googleDriveFiles.d.ts.map +1 -0
  162. package/lib/typescript/commonjs/providers/icloudDocuments.d.ts +101 -0
  163. package/lib/typescript/commonjs/providers/icloudDocuments.d.ts.map +1 -0
  164. package/lib/typescript/commonjs/providers/icloudKV.d.ts +26 -0
  165. package/lib/typescript/commonjs/providers/icloudKV.d.ts.map +1 -0
  166. package/lib/typescript/commonjs/providers/icloudKV.web.d.ts +12 -0
  167. package/lib/typescript/commonjs/providers/icloudKV.web.d.ts.map +1 -0
  168. package/lib/typescript/commonjs/providers/memory.d.ts +90 -0
  169. package/lib/typescript/commonjs/providers/memory.d.ts.map +1 -0
  170. package/lib/typescript/commonjs/resolvers.d.ts +60 -0
  171. package/lib/typescript/commonjs/resolvers.d.ts.map +1 -0
  172. package/lib/typescript/commonjs/specs/NativeRNCloudSync.d.ts +133 -0
  173. package/lib/typescript/commonjs/specs/NativeRNCloudSync.d.ts.map +1 -0
  174. package/lib/typescript/commonjs/store.d.ts +118 -0
  175. package/lib/typescript/commonjs/store.d.ts.map +1 -0
  176. package/lib/typescript/commonjs/testing.d.ts +16 -0
  177. package/lib/typescript/commonjs/testing.d.ts.map +1 -0
  178. package/lib/typescript/commonjs/types.d.ts +367 -0
  179. package/lib/typescript/commonjs/types.d.ts.map +1 -0
  180. package/lib/typescript/module/config.d.ts +33 -0
  181. package/lib/typescript/module/config.d.ts.map +1 -0
  182. package/lib/typescript/module/errors.d.ts +140 -0
  183. package/lib/typescript/module/errors.d.ts.map +1 -0
  184. package/lib/typescript/module/hooks.d.ts +109 -0
  185. package/lib/typescript/module/hooks.d.ts.map +1 -0
  186. package/lib/typescript/module/index.d.ts +37 -0
  187. package/lib/typescript/module/index.d.ts.map +1 -0
  188. package/lib/typescript/module/internal/autoFlush.d.ts +45 -0
  189. package/lib/typescript/module/internal/autoFlush.d.ts.map +1 -0
  190. package/lib/typescript/module/internal/base64.d.ts +12 -0
  191. package/lib/typescript/module/internal/base64.d.ts.map +1 -0
  192. package/lib/typescript/module/internal/bytes.d.ts +12 -0
  193. package/lib/typescript/module/internal/bytes.d.ts.map +1 -0
  194. package/lib/typescript/module/internal/cloudKitRest.d.ts +149 -0
  195. package/lib/typescript/module/internal/cloudKitRest.d.ts.map +1 -0
  196. package/lib/typescript/module/internal/enums.d.ts +10 -0
  197. package/lib/typescript/module/internal/enums.d.ts.map +1 -0
  198. package/lib/typescript/module/internal/googleDriveRest.d.ts +232 -0
  199. package/lib/typescript/module/internal/googleDriveRest.d.ts.map +1 -0
  200. package/lib/typescript/module/internal/keys.d.ts +28 -0
  201. package/lib/typescript/module/internal/keys.d.ts.map +1 -0
  202. package/lib/typescript/module/internal/logger.d.ts +10 -0
  203. package/lib/typescript/module/internal/logger.d.ts.map +1 -0
  204. package/lib/typescript/module/internal/nativeModule.d.ts +29 -0
  205. package/lib/typescript/module/internal/nativeModule.d.ts.map +1 -0
  206. package/lib/typescript/module/internal/timeout.d.ts +36 -0
  207. package/lib/typescript/module/internal/timeout.d.ts.map +1 -0
  208. package/lib/typescript/module/package.json +1 -0
  209. package/lib/typescript/module/providers/cloudKit.d.ts +86 -0
  210. package/lib/typescript/module/providers/cloudKit.d.ts.map +1 -0
  211. package/lib/typescript/module/providers/cloudKitBackup.d.ts +65 -0
  212. package/lib/typescript/module/providers/cloudKitBackup.d.ts.map +1 -0
  213. package/lib/typescript/module/providers/cloudKitEncrypted.d.ts +37 -0
  214. package/lib/typescript/module/providers/cloudKitEncrypted.d.ts.map +1 -0
  215. package/lib/typescript/module/providers/googleDrive.d.ts +35 -0
  216. package/lib/typescript/module/providers/googleDrive.d.ts.map +1 -0
  217. package/lib/typescript/module/providers/googleDriveFiles.d.ts +59 -0
  218. package/lib/typescript/module/providers/googleDriveFiles.d.ts.map +1 -0
  219. package/lib/typescript/module/providers/icloudDocuments.d.ts +101 -0
  220. package/lib/typescript/module/providers/icloudDocuments.d.ts.map +1 -0
  221. package/lib/typescript/module/providers/icloudKV.d.ts +26 -0
  222. package/lib/typescript/module/providers/icloudKV.d.ts.map +1 -0
  223. package/lib/typescript/module/providers/icloudKV.web.d.ts +12 -0
  224. package/lib/typescript/module/providers/icloudKV.web.d.ts.map +1 -0
  225. package/lib/typescript/module/providers/memory.d.ts +90 -0
  226. package/lib/typescript/module/providers/memory.d.ts.map +1 -0
  227. package/lib/typescript/module/resolvers.d.ts +60 -0
  228. package/lib/typescript/module/resolvers.d.ts.map +1 -0
  229. package/lib/typescript/module/specs/NativeRNCloudSync.d.ts +133 -0
  230. package/lib/typescript/module/specs/NativeRNCloudSync.d.ts.map +1 -0
  231. package/lib/typescript/module/store.d.ts +118 -0
  232. package/lib/typescript/module/store.d.ts.map +1 -0
  233. package/lib/typescript/module/testing.d.ts +16 -0
  234. package/lib/typescript/module/testing.d.ts.map +1 -0
  235. package/lib/typescript/module/types.d.ts +367 -0
  236. package/lib/typescript/module/types.d.ts.map +1 -0
  237. package/package.json +186 -0
  238. package/plugin/build/index.d.ts +45 -0
  239. package/plugin/build/index.js +93 -0
  240. package/react-native-cloud-sync.podspec +48 -0
  241. package/src/config.ts +94 -0
  242. package/src/errors.ts +263 -0
  243. package/src/hooks.ts +337 -0
  244. package/src/index.ts +113 -0
  245. package/src/internal/autoFlush.ts +87 -0
  246. package/src/internal/base64.ts +63 -0
  247. package/src/internal/bytes.ts +28 -0
  248. package/src/internal/cloudKitRest.ts +654 -0
  249. package/src/internal/enums.ts +35 -0
  250. package/src/internal/googleDriveRest.ts +765 -0
  251. package/src/internal/keys.ts +160 -0
  252. package/src/internal/logger.ts +23 -0
  253. package/src/internal/nativeModule.ts +149 -0
  254. package/src/internal/timeout.ts +83 -0
  255. package/src/providers/cloudKit.ts +510 -0
  256. package/src/providers/cloudKitBackup.ts +124 -0
  257. package/src/providers/cloudKitEncrypted.ts +175 -0
  258. package/src/providers/googleDrive.ts +251 -0
  259. package/src/providers/googleDriveFiles.ts +117 -0
  260. package/src/providers/icloudDocuments.ts +175 -0
  261. package/src/providers/icloudKV.ts +206 -0
  262. package/src/providers/icloudKV.web.ts +41 -0
  263. package/src/providers/memory.ts +302 -0
  264. package/src/resolvers.ts +133 -0
  265. package/src/specs/NativeRNCloudSync.ts +184 -0
  266. package/src/store.ts +1288 -0
  267. package/src/testing.ts +22 -0
  268. package/src/types.ts +426 -0
@@ -0,0 +1,1064 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.createCloudStore = createCloudStore;
7
+ var _icloudKV = require("./providers/icloudKV");
8
+ var _cloudKit = require("./providers/cloudKit.js");
9
+ var _cloudKitEncrypted = require("./providers/cloudKitEncrypted.js");
10
+ var _googleDrive = require("./providers/googleDrive.js");
11
+ var _bytes = require("./internal/bytes.js");
12
+ var _keys = require("./internal/keys.js");
13
+ var _timeout = require("./internal/timeout.js");
14
+ var _autoFlush = require("./internal/autoFlush.js");
15
+ var _errors = require("./errors.js");
16
+ var _types = require("./types.js");
17
+ /**
18
+ * A durable place to park failed writes.
19
+ *
20
+ * Defaults to memory, which is honest but loses the queue on app restart. Pass
21
+ * an MMKV-backed adapter in production so an offline write survives being
22
+ * killed - that is the whole point of the outbox.
23
+ *
24
+ * Both methods are synchronous: the outbox is read and rewritten on the write
25
+ * path, where there is nowhere to await. AsyncStorage therefore cannot be
26
+ * wrapped directly; keep a synchronous cache in front of it if that is the
27
+ * only store you have.
28
+ */
29
+
30
+ const OUTBOX_KEY = 'rncs.outbox.v1';
31
+
32
+ /**
33
+ * Identity of a queued write: one entry per (provider, key).
34
+ *
35
+ * A single helper rather than a template literal at each site, because the two
36
+ * places that build it have to agree exactly - when they did not, a flush
37
+ * failed to recognise the entries it had just processed and wrote every one of
38
+ * them straight back, so a drained queue never shrank.
39
+ *
40
+ * The separator is an escaped NUL, which cannot appear in a provider name or a
41
+ * key, so the two halves can never run together and make two different pairs
42
+ * collide.
43
+ */
44
+ function outboxId(provider, key) {
45
+ return `${provider}\u0000${key}`;
46
+ }
47
+ const DEFAULT_OUTBOX_MAX_ENTRIES = 1000;
48
+ const DEFAULT_OUTBOX_MAX_ATTEMPTS = 12;
49
+ const DEFAULT_OUTBOX_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;
50
+ const DEFAULT_AVAILABILITY_TTL_MS = 3_000;
51
+ const BUILT_IN = {
52
+ icloudKV: _icloudKV.icloudKV,
53
+ cloudKit: _cloudKit.cloudKit,
54
+ cloudKitEncrypted: _cloudKitEncrypted.cloudKitEncrypted,
55
+ googleDrive: _googleDrive.googleDrive
56
+ };
57
+ function createCloudStore(options) {
58
+ const custom = new Map();
59
+ const useOutbox = options.outbox ?? true;
60
+ const writeMode = options.writeMode ?? 'failover';
61
+ const resolveValue = options.resolve;
62
+ // Repair defaults on with a resolver: without it the losing store keeps its
63
+ // old value and every read has to resolve again, forever.
64
+ const repairOnRead = options.repairOnRead ?? resolveValue != null;
65
+ const storage = options.outboxStorage ?? createMemoryOutboxStorage();
66
+ const codec = options.codec ?? null;
67
+ const validateKeys = options.validateKeys ?? true;
68
+ const timeoutMs = options.timeoutMs;
69
+ const availabilityTtlMs = options.availabilityTtlMs ?? DEFAULT_AVAILABILITY_TTL_MS;
70
+ const maxEntries = options.outboxMaxEntries ?? DEFAULT_OUTBOX_MAX_ENTRIES;
71
+ const maxAttempts = options.outboxMaxAttempts ?? DEFAULT_OUTBOX_MAX_ATTEMPTS;
72
+ const maxAgeMs = options.outboxMaxAgeMs ?? DEFAULT_OUTBOX_MAX_AGE_MS;
73
+ const tiering = options.tiering === 'off' ? null : options.tiering === 'auto' || options.tiering == null ? _types.DEFAULT_TIERING : options.tiering;
74
+
75
+ // ------------------------------------------------------------- providers
76
+
77
+ function resolveProvider(name) {
78
+ const found = custom.get(name) ?? BUILT_IN[name];
79
+ if (found == null) throw new _errors.CloudSyncError(_errors.ErrorCode.CONTAINER_MISCONFIGURED, `[RNCloudSync] Unknown provider '${name}'. Register it with registerProvider() first.`);
80
+ return found;
81
+ }
82
+
83
+ /**
84
+ * Memoised `isAvailable()`.
85
+ *
86
+ * The store asks before every operation, and for `icloudKV` that is a bridge
87
+ * hop while for `googleDrive` it invokes the host's `getAccessToken`. A loop
88
+ * over 100 keys used to cost 100+ probes on top of the work itself. Held
89
+ * briefly, so a token expiring mid-session is still noticed quickly.
90
+ */
91
+ const availability = new Map();
92
+ async function isAvailable(p) {
93
+ if (availabilityTtlMs <= 0) return probe(p);
94
+ const now = Date.now();
95
+ const cached = availability.get(p.name);
96
+ if (cached != null && now - cached.at < availabilityTtlMs) return cached.ok;
97
+ const ok = await probe(p);
98
+ availability.set(p.name, {
99
+ at: Date.now(),
100
+ ok
101
+ });
102
+ return ok;
103
+ }
104
+ async function probe(p) {
105
+ try {
106
+ return await run(p, () => p.isAvailable());
107
+ } catch {
108
+ // `isAvailable` is documented as non-throwing, but a timeout wrapper or a
109
+ // third-party provider can still reject. Unavailable is the safe reading.
110
+ return false;
111
+ }
112
+ }
113
+ function invalidateAvailability() {
114
+ availability.clear();
115
+ }
116
+
117
+ /** Applies the configured per-operation timeout, if any. */
118
+ function run(p, op) {
119
+ if (timeoutMs == null) return op();
120
+ return (0, _timeout.withTimeout)(op(), timeoutMs, p.name);
121
+ }
122
+
123
+ /**
124
+ * Every configured provider that is currently usable, in preference order.
125
+ *
126
+ * Ordering is preserved so `mirror` writes hit the preferred store first -
127
+ * if the process dies mid-write, the copy that landed is the one reads reach
128
+ * first.
129
+ */
130
+ async function allAvailable() {
131
+ const found = [];
132
+ for (const name of options.providers) {
133
+ const p = resolveProvider(name);
134
+ if (await isAvailable(p)) found.push(p);
135
+ }
136
+ return found;
137
+ }
138
+
139
+ /** First configured+available provider, in the caller's preference order. */
140
+ async function primary() {
141
+ for (const name of options.providers) {
142
+ const p = resolveProvider(name);
143
+ if (await isAvailable(p)) return p;
144
+ }
145
+ throw noneAvailable();
146
+ }
147
+ function noneAvailable() {
148
+ return new _errors.CloudSyncError(_errors.ErrorCode.NOT_SIGNED_IN, `[RNCloudSync] None of the configured providers (${options.providers.join(', ')}) ` + `is currently available.`);
149
+ }
150
+ function checkKey(key) {
151
+ if (validateKeys) (0, _keys.assertKey)(key, options.providers);
152
+ }
153
+
154
+ // ----------------------------------------------------------------- codec
155
+
156
+ async function encode(key, value) {
157
+ return codec == null ? value : await codec.encode(value, key);
158
+ }
159
+ async function decode(key, value) {
160
+ return codec == null ? value : await codec.decode(value, key);
161
+ }
162
+
163
+ // ---------------------------------------------------------------- outbox
164
+
165
+ function readOutbox() {
166
+ const raw = storage.getString(OUTBOX_KEY);
167
+ if (raw == null) return [];
168
+ try {
169
+ const parsed = JSON.parse(raw);
170
+ return Array.isArray(parsed) ? parsed : [];
171
+ } catch {
172
+ return [];
173
+ }
174
+ }
175
+ function writeOutbox(entries) {
176
+ storage.set(OUTBOX_KEY, JSON.stringify(entries));
177
+ }
178
+ function reportDropped(entry, reason, error) {
179
+ options.onDropped?.({
180
+ entry,
181
+ reason,
182
+ error
183
+ });
184
+ }
185
+ function enqueue(key, value, provider, lastErrorCode) {
186
+ if (!useOutbox) return;
187
+ const entries = readOutbox().filter(e => !(e.key === key && e.provider === provider));
188
+ entries.push({
189
+ key,
190
+ value,
191
+ provider,
192
+ attempts: 0,
193
+ nextAttemptAt: Date.now(),
194
+ enqueuedAt: Date.now(),
195
+ lastErrorCode
196
+ });
197
+
198
+ // An unbounded queue is a slow leak: every enqueue rewrites the whole blob,
199
+ // so a long offline stretch degrades the write path itself. Drop the oldest
200
+ // and say so, rather than growing without limit or failing silently.
201
+ while (entries.length > maxEntries) {
202
+ const evicted = entries.shift();
203
+ if (evicted != null) reportDropped(evicted, 'queueFull');
204
+ }
205
+ writeOutbox(entries);
206
+ }
207
+
208
+ /**
209
+ * Forgets any queued write for this key/provider.
210
+ *
211
+ * Called after a *successful* direct write, and this is not an optimisation.
212
+ * Without it: an offline `setItem(k, v1)` queues v1, a later online
213
+ * `setItem(k, v2)` succeeds directly, and the next flush writes v1 back over
214
+ * v2. The queue has to be invalidated by the newer write that superseded it.
215
+ */
216
+ function dequeue(key, provider) {
217
+ if (!useOutbox) return;
218
+ const entries = readOutbox();
219
+ const kept = entries.filter(e => !(e.key === key && e.provider === provider));
220
+ if (kept.length !== entries.length) writeOutbox(kept);
221
+ }
222
+ function dequeueMany(keys, provider) {
223
+ if (!useOutbox || keys.length === 0) return;
224
+ const drop = new Set(keys);
225
+ const entries = readOutbox();
226
+ const kept = entries.filter(e => !(drop.has(e.key) && e.provider === provider));
227
+ if (kept.length !== entries.length) writeOutbox(kept);
228
+ }
229
+
230
+ // ------------------------------------------------------------ size rules
231
+
232
+ /**
233
+ * The byte ceiling tiering imposes on a provider, or null when it imposes
234
+ * none. This is what routes a value to the right backing store by size.
235
+ *
236
+ * Both thresholds are honoured. Drive stores whole files and has no
237
+ * comparable small ceiling, so it is the destination of last resort.
238
+ */
239
+ function limitFor(provider) {
240
+ if (tiering == null) return null;
241
+ if (provider.name === 'icloudKV') return tiering.kvMaxBytes;
242
+ if (provider.name === 'cloudKit') return tiering.recordMaxBytes;
243
+ return null;
244
+ }
245
+ function canHold(provider, value) {
246
+ const limit = limitFor(provider);
247
+ return limit == null || (0, _bytes.byteLength)(value) <= limit;
248
+ }
249
+
250
+ /**
251
+ * Picks the destination for a `failover` write when the preferred provider is
252
+ * too small for the value.
253
+ *
254
+ * Candidates must be both large enough AND currently available: routing to a
255
+ * provider that is configured but unreachable just converts a size problem
256
+ * into a write failure.
257
+ */
258
+ async function providerForSize(value, preferred) {
259
+ if (canHold(preferred, value)) return preferred;
260
+ const bytes = (0, _bytes.byteLength)(value);
261
+ for (const name of options.providers) {
262
+ if (name === preferred.name) continue;
263
+ const candidate = resolveProvider(name);
264
+ if (!canHold(candidate, value)) continue;
265
+ if (!(await isAvailable(candidate))) continue;
266
+ return candidate;
267
+ }
268
+ throw new _errors.CloudSyncError(_errors.ErrorCode.PAYLOAD_TOO_LARGE, `[RNCloudSync] Value is ${bytes} bytes, above the ${limitFor(preferred)}-byte limit for ` + `'${preferred.name}', and no larger-capacity provider is configured and available. Add ` + `'cloudKit' or 'googleDrive' to providers.`, {
269
+ limitBytes: limitFor(preferred) ?? undefined,
270
+ actualBytes: bytes,
271
+ provider: preferred.name
272
+ });
273
+ }
274
+
275
+ // ----------------------------------------------------------------- reads
276
+
277
+ async function readOne(p, key) {
278
+ if (p.getItemWithMeta != null) return await run(p, () => p.getItemWithMeta(key));
279
+ const value = await run(p, () => p.getItem(key));
280
+ return value == null ? null : {
281
+ value
282
+ };
283
+ }
284
+ async function readBatch(p, keys) {
285
+ if (p.multiGet != null) return await run(p, () => p.multiGet(keys));
286
+ const out = [];
287
+ for (const key of keys) out.push(await run(p, () => p.getItem(key)));
288
+ return out;
289
+ }
290
+ async function writeBatch(p, entries) {
291
+ if (entries.length === 0) return;
292
+ if (p.multiSet != null) {
293
+ await run(p, () => p.multiSet(entries));
294
+ return;
295
+ }
296
+ for (const [key, value] of entries) await run(p, () => p.setItem(key, value));
297
+ }
298
+ async function removeBatch(p, keys) {
299
+ if (keys.length === 0) return;
300
+ if (p.multiRemove != null) {
301
+ await run(p, () => p.multiRemove(keys));
302
+ return;
303
+ }
304
+ for (const key of keys) await run(p, () => p.removeItem(key));
305
+ }
306
+
307
+ // ---------------------------------------------------------------- writes
308
+
309
+ /** Single-destination write, queueing a retryable failure. */
310
+ async function writeOne(target, key, value) {
311
+ try {
312
+ await run(target, () => target.setItem(key, value));
313
+ // This write supersedes anything queued for the same destination.
314
+ dequeue(key, target.name);
315
+ } catch (e) {
316
+ const err = (0, _errors.normalizeError)(e, target.name);
317
+ if (useOutbox && (0, _errors.isRetryable)(err)) {
318
+ enqueue(key, value, target.name, err.code);
319
+ options.onError?.(err);
320
+ return;
321
+ }
322
+ throw err;
323
+ }
324
+ }
325
+
326
+ /**
327
+ * Removes a key from providers that are reachable but cannot hold this value.
328
+ *
329
+ * Without this, `mirror` plus tiering strands stale data: a value that grows
330
+ * past `kvMaxBytes` is written to CloudKit and Drive and *skipped* on the
331
+ * key-value store, which keeps the older, smaller copy. A read with no
332
+ * resolver prefers that provider and returns the stale value forever, and
333
+ * read repair never cleans it up because it applies the same size guard.
334
+ * The copy the value no longer fits in has to go.
335
+ */
336
+ async function evictWhereTooLarge(targets, key, value) {
337
+ for (const target of targets) {
338
+ if (canHold(target, value)) continue;
339
+ try {
340
+ await run(target, () => target.removeItem(key));
341
+ dequeue(key, target.name);
342
+ } catch (e) {
343
+ // Best effort. A stale copy left behind is reported, not fatal - the
344
+ // value itself did land somewhere.
345
+ options.onError?.((0, _errors.normalizeError)(e, target.name));
346
+ }
347
+ }
348
+ }
349
+
350
+ /**
351
+ * Mirrored write.
352
+ *
353
+ * Succeeds if at least one destination took the value, because one good copy
354
+ * plus a queued retry is a better outcome than rejecting a write the user has
355
+ * already been told about. Retryable failures go to the outbox per provider,
356
+ * so they converge without re-sending to the ones that already succeeded.
357
+ *
358
+ * Rejects only when nothing stored it - silence there would be the false
359
+ * success this package exists to avoid.
360
+ */
361
+ async function writeMany(targets, key, value) {
362
+ const eligible = targets.filter(t => canHold(t, value));
363
+ if (eligible.length === 0) {
364
+ if (targets.length === 0) throw noneAvailable();
365
+
366
+ // Every destination exists but the value is too large for all of them.
367
+ const bytes = (0, _bytes.byteLength)(value);
368
+ const largest = targets.map(limitFor).filter(n => n != null).reduce((a, b) => a == null || b > a ? b : a, undefined);
369
+ throw new _errors.CloudSyncError(_errors.ErrorCode.PAYLOAD_TOO_LARGE, `[RNCloudSync] Value is ${bytes} bytes and does not fit in any configured provider.`, {
370
+ actualBytes: bytes,
371
+ limitBytes: largest
372
+ });
373
+ }
374
+ let stored = 0;
375
+ let fatal = null;
376
+ for (const target of eligible) try {
377
+ await run(target, () => target.setItem(key, value));
378
+ dequeue(key, target.name);
379
+ stored += 1;
380
+ } catch (e) {
381
+ const err = (0, _errors.normalizeError)(e, target.name);
382
+ if (useOutbox && (0, _errors.isRetryable)(err)) {
383
+ enqueue(key, value, target.name, err.code);
384
+ options.onError?.(err);
385
+ continue;
386
+ }
387
+ fatal ??= err;
388
+ options.onError?.(err);
389
+ }
390
+
391
+ // Only once the value has a home somewhere: dropping the old copy first
392
+ // would open a window in which the key exists nowhere.
393
+ if (stored > 0) await evictWhereTooLarge(targets, key, value);
394
+
395
+ // Nothing stored it and nothing was queued - that has to surface.
396
+ if (stored === 0 && fatal != null) throw fatal;
397
+ }
398
+
399
+ /** Mirrored delete, with the same at-least-one rule. */
400
+ async function removeMany(targets, key) {
401
+ // Nothing to delete from is a failed delete, not a completed one. Without
402
+ // this, a mirrored `removeItem` with every provider unavailable resolved
403
+ // successfully having removed the key from nowhere - the same false success
404
+ // this package exists to avoid, and which `writeMany` already refuses.
405
+ if (targets.length === 0) throw noneAvailable();
406
+ let removed = 0;
407
+ let fatal = null;
408
+ for (const target of targets) try {
409
+ await run(target, () => target.removeItem(key));
410
+ dequeue(key, target.name);
411
+ removed += 1;
412
+ } catch (e) {
413
+ const err = (0, _errors.normalizeError)(e, target.name);
414
+ if (useOutbox && (0, _errors.isRetryable)(err)) {
415
+ enqueue(key, null, target.name, err.code);
416
+ options.onError?.(err);
417
+ continue;
418
+ }
419
+ fatal ??= err;
420
+ options.onError?.(err);
421
+ }
422
+ if (removed === 0 && fatal != null) throw fatal;
423
+ }
424
+
425
+ /**
426
+ * Writes the resolved value back to providers that disagreed, and to
427
+ * reachable providers that were missing it entirely.
428
+ *
429
+ * A provider the winner no longer fits in has its stale copy removed instead
430
+ * of being silently left holding it - see {@link evictWhereTooLarge}.
431
+ */
432
+ async function repair(key, winner, candidates, reachable) {
433
+ const byProvider = new Map(candidates.map(c => [c.provider, c.value]));
434
+ const stored = await encode(key, winner);
435
+ for (const [name, provider] of reachable) {
436
+ if (byProvider.get(name) === winner) continue;
437
+ if (!canHold(provider, stored)) {
438
+ if (!byProvider.has(name)) continue;
439
+ try {
440
+ await run(provider, () => provider.removeItem(key));
441
+ } catch (e) {
442
+ options.onError?.((0, _errors.normalizeError)(e, name));
443
+ }
444
+ continue;
445
+ }
446
+ try {
447
+ await run(provider, () => provider.setItem(key, stored));
448
+ } catch (e) {
449
+ options.onError?.((0, _errors.normalizeError)(e, name));
450
+ }
451
+ }
452
+ }
453
+
454
+ // ---------------------------------------------------------------- events
455
+
456
+ const remoteListeners = new Set();
457
+ const accountListeners = new Set();
458
+ let providerSubscriptions = null;
459
+ let flushing = null;
460
+
461
+ /**
462
+ * Subscribes to every configured provider exactly once, lazily.
463
+ *
464
+ * Lazy because `createCloudStore` is often called at module scope, before the
465
+ * native module or a Drive token exists, and eagerly subscribing there would
466
+ * resolve providers too early.
467
+ */
468
+ function ensureSubscribed() {
469
+ if (providerSubscriptions != null) return;
470
+ providerSubscriptions = [];
471
+ for (const name of options.providers) {
472
+ let p;
473
+ try {
474
+ p = resolveProvider(name);
475
+ } catch {
476
+ // An unregistered provider is reported loudly by every other path;
477
+ // subscription should not be the thing that throws first.
478
+ continue;
479
+ }
480
+ if (p.onRemoteChange != null) providerSubscriptions.push(p.onRemoteChange(e => {
481
+ for (const l of remoteListeners) l(e);
482
+ }));
483
+ if (p.onAccountChange != null) providerSubscriptions.push(p.onAccountChange(e => {
484
+ if (isDuplicateAccountEvent(e)) return;
485
+ handleAccountChange(e);
486
+ for (const l of accountListeners) l(e);
487
+ }));
488
+ }
489
+ }
490
+
491
+ /**
492
+ * Collapses the same account event arriving from several providers at once.
493
+ *
494
+ * On Apple platforms `icloudKV` and `cloudKit` both listen to the same two
495
+ * system notifications and relabel them with their own provider name -
496
+ * correctly, because an Apple ID change matters to both. The consequence is
497
+ * that a store configured with both delivers one system event to app
498
+ * listeners twice.
499
+ *
500
+ * Deduplicated on the event's content rather than its provider, over a short
501
+ * window: the providers emit within the same tick, so anything that looks
502
+ * identical that soon after is the same underlying notification. A genuine
503
+ * second change of the same shape inside the window is vanishingly unlikely,
504
+ * and would only cost a repeat of work that is already idempotent.
505
+ */
506
+ const ACCOUNT_EVENT_DEDUPE_MS = 250;
507
+ let lastAccountEvent = null;
508
+ function isDuplicateAccountEvent(e) {
509
+ const key = `${e.status}\u0000${String(e.identityChanged)}`;
510
+ const now = Date.now();
511
+ const seen = lastAccountEvent != null && lastAccountEvent.key === key && now - lastAccountEvent.at < ACCOUNT_EVENT_DEDUPE_MS;
512
+ lastAccountEvent = {
513
+ key,
514
+ at: now
515
+ };
516
+ return seen;
517
+ }
518
+
519
+ /**
520
+ * The store's own reaction to an account event.
521
+ *
522
+ * A different Apple ID or Google account is now signed in, so three pieces of
523
+ * state belong to somebody who is no longer here: memoised availability,
524
+ * whatever the providers cached (Drive file ids, CloudKit reachability), and
525
+ * the outbox. Queued writes are the dangerous one - an entry carries no
526
+ * account identity, so flushing after a switch would write the previous
527
+ * user's data into the new user's account.
528
+ */
529
+ function handleAccountChange(e) {
530
+ invalidateAvailability();
531
+ if (!e.identityChanged) return;
532
+ for (const name of options.providers) try {
533
+ resolveProvider(name).clearCaches?.();
534
+ } catch {
535
+ // Nothing to clear on a provider that will not resolve.
536
+ }
537
+ const pending = readOutbox();
538
+ if (pending.length === 0) return;
539
+ writeOutbox([]);
540
+ for (const entry of pending) reportDropped(entry, 'accountChanged');
541
+ }
542
+
543
+ // ------------------------------------------------------------------ read
544
+
545
+ /**
546
+ * Reads one key across the configured providers.
547
+ *
548
+ * Returns `{ found: false }` only when at least one provider was reachable
549
+ * and none of them held the key. When *nothing* was reachable the caller is
550
+ * told, because resolving `null` there is indistinguishable from "no such
551
+ * key" - and the documented first-launch recipe reacts to `null` by seeding
552
+ * empty state, which is how a signed-out user's real backup gets overwritten.
553
+ */
554
+ async function readAcross(key) {
555
+ let lastError = null;
556
+ let reachedAny = false;
557
+
558
+ // No resolver: first non-null wins and we stop looking. Cheap, and right
559
+ // when only one population of devices ever writes.
560
+ if (resolveValue == null) {
561
+ for (const name of options.providers) {
562
+ const p = resolveProvider(name);
563
+ try {
564
+ if (!(await isAvailable(p))) continue;
565
+ const hit = await readOne(p, key);
566
+ reachedAny = true;
567
+ if (hit != null) return {
568
+ found: true,
569
+ value: await decode(key, hit.value),
570
+ reachedAny
571
+ };
572
+ } catch (e) {
573
+ lastError = e;
574
+ }
575
+ }
576
+ if (lastError != null) throw (0, _errors.normalizeError)(lastError);
577
+ return {
578
+ found: false,
579
+ value: null,
580
+ reachedAny
581
+ };
582
+ }
583
+
584
+ // With a resolver: consult every available provider, because the first one
585
+ // holding a value is not necessarily holding the newest. This is what makes
586
+ // sync work in both directions across a mixed fleet.
587
+ const candidates = [];
588
+ const reachable = new Map();
589
+ for (const name of options.providers) {
590
+ const p = resolveProvider(name);
591
+ try {
592
+ if (!(await isAvailable(p))) continue;
593
+ const hit = await readOne(p, key);
594
+ // Only a provider we actually read from is a repair target. Marking it
595
+ // reachable before the read meant a provider whose read merely failed
596
+ // - a transient network blip - was repaired too, overwriting whatever
597
+ // it held with another provider's value. If the copy we could not read
598
+ // was the newer one, that silently destroyed it.
599
+ reachable.set(p.name, p);
600
+ reachedAny = true;
601
+ if (hit != null) candidates.push({
602
+ provider: p.name,
603
+ value: await decode(key, hit.value),
604
+ modifiedAt: hit.modifiedAt
605
+ });
606
+ } catch (e) {
607
+ lastError = e;
608
+ }
609
+ }
610
+ if (candidates.length === 0) {
611
+ if (lastError != null) throw (0, _errors.normalizeError)(lastError);
612
+ return {
613
+ found: false,
614
+ value: null,
615
+ reachedAny
616
+ };
617
+ }
618
+ const winner = resolveValue(candidates);
619
+ if (winner == null) return {
620
+ found: false,
621
+ value: null,
622
+ reachedAny
623
+ };
624
+
625
+ // Best-effort convergence. Never fails the read - the caller already has
626
+ // the right answer, and a failed repair only costs another resolve later.
627
+ if (repairOnRead) void repair(key, winner, candidates, reachable);
628
+ return {
629
+ found: true,
630
+ value: winner,
631
+ reachedAny
632
+ };
633
+ }
634
+
635
+ // ------------------------------------------------------------------ API
636
+
637
+ const store = {
638
+ getItem: async key => {
639
+ checkKey(key);
640
+ const result = await readAcross(key);
641
+ // Nothing was reachable, so this is not an absent key - it is an unknown
642
+ // one. Saying `null` here is the false negative the error contract exists
643
+ // to prevent.
644
+ if (!result.reachedAny) throw noneAvailable();
645
+ return result.found ? result.value : null;
646
+ },
647
+ setItem: async (key, value) => {
648
+ checkKey(key);
649
+ const stored = await encode(key, value);
650
+ if (writeMode === 'failover') {
651
+ const target = await providerForSize(stored, await primary());
652
+ await writeOne(target, key, stored);
653
+ return;
654
+ }
655
+ await writeMany(await allAvailable(), key, stored);
656
+ },
657
+ removeItem: async key => {
658
+ checkKey(key);
659
+ // A mirrored write must be a mirrored delete. Removing from only the
660
+ // preferred provider would leave a copy behind that reads then fall
661
+ // through to and resurrect.
662
+ const targets = writeMode === 'mirror' ? await allAvailable() : [await primary()];
663
+ await removeMany(targets, key);
664
+ },
665
+ getAllKeys: async () => {
666
+ const seen = new Set();
667
+ for (const name of options.providers) {
668
+ const p = resolveProvider(name);
669
+ try {
670
+ if (!(await isAvailable(p))) continue;
671
+ for (const k of await run(p, () => p.getAllKeys())) seen.add(k);
672
+ } catch {
673
+ // A provider that cannot list should not hide the ones that can.
674
+ }
675
+ }
676
+ return [...seen];
677
+ },
678
+ multiGet: async keys => {
679
+ for (const key of keys) checkKey(key);
680
+ if (keys.length === 0) return [];
681
+ const answers = new Map();
682
+
683
+ // A resolving read has to see every provider's copy of every key, so
684
+ // there is no early exit to exploit - but each provider is still a single
685
+ // batched request rather than one per key.
686
+ if (resolveValue != null) {
687
+ const perKey = new Map(keys.map(k => [k, []]));
688
+ let reachedAny = false;
689
+ for (const name of options.providers) {
690
+ const p = resolveProvider(name);
691
+ try {
692
+ if (!(await isAvailable(p))) continue;
693
+ const values = await readBatch(p, keys);
694
+ reachedAny = true;
695
+ for (let i = 0; i < keys.length; i += 1) {
696
+ const raw = values[i];
697
+ if (raw == null) continue;
698
+ perKey.get(keys[i]).push({
699
+ provider: p.name,
700
+ value: await decode(keys[i], raw)
701
+ });
702
+ }
703
+ } catch {
704
+ // Same rule as `getAllKeys`: one provider failing to answer must not
705
+ // erase the answers the others gave.
706
+ }
707
+ }
708
+ if (!reachedAny) throw noneAvailable();
709
+ for (const key of keys) {
710
+ const candidates = perKey.get(key);
711
+ answers.set(key, candidates.length === 0 ? null : resolveValue(candidates));
712
+ }
713
+ return keys.map(k => [k, answers.get(k) ?? null]);
714
+ }
715
+
716
+ // No resolver: ask each provider only for the keys still unanswered, so a
717
+ // second provider is consulted for the tail rather than for everything.
718
+ let outstanding = [...keys];
719
+ let reachedAny = false;
720
+ for (const name of options.providers) {
721
+ if (outstanding.length === 0) break;
722
+ const p = resolveProvider(name);
723
+ try {
724
+ if (!(await isAvailable(p))) continue;
725
+ const values = await readBatch(p, outstanding);
726
+ reachedAny = true;
727
+ const stillMissing = [];
728
+ for (let i = 0; i < outstanding.length; i += 1) {
729
+ const raw = values[i];
730
+ if (raw == null) stillMissing.push(outstanding[i]);else answers.set(outstanding[i], await decode(outstanding[i], raw));
731
+ }
732
+ outstanding = stillMissing;
733
+ } catch {
734
+ // Leave those keys outstanding for the next provider.
735
+ }
736
+ }
737
+ if (!reachedAny) throw noneAvailable();
738
+ return keys.map(k => [k, answers.get(k) ?? null]);
739
+ },
740
+ multiSet: async entries => {
741
+ for (const [key] of entries) checkKey(key);
742
+ if (entries.length === 0) return;
743
+ const encoded = [];
744
+ for (const [key, value] of entries) encoded.push([key, await encode(key, value)]);
745
+ if (writeMode === 'failover') {
746
+ // Tiering can route two values in the same batch to two different
747
+ // providers, so group by destination rather than assuming one target.
748
+ const preferred = await primary();
749
+ const byTarget = new Map();
750
+ for (const [key, value] of encoded) {
751
+ const target = await providerForSize(value, preferred);
752
+ const bucket = byTarget.get(target.name) ?? {
753
+ provider: target,
754
+ items: []
755
+ };
756
+ bucket.items.push([key, value]);
757
+ byTarget.set(target.name, bucket);
758
+ }
759
+ for (const {
760
+ provider,
761
+ items
762
+ } of byTarget.values()) try {
763
+ await writeBatch(provider, items);
764
+ dequeueMany(items.map(([k]) => k), provider.name);
765
+ } catch (e) {
766
+ const err = (0, _errors.normalizeError)(e, provider.name);
767
+ if (useOutbox && (0, _errors.isRetryable)(err)) {
768
+ for (const [key, value] of items) enqueue(key, value, provider.name, err.code);
769
+ options.onError?.(err);
770
+ continue;
771
+ }
772
+ throw err;
773
+ }
774
+ return;
775
+ }
776
+ const targets = await allAvailable();
777
+ if (targets.length === 0) throw noneAvailable();
778
+ let anyStored = false;
779
+ let fatal = null;
780
+ for (const target of targets) {
781
+ const fits = encoded.filter(([, value]) => canHold(target, value));
782
+ if (fits.length === 0) continue;
783
+ try {
784
+ await writeBatch(target, fits);
785
+ dequeueMany(fits.map(([k]) => k), target.name);
786
+ anyStored = true;
787
+ } catch (e) {
788
+ const err = (0, _errors.normalizeError)(e, target.name);
789
+ if (useOutbox && (0, _errors.isRetryable)(err)) {
790
+ for (const [key, value] of fits) enqueue(key, value, target.name, err.code);
791
+ options.onError?.(err);
792
+ continue;
793
+ }
794
+ fatal ??= err;
795
+ options.onError?.(err);
796
+ }
797
+ }
798
+ if (anyStored) for (const [key, value] of encoded) await evictWhereTooLarge(targets, key, value);
799
+ if (!anyStored && fatal != null) throw fatal;
800
+ if (!anyStored && fatal == null) {
801
+ const bytes = Math.max(...encoded.map(([, v]) => (0, _bytes.byteLength)(v)));
802
+ throw new _errors.CloudSyncError(_errors.ErrorCode.PAYLOAD_TOO_LARGE, `[RNCloudSync] No configured provider can hold these values (largest is ${bytes} bytes).`, {
803
+ actualBytes: bytes
804
+ });
805
+ }
806
+ },
807
+ multiRemove: async keys => {
808
+ for (const key of keys) checkKey(key);
809
+ if (keys.length === 0) return;
810
+ const targets = writeMode === 'mirror' ? await allAvailable() : [await primary()];
811
+ if (targets.length === 0) throw noneAvailable();
812
+ let removedAnywhere = false;
813
+ let fatal = null;
814
+ for (const target of targets) try {
815
+ await removeBatch(target, keys);
816
+ dequeueMany(keys, target.name);
817
+ removedAnywhere = true;
818
+ } catch (e) {
819
+ const err = (0, _errors.normalizeError)(e, target.name);
820
+ if (useOutbox && (0, _errors.isRetryable)(err)) {
821
+ for (const key of keys) enqueue(key, null, target.name, err.code);
822
+ options.onError?.(err);
823
+ continue;
824
+ }
825
+ fatal ??= err;
826
+ options.onError?.(err);
827
+ }
828
+ if (!removedAnywhere && fatal != null) throw fatal;
829
+ },
830
+ clear: async () => {
831
+ const keys = await store.getAllKeys();
832
+ if (keys.length === 0) return {
833
+ removed: []
834
+ };
835
+ await store.multiRemove(keys);
836
+ return {
837
+ removed: keys
838
+ };
839
+ },
840
+ getAllItems: async () => {
841
+ const keys = await store.getAllKeys();
842
+ if (keys.length === 0) return {};
843
+ const out = {};
844
+ for (const [key, value] of await store.multiGet(keys)) if (value != null) out[key] = value;
845
+ return out;
846
+ },
847
+ getQuota: async () => {
848
+ const out = [];
849
+ for (const name of options.providers) {
850
+ const p = resolveProvider(name);
851
+ if (p.getQuota == null) continue;
852
+ try {
853
+ if (!(await isAvailable(p))) continue;
854
+ const quota = await run(p, () => p.getQuota());
855
+ if (quota != null) out.push(quota);
856
+ } catch (e) {
857
+ options.onError?.((0, _errors.normalizeError)(e, name));
858
+ }
859
+ }
860
+ return out;
861
+ },
862
+ migrate: async ({
863
+ from,
864
+ to,
865
+ continueOnError = true,
866
+ filter,
867
+ onProgress
868
+ }) => {
869
+ const src = resolveProvider(from);
870
+ const dst = resolveProvider(to);
871
+ const all = await run(src, () => src.getAllKeys());
872
+ const keys = filter == null ? all : all.filter(filter);
873
+ const copied = [];
874
+ const skipped = [];
875
+ const failed = [];
876
+
877
+ // Values move verbatim. Both ends sit behind the same codec, so decoding
878
+ // on the way out only to re-encode on the way in would be wasted work -
879
+ // and, for a codec with a random nonce, would rewrite every byte.
880
+ for (const key of keys) {
881
+ try {
882
+ const value = await run(src, () => src.getItem(key));
883
+ if (value == null) {
884
+ skipped.push(key);
885
+ } else {
886
+ await run(dst, () => dst.setItem(key, value));
887
+ copied.push(key);
888
+ }
889
+ } catch (e) {
890
+ const err = (0, _errors.normalizeError)(e, from);
891
+ failed.push({
892
+ key,
893
+ error: err
894
+ });
895
+ options.onError?.(err);
896
+ // Aborting on the first bad key leaves the user half migrated with no
897
+ // record of how far it got, which is the worst of both outcomes.
898
+ if (!continueOnError) break;
899
+ }
900
+ onProgress?.(copied.length + skipped.length + failed.length, keys.length);
901
+ }
902
+ return {
903
+ copied,
904
+ skipped,
905
+ failed
906
+ };
907
+ },
908
+ flushOutbox: async () => {
909
+ // Two flushes at once - a reconnect and a foreground firing together -
910
+ // would each snapshot the queue and each re-send every entry in it.
911
+ if (flushing != null) return await flushing;
912
+ flushing = drain().finally(() => {
913
+ flushing = null;
914
+ });
915
+ return await flushing;
916
+ },
917
+ pendingWrites: () => readOutbox(),
918
+ discardPendingWrites: filter => {
919
+ const entries = readOutbox();
920
+ const kept = [];
921
+ const removed = [];
922
+ for (const entry of entries) if (filter == null || filter(entry)) removed.push(entry);else kept.push(entry);
923
+ if (removed.length === 0) return 0;
924
+ writeOutbox(kept);
925
+ for (const entry of removed) reportDropped(entry, 'discarded');
926
+ return removed.length;
927
+ },
928
+ registerProvider: provider => {
929
+ custom.set(provider.name, provider);
930
+ availability.delete(provider.name);
931
+ // A provider registered after the first subscription would otherwise
932
+ // never be listened to. Cheapest correct fix is to resubscribe.
933
+ if (providerSubscriptions != null) {
934
+ for (const un of providerSubscriptions) un();
935
+ providerSubscriptions = null;
936
+ if (remoteListeners.size > 0 || accountListeners.size > 0) ensureSubscribed();
937
+ }
938
+ },
939
+ onRemoteChange: listener => {
940
+ ensureSubscribed();
941
+ remoteListeners.add(listener);
942
+ return () => {
943
+ remoteListeners.delete(listener);
944
+ };
945
+ },
946
+ onAccountChange: listener => {
947
+ ensureSubscribed();
948
+ accountListeners.add(listener);
949
+ return () => {
950
+ accountListeners.delete(listener);
951
+ };
952
+ },
953
+ dispose: () => {
954
+ if (providerSubscriptions != null) for (const un of providerSubscriptions) un();
955
+ providerSubscriptions = null;
956
+ remoteListeners.clear();
957
+ accountListeners.clear();
958
+ detachAutoFlush?.();
959
+ detachAutoFlush = null;
960
+ }
961
+ };
962
+
963
+ // Attached last, so the store it flushes is fully built by the time the first
964
+ // foreground event or timer tick can reach it.
965
+ let detachAutoFlush = null;
966
+ if (options.autoFlush != null && options.autoFlush !== false) detachAutoFlush = (0, _autoFlush.attachAutoFlush)(() => store.flushOutbox(), options.autoFlush === true ? {} : options.autoFlush);
967
+ async function drain() {
968
+ const entries = readOutbox();
969
+ if (entries.length === 0) return {
970
+ drained: 0,
971
+ remaining: 0,
972
+ dropped: []
973
+ };
974
+ const now = Date.now();
975
+ const keep = [];
976
+ const dropped = [];
977
+ const handled = new Set();
978
+ let drained = 0;
979
+ function drop(entry, reason, error) {
980
+ dropped.push({
981
+ entry,
982
+ reason,
983
+ error
984
+ });
985
+ reportDropped(entry, reason, error);
986
+ }
987
+ for (const entry of entries) {
988
+ handled.add(outboxId(entry.provider, entry.key));
989
+ if (now - entry.enqueuedAt > maxAgeMs) {
990
+ drop(entry, 'expired');
991
+ continue;
992
+ }
993
+ if (entry.nextAttemptAt > now) {
994
+ keep.push(entry);
995
+ continue;
996
+ }
997
+ let p;
998
+ try {
999
+ p = resolveProvider(entry.provider);
1000
+ } catch (e) {
1001
+ // The provider it targeted is gone. Nothing will ever drain this.
1002
+ drop(entry, 'notRetryable', (0, _errors.normalizeError)(e, entry.provider));
1003
+ continue;
1004
+ }
1005
+ try {
1006
+ if (entry.value == null) await run(p, () => p.removeItem(entry.key));else await run(p, () => p.setItem(entry.key, entry.value));
1007
+ drained += 1;
1008
+ } catch (e) {
1009
+ const err = (0, _errors.normalizeError)(e, entry.provider);
1010
+ options.onError?.(err);
1011
+
1012
+ // A write only enters the queue for a retryable reason. If retrying it
1013
+ // now fails for one the user must act on - quota, signed out, a payload
1014
+ // the store will never accept - re-queueing turns it into a poison
1015
+ // entry that retries forever, never drains, and never surfaces.
1016
+ if (!(0, _errors.isRetryable)(err)) {
1017
+ drop(entry, 'notRetryable', err);
1018
+ continue;
1019
+ }
1020
+ const attempts = entry.attempts + 1;
1021
+ if (attempts >= maxAttempts) {
1022
+ drop({
1023
+ ...entry,
1024
+ attempts,
1025
+ lastErrorCode: err.code
1026
+ }, 'tooManyAttempts', err);
1027
+ continue;
1028
+ }
1029
+
1030
+ // Exponential backoff, honouring a server-supplied retry hint when
1031
+ // there is one (CloudKit sends `retryAfter`, Drive `Retry-After`).
1032
+ const backoff = err.retryAfterMs ?? Math.min(2 ** attempts * 1000, 5 * 60_000);
1033
+ keep.push({
1034
+ ...entry,
1035
+ attempts,
1036
+ nextAttemptAt: Date.now() + backoff,
1037
+ lastErrorCode: err.code
1038
+ });
1039
+ }
1040
+ }
1041
+
1042
+ // Merge rather than overwrite. A `setItem` that failed while this flush was
1043
+ // awaiting the network enqueued itself into storage; writing the snapshot
1044
+ // back wholesale would silently discard it.
1045
+ const arrived = readOutbox().filter(e => !handled.has(outboxId(e.provider, e.key)));
1046
+ writeOutbox([...keep, ...arrived]);
1047
+ return {
1048
+ drained,
1049
+ remaining: keep.length + arrived.length,
1050
+ dropped
1051
+ };
1052
+ }
1053
+ return store;
1054
+ }
1055
+ function createMemoryOutboxStorage() {
1056
+ const map = new Map();
1057
+ return {
1058
+ getString: k => map.get(k),
1059
+ set: (k, v) => {
1060
+ map.set(k, v);
1061
+ }
1062
+ };
1063
+ }
1064
+ //# sourceMappingURL=store.js.map