react-native-cloud-sync 0.2.0 → 0.3.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 (45) hide show
  1. package/README.md +53 -53
  2. package/lib/commonjs/config.js +11 -1
  3. package/lib/commonjs/config.js.map +1 -1
  4. package/lib/commonjs/index.js.map +1 -1
  5. package/lib/commonjs/internal/cloudKitRest.js +205 -21
  6. package/lib/commonjs/internal/cloudKitRest.js.map +1 -1
  7. package/lib/commonjs/internal/googleDriveRest.js +173 -38
  8. package/lib/commonjs/internal/googleDriveRest.js.map +1 -1
  9. package/lib/commonjs/providers/cloudKit.js +89 -19
  10. package/lib/commonjs/providers/cloudKit.js.map +1 -1
  11. package/lib/module/config.js +10 -1
  12. package/lib/module/config.js.map +1 -1
  13. package/lib/module/index.js.map +1 -1
  14. package/lib/module/internal/cloudKitRest.js +205 -21
  15. package/lib/module/internal/cloudKitRest.js.map +1 -1
  16. package/lib/module/internal/googleDriveRest.js +174 -39
  17. package/lib/module/internal/googleDriveRest.js.map +1 -1
  18. package/lib/module/providers/cloudKit.js +92 -22
  19. package/lib/module/providers/cloudKit.js.map +1 -1
  20. package/lib/typescript/commonjs/config.d.ts +8 -0
  21. package/lib/typescript/commonjs/config.d.ts.map +1 -1
  22. package/lib/typescript/commonjs/index.d.ts +1 -1
  23. package/lib/typescript/commonjs/index.d.ts.map +1 -1
  24. package/lib/typescript/commonjs/internal/cloudKitRest.d.ts +90 -0
  25. package/lib/typescript/commonjs/internal/cloudKitRest.d.ts.map +1 -1
  26. package/lib/typescript/commonjs/internal/googleDriveRest.d.ts +73 -8
  27. package/lib/typescript/commonjs/internal/googleDriveRest.d.ts.map +1 -1
  28. package/lib/typescript/commonjs/providers/cloudKit.d.ts +32 -13
  29. package/lib/typescript/commonjs/providers/cloudKit.d.ts.map +1 -1
  30. package/lib/typescript/module/config.d.ts +8 -0
  31. package/lib/typescript/module/config.d.ts.map +1 -1
  32. package/lib/typescript/module/index.d.ts +1 -1
  33. package/lib/typescript/module/index.d.ts.map +1 -1
  34. package/lib/typescript/module/internal/cloudKitRest.d.ts +90 -0
  35. package/lib/typescript/module/internal/cloudKitRest.d.ts.map +1 -1
  36. package/lib/typescript/module/internal/googleDriveRest.d.ts +73 -8
  37. package/lib/typescript/module/internal/googleDriveRest.d.ts.map +1 -1
  38. package/lib/typescript/module/providers/cloudKit.d.ts +32 -13
  39. package/lib/typescript/module/providers/cloudKit.d.ts.map +1 -1
  40. package/package.json +1 -1
  41. package/src/config.ts +12 -2
  42. package/src/index.ts +3 -1
  43. package/src/internal/cloudKitRest.ts +272 -29
  44. package/src/internal/googleDriveRest.ts +196 -42
  45. package/src/providers/cloudKit.ts +138 -41
@@ -1 +1 @@
1
- {"version":3,"file":"cloudKitRest.d.ts","sourceRoot":"","sources":["../../../../src/internal/cloudKitRest.ts"],"names":[],"mappings":"AAOA;;;;;;;;;;;;;;;;;;;GAmBG;AAEH,MAAM,WAAW,kBAAkB;IACjC,+EAA+E;IAC/E,mBAAmB,EAAE,MAAM,CAAA;IAC3B;;;;;OAKG;IACH,QAAQ,EAAE,MAAM,CAAA;IAChB,WAAW,EAAE,aAAa,GAAG,YAAY,CAAA;IACzC,oFAAoF;IACpF,YAAY,EAAE,MAAM,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,GAAG,MAAM,GAAG,IAAI,CAAA;IAC1D;;;;;;;OAOG;IACH,aAAa,CAAC,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,CAAA;IAC1C,yDAAyD;IACzD,SAAS,CAAC,EAAE,OAAO,KAAK,CAAA;IACxB;;;;;;OAMG;IACH,SAAS,CAAC,EAAE,MAAM,CAAA;CACnB;AAWD,eAAO,MAAM,mBAAmB,WAAW,CAAA;AAC3C,eAAO,MAAM,WAAW,UAAU,CAAA;AAElC,kEAAkE;AAClE,eAAO,MAAM,gBAAgB,QAAc,CAAA;AAyD3C,qBAAa,kBAAkB;IAC7B,OAAO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out.js';
3
3
  * Google Drive `appDataFolder` REST client.
4
4
  *
5
5
  * `appDataFolder` is a hidden per-app, per-Google-account folder: nothing shows
6
- * up in the user's visible Drive, and the data survives an app uninstall because
7
- * it is tied to the account rather than the install.
6
+ * up in the user's visible Drive, and the data is tied to the Google account
7
+ * rather than the device or install, so reinstalling the app or switching
8
+ * devices doesn't lose it. It goes away only if the user disconnects the app
9
+ * from their Drive account or deletes the data folder directly - Google
10
+ * documents both as the ways this folder is actually removed.
8
11
  *
9
12
  * Auth is deliberately injected rather than owned. The library does not depend
10
13
  * on `@react-native-google-signin/google-signin` (or any other sign-in library),
@@ -52,6 +55,37 @@ export interface GoogleDriveConfig {
52
55
  * its own, so without this a dead socket hangs the transfer forever.
53
56
  */
54
57
  timeoutMs?: number;
58
+ /**
59
+ * Persists `uploadFile`'s resumable-session URI across process restarts.
60
+ *
61
+ * Without this, the session lives only in memory: a process killed mid-upload
62
+ * loses it, and the next `uploadFile` for the same name starts over from byte
63
+ * 0 even though Drive still has the bytes already accepted. With it, the next
64
+ * call finds the persisted session, asks Drive for the real offset, and
65
+ * resumes from there instead.
66
+ *
67
+ * A tiny JSON record, not file I/O - back it with AsyncStorage, MMKV, or a
68
+ * single row in whatever the host app already uses. Optional; omitting it
69
+ * keeps today's in-memory-only behaviour.
70
+ */
71
+ sessionStore?: GoogleDriveSessionStore;
72
+ }
73
+ /** What `uploadFile` needs to resume a resumable-upload session later. */
74
+ export interface GoogleDriveUploadSession {
75
+ sessionUrl: string;
76
+ /** The source size the session was started against - resuming into a file
77
+ * that has since changed size would corrupt it, so a mismatch is treated
78
+ * as "start fresh" rather than resumed. */
79
+ size: number;
80
+ }
81
+ /**
82
+ * Host-supplied persistence for in-flight `uploadFile` sessions, keyed by the
83
+ * Drive file name. See {@link GoogleDriveConfig.sessionStore}.
84
+ */
85
+ export interface GoogleDriveSessionStore {
86
+ get: (name: string) => Promise<GoogleDriveUploadSession | null>;
87
+ set: (name: string, session: GoogleDriveUploadSession) => Promise<void>;
88
+ remove: (name: string) => Promise<void>;
55
89
  }
56
90
  /** A local file `uploadFile` reads from, in fixed-size pieces. */
57
91
  export interface DriveChunkSource {
@@ -114,6 +148,14 @@ export declare class GoogleDriveClient {
114
148
  * caller inspects the response itself rather than getting a thrown rejection.
115
149
  */
116
150
  private request;
151
+ /**
152
+ * Best-effort read of Drive's `error.errors[0].reason` from a failed
153
+ * response body - the only way a 403 status distinguishes an invalid token
154
+ * from quota-exceeded from a rate limit. Returns undefined for a body that
155
+ * is missing, unparseable, or doesn't carry the shape Drive documents,
156
+ * rather than throwing a second error while already handling one.
157
+ */
158
+ private driveErrorReason;
117
159
  /**
118
160
  * Resolves a file name to its id within appDataFolder, or null if absent.
119
161
  *
@@ -171,18 +213,41 @@ export declare class GoogleDriveClient {
171
213
  * how many bytes it actually has and resuming from there - rather than
172
214
  * restarting the transfer.
173
215
  *
174
- * That resumability is scoped to this call: the session lives only in
175
- * memory, so if the process dies mid-upload, the next call to `uploadFile`
176
- * starts a fresh session from byte 0. Persisting the session URI so a
177
- * restart can resume it too is future scope, not something callers should
178
- * assume works today.
216
+ * That resumability spans a process restart too, when {@link
217
+ * GoogleDriveConfig.sessionStore} is configured: the session URI is persisted
218
+ * before the first chunk goes out, and a later `uploadFile` for the same name
219
+ * finds it, asks Drive for the real offset, and resumes from there instead of
220
+ * byte 0. Without a `sessionStore`, the session lives only in memory, exactly
221
+ * as before - a process that dies mid-upload loses it, and the next call
222
+ * starts fresh.
179
223
  */
180
224
  uploadFile(name: string, source: DriveChunkSource, onProgress?: (bytesTransferred: number, bytesTotal: number) => void, signal?: AbortLike): Promise<void>;
225
+ /**
226
+ * Finds an existing session to resume, or starts a new one.
227
+ *
228
+ * A persisted session is trusted only when its recorded size still matches
229
+ * `total` - resuming a byte-range PUT into a file that has since changed
230
+ * would corrupt it, so a mismatch is treated the same as no session at all.
231
+ * A persisted session Drive no longer recognises (expired, or the upload id
232
+ * was never valid) is also treated as absent: `queryUploadOffset` failing is
233
+ * the signal, since there is no cheaper way to ask than trying to use it.
234
+ */
235
+ private resumeOrStartSession;
181
236
  private startResumableSession;
182
237
  /** One chunk, with a single retry that re-queries the server's real offset first. */
183
238
  private putChunkWithRetry;
184
239
  private putChunk;
185
- /** Asks Drive how much of an in-flight resumable session it actually has. */
240
+ /**
241
+ * Asks Drive how much of an in-flight resumable session it actually has, or
242
+ * discovers the upload was already complete server-side - the completing
243
+ * chunk's own response can be lost the same way any other one can, and this
244
+ * status check gets the same completion response back in that case,
245
+ * `id` included.
246
+ *
247
+ * Throws (via `request`) when `sessionUrl` is not a session Drive
248
+ * recognises any more - expired, or never valid. Callers treat that as the
249
+ * signal to stop trusting it, since there is no cheaper way to ask.
250
+ */
186
251
  private queryUploadOffset;
187
252
  /**
188
253
  * Downloads `name` into `sink`, in the same fixed-size chunks `uploadFile`
@@ -1 +1 @@
1
- {"version":3,"file":"googleDriveRest.d.ts","sourceRoot":"","sources":["../../../../src/internal/googleDriveRest.ts"],"names":[],"mappings":"AACA,OAAO,EAA+B,KAAK,SAAS,EAAE,MAAM,cAAW,CAAA;AAEvE;;;;;;;;;;;GAWG;AAEH,MAAM,WAAW,iBAAiB;IAChC;;;;OAIG;IACH,cAAc,EAAE,MAAM,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,GAAG,MAAM,GAAG,IAAI,CAAA;IAC5D,iFAAiF;IACjF,aAAa,CAAC,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,CAAA;IAC1C,SAAS,CAAC,EAAE,OAAO,KAAK,CAAA;IACxB;;;;;;OAMG;IACH,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB;;;;;;;;;;;;;OAaG;IACH,eAAe,CAAC,EAAE,QAAQ,GAAG,OAAO,CAAA;IACpC;;;;;;OAMG;IACH,SAAS,CAAC,EAAE,MAAM,CAAA;CACnB;AASD,kEAAkE;AAClE,MAAM,WAAW,gBAAgB;IAC/B,IAAI,EAAE,MAAM,CAAA;IACZ,IAAI,E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/B;;;;;OAKG;IACG,YAAY,CAChB,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,cAAc,EACpB,UAAU,CAAC,EAAE,CAAC,gBAAgB,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,KAAK,IAAI,EACnE,MAAM,CAAC,EAAE,SAAS,GACjB,OAAO,CAAC,OAAO,CAAC;YAgCL,QAAQ;IAMhB,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAkBvC,UAAU,IAAI,OAAO,CAAC,MAAM,EAAE,CAAC;IA2BrC;;;;;OAKG;IACG,iBAAiB,IAAI,OAAO,CAAC,MAAM,CAAC;IAgB1C;;;;;;;;;;;;;OAaG;IACG,WAAW,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC;QAAE,KAAK,EAAE,MAAM,EAAE,CAAC;QAAC,SAAS,EAAE,MAAM,CAAA;KAAE,CAAC;IAuDrF,2DAA2D;IAC3D,OAAO,CAAC,UAAU;IASlB;;;OAGG;IACG,QAAQ,IAAI,OAAO,CAAC,OAAO,CAAC;IASlC,6DAA6D;IAC7D,UAAU,IAAI,IAAI;CAInB"}
@@ -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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U,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,6 +1,6 @@
1
1
  {
2
2
  "name": "react-native-cloud-sync",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
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",
5
5
  "workspaces": [
6
6
  "example"
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/index.ts CHANGED
@@ -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
@@ -1,4 +1,4 @@
1
- import { CloudSyncError, ErrorCode } from '../errors'
1
+ import { CloudSyncError, ErrorCode, timedOut } from '../errors'
2
2
  import { byteLength } from './bytes'
3
3
  import { withTimeout } from './timeout'
4
4
 
@@ -50,6 +50,16 @@ export interface CloudKitRestConfig {
50
50
  onAuthExpired?: () => Promise<void> | void
51
51
  /** Overridable for tests. Defaults to global `fetch`. */
52
52
  fetchImpl?: typeof fetch
53
+ /**
54
+ * Overridable for tests. Defaults to the global `XMLHttpRequest` constructor.
55
+ *
56
+ * Only used for the raw asset-bytes upload/download - `fetch` in React
57
+ * Native exposes no upload-progress events at all, and `XMLHttpRequest.upload
58
+ * .onprogress` (and its response-side `.onprogress`) are what the per-record
59
+ * progress `cloudKitAssets.onProgress` promises actually needs. Every other
60
+ * request in this client stays on `fetch`.
61
+ */
62
+ xhrImpl?: () => XMLHttpRequest
53
63
  /**
54
64
  * Abandon a request that has not answered in this long. Default 30000.
55
65
  *
@@ -60,6 +70,31 @@ export interface CloudKitRestConfig {
60
70
  timeoutMs?: number
61
71
  }
62
72
 
73
+ /**
74
+ * CloudKit Web Services' own ceiling on a single asset upload, undocumented
75
+ * anywhere except the upload endpoint's own reference page: 15 MB, and the
76
+ * upload URL it hands out is valid for 15 minutes. Native `CKAsset` has no such
77
+ * limit - this is specific to the REST upload-token protocol.
78
+ */
79
+ export const MAX_ASSET_UPLOAD_BYTES = 15 * 1024 * 1024
80
+
81
+ /**
82
+ * The "Asset Dictionary" CloudKit Web Services deals in - what the upload
83
+ * endpoint returns after receiving bytes, and what a fetched record's Asset
84
+ * field value looks like. Passed back verbatim as a record field's value to
85
+ * attach an upload to a record; never reconstructed field-by-field, since it
86
+ * is an opaque blob the server itself validates.
87
+ */
88
+ export interface CloudKitAssetDescriptor {
89
+ fileChecksum: string
90
+ size: string | number
91
+ receipt: string
92
+ referenceChecksum?: string
93
+ wrappingKey?: string
94
+ /** Present only when fetching the record that owns this field, not on upload. */
95
+ downloadURL?: string
96
+ }
97
+
63
98
  /**
64
99
  * How many operations one `/records/modify` or `/records/lookup` call carries.
65
100
  *
@@ -108,6 +143,8 @@ interface CloudKitResponse {
108
143
  redirectURL?: string
109
144
  /** Set when a query has more results than one response can carry. */
110
145
  continuationMarker?: string
146
+ /** Present only on an `/assets/upload` response. */
147
+ tokens?: { recordName?: string; fieldName?: string; url?: string }[]
111
148
  }
112
149
 
113
150
  /**
@@ -212,6 +249,35 @@ export class CloudKitRestClient {
212
249
  }
213
250
  }
214
251
 
252
+ /**
253
+ * HTTP-status classification for a response with no CloudKit error envelope
254
+ * of its own to inspect - `post()`'s fallback tail, and the raw asset-bytes
255
+ * transfer, which talks to an opaque single-use upload/download URL rather
256
+ * than a `/records/...` JSON endpoint.
257
+ */
258
+ private async classifyHttpStatus(status: number): Promise<CloudSyncError> {
259
+ if (status === 401 || status === 421) {
260
+ await this.handleAuthExpired()
261
+ return new CloudSyncError(
262
+ ErrorCode.AUTH_EXPIRED,
263
+ `[RNCloudSync] CloudKit returned HTTP ${status}; the web auth token is no longer valid.`,
264
+ { provider: 'cloudKit' }
265
+ )
266
+ }
267
+ if (status === 429 || status === 503)
268
+ return new CloudSyncError(
269
+ ErrorCode.RATE_LIMITED,
270
+ `[RNCloudSync] CloudKit returned HTTP ${status}.`,
271
+ { provider: 'cloudKit' }
272
+ )
273
+
274
+ return new CloudSyncError(
275
+ ErrorCode.UNKNOWN,
276
+ `[RNCloudSync] CloudKit returned HTTP ${status}.`,
277
+ { provider: 'cloudKit' }
278
+ )
279
+ }
280
+
215
281
  private async post(path: string, body: unknown): Promise<CloudKitResponse> {
216
282
  const token = await this.requireAuthToken()
217
283
  const url
@@ -250,29 +316,8 @@ export class CloudKitRestClient {
250
316
  if (json?.serverErrorCode != null)
251
317
  throw await this.toError(json.serverErrorCode, json.reason, json.retryAfter)
252
318
 
253
- if (!res.ok) {
254
- // HTTP-level failure with no parseable CloudKit error body.
255
- if (res.status === 401 || res.status === 421) {
256
- await this.handleAuthExpired()
257
- throw new CloudSyncError(
258
- ErrorCode.AUTH_EXPIRED,
259
- `[RNCloudSync] CloudKit returned HTTP ${res.status}; the web auth token is no longer valid.`,
260
- { provider: 'cloudKit' }
261
- )
262
- }
263
- if (res.status === 429 || res.status === 503)
264
- throw new CloudSyncError(
265
- ErrorCode.RATE_LIMITED,
266
- `[RNCloudSync] CloudKit returned HTTP ${res.status}.`,
267
- { provider: 'cloudKit' }
268
- )
269
-
270
- throw new CloudSyncError(
271
- ErrorCode.UNKNOWN,
272
- `[RNCloudSync] CloudKit returned HTTP ${res.status}.`,
273
- { provider: 'cloudKit' }
274
- )
275
- }
319
+ // HTTP-level failure with no parseable CloudKit error body.
320
+ if (!res.ok) throw await this.classifyHttpStatus(res.status)
276
321
 
277
322
  return json ?? {}
278
323
  }
@@ -442,11 +487,22 @@ export class CloudKitRestClient {
442
487
  { provider: 'cloudKit', limitBytes: MAX_RECORD_BYTES, actualBytes: bytes }
443
488
  )
444
489
 
445
- const record = {
446
- recordType,
447
- recordName,
448
- fields: { [VALUE_FIELD]: { value } },
449
- }
490
+ await this.saveFields(recordName, { [VALUE_FIELD]: { value } }, recordType)
491
+ }
492
+
493
+ /**
494
+ * Creates `recordName`, falling back to an unconditional update when it
495
+ * already exists - the create-then-fall-back dance every write after the
496
+ * first one takes. Shared by {@link saveRecord} (a `value` field) and
497
+ * {@link uploadAsset} (an Asset field plus its `__size` sidecar), which need
498
+ * the exact same dance for a different field set.
499
+ */
500
+ private async saveFields(
501
+ recordName: string,
502
+ fields: Record<string, { value: unknown }>,
503
+ recordType: string
504
+ ): Promise<void> {
505
+ const record = { recordType, recordName, fields }
450
506
 
451
507
  // `atomic` defaults to true server-side. Setting it explicitly documents the
452
508
  // intent and keeps behaviour stable if that default ever changes.
@@ -498,6 +554,193 @@ export class CloudKitRestClient {
498
554
  }
499
555
  }
500
556
 
557
+ /**
558
+ * Uploads `bytes` as `fieldName` on `recordName`, via CloudKit Web Services'
559
+ * asset-upload protocol: request a single-use upload URL, POST the raw bytes
560
+ * to it, then attach the descriptor it returns (plus a `__size` sidecar, so
561
+ * a later {@link fetchAsset} can report real download progress) to the
562
+ * record - the same create-then-update dance {@link saveRecord} uses.
563
+ *
564
+ * `onProgress` reports real bytes transferred, via `XMLHttpRequest` rather
565
+ * than `fetch` - see {@link CloudKitRestConfig.xhrImpl}.
566
+ */
567
+ async uploadAsset(
568
+ recordName: string,
569
+ fieldName: string,
570
+ bytes: Uint8Array,
571
+ onProgress?: (bytesTransferred: number, bytesTotal: number) => void,
572
+ recordType = RECORD_TYPE_DEFAULT
573
+ ): Promise<void> {
574
+ if (bytes.length > MAX_ASSET_UPLOAD_BYTES)
575
+ throw new CloudSyncError(
576
+ ErrorCode.PAYLOAD_TOO_LARGE,
577
+ `[RNCloudSync] Asset is ${bytes.length} bytes; CloudKit Web Services caps a single asset `
578
+ + `upload at ${MAX_ASSET_UPLOAD_BYTES} bytes. Use the googleDrive provider for larger files `
579
+ + `on Android and web.`,
580
+ { provider: 'cloudKit', limitBytes: MAX_ASSET_UPLOAD_BYTES, actualBytes: bytes.length }
581
+ )
582
+
583
+ const uploadUrl = await this.requestAssetUploadUrl(recordType, recordName, fieldName)
584
+ const descriptor = await this.putAssetBytes(uploadUrl, bytes, onProgress)
585
+
586
+ await this.saveFields(recordName, {
587
+ [fieldName]: { value: descriptor },
588
+ [`${fieldName}__size`]: { value: bytes.length },
589
+ }, recordType)
590
+ }
591
+
592
+ /**
593
+ * Downloads the bytes behind `fieldName` on `recordName`, or `null` when the
594
+ * record or the field's asset does not exist.
595
+ *
596
+ * A fetched record's Asset field carries a `downloadURL` - that is the only
597
+ * step this needs beyond the usual record lookup; there is no separate
598
+ * "request a download token" round trip the way upload has one.
599
+ */
600
+ async fetchAsset(
601
+ recordName: string,
602
+ fieldName: string,
603
+ onProgress?: (bytesTransferred: number, bytesTotal: number) => void,
604
+ recordType = RECORD_TYPE_DEFAULT
605
+ ): Promise<Uint8Array | null> {
606
+ void recordType
607
+ const json = await this.post('/records/lookup', { records: [{ recordName }] })
608
+ const record = json.records?.find(r => r.recordName === recordName) ?? json.records?.[0]
609
+ if (record == null) return null
610
+
611
+ if (record.serverErrorCode != null) {
612
+ if (record.serverErrorCode === 'NOT_FOUND') return null
613
+ throw await this.toError(record.serverErrorCode, record.reason, record.retryAfter)
614
+ }
615
+
616
+ const asset = record.fields?.[fieldName]?.value as CloudKitAssetDescriptor | undefined
617
+ if (asset?.downloadURL == null) return null
618
+
619
+ return await this.fetchAssetBytes(asset.downloadURL, onProgress)
620
+ }
621
+
622
+ private async requestAssetUploadUrl(
623
+ recordType: string, recordName: string, fieldName: string
624
+ ): Promise<string> {
625
+ const json = await this.post('/assets/upload', {
626
+ tokens: [{ recordType, recordName, fieldName }],
627
+ })
628
+
629
+ const url = json.tokens?.[0]?.url
630
+ if (url == null)
631
+ throw new CloudSyncError(
632
+ ErrorCode.UNKNOWN,
633
+ '[RNCloudSync] CloudKit did not return an asset upload URL.',
634
+ { provider: 'cloudKit' }
635
+ )
636
+
637
+ return url
638
+ }
639
+
640
+ private get xhr(): () => XMLHttpRequest {
641
+ return this.config.xhrImpl ?? (() => new XMLHttpRequest())
642
+ }
643
+
644
+ /**
645
+ * POSTs raw bytes to a single-use CKWS asset-upload URL, reporting real
646
+ * upload progress via `XMLHttpRequest.upload.onprogress` - `fetch` exposes no
647
+ * upload-progress events in React Native. Scoped to just this one call:
648
+ * every other CloudKit REST request stays on `fetch` through `post()`, for
649
+ * the timeout/error handling already built there.
650
+ */
651
+ private putAssetBytes(
652
+ url: string,
653
+ bytes: Uint8Array,
654
+ onProgress?: (bytesTransferred: number, bytesTotal: number) => void
655
+ ): Promise<CloudKitAssetDescriptor> {
656
+ return new Promise((resolve, reject) => {
657
+ const req = this.xhr()
658
+ req.open('POST', url)
659
+ req.timeout = this.config.timeoutMs ?? DEFAULT_TIMEOUT_MS
660
+
661
+ req.upload.onprogress = (e) => {
662
+ if (e.lengthComputable) onProgress?.(e.loaded, e.total)
663
+ }
664
+
665
+ req.onload = () => {
666
+ if (req.status < 200 || req.status >= 300) {
667
+ this.classifyHttpStatus(req.status).then(reject).catch(reject)
668
+ return
669
+ }
670
+
671
+ try {
672
+ const json = JSON.parse(req.responseText) as { singleFile?: CloudKitAssetDescriptor }
673
+ if (json.singleFile == null) throw new Error('response had no singleFile')
674
+ onProgress?.(bytes.length, bytes.length)
675
+ resolve(json.singleFile)
676
+ }
677
+ catch (e) {
678
+ reject(new CloudSyncError(
679
+ ErrorCode.UNKNOWN,
680
+ '[RNCloudSync] CloudKit did not return an asset descriptor after upload.',
681
+ { provider: 'cloudKit', cause: e }
682
+ ))
683
+ }
684
+ }
685
+
686
+ req.onerror = () => reject(new CloudSyncError(
687
+ ErrorCode.NETWORK_UNAVAILABLE,
688
+ '[RNCloudSync] CloudKit asset upload failed to reach the server.',
689
+ { provider: 'cloudKit' }
690
+ ))
691
+ req.ontimeout = () => reject(timedOut(req.timeout, 'cloudKit'))
692
+
693
+ req.send(bytes)
694
+ })
695
+ }
696
+
697
+ /**
698
+ * GETs raw bytes from a record's asset `downloadURL`, reporting real
699
+ * download progress via `XMLHttpRequest.onprogress`, for the same reason
700
+ * {@link putAssetBytes} uses XHR rather than `fetch`.
701
+ *
702
+ * Treated as self-contained, the same way the upload URL is (Apple's own
703
+ * reference issues that one with no `ckAPIToken`/`ckWebAuthToken` at all) -
704
+ * if that assumption is ever wrong for a download URL specifically, it
705
+ * surfaces as an HTTP-level auth failure here rather than a silent wrong
706
+ * answer.
707
+ */
708
+ private fetchAssetBytes(
709
+ url: string,
710
+ onProgress?: (bytesTransferred: number, bytesTotal: number) => void
711
+ ): Promise<Uint8Array> {
712
+ return new Promise((resolve, reject) => {
713
+ const req = this.xhr()
714
+ req.open('GET', url)
715
+ req.responseType = 'arraybuffer'
716
+ req.timeout = this.config.timeoutMs ?? DEFAULT_TIMEOUT_MS
717
+
718
+ req.onprogress = (e) => {
719
+ if (e.lengthComputable) onProgress?.(e.loaded, e.total)
720
+ }
721
+
722
+ req.onload = () => {
723
+ if (req.status < 200 || req.status >= 300) {
724
+ this.classifyHttpStatus(req.status).then(reject).catch(reject)
725
+ return
726
+ }
727
+
728
+ const buf = req.response as ArrayBuffer
729
+ onProgress?.(buf.byteLength, buf.byteLength)
730
+ resolve(new Uint8Array(buf))
731
+ }
732
+
733
+ req.onerror = () => reject(new CloudSyncError(
734
+ ErrorCode.NETWORK_UNAVAILABLE,
735
+ '[RNCloudSync] CloudKit asset download failed to reach the server.',
736
+ { provider: 'cloudKit' }
737
+ ))
738
+ req.ontimeout = () => reject(timedOut(req.timeout, 'cloudKit'))
739
+
740
+ req.send()
741
+ })
742
+ }
743
+
501
744
  /**
502
745
  * A write that fails instead of clobbering, when the server's copy has moved
503
746
  * on since `recordChangeTag` was read.