react-native-cloud-storage 1.2.2 → 1.2.4

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 (34) hide show
  1. package/README.md +66 -10
  2. package/ios/CloudStorage.swift +30 -28
  3. package/lib/commonjs/RNCloudStorage.js.map +1 -1
  4. package/lib/commonjs/createRNCloudStorage.js.map +1 -1
  5. package/lib/commonjs/google-drive/client.js +169 -0
  6. package/lib/commonjs/google-drive/client.js.map +1 -0
  7. package/lib/commonjs/google-drive/index.js +53 -50
  8. package/lib/commonjs/google-drive/index.js.map +1 -1
  9. package/lib/commonjs/google-drive/types.js +15 -0
  10. package/lib/commonjs/google-drive/types.js.map +1 -1
  11. package/lib/module/RNCloudStorage.js +4 -4
  12. package/lib/module/RNCloudStorage.js.map +1 -1
  13. package/lib/module/createRNCloudStorage.js +2 -2
  14. package/lib/module/createRNCloudStorage.js.map +1 -1
  15. package/lib/module/google-drive/client.js +161 -0
  16. package/lib/module/google-drive/client.js.map +1 -0
  17. package/lib/module/google-drive/index.js +46 -44
  18. package/lib/module/google-drive/index.js.map +1 -1
  19. package/lib/module/google-drive/types.js +9 -1
  20. package/lib/module/google-drive/types.js.map +1 -1
  21. package/lib/typescript/RNCloudStorage.d.ts +2 -2
  22. package/lib/typescript/RNCloudStorage.d.ts.map +1 -1
  23. package/lib/typescript/google-drive/client.d.ts +33 -0
  24. package/lib/typescript/google-drive/client.d.ts.map +1 -0
  25. package/lib/typescript/google-drive/index.d.ts +6 -4
  26. package/lib/typescript/google-drive/index.d.ts.map +1 -1
  27. package/lib/typescript/google-drive/types.d.ts +10 -3
  28. package/lib/typescript/google-drive/types.d.ts.map +1 -1
  29. package/package.json +1 -4
  30. package/src/RNCloudStorage.ts +5 -5
  31. package/src/createRNCloudStorage.ts +2 -2
  32. package/src/google-drive/client.ts +177 -0
  33. package/src/google-drive/index.ts +71 -69
  34. package/src/google-drive/types.ts +12 -4
package/README.md CHANGED
@@ -1,20 +1,80 @@
1
1
  # ☁️ react-native-cloud-storage
2
2
 
3
- Save to & read from iCloud and Google Drive using React Native
4
-
5
3
  ![npm bundle size](https://img.shields.io/bundlephobia/min/react-native-cloud-storage?style=flat-square) ![GitHub](https://img.shields.io/github/license/kuatsu/react-native-cloud-storage?style=flat-square) ![GitHub last commit](https://img.shields.io/github/last-commit/kuatsu/react-native-cloud-storage?style=flat-square)
6
4
 
5
+ This library provides a unified and streamlined API for accessing cloud storage services on iOS, Android and Web. It supports iCloud on iOS and Google Drive on all other platforms.
6
+
7
+ - 💾 Read and write files to the cloud
8
+ - 🧪 Fully compatible with Expo
9
+ - 📱 iOS, Android & Web support
10
+ - 🏎️ Lightning fast iCloud performance using native iOS APIs
11
+ - 🌐 Google Drive REST API implementation for other platforms
12
+ - 🧬 Easy to use React Hooks API, or use the imperative `fs`-style API
13
+ - 👌 Zero dependencies, small bundle size
14
+
7
15
  ## Installation
8
16
 
17
+ ### React Native
18
+
9
19
  ```sh
10
20
  npm install react-native-cloud-storage
11
- # or
12
- yarn add react-native-cloud-storage
21
+ cd ios && pod install
22
+ ```
23
+
24
+ Afterwards, follow the [configuration instructions](https://react-native-cloud-storage.oss.kuatsu.de/docs/installation/react-native).
25
+
26
+ ### Expo
27
+
28
+ ```sh
29
+ npx expo install react-native-cloud-storage
30
+ ```
31
+
32
+ Afterwards, [add the provided config plugin](https://react-native-cloud-storage.oss.kuatsu.de/docs/installation/expo) and `expo prebuild` or rebuild your development client.
33
+
34
+ ## Quick Start
35
+
36
+ ```jsx
37
+ import React from 'react';
38
+ import { Platform, View, Text, Button } from 'react-native';
39
+ import { CloudStorage, useCloudAvailable } from 'react-native-cloud-storage';
40
+
41
+ const App = () => {
42
+ const cloudAvailable = useCloudAvailable();
43
+
44
+ React.useEffect(() => {
45
+ if (Platform.OS !== 'ios') {
46
+ CloudStorage.setGoogleDriveAccessToken('some-access-token'); // get via @react-native-google-signin/google-signin or similar
47
+ }
48
+ }, []);
49
+
50
+ const writeToCloud = async () => {
51
+ await CloudStorage.writeFile('/file.txt', 'Hello, world!');
52
+ console.log('Successfully wrote file to cloud');
53
+ };
54
+
55
+ const readFromCloud = async () => {
56
+ const value = await CloudStorage.readFile('/file.txt');
57
+ console.log('Successfully read file from cloud:', value);
58
+ };
59
+
60
+ return (
61
+ <View>
62
+ {cloudAvailable ? (
63
+ <>
64
+ <Button onPress={writeToCloud} title="Write to Cloud" />
65
+ <Button onPress={readFromCloud} title="Read from Cloud" />
66
+ </>
67
+ ) : (
68
+ <Text>The cloud storage is not available. Are you logged in?</Text>
69
+ )}
70
+ </View>
71
+ );
72
+ };
13
73
  ```
14
74
 
15
75
  ## Documentation
16
76
 
17
- The documentation is located [here](https://react-native-cloud-storage.oss.kuatsu.de/docs/intro).
77
+ A detailed documentation is located [here](https://react-native-cloud-storage.oss.kuatsu.de/docs/intro).
18
78
 
19
79
  ## Contributing
20
80
 
@@ -22,12 +82,8 @@ See the [contributing guide](CONTRIBUTING.md) to learn how to contribute to the
22
82
 
23
83
  ## Example Project
24
84
 
25
- There's a demo application available within the `example` directory. To use the Google Drive implementation for Android (and any other platforms except iOS), you'll need to provide a valid access token for the Google Drive API. You can create one using the [Google OAuth 2.0 Playground](https://developers.google.com/oauthplayground). If you're using an Android emulator, you can make your life easier by feeding the token into the emulator using `adb shell input text '{some_token}'`.
85
+ There's an example app available in the `example` directory. To use the Google Drive implementation (for any platforms other than iOS), you'll need to provide a valid access token for the Google Drive API. For testing purposes, you can create one using the [Google OAuth 2.0 Playground](https://developers.google.com/oauthplayground).
26
86
 
27
87
  ## License
28
88
 
29
89
  MIT
30
-
31
- ---
32
-
33
- Made with [create-react-native-library](https://github.com/callstack/react-native-builder-bob)
@@ -124,36 +124,38 @@ class CloudStorage: NSObject {
124
124
  }
125
125
 
126
126
  @objc(downloadFile:withScope:withResolver:withRejecter:)
127
- func downloadFile(path: String, scope: String, resolve:RCTPromiseResolveBlock,reject:RCTPromiseRejectBlock) -> Void {
128
- let fileManager = FileManager.default
129
-
130
- guard let directory = getDirectory(scope) else {
131
- reject("ERR_READ_ERROR", "Error reading directory \(scope)", NSError())
132
- return
133
- }
134
-
135
- // remove leading slashes
136
- let path = path.replacingOccurrences(of: "^/+", with: "", options: .regularExpression)
137
-
138
- // append path to scope directory and return URL
139
- let filePath = directory.appendingPathComponent(path)
140
-
141
- let isDownloadable = fileManager.isUbiquitousItem(at: filePath)
142
-
143
- if (!isDownloadable) {
144
- reject("ERR_FILE_NOT_DOWNLOADABLE", "File or directory \(path) is not an iCloud file", NSError())
145
- return
146
- }
147
- do {
148
- // trigger download of file
149
- try fileManager.startDownloadingUbiquitousItem(at: filePath)
150
- } catch {
151
- reject("ERR_FILE_NOT_DOWNLOADABLE", "File or directory \(path) not downloadable", error)
152
- return
153
- }
154
- resolve(true)
127
+ func downloadFile(path: String, scope: String, resolve:RCTPromiseResolveBlock,reject:RCTPromiseRejectBlock) -> Void {
128
+ let fileManager = FileManager.default
129
+
130
+ guard let directory = getDirectory(scope) else {
131
+ let error = NSError(domain: "", code: 200, userInfo: [NSLocalizedDescriptionKey : "Error reading directory \(scope)"])
132
+ reject("ERR_READ_ERROR", "Error reading directory \(scope)", error)
133
+ return
155
134
  }
156
135
 
136
+ // remove leading slashes
137
+ let path = path.replacingOccurrences(of: "^/+", with: "", options: .regularExpression)
138
+
139
+ // append path to scope directory and return URL
140
+ let filePath = directory.appendingPathComponent(path)
141
+
142
+ let isDownloadable = fileManager.isUbiquitousItem(at: filePath)
143
+
144
+ if (!isDownloadable) {
145
+ reject("ERR_FILE_NOT_DOWNLOADABLE", "File or directory \(path) is not an iCloud file", NSError(domain: "", code: 202, userInfo: [NSLocalizedDescriptionKey : "File or directory \(path) is not an iCloud file"]))
146
+ return
147
+ }
148
+ do {
149
+ // trigger download of file
150
+ try fileManager.startDownloadingUbiquitousItem(at: filePath)
151
+ } catch {
152
+ let error = NSError(domain: "", code: 202, userInfo: [NSLocalizedDescriptionKey : "File or directory \(path) not downloadable"])
153
+ reject("ERR_FILE_NOT_DOWNLOADABLE", "File or directory \(path) not downloadable", error)
154
+ return
155
+ }
156
+ resolve(true)
157
+ }
158
+
157
159
 
158
160
  @objc(deleteFile:withScope:withResolver:withRejecter:)
159
161
  func deleteFile(path: String, scope: String, resolve:RCTPromiseResolveBlock,reject:RCTPromiseRejectBlock) -> Void {
@@ -1 +1 @@
1
- {"version":3,"names":["_reactNative","require","_createRNCloudStorage","_interopRequireDefault","_googleDrive","_main","_helpers","obj","__esModule","default","nativeInstance","createRNCloudStorage","defaultScope","CloudStorageScope","AppData","RNCloudStorage","getDefaultScope","setDefaultScope","scope","getGoogleDriveAccessToken","GoogleDriveApiClient","accessToken","setGoogleDriveAccessToken","setThrowOnFilesWithSameName","enable","throwOnFilesWithSameName","subscribeToFilesWithSameName","Platform","OS","subscriber","remove","bind","isCloudAvailable","appendFile","path","data","appendToFile","verifyLeadingSlash","exists","fileExists","writeFile","createFile","mkdir","createDirectory","readdir","listFiles","readFile","downloadFile","unlink","deleteFile","stat","native","statFile","birthtime","Date","birthtimeMs","mtime","mtimeMs","isDirectory","isFile","_default","exports"],"sourceRoot":"../../src","sources":["RNCloudStorage.ts"],"mappings":";;;;;;AAAA,IAAAA,YAAA,GAAAC,OAAA;AACA,IAAAC,qBAAA,GAAAC,sBAAA,CAAAF,OAAA;AACA,IAAAG,YAAA,GAAAD,sBAAA,CAAAF,OAAA;AACA,IAAAI,KAAA,GAAAJ,OAAA;AACA,IAAAK,QAAA,GAAAL,OAAA;AAAqD,SAAAE,uBAAAI,GAAA,WAAAA,GAAA,IAAAA,GAAA,CAAAC,UAAA,GAAAD,GAAA,KAAAE,OAAA,EAAAF,GAAA;AAErD,MAAMG,cAAc,GAAG,IAAAC,6BAAoB,GAAE;AAC7C,IAAIC,YAAY,GAAGC,uBAAiB,CAACC,OAAO;AAE5C,MAAMC,cAAc,GAAG;EACrBC,eAAe,EAAEA,CAAA,KAAMJ,YAAY;EACnCK,eAAe,EAAGC,KAAwB,IAAMN,YA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IAAIN,YAAY,CAAC;IAE7F,OAAO;MACL,GAAGuC,MAAM;MACTE,SAAS,EAAE,IAAIC,IAAI,CAACH,MAAM,CAACI,WAAW,CAAC;MACvCC,KAAK,EAAE,IAAIF,IAAI,CAACH,MAAM,CAACM,OAAO,CAAC;MAC/BC,WAAW,EAAEA,CAAA,KAAMP,MAAM,CAACO,WAAW;MACrCC,MAAM,EAAEA,CAAA,KAAMR,MAAM,CAACQ;IACvB,CAAC;EACH;AACF,CAAC;AAAC,IAAAC,QAAA,GAEa7C,cAAc;AAAA8C,OAAA,CAAApD,OAAA,GAAAmD,QAAA"}
1
+ {"version":3,"names":["_reactNative","require","_createRNCloudStorage","_interopRequireDefault","_googleDrive","_main","_helpers","obj","__esModule","default","nativeInstance","createRNCloudStorage","defaultScope","CloudStorageScope","AppData","RNCloudStorage","getDefaultScope","setDefaultScope","scope","getGoogleDriveAccessToken","GoogleDrive","accessToken","setGoogleDriveAccessToken","setThrowOnFilesWithSameName","enable","throwOnFilesWithSameName","subscribeToFilesWithSameName","Platform","OS","subscriber","remove","bind","isCloudAvailable","appendFile","path","data","appendToFile","verifyLeadingSlash","exists","fileExists","writeFile","createFile","mkdir","createDirectory","readdir","listFiles","readFile","downloadFile","unlink","deleteFile","stat","native","statFile","birthtime","Date","birthtimeMs","mtime","mtimeMs","isDirectory","isFile","_default","exports"],"sourceRoot":"../../src","sources":["RNCloudStorage.ts"],"mappings":";;;;;;AAAA,IAAAA,YAAA,GAAAC,OAAA;AACA,IAAAC,qBAAA,GAAAC,sBAAA,CAAAF,OAAA;AACA,IAAAG,YAAA,GAAAD,sBAAA,CAAAF,OAAA;AACA,IAAAI,KAAA,GAAAJ,OAAA;AACA,IAAAK,QAAA,GAAAL,OAAA;AAAqD,SAAAE,uBAAAI,GAAA,WAAAA,GAAA,IAAAA,GAAA,CAAAC,UAAA,GAAAD,GAAA,KAAAE,OAAA,EAAAF,GAAA;AAErD,MAAMG,cAAc,GAAG,IAAAC,6BAAoB,GAAE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,CAAOhB,IAAY,EAAEhB,KAAyB,KAAoC;IACtF,MAAMiC,MAAM,GAAG,MAAMzC,cAAc,CAAC0C,QAAQ,CAAC,IAAAf,2BAAkB,EAACH,IAAI,CAAC,EAAEhB,KAAK,IAAIN,YAAY,CAAC;IAE7F,OAAO;MACL,GAAGuC,MAAM;MACTE,SAAS,EAAE,IAAIC,IAAI,CAACH,MAAM,CAACI,WAAW,CAAC;MACvCC,KAAK,EAAE,IAAIF,IAAI,CAACH,MAAM,CAACM,OAAO,CAAC;MAC/BC,WAAW,EAAEA,CAAA,KAAMP,MAAM,CAACO,WAAW;MACrCC,MAAM,EAAEA,CAAA,KAAMR,MAAM,CAACQ;IACvB,CAAC;EACH;AACF,CAAC;AAAC,IAAAC,QAAA,GAEa7C,cAAc;AAAA8C,OAAA,CAAApD,OAAA,GAAAmD,QAAA"}
@@ -1 +1 @@
1
- {"version":3,"names":["_reactNative","require","_googleDrive","_interopRequireDefault","_native","_CloudStorageError","obj","__esModule","default","LINKING_ERROR","Platform","select","ios","nativeIosInstance","NativeModules","CloudStorage","Proxy","get","target","prop","originalFunction","arguments","error","code","Object","values","CloudStorageErrorCode","includes","CloudStorageError","message","UNKNOWN","createRNCloudStorage","OS","Error","GoogleDriveApiClient"],"sourceRoot":"../../src","sources":["createRNCloudStorage.ts"],"mappings":";;;;;;AAAA,IAAAA,YAAA,GAAAC,OAAA;AAEA,IAAAC,YAAA,GAAAC,sBAAA,CAAAF,OAAA;AACA,IAAAG,OAAA,GAAAH,OAAA;AACA,IAAAI,kBAAA,GAAAF,sBAAA,CAAAF,OAAA;AAA0D,SAAAE,uBAAAG,GAAA,WAAAA,GAAA,IAAAA,GAAA,CAAAC,UAAA,GAAAD,GAAA,KAAAE,OAAA,EAAAF,GAAA;AAE1D,MAAMG,aAAa,GAChB,qFAAoF,GACrFC,qBAAQ,CAACC,MAAM,CAAC;EAAEC,GAAG,EAAE,gCAAgC;EAAEJ,OAAO,EAAE;AAAG,CAAC,CAAC,GACvE,sDAAsD,GACtD,+BAA+B;;AAEjC;AACA,MAAMK,iBAAiB,GAAGC,0BAAa,CAACC,YAAY,GAChD,IAAIC,KAAK,CAACF,0BAAa,CAACC,YAAY,EAAE;EACpCE,GAAGA,CAACC,MAA4B,EAAEC,IAAgC,EAAE;IAClE,MAAMC,gBAAgB,GAAGF,MAAM,CAACC,IAAI,CAAC;IACrC,IAAI,OAAOC,gBAAgB,KAAK,UAAU,EAAE;MAC1C,OAAO,kBAA0B;QAC/B,IAAI;UACF;UACA,OAAO,MAAMA,gBAAgB,CAAC,GAAAC,SAAO,CAAC;QACxC,CAAC,CAAC,OAAOC,KAAU,EAAE;UACnB,IAAIA,KAAK,aAALA,KAAK,eAALA,KAAK,CAAEC,IAAI,IAAIC,MAAM,CAACC,MAAM,CAACC,6BAAqB,CAAC,CAACC,QAAQ,CAACL,KAAK,CAACC,IAAI,CAAC,EAAE;YAC5E,MAAM,IAAIK,0BAAiB,CAAC,CAAAN,KAAK,aAALA,KAAK,uBAALA,KAAK,CAAEO,OAAO,KAAI,EAAE,EAAEP,KAAK,CAACC,IAAI,CAA0B;UACxF,CAAC,MAAM;YACL,MAAM,IAAIK,0BAAiB,CAAC,eAAe,EAAEF,6BAAqB,CAACI,OAAO,EAAER,KAAK,CAAC;UACpF;QACF;MACF,CAAC;IACH;IACA,OAAOF,gBAAgB;EACzB;AACF,CAAC,CAAC,GACF,IAAI;AAEO,SAASW,oBAAoBA,CAAA,EAAyB;EACnE,IAAIrB,qBAAQ,CAACsB,EAAE,KAAK,KAAK,EAAE;IACzB,OACEnB,iBAAiB,IACjB,IAAIG,KAAK,CACP,CAAC,CAAC,EACF;MACEC,GAAGA,CAAA,EAAG;QACJ,MAAM,IAAIgB,KAAK,CAACxB,aAAa,CAAC;MAChC;IACF,CAAC,CACF;EAEL;EAEA,OAAO,IAAIyB,oBAAoB,EAAE;AACnC"}
1
+ {"version":3,"names":["_reactNative","require","_googleDrive","_interopRequireDefault","_native","_CloudStorageError","obj","__esModule","default","LINKING_ERROR","Platform","select","ios","nativeIosInstance","NativeModules","CloudStorage","Proxy","get","target","prop","originalFunction","arguments","error","code","Object","values","CloudStorageErrorCode","includes","CloudStorageError","message","UNKNOWN","createRNCloudStorage","OS","Error","GoogleDrive"],"sourceRoot":"../../src","sources":["createRNCloudStorage.ts"],"mappings":";;;;;;AAAA,IAAAA,YAAA,GAAAC,OAAA;AAEA,IAAAC,YAAA,GAAAC,sBAAA,CAAAF,OAAA;AACA,IAAAG,OAAA,GAAAH,OAAA;AACA,IAAAI,kBAAA,GAAAF,sBAAA,CAAAF,OAAA;AAA0D,SAAAE,uBAAAG,GAAA,WAAAA,GAAA,IAAAA,GAAA,CAAAC,UAAA,GAAAD,GAAA,KAAAE,OAAA,EAAAF,GAAA;AAE1D,MAAMG,aAAa,GAChB,qFAAoF,GACrFC,qBAAQ,CAACC,MAAM,CAAC;EAAEC,GAAG,EAAE,gCAAgC;EAAEJ,OAAO,EAAE;AAAG,CAAC,CAAC,GACvE,sDAAsD,GACtD,+BAA+B;;AAEjC;AACA,MAAMK,iBAAiB,GAAGC,0BAAa,CAACC,YAAY,GAChD,IAAIC,KAAK,CAACF,0BAAa,CAACC,YAAY,EAAE;EACpCE,GAAGA,CAACC,MAA4B,EAAEC,IAAgC,EAAE;IAClE,MAAMC,gBAAgB,GAAGF,MAAM,CAACC,IAAI,CAAC;IACrC,IAAI,OAAOC,gBAAgB,KAAK,UAAU,EAAE;MAC1C,OAAO,kBAA0B;QAC/B,IAAI;UACF;UACA,OAAO,MAAMA,gBAAgB,CAAC,GAAAC,SAAO,CAAC;QACxC,CAAC,CAAC,OAAOC,KAAU,EAAE;UACnB,IAAIA,KAAK,aAALA,KAAK,eAALA,KAAK,CAAEC,IAAI,IAAIC,MAAM,CAACC,MAAM,CAACC,6BAAqB,CAAC,CAACC,QAAQ,CAACL,KAAK,CAACC,IAAI,CAAC,EAAE;YAC5E,MAAM,IAAIK,0BAAiB,CAAC,CAAAN,KAAK,aAALA,KAAK,uBAALA,KAAK,CAAEO,OAAO,KAAI,EAAE,EAAEP,KAAK,CAACC,IAAI,CAA0B;UACxF,CAAC,MAAM;YACL,MAAM,IAAIK,0BAAiB,CAAC,eAAe,EAAEF,6BAAqB,CAACI,OAAO,EAAER,KAAK,CAAC;UACpF;QACF;MACF,CAAC;IACH;IACA,OAAOF,gBAAgB;EACzB;AACF,CAAC,CAAC,GACF,IAAI;AAEO,SAASW,oBAAoBA,CAAA,EAAyB;EACnE,IAAIrB,qBAAQ,CAACsB,EAAE,KAAK,KAAK,EAAE;IACzB,OACEnB,iBAAiB,IACjB,IAAIG,KAAK,CACP,CAAC,CAAC,EACF;MACEC,GAAGA,CAAA,EAAG;QACJ,MAAM,IAAIgB,KAAK,CAACxB,aAAa,CAAC;MAChC;IACF,CAAC,CACF;EAEL;EAEA,OAAO,IAAIyB,oBAAW,EAAE;AAC1B"}
@@ -0,0 +1,169 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.default = exports.GoogleDriveHttpError = void 0;
7
+ var _types = require("./types");
8
+ const BASE_URL = 'https://www.googleapis.com/drive/v3';
9
+ const BASE_UPLOAD_URL = 'https://www.googleapis.com/upload/drive/v3';
10
+ const MULTIPART_BOUNDARY = 'foo_bar_baz';
11
+ class GoogleDriveHttpError extends Error {
12
+ constructor(message, status, json) {
13
+ super(message);
14
+ this.status = status;
15
+ this.json = json;
16
+ }
17
+ }
18
+
19
+ // TODO: fetch timeout
20
+ // TODO: properly handle errors
21
+ exports.GoogleDriveHttpError = GoogleDriveHttpError;
22
+ class GoogleDriveApiClient {
23
+ constructor() {
24
+ let accessToken = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
25
+ this.accessToken = accessToken;
26
+ }
27
+ buildQueryString(query) {
28
+ let res = Object.entries(query).filter(_ref => {
29
+ let [, value] = _ref;
30
+ return value !== undefined;
31
+ }).map(_ref2 => {
32
+ let [key, value] = _ref2;
33
+ if (typeof value === 'boolean') return `${encodeURIComponent(key)}=${value ? 'true' : 'false'}`;
34
+ return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
35
+ }).join('&');
36
+ if (res) {
37
+ res = `?${res}`;
38
+ }
39
+ return res;
40
+ }
41
+ async request(operation) {
42
+ let {
43
+ queryParameters,
44
+ baseUrl,
45
+ ...options
46
+ } = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
47
+ let path = `${baseUrl ?? BASE_URL}${operation}`;
48
+ if (queryParameters) {
49
+ path += this.buildQueryString(queryParameters);
50
+ }
51
+ const response = await fetch(path, {
52
+ ...options,
53
+ headers: {
54
+ ...options.headers,
55
+ Authorization: `Bearer ${this.accessToken}`
56
+ }
57
+ });
58
+ if (!response.ok) {
59
+ let errorMessage;
60
+ let json = null;
61
+ try {
62
+ var _json$error;
63
+ json = await response.json();
64
+ errorMessage = ((_json$error = json.error) === null || _json$error === void 0 ? void 0 : _json$error.message) ?? `Request failed with status ${response.status}`;
65
+ } catch (e) {
66
+ errorMessage = `Request failed with status ${response.status}`;
67
+ }
68
+ throw new GoogleDriveHttpError(errorMessage, response.status, json);
69
+ }
70
+ if (options !== null && options !== void 0 && options.headers && 'Accept' in options.headers && options.headers.Accept !== 'application/json') {
71
+ return response.text();
72
+ }
73
+ return response.json();
74
+ }
75
+ buildMultiPartBody(metadata, media) {
76
+ const body = [];
77
+ body.push(`--${MULTIPART_BOUNDARY}\r\n`);
78
+ body.push(`Content-Type: ${_types.MimeTypes.JSON}; charset=UTF-8\r\n\r\n`);
79
+ body.push(`${JSON.stringify(metadata)}\r\n`);
80
+ body.push(`--${MULTIPART_BOUNDARY}\r\n`);
81
+ body.push(`Content-Type: ${media.mimeType}\r\n\r\n`);
82
+ body.push(`${media.body}\r\n`);
83
+ body.push(`--${MULTIPART_BOUNDARY}--`);
84
+ return body.join('');
85
+ }
86
+ async listFiles(space) {
87
+ const files = [];
88
+ let pageToken;
89
+ const fields = ['id', 'kind', 'mimeType', 'name', 'parents', 'spaces', 'size', 'createdTime', 'modifiedTime'];
90
+ do {
91
+ const queryParameters = {
92
+ fields: `files(${fields.join(',')}),nextPageToken`,
93
+ spaces: space
94
+ };
95
+ const response = await this.request(`/files`, {
96
+ queryParameters
97
+ });
98
+ files.push(...response.files);
99
+ pageToken = response.nextPageToken ?? undefined;
100
+ } while (pageToken);
101
+ return files;
102
+ }
103
+ async getFile(fileId) {
104
+ const queryParameters = {
105
+ fields: ['id', 'kind', 'mimeType', 'name', 'parents', 'spaces', 'size', 'createdTime', 'modifiedTime'].join(',')
106
+ };
107
+ return this.request(`/files/${fileId}`, {
108
+ queryParameters
109
+ });
110
+ }
111
+ async getFileText(fileId) {
112
+ return this.request(`/files/${fileId}`, {
113
+ queryParameters: {
114
+ alt: 'media'
115
+ },
116
+ headers: {
117
+ Accept: 'text/plain'
118
+ }
119
+ });
120
+ }
121
+ async deleteFile(fileId) {
122
+ return this.request(`/files/${fileId}`, {
123
+ method: 'DELETE'
124
+ });
125
+ }
126
+ async createFile(metadata, media) {
127
+ const multipartRequestBody = this.buildMultiPartBody(metadata, media);
128
+ await this.request(`/files`, {
129
+ queryParameters: {
130
+ uploadType: 'multipart'
131
+ },
132
+ method: 'POST',
133
+ headers: {
134
+ 'Content-Type': `multipart/related; boundary=${MULTIPART_BOUNDARY}`,
135
+ 'Content-Length': multipartRequestBody.length.toString()
136
+ },
137
+ body: multipartRequestBody,
138
+ baseUrl: BASE_UPLOAD_URL
139
+ });
140
+ }
141
+ async createDirectory(metadata) {
142
+ await this.request(`/files`, {
143
+ method: 'POST',
144
+ headers: {
145
+ 'Content-Type': `application/json`
146
+ },
147
+ body: JSON.stringify({
148
+ ...metadata,
149
+ mimeType: _types.MimeTypes.FOLDER
150
+ })
151
+ });
152
+ }
153
+ async updateFile(fileId, media) {
154
+ await this.request(`/files/${fileId}`, {
155
+ queryParameters: {
156
+ uploadType: 'media'
157
+ },
158
+ method: 'PATCH',
159
+ headers: {
160
+ 'Content-Type': media.mimeType,
161
+ 'Content-Length': media.body.length.toString()
162
+ },
163
+ body: media.body,
164
+ baseUrl: BASE_UPLOAD_URL
165
+ });
166
+ }
167
+ }
168
+ exports.default = GoogleDriveApiClient;
169
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"names":["_types","require","BASE_URL","BASE_UPLOAD_URL","MULTIPART_BOUNDARY","GoogleDriveHttpError","Error","constructor","message","status","json","exports","GoogleDriveApiClient","accessToken","arguments","length","undefined","buildQueryString","query","res","Object","entries","filter","_ref","value","map","_ref2","key","encodeURIComponent","join","request","operation","queryParameters","baseUrl","options","path","response","fetch","headers","Authorization","ok","errorMessage","_json$error","error","e","Accept","text","buildMultiPartBody","metadata","media","body","push","MimeTypes","JSON","stringify","mimeType","listFiles","space","files","pageToken","fields","spaces","nextPageToken","getFile","fileId","getFileText","alt","deleteFile","method","createFile","multipartRequestBody","uploadType","toString","createDirectory","FOLDER","updateFile","default"],"sourceRoot":"../../../src","sources":["google-drive/client.ts"],"mappings":";;;;;;AAAA,IAAAA,MAAA,GAAAC,OAAA;AAQA,MAAMC,QAAQ,GAAG,qCAAqC;AACtD,MAAMC,eAAe,GAAG,4CAA4C;AACpE,MAAMC,kBAAkB,GAAG,aAAa;AAEjC,MAAMC,oBAAoB,SAASC,KAAK,CAAC;EAI9CC,WAAWA,CAACC,OAAe,EAAEC,MAAc,EAAEC,IAAS,EAAE;IACtD,KAAK,CAACF,OAAO,CAAC;IACd,IAAI,CAACC,MAAM,GAAGA,MAAM;IACpB,IAAI,CAACC,IAAI,GAAGA,IAAI;EAClB;AACF;;AAEA;AACA;AAAAC,OAAA,CAAAN,oBAAA,GAAAA,oBAAA;AACe,MAAMO,oBAAoB,CAAC;EAGxCL,WAAWA,CAAA,EAA2B;IAAA,IAA1BM,WAAmB,GAAAC,SAAA,CAAAC,MAAA,QAAAD,SAAA,QAAAE,SAAA,GAAAF,SAAA,MAAG,EAAE;IAClC,IAAI,CAACD,WAAW,GAAGA,WA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C,UAAU,EAAE;MAAQ,CAAC;MACxCH,MAAM,EAAE,OAAO;MACf9B,OAAO,EAAE;QACP,cAAc,EAAEW,KAAK,CAACM,QAAQ;QAC9B,gBAAgB,EAAEN,KAAK,CAACC,IAAI,CAACnC,MAAM,CAACyD,QAAQ;MAC9C,CAAC;MACDtB,IAAI,EAAED,KAAK,CAACC,IAAI;MAChBjB,OAAO,EAAE9B;IACX,CAAC,CAAC;EACJ;AACF;AAACQ,OAAA,CAAAiE,OAAA,GAAAhE,oBAAA"}
@@ -4,23 +4,29 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports.default = void 0;
7
- var _reactNativeGoogleDriveApiWrapperJs = require("react-native-google-drive-api-wrapper-js");
8
7
  var _native = require("../types/native");
9
8
  var _CloudStorageError = _interopRequireDefault(require("../utils/CloudStorageError"));
9
+ var _types = require("./types");
10
10
  var _reactNative = require("react-native");
11
+ var _client = _interopRequireWildcard(require("./client"));
12
+ function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
13
+ function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
11
14
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
12
- class GoogleDriveApiClient {
13
- static drive = new _reactNativeGoogleDriveApiWrapperJs.GDrive();
15
+ // TODO: replace legacyDrive fully with new drive implementation
16
+ /**
17
+ * A proxy class that wraps the Google Drive API client implementation to match the native iOS interface.
18
+ */
19
+ class GoogleDrive {
20
+ static drive = new _client.default();
14
21
  static throwOnFilesWithSameName = false;
15
22
  constructor() {
16
23
  this.filesWithSameNameSubscribers = [];
17
- GoogleDriveApiClient.drive.fetchTimeout = 3000;
18
24
  return new Proxy(this, {
19
25
  // before calling any function, check if the access token is set
20
26
  get(target, prop) {
21
27
  const allowedFunctions = ['isCloudAvailable', 'subscribeToFilesWithSameName'];
22
28
  if (typeof target[prop] === 'function' && !allowedFunctions.includes(prop.toString())) {
23
- if (!GoogleDriveApiClient.drive.accessToken) {
29
+ if (!GoogleDrive.drive.accessToken.length) {
24
30
  throw new _CloudStorageError.default(`Google Drive access token is not set, cannot call function ${prop.toString()}`, _native.CloudStorageErrorCode.GOOGLE_DRIVE_ACCESS_TOKEN_MISSING);
25
31
  }
26
32
  }
@@ -31,7 +37,7 @@ class GoogleDriveApiClient {
31
37
 
32
38
  // when setting accessToken, set it on the GDrive instance
33
39
  static set accessToken(accessToken) {
34
- GoogleDriveApiClient.drive.accessToken = accessToken;
40
+ GoogleDrive.drive.accessToken = accessToken ?? '';
35
41
 
36
42
  // emit an event for the useIsCloudAvailable hook
37
43
  _reactNative.DeviceEventEmitter.emit('RNCloudStorage.cloud.availability-changed', {
@@ -39,7 +45,7 @@ class GoogleDriveApiClient {
39
45
  });
40
46
  }
41
47
  static get accessToken() {
42
- return GoogleDriveApiClient.drive.accessToken;
48
+ return GoogleDrive.drive.accessToken.length ? GoogleDrive.drive.accessToken : null;
43
49
  }
44
50
  subscribeToFilesWithSameName(subscriber) {
45
51
  this.filesWithSameNameSubscribers.push(subscriber);
@@ -49,10 +55,7 @@ class GoogleDriveApiClient {
49
55
  }
50
56
  };
51
57
  }
52
- isCloudAvailable = async () => {
53
- var _GoogleDriveApiClient;
54
- return !!((_GoogleDriveApiClient = GoogleDriveApiClient.accessToken) !== null && _GoogleDriveApiClient !== void 0 && _GoogleDriveApiClient.length);
55
- };
58
+ isCloudAvailable = async () => !!GoogleDrive.drive.accessToken.length;
56
59
  getRootDirectory(scope) {
57
60
  switch (scope) {
58
61
  case 'documents':
@@ -72,7 +75,7 @@ class GoogleDriveApiClient {
72
75
  };
73
76
  }
74
77
  findParentDirectoryId(files, directoryTree) {
75
- const possibleTopDirectories = files.filter(f => f.mimeType === _reactNativeGoogleDriveApiWrapperJs.MimeTypes.FOLDER).filter(f => f.name === directoryTree[0]);
78
+ const possibleTopDirectories = files.filter(f => f.mimeType === _types.MimeTypes.FOLDER).filter(f => f.name === directoryTree[0]);
76
79
  let topDirectoryId;
77
80
  if (possibleTopDirectories.length === 0) return null;else if (possibleTopDirectories.length === 1) {
78
81
  topDirectoryId = possibleTopDirectories[0].id;
@@ -81,7 +84,7 @@ class GoogleDriveApiClient {
81
84
  the files array - if it does not, it means that the directory is a child of the root directory and the one we're
82
85
  looking for */
83
86
  for (const possibleTopDirectory of possibleTopDirectories) {
84
- if (!files.find(f => f.id === possibleTopDirectory.parents[0] && f.mimeType === _reactNativeGoogleDriveApiWrapperJs.MimeTypes.FOLDER)) {
87
+ if (!files.find(f => f.id === possibleTopDirectory.parents[0] && f.mimeType === _types.MimeTypes.FOLDER)) {
85
88
  topDirectoryId = possibleTopDirectory.id;
86
89
  break;
87
90
  }
@@ -109,19 +112,12 @@ class GoogleDriveApiClient {
109
112
  * @returns A promise that resolves to the ID of the root directory or null if it could not be found.
110
113
  */
111
114
  async getRootDirectoryId(scope) {
112
- const files = await this.listInternalFiles(scope);
115
+ const files = await GoogleDrive.drive.listFiles(this.getRootDirectory(scope));
113
116
  for (const file of files) {
114
117
  if (!files.find(f => f.id === file.parents[0])) return file.parents[0] ?? null;
115
118
  }
116
119
  return null;
117
120
  }
118
- async listInternalFiles(scope) {
119
- const files = await GoogleDriveApiClient.drive.files.list({
120
- spaces: [this.getRootDirectory(scope)],
121
- fields: 'files(id,kind,mimeType,name,parents,spaces)'
122
- });
123
- return files.files;
124
- }
125
121
  checkIfMultipleFilesWithSameName(path, files, filename, parentDirectoryId) {
126
122
  let possibleFiles;
127
123
  if (parentDirectoryId) {
@@ -130,7 +126,7 @@ class GoogleDriveApiClient {
130
126
  possibleFiles = files.filter(f => f.name === filename && !files.find(f2 => f2.id === f.parents[0]));
131
127
  }
132
128
  if (possibleFiles.length <= 1) return;
133
- if (GoogleDriveApiClient.throwOnFilesWithSameName) {
129
+ if (GoogleDrive.throwOnFilesWithSameName) {
134
130
  throw new _CloudStorageError.default(`Multiple files with the same name found at path ${path}: ${possibleFiles.map(f => f.id).join(', ')}`, _native.CloudStorageErrorCode.MULTIPLE_FILES_SAME_NAME);
135
131
  } else {
136
132
  this.filesWithSameNameSubscribers.forEach(s => s({
@@ -142,7 +138,7 @@ class GoogleDriveApiClient {
142
138
  async getFileId(path, scope) {
143
139
  let throwIfDirectory = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
144
140
  try {
145
- const files = await this.listInternalFiles(scope);
141
+ const files = await GoogleDrive.drive.listFiles(this.getRootDirectory(scope));
146
142
  if (path === '' || path === '/') {
147
143
  const rootDirectoryId = await this.getRootDirectoryId(scope);
148
144
  if (!rootDirectoryId) throw new _CloudStorageError.default(`Root directory in scope ${scope} not found`, _native.CloudStorageErrorCode.DIRECTORY_NOT_FOUND);
@@ -164,13 +160,13 @@ class GoogleDriveApiClient {
164
160
  file = files.find(f => f.name === filename && f.parents[0] === parentDirectoryId);
165
161
  }
166
162
  if (!file) throw new _CloudStorageError.default(`File not found`, _native.CloudStorageErrorCode.FILE_NOT_FOUND);
167
- if (file.mimeType === _reactNativeGoogleDriveApiWrapperJs.MimeTypes.FOLDER && throwIfDirectory) {
163
+ if (file.mimeType === _types.MimeTypes.FOLDER && throwIfDirectory) {
168
164
  throw new _CloudStorageError.default(`Path ${path} is a directory`, _native.CloudStorageErrorCode.PATH_IS_DIRECTORY);
169
165
  }
170
166
  return file.id;
171
167
  } catch (e) {
172
168
  var _e$json, _e$json$error;
173
- if (e instanceof _reactNativeGoogleDriveApiWrapperJs.HttpError && ((_e$json = e.json) === null || _e$json === void 0 ? void 0 : (_e$json$error = _e$json.error) === null || _e$json$error === void 0 ? void 0 : _e$json$error.status) === 'UNAUTHENTICATED') {
169
+ if (e instanceof _client.GoogleDriveHttpError && ((_e$json = e.json) === null || _e$json === void 0 ? void 0 : (_e$json$error = _e$json.error) === null || _e$json$error === void 0 ? void 0 : _e$json$error.status) === 'UNAUTHENTICATED') {
174
170
  throw new _CloudStorageError.default(`Could not authenticate with Google Drive`, _native.CloudStorageErrorCode.AUTHENTICATION_FAILED, e.json);
175
171
  } else {
176
172
  if (e instanceof _CloudStorageError.default) throw e;
@@ -191,7 +187,7 @@ class GoogleDriveApiClient {
191
187
  let prevContent = '';
192
188
  try {
193
189
  fileId = await this.getFileId(path, scope);
194
- prevContent = await GoogleDriveApiClient.drive.files.getText(fileId);
190
+ prevContent = await GoogleDrive.drive.getFileText(fileId);
195
191
  } catch (e) {
196
192
  if (e instanceof _CloudStorageError.default && e.code === _native.CloudStorageErrorCode.FILE_NOT_FOUND) {
197
193
  /* do nothing, simply create the file */
@@ -199,20 +195,26 @@ class GoogleDriveApiClient {
199
195
  throw e;
200
196
  }
201
197
  }
202
- const uploader = GoogleDriveApiClient.drive.files.newMultipartUploader().setData(prevContent + data, _reactNativeGoogleDriveApiWrapperJs.MimeTypes.TEXT);
203
- if (fileId) uploader.setIdOfFileToUpdate(fileId);else {
204
- const files = await this.listInternalFiles(scope);
198
+ if (fileId) {
199
+ await GoogleDrive.drive.updateFile(fileId, {
200
+ body: prevContent + data,
201
+ mimeType: _types.MimeTypes.TEXT
202
+ });
203
+ } else {
204
+ const files = await GoogleDrive.drive.listFiles(this.getRootDirectory(scope));
205
205
  const {
206
206
  directories,
207
207
  filename
208
208
  } = this.resolvePathToDirectories(path);
209
209
  const parentDirectoryId = this.findParentDirectoryId(files, directories);
210
- uploader.setRequestBody({
210
+ await GoogleDrive.drive.createFile({
211
211
  name: filename,
212
212
  parents: parentDirectoryId ? [parentDirectoryId] : scope === 'app_data' ? [this.getRootDirectory(scope)] : undefined
213
+ }, {
214
+ body: data,
215
+ mimeType: _types.MimeTypes.TEXT
213
216
  });
214
217
  }
215
- await uploader.execute();
216
218
  }
217
219
  async createFile(path, data, scope, overwrite) {
218
220
  let fileId;
@@ -238,23 +240,29 @@ class GoogleDriveApiClient {
238
240
  }
239
241
  }
240
242
  }
241
- const uploader = GoogleDriveApiClient.drive.files.newMultipartUploader().setData(data, _reactNativeGoogleDriveApiWrapperJs.MimeTypes.TEXT);
242
- if (fileId) uploader.setIdOfFileToUpdate(fileId);else {
243
- const files = await this.listInternalFiles(scope);
243
+ if (fileId) {
244
+ await GoogleDrive.drive.updateFile(fileId, {
245
+ body: data,
246
+ mimeType: _types.MimeTypes.TEXT
247
+ });
248
+ } else {
249
+ const files = await GoogleDrive.drive.listFiles(this.getRootDirectory(scope));
244
250
  const {
245
251
  directories,
246
252
  filename
247
253
  } = this.resolvePathToDirectories(path);
248
254
  const parentDirectoryId = this.findParentDirectoryId(files, directories);
249
- uploader.setRequestBody({
255
+ await GoogleDrive.drive.createFile({
250
256
  name: filename,
251
257
  parents: parentDirectoryId ? [parentDirectoryId] : scope === 'app_data' ? [this.getRootDirectory(scope)] : undefined
258
+ }, {
259
+ body: data,
260
+ mimeType: _types.MimeTypes.TEXT
252
261
  });
253
262
  }
254
- await uploader.execute();
255
263
  }
256
264
  async listFiles(path, scope) {
257
- const allFiles = await this.listInternalFiles(scope);
265
+ const allFiles = await GoogleDrive.drive.listFiles(this.getRootDirectory(scope));
258
266
  if (path !== '') {
259
267
  const fileId = await this.getFileId(path, scope, false);
260
268
  const files = allFiles.filter(f => (f.parents ?? [])[0] === fileId);
@@ -277,23 +285,20 @@ class GoogleDriveApiClient {
277
285
  throw e;
278
286
  }
279
287
  }
280
- const uploader = GoogleDriveApiClient.drive.files.newMetadataOnlyUploader();
281
- const files = await this.listInternalFiles(scope);
288
+ const files = await GoogleDrive.drive.listFiles(this.getRootDirectory(scope));
282
289
  const {
283
290
  directories,
284
291
  filename
285
292
  } = this.resolvePathToDirectories(path);
286
293
  const parentDirectoryId = this.findParentDirectoryId(files, directories);
287
- uploader.setRequestBody({
294
+ await GoogleDrive.drive.createDirectory({
288
295
  name: filename,
289
- mimeType: _reactNativeGoogleDriveApiWrapperJs.MimeTypes.FOLDER,
290
296
  parents: parentDirectoryId ? [parentDirectoryId] : scope === 'app_data' ? [this.getRootDirectory(scope)] : undefined
291
297
  });
292
- await uploader.execute();
293
298
  }
294
299
  async readFile(path, scope) {
295
300
  const fileId = await this.getFileId(path, scope);
296
- const content = await GoogleDriveApiClient.drive.files.getText(fileId);
301
+ const content = await GoogleDrive.drive.getFileText(fileId);
297
302
  return content;
298
303
  }
299
304
  async downloadFile(_path, _scope) {
@@ -302,21 +307,19 @@ class GoogleDriveApiClient {
302
307
  }
303
308
  async deleteFile(path, scope) {
304
309
  const fileId = await this.getFileId(path, scope);
305
- await GoogleDriveApiClient.drive.files.delete(fileId);
310
+ await GoogleDrive.drive.deleteFile(fileId);
306
311
  }
307
312
  async statFile(path, scope) {
308
313
  const fileId = await this.getFileId(path, scope, false);
309
- const file = await (await GoogleDriveApiClient.drive.files.get(fileId, {
310
- fields: 'id,kind,mimeType,name,parents,spaces,size,createdTime,modifiedTime'
311
- })).json();
314
+ const file = await GoogleDrive.drive.getFile(fileId);
312
315
  return {
313
316
  size: file.size ?? 0,
314
317
  birthtimeMs: new Date(file.createdTime).getTime(),
315
318
  mtimeMs: new Date(file.modifiedTime).getTime(),
316
- isDirectory: file.mimeType === _reactNativeGoogleDriveApiWrapperJs.MimeTypes.FOLDER,
317
- isFile: file.mimeType !== _reactNativeGoogleDriveApiWrapperJs.MimeTypes.FOLDER
319
+ isDirectory: file.mimeType === _types.MimeTypes.FOLDER,
320
+ isFile: file.mimeType !== _types.MimeTypes.FOLDER
318
321
  };
319
322
  }
320
323
  }
321
- exports.default = GoogleDriveApiClient;
324
+ exports.default = GoogleDrive;
322
325
  //# sourceMappingURL=index.js.map