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
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Writes `key` as an own, enumerable data property of `target`.
3
+ *
4
+ * A plain `target[key] = value` goes through the `__proto__` accessor when the
5
+ * key is literally `"__proto__"`: an object value silently becomes the
6
+ * record's prototype (so every other lookup on it starts answering from data a
7
+ * remote device wrote) and a string value is dropped. Keys here come from
8
+ * listings and from app-supplied key lists, so neither outcome is acceptable.
9
+ */
10
+ export function setOwn<T>(target: Record<string, T>, key: string, value: T): void {
11
+ Object.defineProperty(target, key, {
12
+ value,
13
+ enumerable: true,
14
+ writable: true,
15
+ configurable: true,
16
+ })
17
+ }
18
+
19
+ /** `Object.hasOwn`, which Hermes and older JSC do not all ship. */
20
+ export function hasOwn(target: object, key: string): boolean {
21
+ return Object.prototype.hasOwnProperty.call(target, key)
22
+ }
23
+
24
+ /**
25
+ * Upper bound on any server-supplied retry delay.
26
+ *
27
+ * `Retry-After` and CloudKit's `retryAfter` are honoured, but not blindly: a
28
+ * huge value (or a hostile/broken proxy in front of the API) would otherwise
29
+ * park a queued write until it expired, and a negative one would retry in a
30
+ * tight loop.
31
+ */
32
+ export const MAX_RETRY_AFTER_MS = 60 * 60 * 1000
33
+
34
+ /** A server retry hint in ms, clamped to `[0, MAX_RETRY_AFTER_MS]`, or undefined. */
35
+ export function clampRetryAfterMs(ms: number | undefined): number | undefined {
36
+ if (ms == null || !Number.isFinite(ms)) return undefined
37
+ return Math.min(Math.max(ms, 0), MAX_RETRY_AFTER_MS)
38
+ }
@@ -2,7 +2,9 @@ import { Platform } from 'react-native'
2
2
 
3
3
  import { getNativeModule, hasNativeModule, requireNativeModule, subscribeNativeEvent } from '../internal/nativeModule'
4
4
  import { getCloudKitClient, getSharedFileAdapter, isCloudKitConfigured } from '../config'
5
- import { CloudKitRestClient, type CloudKitRestConfig, MAX_ASSET_UPLOAD_BYTES } from '../internal/cloudKitRest'
5
+ import {
6
+ CloudKitRestClient, type CloudKitRestConfig, ENCRYPTED_RECORD_PREFIX, MAX_ASSET_UPLOAD_BYTES,
7
+ } from '../internal/cloudKitRest'
6
8
  import { CloudSyncError, ErrorCode, normalizeError, unsupportedPlatform } from '../errors'
7
9
  import { toAccountStatus } from '../internal/enums'
8
10
  import { base64ToBytes, bytesToBase64 } from '../internal/base64'
@@ -46,6 +48,28 @@ function isNative(): boolean {
46
48
  return (os === 'ios' || os === 'macos') && hasNativeModule()
47
49
  }
48
50
 
51
+ /**
52
+ * Rejects a key in `cloudKitEncrypted`'s record-name namespace.
53
+ *
54
+ * Both providers share one zone, and CloudKit record names are unique across
55
+ * record types, so a plain key spelled like an encrypted record name would
56
+ * address - and could delete - the encrypted provider's record.
57
+ */
58
+ function assertPlainKey(key: string, provider: string): void {
59
+ if (key.startsWith(ENCRYPTED_RECORD_PREFIX))
60
+ throw new CloudSyncError(
61
+ ErrorCode.INVALID_KEY,
62
+ `[RNCloudSync] '${key}' starts with '${ENCRYPTED_RECORD_PREFIX}', which is reserved for `
63
+ + `cloudKitEncrypted's record names.`,
64
+ { provider }
65
+ )
66
+ }
67
+
68
+ /** Drops record names in `cloudKitEncrypted`'s namespace from a listing. */
69
+ function plainKeys(names: string[]): string[] {
70
+ return names.filter(n => !n.startsWith(ENCRYPTED_RECORD_PREFIX))
71
+ }
72
+
49
73
  export const cloudKit: CloudProvider = {
50
74
  name: NAME,
51
75
 
@@ -84,6 +108,7 @@ export const cloudKit: CloudProvider = {
84
108
  },
85
109
 
86
110
  getItem: async (key: string) => {
111
+ assertPlainKey(key, NAME)
87
112
  try {
88
113
  if (isNative()) return await requireNativeModule().ckGetRecord('KVBlob', key, null, false)
89
114
  return await getCloudKitClient().getRecord(key)
@@ -103,6 +128,7 @@ export const cloudKit: CloudProvider = {
103
128
  * {@link resolveByModifiedAt} is built to handle.
104
129
  */
105
130
  getItemWithMeta: async (key: string) => {
131
+ assertPlainKey(key, NAME)
106
132
  if (isNative()) {
107
133
  const value = await cloudKit.getItem(key)
108
134
  return value == null ? null : { value }
@@ -122,13 +148,14 @@ export const cloudKit: CloudProvider = {
122
148
  * round trip and N - and between one rate-limit budget and N.
123
149
  */
124
150
  multiGet: async (keys: string[]) => {
125
- if (isNative()) {
126
- const out: (string | null)[] = []
127
- for (const key of keys)
128
- out.push(await requireNativeModule().ckGetRecord('KVBlob', key, null, false))
129
- return out
130
- }
151
+ for (const key of keys) assertPlainKey(key, NAME)
131
152
  try {
153
+ if (isNative()) {
154
+ const out: (string | null)[] = []
155
+ for (const key of keys)
156
+ out.push(await requireNativeModule().ckGetRecord('KVBlob', key, null, false))
157
+ return out
158
+ }
132
159
  return await getCloudKitClient().getRecords(keys)
133
160
  }
134
161
  catch (e) {
@@ -136,13 +163,38 @@ export const cloudKit: CloudProvider = {
136
163
  }
137
164
  },
138
165
 
139
- multiSet: async (entries: [string, string][]) => {
140
- if (isNative()) {
141
- for (const [key, value] of entries)
142
- await requireNativeModule().ckSaveRecord('KVBlob', key, value, null, false)
143
- return
166
+ /**
167
+ * Values plus server modification times, in one `/records/lookup` per 200
168
+ * keys over REST. Natively there is no timestamp to report (the bridge
169
+ * returns values only - see {@link getItemWithMeta}), so this is `multiGet`
170
+ * with `modifiedAt` left undefined, which the resolver handles.
171
+ */
172
+ multiGetWithMeta: async (keys: string[]) => {
173
+ for (const key of keys) assertPlainKey(key, NAME)
174
+ try {
175
+ if (isNative()) {
176
+ const out: ({ value: string } | null)[] = []
177
+ for (const key of keys) {
178
+ const value = await requireNativeModule().ckGetRecord('KVBlob', key, null, false)
179
+ out.push(value == null ? null : { value })
180
+ }
181
+ return out
182
+ }
183
+ return await getCloudKitClient().getRecordsWithMeta(keys)
144
184
  }
185
+ catch (e) {
186
+ throw normalizeError(e, NAME)
187
+ }
188
+ },
189
+
190
+ multiSet: async (entries: [string, string][]) => {
191
+ for (const [key] of entries) assertPlainKey(key, NAME)
145
192
  try {
193
+ if (isNative()) {
194
+ for (const [key, value] of entries)
195
+ await requireNativeModule().ckSaveRecord('KVBlob', key, value, null, false)
196
+ return
197
+ }
146
198
  await getCloudKitClient().saveRecords(entries)
147
199
  }
148
200
  catch (e) {
@@ -151,11 +203,12 @@ export const cloudKit: CloudProvider = {
151
203
  },
152
204
 
153
205
  multiRemove: async (keys: string[]) => {
154
- if (isNative()) {
155
- for (const key of keys) await requireNativeModule().ckDeleteRecord(key, null)
156
- return
157
- }
206
+ for (const key of keys) assertPlainKey(key, NAME)
158
207
  try {
208
+ if (isNative()) {
209
+ for (const key of keys) await requireNativeModule().ckDeleteRecord(key, null)
210
+ return
211
+ }
159
212
  await getCloudKitClient().deleteRecords(keys)
160
213
  }
161
214
  catch (e) {
@@ -170,6 +223,7 @@ export const cloudKit: CloudProvider = {
170
223
  },
171
224
 
172
225
  setItem: async (key: string, value: string) => {
226
+ assertPlainKey(key, NAME)
173
227
  try {
174
228
  if (isNative()) {
175
229
  await requireNativeModule().ckSaveRecord('KVBlob', key, value, null, false)
@@ -183,6 +237,7 @@ export const cloudKit: CloudProvider = {
183
237
  },
184
238
 
185
239
  removeItem: async (key: string) => {
240
+ assertPlainKey(key, NAME)
186
241
  try {
187
242
  if (isNative()) {
188
243
  await requireNativeModule().ckDeleteRecord(key, null)
@@ -197,8 +252,8 @@ export const cloudKit: CloudProvider = {
197
252
 
198
253
  getAllKeys: async () => {
199
254
  try {
200
- if (isNative()) return await requireNativeModule().ckQueryRecordNames('KVBlob', null)
201
- return await getCloudKitClient().queryRecordNames()
255
+ if (isNative()) return plainKeys(await requireNativeModule().ckQueryRecordNames('KVBlob', null))
256
+ return plainKeys(await getCloudKitClient().queryRecordNames())
202
257
  }
203
258
  catch (e) {
204
259
  throw normalizeError(e, NAME)
@@ -278,6 +333,7 @@ export function createCloudKitProvider(
278
333
  getAccountStatus: () => Promise.resolve<AccountStatus>('available'),
279
334
 
280
335
  getItem: async (key: string) => {
336
+ assertPlainKey(key, name)
281
337
  try {
282
338
  return await client.getRecord(key)
283
339
  }
@@ -287,6 +343,7 @@ export function createCloudKitProvider(
287
343
  },
288
344
 
289
345
  getItemWithMeta: async (key: string) => {
346
+ assertPlainKey(key, name)
290
347
  try {
291
348
  return await client.getRecordWithMeta(key)
292
349
  }
@@ -296,6 +353,7 @@ export function createCloudKitProvider(
296
353
  },
297
354
 
298
355
  setItem: async (key: string, value: string) => {
356
+ assertPlainKey(key, name)
299
357
  try {
300
358
  await client.saveRecord(key, value)
301
359
  }
@@ -305,6 +363,7 @@ export function createCloudKitProvider(
305
363
  },
306
364
 
307
365
  removeItem: async (key: string) => {
366
+ assertPlainKey(key, name)
308
367
  try {
309
368
  await client.deleteRecord(key)
310
369
  }
@@ -315,7 +374,7 @@ export function createCloudKitProvider(
315
374
 
316
375
  getAllKeys: async () => {
317
376
  try {
318
- return await client.queryRecordNames()
377
+ return plainKeys(await client.queryRecordNames())
319
378
  }
320
379
  catch (e) {
321
380
  throw normalizeError(e, name)
@@ -323,6 +382,7 @@ export function createCloudKitProvider(
323
382
  },
324
383
 
325
384
  multiGet: async (keys: string[]) => {
385
+ for (const key of keys) assertPlainKey(key, name)
326
386
  try {
327
387
  return await client.getRecords(keys)
328
388
  }
@@ -331,7 +391,18 @@ export function createCloudKitProvider(
331
391
  }
332
392
  },
333
393
 
394
+ multiGetWithMeta: async (keys: string[]) => {
395
+ for (const key of keys) assertPlainKey(key, name)
396
+ try {
397
+ return await client.getRecordsWithMeta(keys)
398
+ }
399
+ catch (e) {
400
+ throw normalizeError(e, name)
401
+ }
402
+ },
403
+
334
404
  multiSet: async (entries: [string, string][]) => {
405
+ for (const [key] of entries) assertPlainKey(key, name)
335
406
  try {
336
407
  await client.saveRecords(entries)
337
408
  }
@@ -341,6 +412,7 @@ export function createCloudKitProvider(
341
412
  },
342
413
 
343
414
  multiRemove: async (keys: string[]) => {
415
+ for (const key of keys) assertPlainKey(key, name)
344
416
  try {
345
417
  await client.deleteRecords(keys)
346
418
  }
@@ -430,6 +502,9 @@ export const assets = {
430
502
  zoneName?: string | null
431
503
  }
432
504
  ): Promise<void> => {
505
+ // Same namespace rule as the key-value methods: an asset write must not be
506
+ // able to address - and overwrite - a cloudKitEncrypted record.
507
+ assertPlainKey(options.recordName, NAME)
433
508
  if (isNative()) {
434
509
  try {
435
510
  await requireNativeModule().ckSaveAsset(
@@ -493,7 +568,7 @@ export const assets = {
493
568
  *
494
569
  * Pass `destinationUri` for anything the user is going to keep or hand to a
495
570
  * share sheet. Natively, without it the file lands in the app's temporary
496
- * directory under a name derived from the record, and iOS may reclaim that
571
+ * directory as `rncs-asset-<hash of zone, record and field>`, and iOS may reclaim that
497
572
  * at any time - fine for restoring straight back into the app, wrong for an
498
573
  * export. Parent directories are created if they do not exist. Over REST,
499
574
  * `destinationUri` is required: there is no OS-managed temporary directory
@@ -507,6 +582,7 @@ export const assets = {
507
582
  destinationUri?: string
508
583
  }
509
584
  ): Promise<string | null> => {
585
+ assertPlainKey(options.recordName, NAME)
510
586
  if (isNative())
511
587
  try {
512
588
  return await requireNativeModule().ckFetchAsset(
@@ -1,7 +1,8 @@
1
1
  import { Platform } from 'react-native'
2
2
 
3
3
  import { getNativeModule, hasNativeModule, requireNativeModule } from '../internal/nativeModule'
4
- import { normalizeError, unsupportedPlatform } from '../errors'
4
+ import { CloudSyncError, ErrorCode, normalizeError, unsupportedPlatform } from '../errors'
5
+ import { ENCRYPTED_RECORD_PREFIX } from '../internal/cloudKitRest'
5
6
  import { toAccountStatus } from '../internal/enums'
6
7
  import type { AccountStatus, CloudProvider } from '../types'
7
8
 
@@ -17,6 +18,28 @@ const NAME = 'cloudKitEncrypted' as const
17
18
  */
18
19
  const RECORD_TYPE = 'EncryptedKVBlob'
19
20
 
21
+ /** CloudKit's ceiling on a record name, which the prefix eats into. */
22
+ const CK_MAX_RECORD_NAME = 255
23
+
24
+ /**
25
+ * The CloudKit record name for `key`.
26
+ *
27
+ * Prefixed because record names are unique per zone *across* record types: a
28
+ * separate record type alone did not keep this provider's `token` apart from
29
+ * `cloudKit`'s `token`, so one provider's delete removed the other's record.
30
+ */
31
+ function toRecordName(key: string): string {
32
+ const recordName = `${ENCRYPTED_RECORD_PREFIX}${key}`
33
+ if (recordName.length > CK_MAX_RECORD_NAME)
34
+ throw new CloudSyncError(
35
+ ErrorCode.INVALID_KEY,
36
+ `[RNCloudSync] '${key}' is too long for ${NAME}: with its '${ENCRYPTED_RECORD_PREFIX}' `
37
+ + `record-name prefix it exceeds CloudKit's ${CK_MAX_RECORD_NAME}-character limit.`,
38
+ { provider: NAME }
39
+ )
40
+ return recordName
41
+ }
42
+
20
43
  function isNative(): boolean {
21
44
  const os: string | undefined = Platform?.OS
22
45
  return (os === 'ios' || os === 'macos') && hasNativeModule()
@@ -98,7 +121,7 @@ export const cloudKitEncrypted: CloudProvider = {
98
121
  getItem: async (key: string) => {
99
122
  assertNative()
100
123
  try {
101
- return await requireNativeModule().ckGetRecord(RECORD_TYPE, key, null, true)
124
+ return await requireNativeModule().ckGetRecord(RECORD_TYPE, toRecordName(key), null, true)
102
125
  }
103
126
  catch (e) {
104
127
  throw normalizeError(e, NAME)
@@ -108,7 +131,7 @@ export const cloudKitEncrypted: CloudProvider = {
108
131
  setItem: async (key: string, value: string) => {
109
132
  assertNative()
110
133
  try {
111
- await requireNativeModule().ckSaveRecord(RECORD_TYPE, key, value, null, true)
134
+ await requireNativeModule().ckSaveRecord(RECORD_TYPE, toRecordName(key), value, null, true)
112
135
  }
113
136
  catch (e) {
114
137
  throw normalizeError(e, NAME)
@@ -118,7 +141,7 @@ export const cloudKitEncrypted: CloudProvider = {
118
141
  removeItem: async (key: string) => {
119
142
  assertNative()
120
143
  try {
121
- await requireNativeModule().ckDeleteRecord(key, null)
144
+ await requireNativeModule().ckDeleteRecord(toRecordName(key), null)
122
145
  }
123
146
  catch (e) {
124
147
  throw normalizeError(e, NAME)
@@ -132,7 +155,13 @@ export const cloudKitEncrypted: CloudProvider = {
132
155
  getAllKeys: async () => {
133
156
  assertNative()
134
157
  try {
135
- return await requireNativeModule().ckQueryRecordNames(RECORD_TYPE, null)
158
+ const names = await requireNativeModule().ckQueryRecordNames(RECORD_TYPE, null)
159
+ // Only prefixed names are this provider's keys. An unprefixed record of
160
+ // this type predates the prefix and is not readable through it, so it is
161
+ // not listed as though it were.
162
+ return names
163
+ .filter(n => n.startsWith(ENCRYPTED_RECORD_PREFIX))
164
+ .map(n => n.slice(ENCRYPTED_RECORD_PREFIX.length))
136
165
  }
137
166
  catch (e) {
138
167
  throw normalizeError(e, NAME)
@@ -144,7 +173,7 @@ export const cloudKitEncrypted: CloudProvider = {
144
173
  try {
145
174
  const out: (string | null)[] = []
146
175
  for (const key of keys)
147
- out.push(await requireNativeModule().ckGetRecord(RECORD_TYPE, key, null, true))
176
+ out.push(await requireNativeModule().ckGetRecord(RECORD_TYPE, toRecordName(key), null, true))
148
177
  return out
149
178
  }
150
179
  catch (e) {
@@ -156,7 +185,7 @@ export const cloudKitEncrypted: CloudProvider = {
156
185
  assertNative()
157
186
  try {
158
187
  for (const [key, value] of entries)
159
- await requireNativeModule().ckSaveRecord(RECORD_TYPE, key, value, null, true)
188
+ await requireNativeModule().ckSaveRecord(RECORD_TYPE, toRecordName(key), value, null, true)
160
189
  }
161
190
  catch (e) {
162
191
  throw normalizeError(e, NAME)
@@ -166,7 +195,7 @@ export const cloudKitEncrypted: CloudProvider = {
166
195
  multiRemove: async (keys: string[]) => {
167
196
  assertNative()
168
197
  try {
169
- for (const key of keys) await requireNativeModule().ckDeleteRecord(key, null)
198
+ for (const key of keys) await requireNativeModule().ckDeleteRecord(toRecordName(key), null)
170
199
  }
171
200
  catch (e) {
172
201
  throw normalizeError(e, NAME)
@@ -64,6 +64,22 @@ function makeDriveProvider(
64
64
  }
65
65
  },
66
66
 
67
+ /**
68
+ * Values plus `modifiedTime` for many keys. The name lookups - which is
69
+ * where the timestamps come from - collapse into one listing per 50 keys;
70
+ * each value is still its own download, since Drive has no batch endpoint
71
+ * for content. Lets the store resolve a batch read without one fresh
72
+ * `getItemWithMeta` listing per key.
73
+ */
74
+ multiGetWithMeta: async (keys: string[]) => {
75
+ try {
76
+ return await getClient().getItemsWithMeta(keys)
77
+ }
78
+ catch (e) {
79
+ throw normalizeError(e, name)
80
+ }
81
+ },
82
+
67
83
  setItem: async (key: string, value: string) => {
68
84
  try {
69
85
  await getClient().setItem(key, value)
@@ -112,13 +128,19 @@ function makeDriveProvider(
112
128
  // 2020 and never carried media bodies). Advertising a batch API that
113
129
  // secretly looped would hide N round trips behind a call that looks like
114
130
  // one, so the store's own sequential fallback is used - same cost, honest
115
- // about it.
131
+ // about it. `multiGetWithMeta` above is the exception because it really
132
+ // does save requests: the per-key listing, not the download.
116
133
 
117
134
  clearCaches: () => {
118
135
  // Memoised file ids belong to the account that was signed in when they
119
136
  // were recorded. Handing them to the next user is a cross-account leak.
120
137
  if (isConfigured()) getClient().clearCache()
121
138
  stopWatching()
139
+ // The cursor belonged to the previous account, but the subscribers did
140
+ // not: stopping here without restarting left every existing
141
+ // `onRemoteChange` listener silently subscribed to nothing after an
142
+ // account switch.
143
+ if (changeListeners.size > 0) startWatching()
122
144
  },
123
145
 
124
146
  /**
@@ -149,10 +171,20 @@ function makeDriveProvider(
149
171
  let timer: ReturnType<typeof setInterval> | null = null
150
172
  let cursor: string | null = null
151
173
  let polling = false
174
+ /**
175
+ * Bumped on every stop, so a poll that was already in flight when watching
176
+ * stopped (an unsubscribe, an account switch) cannot write the previous
177
+ * session's cursor - or report its changes - into the next one.
178
+ */
179
+ let generation = 0
152
180
 
153
181
  function startWatching(): void {
154
182
  if (timer != null || !isConfigured()) return
155
183
 
184
+ // Take the starting cursor now, not one interval later: anything another
185
+ // device wrote between subscribing and the first tick would otherwise land
186
+ // before the cursor and never be reported.
187
+ void poll()
156
188
  timer = setInterval(() => {
157
189
  void poll()
158
190
  }, pollIntervalMs)
@@ -165,6 +197,7 @@ function makeDriveProvider(
165
197
  if (timer != null) clearInterval(timer)
166
198
  timer = null
167
199
  cursor = null
200
+ generation += 1
168
201
  }
169
202
 
170
203
  async function poll(): Promise<void> {
@@ -172,6 +205,7 @@ function makeDriveProvider(
172
205
  // would otherwise pile up requests behind it.
173
206
  if (polling || !isConfigured()) return
174
207
  polling = true
208
+ const started = generation
175
209
 
176
210
  try {
177
211
  const client = getClient()
@@ -179,11 +213,13 @@ function makeDriveProvider(
179
213
  // First tick only establishes the starting cursor. Reporting everything
180
214
  // that ever happened as "just changed" would make every subscriber
181
215
  // re-read the whole store on launch.
182
- cursor = await client.getStartPageToken()
216
+ const start = await client.getStartPageToken()
217
+ if (started === generation) cursor = start
183
218
  return
184
219
  }
185
220
 
186
221
  const { names, nextToken } = await client.pollChanges(cursor)
222
+ if (started !== generation) return
187
223
  cursor = nextToken
188
224
  if (names.length === 0) return
189
225
 
@@ -1,7 +1,7 @@
1
1
  import { Platform } from 'react-native'
2
2
 
3
3
  import { getNativeModule, requireNativeModule } from '../internal/nativeModule'
4
- import { normalizeError, unsupportedPlatform } from '../errors'
4
+ import { CloudSyncError, ErrorCode, normalizeError, unsupportedPlatform } from '../errors'
5
5
 
6
6
  const NAME = 'icloudDocuments' as const
7
7
 
@@ -24,6 +24,40 @@ function assertSupported(): void {
24
24
  )
25
25
  }
26
26
 
27
+ /**
28
+ * A document name must be one file name inside the app's Documents folder.
29
+ * Mirrors `validateDocumentName` in `ios/CloudSyncImpl.swift`, so the failure is
30
+ * the same typed error with or without a native round trip.
31
+ */
32
+ function assertValidName(name: string): void {
33
+ const invalid = typeof name !== 'string'
34
+ || name === '' || name === '.' || name === '..'
35
+ || name.includes('/') || name.includes('\0')
36
+ || (name.startsWith('.') && name.endsWith('.icloud'))
37
+ if (invalid)
38
+ throw new CloudSyncError(
39
+ ErrorCode.INVALID_KEY,
40
+ `'${String(name)}' is not a valid iCloud Drive document name. Use a single file name: `
41
+ + `non-empty, no '/', not '.' or '..'.`,
42
+ { provider: NAME }
43
+ )
44
+ }
45
+
46
+ /**
47
+ * The native wait is a polling loop on a background thread. `NaN` never
48
+ * compared past its deadline, so it held that thread for good, and enough of
49
+ * them starve the queue every other iCloud Drive call runs on. Native code also
50
+ * clamps the wait to an hour, so `Infinity` means "as long as allowed".
51
+ */
52
+ function assertValidTimeout(timeoutMs: number | undefined): void {
53
+ if (timeoutMs === undefined) return
54
+ if (typeof timeoutMs !== 'number' || Number.isNaN(timeoutMs) || timeoutMs < 0)
55
+ throw new RangeError(
56
+ `[RNCloudSync] icloudDocuments.fetch timeoutMs must be a non-negative number of `
57
+ + `milliseconds (got ${String(timeoutMs)}).`
58
+ )
59
+ }
60
+
27
61
  export interface DocumentEntry {
28
62
  name: string
29
63
  sizeBytes: number
@@ -50,7 +84,7 @@ export interface DocumentFetchOptions {
50
84
  */
51
85
  destinationUri?: string
52
86
  /**
53
- * How long to wait for the download. Default 60000.
87
+ * How long to wait for the download. Default 60000, capped at one hour.
54
88
  *
55
89
  * A timeout is not a failure of the transfer - iOS keeps downloading in the
56
90
  * background - so `ERR_TIMEOUT` here means "not yet", and it is classified as
@@ -109,6 +143,7 @@ export const icloudDocuments = {
109
143
  */
110
144
  save: async (options: { fileUri: string; name: string }): Promise<string> => {
111
145
  assertSupported()
146
+ assertValidName(options.name)
112
147
  try {
113
148
  return await requireNativeModule().docSave(options.fileUri, options.name)
114
149
  }
@@ -133,6 +168,8 @@ export const icloudDocuments = {
133
168
  options: { name: string } & DocumentFetchOptions
134
169
  ): Promise<string | null> => {
135
170
  assertSupported()
171
+ assertValidName(options.name)
172
+ assertValidTimeout(options.timeoutMs)
136
173
  try {
137
174
  return await requireNativeModule().docFetch(
138
175
  options.name,
@@ -165,6 +202,7 @@ export const icloudDocuments = {
165
202
  */
166
203
  remove: async (name: string): Promise<boolean> => {
167
204
  assertSupported()
205
+ assertValidName(name)
168
206
  try {
169
207
  return await requireNativeModule().docRemove(name)
170
208
  }
@@ -63,17 +63,27 @@ export const icloudKV: CloudProvider = {
63
63
  const m = getNativeModule()
64
64
  if (m == null) return false
65
65
  try {
66
- return await m.isAvailable()
66
+ // The key-value store's own status, not CloudKit's: `isAvailable()` goes
67
+ // through `CKContainer`, which raises an uncatchable `CKException` in an
68
+ // app that has only the key-value-store entitlement.
69
+ return (await m.kvGetAccountStatus()) === 'available'
67
70
  }
68
71
  catch {
69
72
  return false
70
73
  }
71
74
  },
72
75
 
76
+ /**
77
+ * Resolves `'couldNotDetermine'` off Apple platforms rather than throwing -
78
+ * the same answer the `.web.ts` build gives, so a react-native-web bundle
79
+ * behaves the same whether or not its bundler resolves platform extensions.
80
+ * A status question has a truthful answer everywhere; only reads and writes
81
+ * reject with `ERR_UNSUPPORTED_PLATFORM`.
82
+ */
73
83
  getAccountStatus: async (): Promise<AccountStatus> => {
74
- assertPlatform()
84
+ if (!isApplePlatform()) return 'couldNotDetermine'
75
85
  try {
76
- return toAccountStatus(await requireNativeModule().getAccountStatus())
86
+ return toAccountStatus(await requireNativeModule().kvGetAccountStatus())
77
87
  }
78
88
  catch (e) {
79
89
  throw normalizeError(e, NAME)
@@ -7,8 +7,14 @@ const DETAIL
7
7
  = 'NSUbiquitousKeyValueStore has no browser API. Use the cloudKit provider, which '
8
8
  + 'reaches the same private database over CloudKit Web Services.'
9
9
 
10
- function reject(): never {
11
- throw unsupportedPlatform(NAME, DETAIL)
10
+ /**
11
+ * A rejected promise, not a synchronous throw. The native build's methods are
12
+ * `async`, so `icloudKV.getItem(k).catch(...)` works there; a throw here escaped
13
+ * that `.catch` and crashed the caller on exactly the builds that are supposed
14
+ * to fail politely.
15
+ */
16
+ function reject(): Promise<never> {
17
+ return Promise.reject(unsupportedPlatform(NAME, DETAIL))
12
18
  }
13
19
 
14
20
  /**
@@ -210,6 +210,14 @@ export function createMemoryProvider(options: MemoryProviderOptions = {}): Memor
210
210
  return keys.map(k => data.get(k)?.value ?? null)
211
211
  },
212
212
 
213
+ multiGetWithMeta: async (keys: string[]) => {
214
+ await gate('getItem', keys)
215
+ return keys.map((k) => {
216
+ const entry = data.get(k)
217
+ return entry == null ? null : { value: entry.value, modifiedAt: entry.modifiedAt }
218
+ })
219
+ },
220
+
213
221
  multiSet: async (entries: [string, string][]) => {
214
222
  await gate('setItem', entries.map(([k]) => k))
215
223
  const now = Date.now()