react-native-cloud-sync 0.2.0 → 0.4.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 (55) hide show
  1. package/README.md +120 -80
  2. package/lib/commonjs/config.js +11 -1
  3. package/lib/commonjs/config.js.map +1 -1
  4. package/lib/commonjs/hooks.js +242 -0
  5. package/lib/commonjs/hooks.js.map +1 -1
  6. package/lib/commonjs/index.js.map +1 -1
  7. package/lib/commonjs/internal/cloudKitRest.js +205 -21
  8. package/lib/commonjs/internal/cloudKitRest.js.map +1 -1
  9. package/lib/commonjs/internal/googleDriveRest.js +173 -38
  10. package/lib/commonjs/internal/googleDriveRest.js.map +1 -1
  11. package/lib/commonjs/providers/cloudKit.js +89 -19
  12. package/lib/commonjs/providers/cloudKit.js.map +1 -1
  13. package/lib/module/config.js +10 -1
  14. package/lib/module/config.js.map +1 -1
  15. package/lib/module/hooks.js +240 -0
  16. package/lib/module/hooks.js.map +1 -1
  17. package/lib/module/index.js +2 -2
  18. package/lib/module/index.js.map +1 -1
  19. package/lib/module/internal/cloudKitRest.js +205 -21
  20. package/lib/module/internal/cloudKitRest.js.map +1 -1
  21. package/lib/module/internal/googleDriveRest.js +174 -39
  22. package/lib/module/internal/googleDriveRest.js.map +1 -1
  23. package/lib/module/providers/cloudKit.js +92 -22
  24. package/lib/module/providers/cloudKit.js.map +1 -1
  25. package/lib/typescript/commonjs/config.d.ts +8 -0
  26. package/lib/typescript/commonjs/config.d.ts.map +1 -1
  27. package/lib/typescript/commonjs/hooks.d.ts +68 -0
  28. package/lib/typescript/commonjs/hooks.d.ts.map +1 -1
  29. package/lib/typescript/commonjs/index.d.ts +3 -3
  30. package/lib/typescript/commonjs/index.d.ts.map +1 -1
  31. package/lib/typescript/commonjs/internal/cloudKitRest.d.ts +90 -0
  32. package/lib/typescript/commonjs/internal/cloudKitRest.d.ts.map +1 -1
  33. package/lib/typescript/commonjs/internal/googleDriveRest.d.ts +73 -8
  34. package/lib/typescript/commonjs/internal/googleDriveRest.d.ts.map +1 -1
  35. package/lib/typescript/commonjs/providers/cloudKit.d.ts +32 -13
  36. package/lib/typescript/commonjs/providers/cloudKit.d.ts.map +1 -1
  37. package/lib/typescript/module/config.d.ts +8 -0
  38. package/lib/typescript/module/config.d.ts.map +1 -1
  39. package/lib/typescript/module/hooks.d.ts +68 -0
  40. package/lib/typescript/module/hooks.d.ts.map +1 -1
  41. package/lib/typescript/module/index.d.ts +3 -3
  42. package/lib/typescript/module/index.d.ts.map +1 -1
  43. package/lib/typescript/module/internal/cloudKitRest.d.ts +90 -0
  44. package/lib/typescript/module/internal/cloudKitRest.d.ts.map +1 -1
  45. package/lib/typescript/module/internal/googleDriveRest.d.ts +73 -8
  46. package/lib/typescript/module/internal/googleDriveRest.d.ts.map +1 -1
  47. package/lib/typescript/module/providers/cloudKit.d.ts +32 -13
  48. package/lib/typescript/module/providers/cloudKit.d.ts.map +1 -1
  49. package/package.json +5 -2
  50. package/src/config.ts +12 -2
  51. package/src/hooks.ts +294 -0
  52. package/src/index.ts +5 -3
  53. package/src/internal/cloudKitRest.ts +272 -29
  54. package/src/internal/googleDriveRest.ts +196 -42
  55. package/src/providers/cloudKit.ts +138 -41
@@ -26,11 +26,13 @@ export declare const zones: {
26
26
  /**
27
27
  * Binary assets (`CKAsset`).
28
28
  *
29
- * Native only. CloudKit Web Services does expose an asset upload flow, but it
30
- * is a separate multi-step protocol (request an upload URL, POST the bytes,
31
- * then reference the returned token in a record) that this package does not
32
- * implement yet - so on Android and web these reject with
33
- * `ERR_UNSUPPORTED_PLATFORM` rather than appearing to work.
29
+ * Native on iOS/macOS. On Android and web, `save`/`fetch` go through CloudKit
30
+ * Web Services' own asset-upload protocol (request a single-use upload URL,
31
+ * POST the bytes, attach the returned descriptor to the record) - see
32
+ * {@link MAX_ASSET_UPLOAD_BYTES} for the one hard limit that comes with it.
33
+ * Custom zones and the native temporary-directory fallback remain native-only
34
+ * (`ERR_UNSUPPORTED_PLATFORM`), since the REST client has no equivalent of
35
+ * either.
34
36
  *
35
37
  * Assets are deliberately an explicit API rather than something the store
36
38
  * facade routes to automatically: the caller passes a file path, not a string,
@@ -40,9 +42,12 @@ export declare const assets: {
40
42
  /**
41
43
  * Uploads a local file as a field on a record.
42
44
  *
43
- * Progress is reported per record through {@link onProgress}; a CKAsset is
44
- * streamed from disk, so a large file does not have to be held in memory the
45
- * way a base64 round trip would.
45
+ * Progress is reported per record through {@link onProgress}. Natively, a
46
+ * `CKAsset` is streamed from disk so a large file never has to be held in
47
+ * memory; over REST the whole file is read once, which is fine given
48
+ * {@link MAX_ASSET_UPLOAD_BYTES} - CloudKit Web Services itself caps a
49
+ * single asset upload at 15 MB, so nothing this package could stream would
50
+ * ever be large enough to need it.
46
51
  */
47
52
  save: (options: {
48
53
  recordName: string;
@@ -57,10 +62,12 @@ export declare const assets: {
57
62
  * record or field does not exist.
58
63
  *
59
64
  * Pass `destinationUri` for anything the user is going to keep or hand to a
60
- * share sheet. Without it the file lands in the app's temporary directory
61
- * under a name derived from the record, and iOS may reclaim that at any
62
- * time - fine for restoring straight back into the app, wrong for an export.
63
- * Parent directories are created if they do not exist.
65
+ * share sheet. Natively, without it the file lands in the app's temporary
66
+ * directory under a name derived from the record, and iOS may reclaim that
67
+ * at any time - fine for restoring straight back into the app, wrong for an
68
+ * export. Parent directories are created if they do not exist. Over REST,
69
+ * `destinationUri` is required: there is no OS-managed temporary directory
70
+ * this package can fall back to without a native module.
64
71
  */
65
72
  fetch: (options: {
66
73
  recordName: string;
@@ -75,12 +82,24 @@ export declare const assets: {
75
82
  * Identified by record and field rather than by a handle, because that is
76
83
  * what identifies a transfer everywhere else in this API - `onProgress`
77
84
  * reports the same pair, so a UI already has it.
85
+ *
86
+ * Native only, still - the REST transfer has no in-flight handle to cancel
87
+ * yet. Resolves `false` on Android/web rather than throwing, the same as
88
+ * before, so this is a known gap rather than a broken promise: a REST
89
+ * `save`/`fetch` cannot currently be stopped once started.
78
90
  */
79
91
  cancel: (options: {
80
92
  recordName: string;
81
93
  fieldName: string;
82
94
  }) => Promise<boolean>;
83
- /** Upload/download progress for asset transfers. Native only. */
95
+ /**
96
+ * Upload/download progress for asset transfers.
97
+ *
98
+ * Native on iOS/macOS, bridged from the same event every transfer already
99
+ * reports. On Android/web there is no native module to bridge, so this
100
+ * subscribes to the in-JS feed the REST `save`/`fetch` path publishes into
101
+ * instead - same event shape either way.
102
+ */
84
103
  onProgress: (listener: (e: AssetProgressEvent) => void) => Unsubscribe;
85
104
  };
86
105
  //# sourceMappingURL=cloudKit.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"cloudKit.d.ts","sourceRoot":"","sources":["../../../../src/providers/cloudKit.ts"],"names":[],"mappings":"AAIA,OAAO,EAAsB,KAAK,kBAAkB,EAAE,MAAM,6BAA0B,CAAA;AAGtF,OAAO,KAAK,EAGV,kBAAkB,EAClB,aAAa,EACb,YAAY,EACZ,WAAW,EACZ,MAAM,aAAU,CAAA;AAiCjB,eAAO,MAAM,QAAQ,EAAE,aAoMtB,CAAA;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,sBAAsB,CACpC,MAAM,EAAE,kBAAkB,GAAG;IAAE,IAAI,CAAC,EAAE,YAAY,CAAA;CAAE,GACnD,aAAa,CA8Ff;AAED,yEAAyE;AACzE,eAAO,MAAM,KAAK;uBACS,MAAM,KAAG,OAAO,CAAC,IAAI,CAAC;uBAQtB,MAAM,KAAG,OAAO,CAAC,IAAI,CAAC;gBAQ/B,OAAO,CAAC,MAAM,EAAE,CAAC;CAQlC,CAAA;AAED;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,MAAM;IACjB;;;;;;OAMG;oBAEQ;QACP,UAAU,EAAE,MAAM,CAAA;QAClB,SAAS,EAAE,MAAM,CAAA;QACjB,qCAAqC;QACrC,OAAO,EAAE,MAAM,CAAA;QACf,UAAU,CAAC,EAAE,MAAM,CAAA;QACnB,QAAQ,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;KACzB,KACA,OAAO,CAAC,IAAI,CAAC;IAsBhB;;;;;;;;;OASG;qBAEQ;QACP,UAAU,EAAE,MAAM,CAAA;QAClB,SAAS,EAAE,MAAM,CAAA;QACjB,QAAQ,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;QACxB,cAAc,CAAC,EAAE,MAAM,CAAA;KACxB,KACA,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC;IAoBzB;;;;;;;OAOG;sBAEQ;QAAE,UAAU,EAAE,MAAM,CAAC;QAAC,SAAS,EAAE,MAAM,CAAA;KAAE,KACjD,OAAO,CAAC,OAAO,CAAC;IAUnB,iEAAiE;2BAC1C,CAAC,CAAC,EAAE,kBAAkB,KAAK,IAAI,KAAG,WAAW;CAerE,CAAA"}
1
+ {"version":3,"file":"cloudKit.d.ts","sourceRoot":"","sources":["../../../../src/providers/cloudKit.ts"],"names":[],"mappings":"AAIA,OAAO,EAAsB,KAAK,kBAAkB,EAA0B,MAAM,6BAA0B,CAAA;AAI9G,OAAO,KAAK,EAGV,kBAAkB,EAClB,aAAa,EACb,YAAY,EACZ,WAAW,EACZ,MAAM,aAAU,CAAA;AAiCjB,eAAO,MAAM,QAAQ,EAAE,aAoMtB,CAAA;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,sBAAsB,CACpC,MAAM,EAAE,kBAAkB,GAAG;IAAE,IAAI,CAAC,EAAE,YAAY,CAAA;CAAE,GACnD,aAAa,CA8Ff;AAED,yEAAyE;AACzE,eAAO,MAAM,KAAK;uBACS,MAAM,KAAG,OAAO,CAAC,IAAI,CAAC;uBAQtB,MAAM,KAAG,OAAO,CAAC,IAAI,CAAC;gBAQ/B,OAAO,CAAC,MAAM,EAAE,CAAC;CAQlC,CAAA;AAaD;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,MAAM;IACjB;;;;;;;;;OASG;oBAEQ;QACP,UAAU,EAAE,MAAM,CAAA;QAClB,SAAS,EAAE,MAAM,CAAA;QACjB,qCAAqC;QACrC,OAAO,EAAE,MAAM,CAAA;QACf,UAAU,CAAC,EAAE,MAAM,CAAA;QACnB,QAAQ,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;KACzB,KACA,OAAO,CAAC,IAAI,CAAC;IA0DhB;;;;;;;;;;;OAWG;qBAEQ;QACP,UAAU,EAAE,MAAM,CAAA;QAClB,SAAS,EAAE,MAAM,CAAA;QACjB,QAAQ,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;QACxB,cAAc,CAAC,EAAE,MAAM,CAAA;KACxB,KACA,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC;IA+CzB;;;;;;;;;;;;OAYG;sBAEQ;QAAE,UAAU,EAAE,MAAM,CAAC;QAAC,SAAS,EAAE,MAAM,CAAA;KAAE,KACjD,OAAO,CAAC,OAAO,CAAC;IAUnB;;;;;;;OAOG;2BACoB,CAAC,CAAC,EAAE,kBAAkB,KAAK,IAAI,KAAG,WAAW;CAkBrE,CAAA"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "react-native-cloud-sync",
3
- "version": "0.2.0",
4
- "description": "Sync React Native app data across iCloud, CloudKit and Google Drive behind one API - offline-first with automatic retry, real-time updates and optional end-to-end encryption. iOS, Android, Web, old and new architecture",
3
+ "version": "0.4.0",
4
+ "description": "Sync React Native app data across iCloud key-value store, CloudKit, iCloud Drive and Google Drive behind one API - offline-first with automatic retry, real-time updates and optional end-to-end encryption. iOS, Android, Web, old and new architecture",
5
5
  "workspaces": [
6
6
  "example"
7
7
  ],
@@ -142,9 +142,11 @@
142
142
  "@react-native/jest-preset": "^0.86.2",
143
143
  "@react-native/metro-config": "^0.86.2",
144
144
  "@stylistic/eslint-plugin": "^5.10.0",
145
+ "@testing-library/react-native": "^13.3.3",
145
146
  "@types/jest": "^29.5.14",
146
147
  "@types/node": "^26.2.0",
147
148
  "@types/react": "^19.2.18",
149
+ "@types/react-test-renderer": "^19",
148
150
  "babel-jest": "^29.7.0",
149
151
  "del-cli": "^7.0.0",
150
152
  "eslint": "^10.8.0",
@@ -155,6 +157,7 @@
155
157
  "react": "19.2.3",
156
158
  "react-native": "0.86.2",
157
159
  "react-native-builder-bob": "^0.43.0",
160
+ "react-test-renderer": "19.2.3",
158
161
  "typescript": "^6.0.3",
159
162
  "typescript-eslint": "^8.66.0"
160
163
  },
package/src/config.ts CHANGED
@@ -74,14 +74,24 @@ export function getGoogleDriveFileAdapter(): GoogleDriveFileAdapter {
74
74
  if (driveFileAdapter == null)
75
75
  throw new CloudSyncError(
76
76
  ErrorCode.CONTAINER_MISCONFIGURED,
77
- '[RNCloudSync] googleDriveFiles needs a file adapter. Call configureGoogleDriveFiles({ '
78
- + 'statSize, readChunk, writeChunk, appendChunk }) before saving or fetching a file.',
77
+ '[RNCloudSync] This needs a file adapter. Call configureGoogleDriveFiles({ '
78
+ + 'statSize, readChunk, writeChunk, appendChunk }) before saving or fetching a file - shared '
79
+ + 'by googleDriveFiles and by cloudKitAssets on Android/web.',
79
80
  { provider: 'googleDrive' }
80
81
  )
81
82
 
82
83
  return driveFileAdapter
83
84
  }
84
85
 
86
+ /**
87
+ * Same adapter and same `configureGoogleDriveFiles` call, under a name that
88
+ * doesn't imply it's Drive-specific. `cloudKitAssets`'s REST path (Android/web)
89
+ * reads and writes local files the exact same way `googleDriveFiles` does, and
90
+ * asking a host app to register two near-identical adapters for that would be
91
+ * pure friction for no benefit.
92
+ */
93
+ export const getSharedFileAdapter = getGoogleDriveFileAdapter
94
+
85
95
  export function isGoogleDriveFilesConfigured(): boolean {
86
96
  return driveFileAdapter != null
87
97
  }
package/src/hooks.ts CHANGED
@@ -171,6 +171,300 @@ export function useCloudItem<T = unknown>(
171
171
  return { value, loading, error, setValue, remove, refresh: read }
172
172
  }
173
173
 
174
+ export interface UseCloudItemsResult<T> {
175
+ /**
176
+ * Parsed value per key. A key mapped to `null` was fetched and does not
177
+ * exist; a key absent from this object has not been fetched yet.
178
+ */
179
+ values: Record<string, T | null>
180
+ /** True only during the initial fetch of `keys`, and during an explicit `refresh()`. */
181
+ loading: boolean
182
+ /** The last read or write failure, or null. Cleared by the next success. */
183
+ error: CloudSyncError | null
184
+ /** Writes through to the store and updates local state optimistically. */
185
+ setValue: (key: string, next: T) => Promise<void>
186
+ remove: (key: string) => Promise<void>
187
+ /** Re-fetches every key currently tracked. */
188
+ refresh: () => Promise<void>
189
+ }
190
+
191
+ export interface UseCloudItemsOptions<T> {
192
+ parse?: (raw: string) => T
193
+ serialize?: (value: T) => string
194
+ /**
195
+ * Re-fetch a key when another device changes it. Default true.
196
+ *
197
+ * An event naming no keys (an account or quota event) re-fetches every
198
+ * tracked key, same as `useCloudItem`.
199
+ */
200
+ watch?: boolean
201
+ }
202
+
203
+ /**
204
+ * Binds a list of keys to component state with one batched `multiGet`.
205
+ *
206
+ * The multi-key sibling of `useCloudItem` - a screen with many cloud-backed
207
+ * records (a list, one key per item) otherwise ends up calling `useCloudItem`
208
+ * once per row: one `getItem` and one `onRemoteChange` subscription each,
209
+ * instead of a single batched read.
210
+ *
211
+ * Only ever fetches keys it does not already hold an answer for. Mount,
212
+ * `refresh()`, and a matching remote-change event all fetch normally, but a
213
+ * key merely joining the tracked list - because a caller like
214
+ * `useCloudCollection` just added it after a local write - is never
215
+ * re-fetched on that account alone, so a slow fetch elsewhere in the list
216
+ * can't land a stale value on top of a write that already resolved locally.
217
+ *
218
+ * ```tsx
219
+ * const { values, setValue } = useCloudItems<Note>(store, noteIds)
220
+ * ```
221
+ */
222
+ export function useCloudItems<T = unknown>(
223
+ store: CloudStore,
224
+ keys: string[],
225
+ options: UseCloudItemsOptions<T> = {}
226
+ ): UseCloudItemsResult<T> {
227
+ const {
228
+ parse = JSON.parse as (raw: string) => T,
229
+ serialize = JSON.stringify as (value: T) => string,
230
+ watch = true,
231
+ } = options
232
+
233
+ const [values, setValuesState] = useState<Record<string, T | null>>({})
234
+ const [loading, setLoading] = useState(true)
235
+ const [error, setError] = useState<CloudSyncError | null>(null)
236
+
237
+ const mounted = useRef(true)
238
+ useEffect(() => {
239
+ mounted.current = true
240
+ return () => {
241
+ mounted.current = false
242
+ }
243
+ }, [])
244
+
245
+ const parseRef = useRef(parse)
246
+ parseRef.current = parse
247
+
248
+ const keysRef = useRef(keys)
249
+ keysRef.current = keys
250
+ const keysSignature = JSON.stringify(keys)
251
+
252
+ // Latest values alongside the state, so effects can read "do we already
253
+ // have this key" without taking `values` itself as a dependency.
254
+ const valuesRef = useRef<Record<string, T | null>>(values)
255
+ const setValues = useCallback(
256
+ (updater: (prev: Record<string, T | null>) => Record<string, T | null>): void => {
257
+ setValuesState((prev) => {
258
+ const next = updater(prev)
259
+ valuesRef.current = next
260
+ return next
261
+ })
262
+ },
263
+ []
264
+ )
265
+
266
+ // Per-key ticket, not one shared counter: two fetches for disjoint keys
267
+ // run concurrently (an initial load still in flight plus a remote event for
268
+ // a key that just appeared), and a shared ticket would let the second
269
+ // invalidate the first's unrelated result.
270
+ const keyTicket = useRef<Map<string, number>>(new Map())
271
+ const bump = (key: string): number => {
272
+ const next = (keyTicket.current.get(key) ?? 0) + 1
273
+ keyTicket.current.set(key, next)
274
+ return next
275
+ }
276
+
277
+ const fetchKeys = useCallback(async (toFetch: string[]): Promise<void> => {
278
+ if (toFetch.length === 0) return
279
+ const mine = new Map(toFetch.map(k => [k, bump(k)]))
280
+
281
+ try {
282
+ const pairs = await store.multiGet(toFetch)
283
+ if (!mounted.current) return
284
+ setValues((prev) => {
285
+ const next = { ...prev }
286
+ for (const [k, raw] of pairs) {
287
+ // A write or a newer fetch already claimed this key - this answer
288
+ // is no longer the current one.
289
+ if (keyTicket.current.get(k) !== mine.get(k)) continue
290
+ next[k] = raw == null ? null : parseRef.current(raw)
291
+ }
292
+ return next
293
+ })
294
+ setError(null)
295
+ }
296
+ catch (e) {
297
+ if (!mounted.current) return
298
+ // Only surface the failure if at least one of these keys is still
299
+ // uncontested - a fetch overtaken by a write or another fetch failing
300
+ // is not new information.
301
+ const stillCurrent = toFetch.some(k => keyTicket.current.get(k) === mine.get(k))
302
+ if (stillCurrent) setError(normalizeError(e))
303
+ }
304
+ }, [store, setValues])
305
+
306
+ // Fetches keys new to the tracked list and drops values for keys no longer
307
+ // in it. Doubles as the initial load: on mount every key is "missing".
308
+ const hasLoadedOnce = useRef(false)
309
+ useEffect(() => {
310
+ const current = keysRef.current
311
+ const missing = current.filter(k => !(k in valuesRef.current))
312
+
313
+ const keep = new Set(current)
314
+ setValues((prev) => {
315
+ let changed = false
316
+ const next: Record<string, T | null> = {}
317
+ for (const k of Object.keys(prev))
318
+ if (keep.has(k)) next[k] = prev[k]
319
+ else changed = true
320
+
321
+ return changed ? next : prev
322
+ })
323
+
324
+ if (!hasLoadedOnce.current) {
325
+ hasLoadedOnce.current = true
326
+ setLoading(true)
327
+ void fetchKeys(missing).finally(() => {
328
+ if (mounted.current) setLoading(false)
329
+ })
330
+ }
331
+ else if (missing.length > 0) {
332
+ void fetchKeys(missing)
333
+ }
334
+ }, [keysSignature, fetchKeys, setValues])
335
+
336
+ useEffect(() => {
337
+ if (!watch) return
338
+ return store.onRemoteChange((e) => {
339
+ if (e.keys.length === 0) {
340
+ void fetchKeys(keysRef.current)
341
+ return
342
+ }
343
+ const intersecting = e.keys.filter(k => keysRef.current.includes(k))
344
+ if (intersecting.length > 0) void fetchKeys(intersecting)
345
+ })
346
+ }, [store, watch, fetchKeys])
347
+
348
+ const setValue = useCallback(async (key: string, next: T): Promise<void> => {
349
+ bump(key)
350
+ setValues(prev => ({ ...prev, [key]: next }))
351
+ try {
352
+ await store.setItem(key, serialize(next))
353
+ if (mounted.current) setError(null)
354
+ }
355
+ catch (e) {
356
+ if (mounted.current) setError(normalizeError(e))
357
+ throw e
358
+ }
359
+ }, [store, serialize, setValues])
360
+
361
+ const remove = useCallback(async (key: string): Promise<void> => {
362
+ bump(key)
363
+ setValues(prev => ({ ...prev, [key]: null }))
364
+ try {
365
+ await store.removeItem(key)
366
+ if (mounted.current) setError(null)
367
+ }
368
+ catch (e) {
369
+ if (mounted.current) setError(normalizeError(e))
370
+ throw e
371
+ }
372
+ }, [store, setValues])
373
+
374
+ const refresh = useCallback(async (): Promise<void> => {
375
+ setLoading(true)
376
+ try {
377
+ await fetchKeys(keysRef.current)
378
+ }
379
+ finally {
380
+ if (mounted.current) setLoading(false)
381
+ }
382
+ }, [fetchKeys])
383
+
384
+ return { values, loading, error, setValue, remove, refresh }
385
+ }
386
+
387
+ export interface UseCloudCollectionResult<T> extends UseCloudItemsResult<T> {
388
+ /** Keys currently in the collection. */
389
+ keys: string[]
390
+ }
391
+
392
+ /**
393
+ * Live-binds every key starting with `prefix` to component state.
394
+ *
395
+ * Adds the membership index `useCloudItems` needs but does not derive
396
+ * itself: `getAllKeys()` filtered by prefix on mount and after any remote
397
+ * change that could plausibly have added or removed a member, then
398
+ * `useCloudItems` for the values.
399
+ *
400
+ * A `setValue` for a key not seen before joins the collection immediately -
401
+ * a newly created record should appear in its own list without waiting on a
402
+ * round trip to confirm it.
403
+ *
404
+ * ```tsx
405
+ * const { keys, values, setValue, remove } = useCloudCollection<Note>(store, 'note:')
406
+ * ```
407
+ */
408
+ export function useCloudCollection<T = unknown>(
409
+ store: CloudStore,
410
+ prefix: string,
411
+ options: UseCloudItemsOptions<T> = {}
412
+ ): UseCloudCollectionResult<T> {
413
+ const { watch = true } = options
414
+
415
+ const [keys, setKeys] = useState<string[]>([])
416
+ const mounted = useRef(true)
417
+ useEffect(() => {
418
+ mounted.current = true
419
+ return () => {
420
+ mounted.current = false
421
+ }
422
+ }, [])
423
+
424
+ const listKeys = useCallback(async (): Promise<void> => {
425
+ const all = await store.getAllKeys()
426
+ if (!mounted.current) return
427
+ setKeys(all.filter(k => k.startsWith(prefix)))
428
+ }, [store, prefix])
429
+
430
+ useEffect(() => {
431
+ void listKeys()
432
+ }, [listKeys])
433
+
434
+ useEffect(() => {
435
+ if (!watch) return
436
+ return store.onRemoteChange((e) => {
437
+ // A prefix collection can gain or lose members on another device, not
438
+ // just change the value of one already in it - re-list on an opaque
439
+ // event too, not only one that names a key under this prefix.
440
+ if (e.keys.length > 0 && !e.keys.some(k => k.startsWith(prefix))) return
441
+ void listKeys()
442
+ })
443
+ }, [store, prefix, watch, listKeys])
444
+
445
+ const items = useCloudItems<T>(store, keys, options)
446
+
447
+ const setValue = useCallback(async (key: string, next: T): Promise<void> => {
448
+ if (key.startsWith(prefix)) setKeys(prev => (prev.includes(key) ? prev : [...prev, key]))
449
+ await items.setValue(key, next)
450
+ }, [items, prefix])
451
+
452
+ const remove = useCallback(async (key: string): Promise<void> => {
453
+ await items.remove(key)
454
+ setKeys(prev => (prev.includes(key) ? prev.filter(k => k !== key) : prev))
455
+ }, [items])
456
+
457
+ const refresh = useCallback(async (): Promise<void> => {
458
+ // Concurrent, not sequential: a key that only `listKeys` turns up gets
459
+ // its value shortly after anyway, through the same membership-diff
460
+ // effect that handles a live remote event, so there is nothing to gain
461
+ // from waiting for the listing before starting `items.refresh()`.
462
+ await Promise.all([listKeys(), items.refresh()])
463
+ }, [listKeys, items])
464
+
465
+ return { ...items, setValue, remove, refresh, keys }
466
+ }
467
+
174
468
  export interface UseAccountStatusResult {
175
469
  status: AccountStatus | null
176
470
  /**
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.
@@ -63,7 +63,9 @@ export {
63
63
  } from './config'
64
64
 
65
65
  export type { CloudKitRestConfig } from './internal/cloudKitRest'
66
- export type { GoogleDriveConfig, GoogleDriveFileAdapter } from './internal/googleDriveRest'
66
+ export type {
67
+ GoogleDriveConfig, GoogleDriveFileAdapter, GoogleDriveSessionStore, GoogleDriveUploadSession
68
+ } from './internal/googleDriveRest'
67
69
 
68
70
  // The `GoogleDriveFileAdapter` contract is base64 in and base64 out, while every
69
71
  // modern filesystem API is byte-oriented - so the codec that bridges them ships