react-native-cloud-sync 0.3.0 → 0.5.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 (166) hide show
  1. package/README.md +116 -58
  2. package/ios/CloudSyncError.swift +21 -0
  3. package/ios/CloudSyncImpl.swift +515 -95
  4. package/ios/RNCloudSync.mm +73 -1
  5. package/jest-mock.js +1 -0
  6. package/lib/commonjs/hooks.js +309 -3
  7. package/lib/commonjs/hooks.js.map +1 -1
  8. package/lib/commonjs/internal/autoFlush.js +10 -1
  9. package/lib/commonjs/internal/autoFlush.js.map +1 -1
  10. package/lib/commonjs/internal/base64.js +25 -5
  11. package/lib/commonjs/internal/base64.js.map +1 -1
  12. package/lib/commonjs/internal/cloudKitRest.js +91 -15
  13. package/lib/commonjs/internal/cloudKitRest.js.map +1 -1
  14. package/lib/commonjs/internal/googleDriveRest.js +304 -38
  15. package/lib/commonjs/internal/googleDriveRest.js.map +1 -1
  16. package/lib/commonjs/internal/keys.js +34 -17
  17. package/lib/commonjs/internal/keys.js.map +1 -1
  18. package/lib/commonjs/internal/records.js +48 -0
  19. package/lib/commonjs/internal/records.js.map +1 -0
  20. package/lib/commonjs/providers/cloudKit.js +85 -17
  21. package/lib/commonjs/providers/cloudKit.js.map +1 -1
  22. package/lib/commonjs/providers/cloudKitEncrypted.js +30 -7
  23. package/lib/commonjs/providers/cloudKitEncrypted.js.map +1 -1
  24. package/lib/commonjs/providers/googleDrive.js +37 -2
  25. package/lib/commonjs/providers/googleDrive.js.map +1 -1
  26. package/lib/commonjs/providers/icloudDocuments.js +27 -0
  27. package/lib/commonjs/providers/icloudDocuments.js.map +1 -1
  28. package/lib/commonjs/providers/icloudKV.js +13 -3
  29. package/lib/commonjs/providers/icloudKV.js.map +1 -1
  30. package/lib/commonjs/providers/icloudKV.web.js +8 -1
  31. package/lib/commonjs/providers/icloudKV.web.js.map +1 -1
  32. package/lib/commonjs/providers/memory.js +10 -0
  33. package/lib/commonjs/providers/memory.js.map +1 -1
  34. package/lib/commonjs/resolvers.js +27 -13
  35. package/lib/commonjs/resolvers.js.map +1 -1
  36. package/lib/commonjs/specs/NativeRNCloudSync.js +3 -0
  37. package/lib/commonjs/specs/NativeRNCloudSync.js.map +1 -1
  38. package/lib/commonjs/store.js +360 -173
  39. package/lib/commonjs/store.js.map +1 -1
  40. package/lib/commonjs/types.js.map +1 -1
  41. package/lib/module/hooks.js +307 -3
  42. package/lib/module/hooks.js.map +1 -1
  43. package/lib/module/index.js +2 -2
  44. package/lib/module/internal/autoFlush.js +10 -1
  45. package/lib/module/internal/autoFlush.js.map +1 -1
  46. package/lib/module/internal/base64.js +25 -5
  47. package/lib/module/internal/base64.js.map +1 -1
  48. package/lib/module/internal/cloudKitRest.js +89 -13
  49. package/lib/module/internal/cloudKitRest.js.map +1 -1
  50. package/lib/module/internal/googleDriveRest.js +304 -38
  51. package/lib/module/internal/googleDriveRest.js.map +1 -1
  52. package/lib/module/internal/keys.js +33 -17
  53. package/lib/module/internal/keys.js.map +1 -1
  54. package/lib/module/internal/records.js +41 -0
  55. package/lib/module/internal/records.js.map +1 -0
  56. package/lib/module/providers/cloudKit.js +86 -18
  57. package/lib/module/providers/cloudKit.js.map +1 -1
  58. package/lib/module/providers/cloudKitEncrypted.js +31 -8
  59. package/lib/module/providers/cloudKitEncrypted.js.map +1 -1
  60. package/lib/module/providers/googleDrive.js +37 -2
  61. package/lib/module/providers/googleDrive.js.map +1 -1
  62. package/lib/module/providers/icloudDocuments.js +28 -1
  63. package/lib/module/providers/icloudDocuments.js.map +1 -1
  64. package/lib/module/providers/icloudKV.js +13 -3
  65. package/lib/module/providers/icloudKV.js.map +1 -1
  66. package/lib/module/providers/icloudKV.web.js +8 -1
  67. package/lib/module/providers/icloudKV.web.js.map +1 -1
  68. package/lib/module/providers/memory.js +10 -0
  69. package/lib/module/providers/memory.js.map +1 -1
  70. package/lib/module/resolvers.js +27 -12
  71. package/lib/module/resolvers.js.map +1 -1
  72. package/lib/module/specs/NativeRNCloudSync.js +4 -0
  73. package/lib/module/specs/NativeRNCloudSync.js.map +1 -1
  74. package/lib/module/store.js +360 -173
  75. package/lib/module/store.js.map +1 -1
  76. package/lib/module/types.js.map +1 -1
  77. package/lib/typescript/commonjs/errors.d.ts +16 -16
  78. package/lib/typescript/commonjs/errors.d.ts.map +1 -1
  79. package/lib/typescript/commonjs/hooks.d.ts +68 -0
  80. package/lib/typescript/commonjs/hooks.d.ts.map +1 -1
  81. package/lib/typescript/commonjs/index.d.ts +2 -2
  82. package/lib/typescript/commonjs/internal/autoFlush.d.ts.map +1 -1
  83. package/lib/typescript/commonjs/internal/base64.d.ts.map +1 -1
  84. package/lib/typescript/commonjs/internal/cloudKitRest.d.ts +20 -0
  85. package/lib/typescript/commonjs/internal/cloudKitRest.d.ts.map +1 -1
  86. package/lib/typescript/commonjs/internal/googleDriveRest.d.ts +19 -0
  87. package/lib/typescript/commonjs/internal/googleDriveRest.d.ts.map +1 -1
  88. package/lib/typescript/commonjs/internal/keys.d.ts +18 -3
  89. package/lib/typescript/commonjs/internal/keys.d.ts.map +1 -1
  90. package/lib/typescript/commonjs/internal/records.d.ts +24 -0
  91. package/lib/typescript/commonjs/internal/records.d.ts.map +1 -0
  92. package/lib/typescript/commonjs/providers/cloudKit.d.ts +1 -1
  93. package/lib/typescript/commonjs/providers/cloudKit.d.ts.map +1 -1
  94. package/lib/typescript/commonjs/providers/cloudKitBackup.d.ts +1 -1
  95. package/lib/typescript/commonjs/providers/cloudKitBackup.d.ts.map +1 -1
  96. package/lib/typescript/commonjs/providers/cloudKitEncrypted.d.ts.map +1 -1
  97. package/lib/typescript/commonjs/providers/googleDrive.d.ts.map +1 -1
  98. package/lib/typescript/commonjs/providers/googleDriveFiles.d.ts.map +1 -1
  99. package/lib/typescript/commonjs/providers/icloudDocuments.d.ts +1 -1
  100. package/lib/typescript/commonjs/providers/icloudDocuments.d.ts.map +1 -1
  101. package/lib/typescript/commonjs/providers/icloudKV.d.ts.map +1 -1
  102. package/lib/typescript/commonjs/providers/icloudKV.web.d.ts.map +1 -1
  103. package/lib/typescript/commonjs/providers/memory.d.ts.map +1 -1
  104. package/lib/typescript/commonjs/resolvers.d.ts +6 -3
  105. package/lib/typescript/commonjs/resolvers.d.ts.map +1 -1
  106. package/lib/typescript/commonjs/specs/NativeRNCloudSync.d.ts +12 -3
  107. package/lib/typescript/commonjs/specs/NativeRNCloudSync.d.ts.map +1 -1
  108. package/lib/typescript/commonjs/store.d.ts.map +1 -1
  109. package/lib/typescript/commonjs/types.d.ts +31 -3
  110. package/lib/typescript/commonjs/types.d.ts.map +1 -1
  111. package/lib/typescript/module/errors.d.ts +16 -16
  112. package/lib/typescript/module/errors.d.ts.map +1 -1
  113. package/lib/typescript/module/hooks.d.ts +68 -0
  114. package/lib/typescript/module/hooks.d.ts.map +1 -1
  115. package/lib/typescript/module/index.d.ts +2 -2
  116. package/lib/typescript/module/internal/autoFlush.d.ts.map +1 -1
  117. package/lib/typescript/module/internal/base64.d.ts.map +1 -1
  118. package/lib/typescript/module/internal/cloudKitRest.d.ts +20 -0
  119. package/lib/typescript/module/internal/cloudKitRest.d.ts.map +1 -1
  120. package/lib/typescript/module/internal/googleDriveRest.d.ts +19 -0
  121. package/lib/typescript/module/internal/googleDriveRest.d.ts.map +1 -1
  122. package/lib/typescript/module/internal/keys.d.ts +18 -3
  123. package/lib/typescript/module/internal/keys.d.ts.map +1 -1
  124. package/lib/typescript/module/internal/records.d.ts +24 -0
  125. package/lib/typescript/module/internal/records.d.ts.map +1 -0
  126. package/lib/typescript/module/providers/cloudKit.d.ts +1 -1
  127. package/lib/typescript/module/providers/cloudKit.d.ts.map +1 -1
  128. package/lib/typescript/module/providers/cloudKitBackup.d.ts +1 -1
  129. package/lib/typescript/module/providers/cloudKitBackup.d.ts.map +1 -1
  130. package/lib/typescript/module/providers/cloudKitEncrypted.d.ts.map +1 -1
  131. package/lib/typescript/module/providers/googleDrive.d.ts.map +1 -1
  132. package/lib/typescript/module/providers/googleDriveFiles.d.ts.map +1 -1
  133. package/lib/typescript/module/providers/icloudDocuments.d.ts +1 -1
  134. package/lib/typescript/module/providers/icloudDocuments.d.ts.map +1 -1
  135. package/lib/typescript/module/providers/icloudKV.d.ts.map +1 -1
  136. package/lib/typescript/module/providers/icloudKV.web.d.ts.map +1 -1
  137. package/lib/typescript/module/providers/memory.d.ts.map +1 -1
  138. package/lib/typescript/module/resolvers.d.ts +6 -3
  139. package/lib/typescript/module/resolvers.d.ts.map +1 -1
  140. package/lib/typescript/module/specs/NativeRNCloudSync.d.ts +12 -3
  141. package/lib/typescript/module/specs/NativeRNCloudSync.d.ts.map +1 -1
  142. package/lib/typescript/module/store.d.ts.map +1 -1
  143. package/lib/typescript/module/types.d.ts +31 -3
  144. package/lib/typescript/module/types.d.ts.map +1 -1
  145. package/package.json +36 -23
  146. package/plugin/build/index.js +45 -13
  147. package/react-native-cloud-sync.podspec +10 -3
  148. package/src/hooks.ts +357 -3
  149. package/src/index.ts +2 -2
  150. package/src/internal/autoFlush.ts +10 -1
  151. package/src/internal/base64.ts +26 -5
  152. package/src/internal/cloudKitRest.ts +103 -14
  153. package/src/internal/googleDriveRest.ts +338 -37
  154. package/src/internal/keys.ts +42 -16
  155. package/src/internal/records.ts +38 -0
  156. package/src/providers/cloudKit.ts +96 -20
  157. package/src/providers/cloudKitEncrypted.ts +37 -8
  158. package/src/providers/googleDrive.ts +38 -2
  159. package/src/providers/icloudDocuments.ts +40 -2
  160. package/src/providers/icloudKV.ts +13 -3
  161. package/src/providers/icloudKV.web.ts +8 -2
  162. package/src/providers/memory.ts +8 -0
  163. package/src/resolvers.ts +28 -13
  164. package/src/specs/NativeRNCloudSync.ts +16 -2
  165. package/src/store.ts +433 -190
  166. package/src/types.ts +32 -3
package/src/hooks.ts CHANGED
@@ -2,6 +2,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
2
2
 
3
3
  import type { CloudStore } from './store'
4
4
  import { normalizeError, type CloudSyncError } from './errors'
5
+ import { hasOwn, setOwn } from './internal/records'
5
6
  import type {
6
7
  AccountChangeEvent,
7
8
  AccountStatus,
@@ -123,9 +124,20 @@ export function useCloudItem<T = unknown>(
123
124
  }
124
125
  }, [store, key])
125
126
 
127
+ const initialRef = useRef(initialValue)
128
+ initialRef.current = initialValue
129
+ const loadedKey = useRef(key)
130
+
126
131
  useEffect(() => {
132
+ // A different key: the value on screen belongs to the previous one. Fall
133
+ // back to `initialValue` while the new key loads rather than showing the
134
+ // old key's value under the new key's name.
135
+ if (loadedKey.current !== key) {
136
+ loadedKey.current = key
137
+ setLocalValue(initialRef.current)
138
+ }
127
139
  void read()
128
- }, [read])
140
+ }, [read, key])
129
141
 
130
142
  useEffect(() => {
131
143
  if (!watch) return
@@ -144,7 +156,10 @@ export function useCloudItem<T = unknown>(
144
156
  // discard a value the outbox is still going to deliver.
145
157
  setLocalValue(next)
146
158
  // Invalidate any read in flight, so its older answer cannot land on top.
159
+ // That read's `finally` will no longer clear `loading`, so clear it here:
160
+ // the local value is now the current one.
147
161
  ticket.current += 1
162
+ setLoading(false)
148
163
  try {
149
164
  await store.setItem(key, serialize(next))
150
165
  if (mounted.current) setError(null)
@@ -158,6 +173,7 @@ export function useCloudItem<T = unknown>(
158
173
  const remove = useCallback(async (): Promise<void> => {
159
174
  setLocalValue(null)
160
175
  ticket.current += 1
176
+ setLoading(false)
161
177
  try {
162
178
  await store.removeItem(key)
163
179
  if (mounted.current) setError(null)
@@ -171,6 +187,338 @@ export function useCloudItem<T = unknown>(
171
187
  return { value, loading, error, setValue, remove, refresh: read }
172
188
  }
173
189
 
190
+ export interface UseCloudItemsResult<T> {
191
+ /**
192
+ * Parsed value per key. A key mapped to `null` was fetched and does not
193
+ * exist; a key absent from this object has not been fetched yet.
194
+ */
195
+ values: Record<string, T | null>
196
+ /** True only during the initial fetch of `keys`, and during an explicit `refresh()`. */
197
+ loading: boolean
198
+ /** The last read or write failure, or null. Cleared by the next success. */
199
+ error: CloudSyncError | null
200
+ /** Writes through to the store and updates local state optimistically. */
201
+ setValue: (key: string, next: T) => Promise<void>
202
+ remove: (key: string) => Promise<void>
203
+ /** Re-fetches every key currently tracked. */
204
+ refresh: () => Promise<void>
205
+ }
206
+
207
+ export interface UseCloudItemsOptions<T> {
208
+ parse?: (raw: string) => T
209
+ serialize?: (value: T) => string
210
+ /**
211
+ * Re-fetch a key when another device changes it. Default true.
212
+ *
213
+ * An event naming no keys (an account or quota event) re-fetches every
214
+ * tracked key, same as `useCloudItem`.
215
+ */
216
+ watch?: boolean
217
+ }
218
+
219
+ /**
220
+ * Binds a list of keys to component state with one batched `multiGet`.
221
+ *
222
+ * The multi-key sibling of `useCloudItem` - a screen with many cloud-backed
223
+ * records (a list, one key per item) otherwise ends up calling `useCloudItem`
224
+ * once per row: one `getItem` and one `onRemoteChange` subscription each,
225
+ * instead of a single batched read.
226
+ *
227
+ * Only ever fetches keys it does not already hold an answer for. Mount,
228
+ * `refresh()`, and a matching remote-change event all fetch normally, but a
229
+ * key merely joining the tracked list - because a caller like
230
+ * `useCloudCollection` just added it after a local write - is never
231
+ * re-fetched on that account alone, so a slow fetch elsewhere in the list
232
+ * can't land a stale value on top of a write that already resolved locally.
233
+ *
234
+ * ```tsx
235
+ * const { values, setValue } = useCloudItems<Note>(store, noteIds)
236
+ * ```
237
+ */
238
+ export function useCloudItems<T = unknown>(
239
+ store: CloudStore,
240
+ keys: string[],
241
+ options: UseCloudItemsOptions<T> = {}
242
+ ): UseCloudItemsResult<T> {
243
+ const {
244
+ parse = JSON.parse as (raw: string) => T,
245
+ serialize = JSON.stringify as (value: T) => string,
246
+ watch = true,
247
+ } = options
248
+
249
+ const [values, setValuesState] = useState<Record<string, T | null>>({})
250
+ const [loading, setLoading] = useState(true)
251
+ const [error, setError] = useState<CloudSyncError | null>(null)
252
+
253
+ const mounted = useRef(true)
254
+ useEffect(() => {
255
+ mounted.current = true
256
+ return () => {
257
+ mounted.current = false
258
+ }
259
+ }, [])
260
+
261
+ const parseRef = useRef(parse)
262
+ parseRef.current = parse
263
+
264
+ const keysRef = useRef(keys)
265
+ keysRef.current = keys
266
+ const keysSignature = JSON.stringify(keys)
267
+
268
+ // Latest values alongside the state, so effects can read "do we already
269
+ // have this key" without taking `values` itself as a dependency.
270
+ const valuesRef = useRef<Record<string, T | null>>(values)
271
+ const setValues = useCallback(
272
+ (updater: (prev: Record<string, T | null>) => Record<string, T | null>): void => {
273
+ setValuesState((prev) => {
274
+ const next = updater(prev)
275
+ valuesRef.current = next
276
+ return next
277
+ })
278
+ },
279
+ []
280
+ )
281
+
282
+ // Per-key ticket, not one shared counter: two fetches for disjoint keys
283
+ // run concurrently (an initial load still in flight plus a remote event for
284
+ // a key that just appeared), and a shared ticket would let the second
285
+ // invalidate the first's unrelated result.
286
+ const keyTicket = useRef<Map<string, number>>(new Map())
287
+ const bump = (key: string): number => {
288
+ const next = (keyTicket.current.get(key) ?? 0) + 1
289
+ keyTicket.current.set(key, next)
290
+ return next
291
+ }
292
+
293
+ const fetchKeys = useCallback(async (toFetch: string[]): Promise<void> => {
294
+ if (toFetch.length === 0) return
295
+ const mine = new Map(toFetch.map(k => [k, bump(k)]))
296
+
297
+ try {
298
+ const pairs = await store.multiGet(toFetch)
299
+ if (!mounted.current) return
300
+ setValues((prev) => {
301
+ const next = { ...prev }
302
+ for (const [k, raw] of pairs) {
303
+ // A write or a newer fetch already claimed this key - this answer
304
+ // is no longer the current one.
305
+ if (keyTicket.current.get(k) !== mine.get(k)) continue
306
+ // Left the tracked list while this fetch was in flight. Storing it
307
+ // would also mark it "already fetched", so if it rejoined later it
308
+ // would show this answer instead of being fetched again.
309
+ if (!keysRef.current.includes(k)) continue
310
+ setOwn(next, k, raw == null ? null : parseRef.current(raw))
311
+ }
312
+ return next
313
+ })
314
+ setError(null)
315
+ }
316
+ catch (e) {
317
+ if (!mounted.current) return
318
+ // Only surface the failure if at least one of these keys is still
319
+ // uncontested - a fetch overtaken by a write or another fetch failing
320
+ // is not new information.
321
+ const stillCurrent = toFetch.some(k => keyTicket.current.get(k) === mine.get(k))
322
+ if (stillCurrent) setError(normalizeError(e))
323
+ }
324
+ }, [store, setValues])
325
+
326
+ // Fetches keys new to the tracked list and drops values for keys no longer
327
+ // in it. Doubles as the initial load: on mount every key is "missing".
328
+ const hasLoadedOnce = useRef(false)
329
+ useEffect(() => {
330
+ const current = keysRef.current
331
+ // Own properties only: `in` also sees Object.prototype, so a key named
332
+ // `constructor` or `toString` was treated as already fetched and never
333
+ // loaded.
334
+ const missing = current.filter(k => !hasOwn(valuesRef.current, k))
335
+
336
+ const keep = new Set(current)
337
+ setValues((prev) => {
338
+ let changed = false
339
+ const next: Record<string, T | null> = {}
340
+ for (const k of Object.keys(prev))
341
+ if (keep.has(k)) setOwn(next, k, prev[k])
342
+ else changed = true
343
+
344
+ return changed ? next : prev
345
+ })
346
+
347
+ if (!hasLoadedOnce.current) {
348
+ hasLoadedOnce.current = true
349
+ setLoading(true)
350
+ void fetchKeys(missing).finally(() => {
351
+ if (mounted.current) setLoading(false)
352
+ })
353
+ }
354
+ else if (missing.length > 0) {
355
+ void fetchKeys(missing)
356
+ }
357
+ }, [keysSignature, fetchKeys, setValues])
358
+
359
+ useEffect(() => {
360
+ if (!watch) return
361
+ return store.onRemoteChange((e) => {
362
+ if (e.keys.length === 0) {
363
+ void fetchKeys(keysRef.current)
364
+ return
365
+ }
366
+ const intersecting = e.keys.filter(k => keysRef.current.includes(k))
367
+ if (intersecting.length > 0) void fetchKeys(intersecting)
368
+ })
369
+ }, [store, watch, fetchKeys])
370
+
371
+ const setValue = useCallback(async (key: string, next: T): Promise<void> => {
372
+ bump(key)
373
+ setValues(prev => ({ ...prev, [key]: next }))
374
+ try {
375
+ await store.setItem(key, serialize(next))
376
+ if (mounted.current) setError(null)
377
+ }
378
+ catch (e) {
379
+ if (mounted.current) setError(normalizeError(e))
380
+ throw e
381
+ }
382
+ }, [store, serialize, setValues])
383
+
384
+ const remove = useCallback(async (key: string): Promise<void> => {
385
+ bump(key)
386
+ setValues(prev => ({ ...prev, [key]: null }))
387
+ try {
388
+ await store.removeItem(key)
389
+ if (mounted.current) setError(null)
390
+ }
391
+ catch (e) {
392
+ if (mounted.current) setError(normalizeError(e))
393
+ throw e
394
+ }
395
+ }, [store, setValues])
396
+
397
+ const refresh = useCallback(async (): Promise<void> => {
398
+ setLoading(true)
399
+ try {
400
+ await fetchKeys(keysRef.current)
401
+ }
402
+ finally {
403
+ if (mounted.current) setLoading(false)
404
+ }
405
+ }, [fetchKeys])
406
+
407
+ return { values, loading, error, setValue, remove, refresh }
408
+ }
409
+
410
+ export interface UseCloudCollectionResult<T> extends UseCloudItemsResult<T> {
411
+ /** Keys currently in the collection. */
412
+ keys: string[]
413
+ }
414
+
415
+ /**
416
+ * Live-binds every key starting with `prefix` to component state.
417
+ *
418
+ * Adds the membership index `useCloudItems` needs but does not derive
419
+ * itself: `getAllKeys()` filtered by prefix on mount and after any remote
420
+ * change that could plausibly have added or removed a member, then
421
+ * `useCloudItems` for the values.
422
+ *
423
+ * A `setValue` for a key not seen before joins the collection immediately -
424
+ * a newly created record should appear in its own list without waiting on a
425
+ * round trip to confirm it.
426
+ *
427
+ * ```tsx
428
+ * const { keys, values, setValue, remove } = useCloudCollection<Note>(store, 'note:')
429
+ * ```
430
+ */
431
+ export function useCloudCollection<T = unknown>(
432
+ store: CloudStore,
433
+ prefix: string,
434
+ options: UseCloudItemsOptions<T> = {}
435
+ ): UseCloudCollectionResult<T> {
436
+ const { watch = true } = options
437
+
438
+ const [keys, setKeys] = useState<string[]>([])
439
+ const mounted = useRef(true)
440
+ useEffect(() => {
441
+ mounted.current = true
442
+ return () => {
443
+ mounted.current = false
444
+ }
445
+ }, [])
446
+
447
+ /**
448
+ * Local membership changes, in order, so a listing that was already in
449
+ * flight when one happened cannot undo it: a key created by `setValue`
450
+ * while `getAllKeys` was running would otherwise vanish from the list when
451
+ * the older listing landed, and a removed key would reappear.
452
+ */
453
+ const localOps = useRef<{ seq: number; key: string; op: 'add' | 'remove' }[]>([])
454
+ const opSeq = useRef(0)
455
+ const listTicket = useRef(0)
456
+
457
+ const recordOp = (key: string, op: 'add' | 'remove'): void => {
458
+ opSeq.current += 1
459
+ localOps.current.push({ seq: opSeq.current, key, op })
460
+ }
461
+
462
+ const listKeys = useCallback(async (): Promise<void> => {
463
+ const mine = ++listTicket.current
464
+ const startedAt = opSeq.current
465
+ const all = await store.getAllKeys()
466
+ // A newer listing started after this one; its answer is the fresher one.
467
+ if (!mounted.current || listTicket.current !== mine) return
468
+
469
+ const listed = new Set(all.filter(k => k.startsWith(prefix)))
470
+ for (const { seq, key, op } of localOps.current) {
471
+ if (seq <= startedAt) continue
472
+ if (op === 'add') listed.add(key)
473
+ else listed.delete(key)
474
+ }
475
+ // Everything up to this listing's start is reflected in what it saw.
476
+ localOps.current = localOps.current.filter(o => o.seq > startedAt)
477
+ setKeys([...listed])
478
+ }, [store, prefix])
479
+
480
+ useEffect(() => {
481
+ void listKeys()
482
+ }, [listKeys])
483
+
484
+ useEffect(() => {
485
+ if (!watch) return
486
+ return store.onRemoteChange((e) => {
487
+ // A prefix collection can gain or lose members on another device, not
488
+ // just change the value of one already in it - re-list on an opaque
489
+ // event too, not only one that names a key under this prefix.
490
+ if (e.keys.length > 0 && !e.keys.some(k => k.startsWith(prefix))) return
491
+ void listKeys()
492
+ })
493
+ }, [store, prefix, watch, listKeys])
494
+
495
+ const items = useCloudItems<T>(store, keys, options)
496
+
497
+ const setValue = useCallback(async (key: string, next: T): Promise<void> => {
498
+ if (key.startsWith(prefix)) {
499
+ recordOp(key, 'add')
500
+ setKeys(prev => (prev.includes(key) ? prev : [...prev, key]))
501
+ }
502
+ await items.setValue(key, next)
503
+ }, [items, prefix])
504
+
505
+ const remove = useCallback(async (key: string): Promise<void> => {
506
+ await items.remove(key)
507
+ recordOp(key, 'remove')
508
+ setKeys(prev => (prev.includes(key) ? prev.filter(k => k !== key) : prev))
509
+ }, [items])
510
+
511
+ const refresh = useCallback(async (): Promise<void> => {
512
+ // Concurrent, not sequential: a key that only `listKeys` turns up gets
513
+ // its value shortly after anyway, through the same membership-diff
514
+ // effect that handles a live remote event, so there is nothing to gain
515
+ // from waiting for the listing before starting `items.refresh()`.
516
+ await Promise.all([listKeys(), items.refresh()])
517
+ }, [listKeys, items])
518
+
519
+ return { ...items, setValue, remove, refresh, keys }
520
+ }
521
+
174
522
  export interface UseAccountStatusResult {
175
523
  status: AccountStatus | null
176
524
  /**
@@ -205,15 +553,20 @@ export function useAccountStatus(provider: CloudProvider): UseAccountStatusResul
205
553
  }
206
554
  }, [])
207
555
 
556
+ // Bumped by every refresh and every account event, so a status query that
557
+ // was in flight when an event arrived cannot overwrite the newer status.
558
+ const ticket = useRef(0)
559
+
208
560
  const refresh = useCallback(async (): Promise<void> => {
561
+ const mine = ++ticket.current
209
562
  try {
210
563
  const next = await provider.getAccountStatus()
211
- if (!mounted.current) return
564
+ if (!mounted.current || ticket.current !== mine) return
212
565
  setStatus(next)
213
566
  setError(null)
214
567
  }
215
568
  catch (e) {
216
- if (mounted.current) setError(normalizeError(e))
569
+ if (mounted.current && ticket.current === mine) setError(normalizeError(e))
217
570
  }
218
571
  }, [provider])
219
572
 
@@ -224,6 +577,7 @@ export function useAccountStatus(provider: CloudProvider): UseAccountStatusResul
224
577
  useEffect(() => {
225
578
  if (provider.onAccountChange == null) return
226
579
  return provider.onAccountChange((e: AccountChangeEvent) => {
580
+ ticket.current += 1
227
581
  setStatus(e.status)
228
582
  if (e.identityChanged) setIdentityChanged(true)
229
583
  })
package/src/index.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  /**
2
2
  * react-native-cloud-sync
3
3
  *
4
- * iCloud key-value store, CloudKit and Google Drive behind one API, on iOS,
5
- * Android and the web, on both React Native architectures.
4
+ * iCloud key-value store, CloudKit, iCloud Drive and Google Drive behind one API,
5
+ * on iOS, Android and the web, on both React Native architectures.
6
6
  */
7
7
 
8
8
  // Providers, each usable directly.
@@ -62,7 +62,16 @@ export function attachAutoFlush(
62
62
  let appStateSub: { remove: () => void } | null = null
63
63
 
64
64
  if (intervalMs > 0) {
65
- timer = setInterval(safeFlush, intervalMs)
65
+ // "While the app is in the foreground": a timer can still fire in the
66
+ // background (headless JS, a background fetch window), and a flush there
67
+ // spends the user's background budget on network nobody is waiting for.
68
+ // An unknown state is treated as foreground so the interval never
69
+ // silently stops working.
70
+ timer = setInterval(() => {
71
+ const state = AppState.currentState
72
+ if (state != null && state !== 'active' && state !== 'unknown') return
73
+ safeFlush()
74
+ }, intervalMs)
66
75
  // A pending retry must never be the reason a process stays alive.
67
76
  timer.unref?.()
68
77
  }
@@ -42,17 +42,20 @@ export function bytesToBase64(bytes: Uint8Array): string {
42
42
  export function base64ToBytes(base64: string): Uint8Array {
43
43
  // Strip whitespace some fs libraries insert into long base64 strings, and
44
44
  // any padding - length is derived from the real character count instead.
45
- const clean = base64.replace(/[\r\n\s]/g, '').replace(/=+$/, '')
45
+ const clean = base64.replace(/\s/g, '').replace(/={1,2}$/, '')
46
46
  const len = clean.length
47
+ // One leftover character carries 6 bits - not a byte. Real base64 never
48
+ // ends that way, so it is truncated or not base64 at all.
49
+ if (len % 4 === 1) throw invalidBase64()
47
50
  const outLen = Math.floor((len * 3) / 4)
48
51
  const bytes = new Uint8Array(outLen)
49
52
 
50
53
  let p = 0
51
54
  for (let i = 0; i < len; i += 4) {
52
- const e0 = DECODE_TABLE[clean.charCodeAt(i)] ?? -1
53
- const e1 = i + 1 < len ? DECODE_TABLE[clean.charCodeAt(i + 1)] ?? -1 : -1
54
- const e2 = i + 2 < len ? DECODE_TABLE[clean.charCodeAt(i + 2)] ?? -1 : -1
55
- const e3 = i + 3 < len ? DECODE_TABLE[clean.charCodeAt(i + 3)] ?? -1 : -1
55
+ const e0 = sextet(clean, i)
56
+ const e1 = i + 1 < len ? sextet(clean, i + 1) : 0
57
+ const e2 = i + 2 < len ? sextet(clean, i + 2) : 0
58
+ const e3 = i + 3 < len ? sextet(clean, i + 3) : 0
56
59
 
57
60
  if (p < outLen) bytes[p++] = (e0 << 2) | (e1 >> 4)
58
61
  if (p < outLen) bytes[p++] = ((e1 & 0x0f) << 4) | (e2 >> 2)
@@ -61,3 +64,21 @@ export function base64ToBytes(base64: string): Uint8Array {
61
64
 
62
65
  return bytes
63
66
  }
67
+
68
+ /**
69
+ * The 6-bit value at `i`, rejecting anything outside the alphabet.
70
+ *
71
+ * Silently mapping an invalid character to -1 used to write `0xFC`-style
72
+ * garbage into the output, so a corrupted or non-base64 chunk from a file
73
+ * adapter became a corrupted upload or restore with no error anywhere.
74
+ */
75
+ function sextet(s: string, i: number): number {
76
+ const code = s.charCodeAt(i)
77
+ const v = code < 128 ? DECODE_TABLE[code] : -1
78
+ if (v < 0) throw invalidBase64()
79
+ return v
80
+ }
81
+
82
+ function invalidBase64(): TypeError {
83
+ return new TypeError('[RNCloudSync] base64ToBytes: input is not valid base64.')
84
+ }