box-node-sdk 1.37.0 → 1.39.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 (174) hide show
  1. package/CHANGELOG.md +38 -2
  2. package/README.md +2 -0
  3. package/lib/api-request-manager.d.ts +38 -0
  4. package/lib/api-request-manager.js +48 -55
  5. package/lib/api-request-manager.js.map +1 -0
  6. package/lib/api-request.d.ts +137 -0
  7. package/lib/api-request.js +202 -281
  8. package/lib/api-request.js.map +1 -0
  9. package/lib/box-client.d.ts +271 -0
  10. package/lib/box-client.js +580 -713
  11. package/lib/box-client.js.map +1 -0
  12. package/lib/box-node-sdk.d.ts +216 -0
  13. package/lib/box-node-sdk.js +317 -352
  14. package/lib/box-node-sdk.js.map +1 -0
  15. package/lib/chunked-uploader.d.ts +129 -0
  16. package/lib/chunked-uploader.js +287 -358
  17. package/lib/chunked-uploader.js.map +1 -0
  18. package/lib/enterprise-event-stream.d.ts +82 -0
  19. package/lib/enterprise-event-stream.js +189 -203
  20. package/lib/enterprise-event-stream.js.map +1 -0
  21. package/lib/event-stream.d.ts +92 -0
  22. package/lib/event-stream.js +274 -302
  23. package/lib/event-stream.js.map +1 -0
  24. package/lib/managers/collaboration-allowlist.d.ts +137 -0
  25. package/lib/managers/collaboration-allowlist.js +200 -0
  26. package/lib/managers/collaboration-allowlist.js.map +1 -0
  27. package/lib/managers/collaboration-whitelist.d.ts +3 -0
  28. package/lib/managers/collaboration-whitelist.js +8 -222
  29. package/lib/managers/collaboration-whitelist.js.map +1 -0
  30. package/lib/managers/collaborations.d.ts +166 -0
  31. package/lib/managers/collaborations.js +225 -258
  32. package/lib/managers/collaborations.js.map +1 -0
  33. package/lib/managers/collections.d.ts +42 -0
  34. package/lib/managers/collections.js +45 -50
  35. package/lib/managers/collections.js.map +1 -0
  36. package/lib/managers/comments.d.ts +103 -0
  37. package/lib/managers/comments.js +158 -173
  38. package/lib/managers/comments.js.map +1 -0
  39. package/lib/managers/device-pins.d.ts +52 -0
  40. package/lib/managers/device-pins.js +75 -88
  41. package/lib/managers/device-pins.js.map +1 -0
  42. package/lib/managers/enterprise.d.ts +162 -0
  43. package/lib/managers/enterprise.js +168 -199
  44. package/lib/managers/enterprise.js.map +1 -0
  45. package/lib/managers/events.d.ts +179 -0
  46. package/lib/managers/events.js +232 -254
  47. package/lib/managers/events.js.map +1 -0
  48. package/lib/managers/files.d.ts +773 -0
  49. package/lib/managers/files.js +1401 -1602
  50. package/lib/managers/files.js.map +1 -0
  51. package/lib/managers/folders.d.ts +347 -0
  52. package/lib/managers/folders.js +551 -630
  53. package/lib/managers/folders.js.map +1 -0
  54. package/lib/managers/groups.d.ts +202 -0
  55. package/lib/managers/groups.js +238 -288
  56. package/lib/managers/groups.js.map +1 -0
  57. package/lib/managers/legal-hold-policies.d.ts +190 -0
  58. package/lib/managers/legal-hold-policies.js +228 -272
  59. package/lib/managers/legal-hold-policies.js.map +1 -0
  60. package/lib/managers/metadata.d.ts +228 -0
  61. package/lib/managers/metadata.js +265 -329
  62. package/lib/managers/metadata.js.map +1 -0
  63. package/lib/managers/recent-items.d.ts +38 -0
  64. package/lib/managers/recent-items.js +32 -39
  65. package/lib/managers/recent-items.js.map +1 -0
  66. package/lib/managers/retention-policies.d.ts +251 -0
  67. package/lib/managers/retention-policies.js +278 -281
  68. package/lib/managers/retention-policies.js.map +1 -0
  69. package/lib/managers/search.d.ts +82 -0
  70. package/lib/managers/search.js +68 -88
  71. package/lib/managers/search.js.map +1 -0
  72. package/lib/managers/shared-items.d.ts +33 -0
  73. package/lib/managers/shared-items.js +54 -62
  74. package/lib/managers/shared-items.js.map +1 -0
  75. package/lib/managers/sign-requests.generated.d.ts +92 -0
  76. package/lib/managers/sign-requests.generated.js +97 -0
  77. package/lib/managers/sign-requests.generated.js.map +1 -0
  78. package/lib/managers/storage-policies.d.ts +86 -0
  79. package/lib/managers/storage-policies.js +108 -142
  80. package/lib/managers/storage-policies.js.map +1 -0
  81. package/lib/managers/tasks.d.ts +161 -0
  82. package/lib/managers/tasks.js +219 -260
  83. package/lib/managers/tasks.js.map +1 -0
  84. package/lib/managers/terms-of-service.d.ts +161 -0
  85. package/lib/managers/terms-of-service.js +250 -273
  86. package/lib/managers/terms-of-service.js.map +1 -0
  87. package/lib/managers/trash.d.ts +30 -0
  88. package/lib/managers/trash.js +30 -41
  89. package/lib/managers/trash.js.map +1 -0
  90. package/lib/managers/users.d.ts +130 -0
  91. package/lib/managers/users.js +160 -203
  92. package/lib/managers/users.js.map +1 -0
  93. package/lib/managers/web-links.d.ts +127 -0
  94. package/lib/managers/web-links.js +183 -209
  95. package/lib/managers/web-links.js.map +1 -0
  96. package/lib/managers/webhooks.d.ts +166 -0
  97. package/lib/managers/webhooks.js +303 -308
  98. package/lib/managers/webhooks.js.map +1 -0
  99. package/lib/schemas/file-base.generated.d.ts +32 -0
  100. package/lib/schemas/file-base.generated.js +3 -0
  101. package/lib/schemas/file-base.generated.js.map +1 -0
  102. package/lib/schemas/file-mini.generated.d.ts +41 -0
  103. package/lib/schemas/file-mini.generated.js +3 -0
  104. package/lib/schemas/file-mini.generated.js.map +1 -0
  105. package/lib/schemas/file-version-base.generated.d.ts +19 -0
  106. package/lib/schemas/file-version-base.generated.js +3 -0
  107. package/lib/schemas/file-version-base.generated.js.map +1 -0
  108. package/lib/schemas/file-version-mini.generated.d.ts +14 -0
  109. package/lib/schemas/file-version-mini.generated.js +3 -0
  110. package/lib/schemas/file-version-mini.generated.js.map +1 -0
  111. package/lib/schemas/folder-base.generated.d.ts +32 -0
  112. package/lib/schemas/folder-base.generated.js +3 -0
  113. package/lib/schemas/folder-base.generated.js.map +1 -0
  114. package/lib/schemas/folder-mini.generated.d.ts +31 -0
  115. package/lib/schemas/folder-mini.generated.js +3 -0
  116. package/lib/schemas/folder-mini.generated.js.map +1 -0
  117. package/lib/schemas/index.d.ts +13 -0
  118. package/lib/schemas/index.js +26 -0
  119. package/lib/schemas/index.js.map +1 -0
  120. package/lib/schemas/sign-request-create-request.generated.d.ts +62 -0
  121. package/lib/schemas/sign-request-create-request.generated.js +3 -0
  122. package/lib/schemas/sign-request-create-request.generated.js.map +1 -0
  123. package/lib/schemas/sign-request-create-signer.generated.d.ts +38 -0
  124. package/lib/schemas/sign-request-create-signer.generated.js +3 -0
  125. package/lib/schemas/sign-request-create-signer.generated.js.map +1 -0
  126. package/lib/schemas/sign-request-prefill-tag.generated.d.ts +28 -0
  127. package/lib/schemas/sign-request-prefill-tag.generated.js +3 -0
  128. package/lib/schemas/sign-request-prefill-tag.generated.js.map +1 -0
  129. package/lib/schemas/sign-request-signer-input.generated.d.ts +18 -0
  130. package/lib/schemas/sign-request-signer-input.generated.js +3 -0
  131. package/lib/schemas/sign-request-signer-input.generated.js.map +1 -0
  132. package/lib/schemas/sign-request-signer.generated.d.ts +23 -0
  133. package/lib/schemas/sign-request-signer.generated.js +3 -0
  134. package/lib/schemas/sign-request-signer.generated.js.map +1 -0
  135. package/lib/schemas/sign-request.generated.d.ts +50 -0
  136. package/lib/schemas/sign-request.generated.js +3 -0
  137. package/lib/schemas/sign-request.generated.js.map +1 -0
  138. package/lib/schemas/sign-requests.generated.d.ts +27 -0
  139. package/lib/schemas/sign-requests.generated.js +3 -0
  140. package/lib/schemas/sign-requests.generated.js.map +1 -0
  141. package/lib/sessions/anonymous-session.d.ts +69 -0
  142. package/lib/sessions/anonymous-session.js +88 -102
  143. package/lib/sessions/anonymous-session.js.map +1 -0
  144. package/lib/sessions/app-auth-session.d.ts +92 -0
  145. package/lib/sessions/app-auth-session.js +140 -160
  146. package/lib/sessions/app-auth-session.js.map +1 -0
  147. package/lib/sessions/basic-session.d.ts +56 -0
  148. package/lib/sessions/basic-session.js +40 -50
  149. package/lib/sessions/basic-session.js.map +1 -0
  150. package/lib/sessions/persistent-session.d.ts +96 -0
  151. package/lib/sessions/persistent-session.js +191 -211
  152. package/lib/sessions/persistent-session.js.map +1 -0
  153. package/lib/token-manager.d.ts +191 -0
  154. package/lib/token-manager.js +390 -465
  155. package/lib/token-manager.js.map +1 -0
  156. package/lib/util/config.d.ts +86 -0
  157. package/lib/util/config.js +146 -152
  158. package/lib/util/config.js.map +1 -0
  159. package/lib/util/errors.d.ts +50 -0
  160. package/lib/util/errors.js +134 -145
  161. package/lib/util/errors.js.map +1 -0
  162. package/lib/util/exponential-backoff.d.ts +11 -0
  163. package/lib/util/exponential-backoff.js +10 -22
  164. package/lib/util/exponential-backoff.js.map +1 -0
  165. package/lib/util/paging-iterator.d.ts +53 -0
  166. package/lib/util/paging-iterator.js +202 -218
  167. package/lib/util/paging-iterator.js.map +1 -0
  168. package/lib/util/serializable.d.ts +10 -0
  169. package/lib/util/serializable.js +18 -0
  170. package/lib/util/serializable.js.map +1 -0
  171. package/lib/util/url-path.d.ts +16 -0
  172. package/lib/util/url-path.js +20 -35
  173. package/lib/util/url-path.js.map +1 -0
  174. package/package.json +21 -2
package/lib/box-client.js CHANGED
@@ -1,87 +1,57 @@
1
+ "use strict";
1
2
  /**
2
3
  * @fileoverview Box API Client
3
4
  */
4
-
5
- 'use strict';
6
-
7
-
5
+ var __importDefault = (this && this.__importDefault) || function (mod) {
6
+ return (mod && mod.__esModule) ? mod : { "default": mod };
7
+ };
8
+ var bluebird_1 = require("bluebird");
8
9
  // ------------------------------------------------------------------------------
9
- // Typedefs and Callbacks
10
+ // API Resource Managers
10
11
  // ------------------------------------------------------------------------------
11
-
12
- /**
13
- * A collaboration role constant
14
- * @typedef {string} CollaborationRole
15
- */
16
-
17
- /**
18
- * A Box file or folder type constant
19
- * @typedef {string} ItemType
20
- */
21
-
22
- /**
23
- * An access level constant. Used for setting and updating shared links, folder upload, etc.
24
- * @typedef {?Object} AccessLevel
25
- */
26
-
12
+ var collaboration_allowlist_1 = __importDefault(require("./managers/collaboration-allowlist"));
13
+ var collaborations_1 = __importDefault(require("./managers/collaborations"));
14
+ var collections_1 = __importDefault(require("./managers/collections"));
15
+ var comments_1 = __importDefault(require("./managers/comments"));
16
+ var device_pins_1 = __importDefault(require("./managers/device-pins"));
17
+ var enterprise_1 = __importDefault(require("./managers/enterprise"));
18
+ var events_1 = __importDefault(require("./managers/events"));
19
+ var files_1 = __importDefault(require("./managers/files"));
20
+ var folders_1 = __importDefault(require("./managers/folders"));
21
+ var groups_1 = __importDefault(require("./managers/groups"));
22
+ var legal_hold_policies_1 = __importDefault(require("./managers/legal-hold-policies"));
23
+ var metadata_1 = __importDefault(require("./managers/metadata"));
24
+ var recent_items_1 = __importDefault(require("./managers/recent-items"));
25
+ var retention_policies_1 = __importDefault(require("./managers/retention-policies"));
26
+ var search_1 = __importDefault(require("./managers/search"));
27
+ var shared_items_1 = __importDefault(require("./managers/shared-items"));
28
+ var sign_requests_generated_1 = __importDefault(require("./managers/sign-requests.generated"));
29
+ var storage_policies_1 = __importDefault(require("./managers/storage-policies"));
30
+ var tasks_1 = __importDefault(require("./managers/tasks"));
31
+ var terms_of_service_1 = __importDefault(require("./managers/terms-of-service"));
32
+ var trash_1 = __importDefault(require("./managers/trash"));
33
+ var users_1 = __importDefault(require("./managers/users"));
34
+ var web_links_1 = __importDefault(require("./managers/web-links"));
35
+ var webhooks_1 = __importDefault(require("./managers/webhooks"));
27
36
  // ------------------------------------------------------------------------------
28
37
  // Requirements
29
38
  // ------------------------------------------------------------------------------
30
- var util = require('util'),
31
- qs = require('querystring'),
32
- errors = require('./util/errors'),
33
- httpStatusCodes = require('http-status'),
34
- isIP = require('net').isIP,
35
- merge = require('merge-options'),
36
- PagingIterator = require('./util/paging-iterator'),
37
- Promise = require('bluebird'),
38
- pkg = require('../package.json');
39
-
40
- // API Resource Managers
41
- var Users = require('./managers/users'),
42
- Files = require('./managers/files'),
43
- Folders = require('./managers/folders'),
44
- Collaborations = require('./managers/collaborations'),
45
- Groups = require('./managers/groups'),
46
- Comments = require('./managers/comments'),
47
- SharedItems = require('./managers/shared-items'),
48
- Metadata = require('./managers/metadata'),
49
- Collections = require('./managers/collections'),
50
- Events = require('./managers/events'),
51
- Search = require('./managers/search'),
52
- Tasks = require('./managers/tasks'),
53
- Trash = require('./managers/trash'),
54
- Enterprise = require('./managers/enterprise'),
55
- LegalHoldPolicies = require('./managers/legal-hold-policies'),
56
- WebLinks = require('./managers/web-links'),
57
- RetentionPolicies = require('./managers/retention-policies'),
58
- DevicePins = require('./managers/device-pins'),
59
- Webhooks = require('./managers/webhooks'),
60
- RecentItems = require('./managers/recent-items'),
61
- CollaborationWhitelist = require('./managers/collaboration-whitelist'),
62
- TermsOfService = require('./managers/terms-of-service'),
63
- StoragePolicies = require('./managers/storage-policies');
64
-
39
+ var util = require('util'), qs = require('querystring'), errors = require('./util/errors'), httpStatusCodes = require('http-status'), isIP = require('net').isIP, merge = require('merge-options'), PagingIterator = require('./util/paging-iterator'), pkg = require('../package.json');
65
40
  // ------------------------------------------------------------------------------
66
41
  // Private
67
42
  // ------------------------------------------------------------------------------
68
-
69
- // The Authorization header label
70
- var HEADER_AUTHORIZATION = 'Authorization',
71
- // Prefix our token with this string in the Authorization header
72
- HEADER_AUTHORIZATION_PREFIX = 'Bearer ',
73
- // The 'BoxApi' header label
74
- HEADER_BOXAPI = 'BoxApi',
75
- // The XFF header label - Used to give the API better information for uploads, rate-limiting, etc.
76
- HEADER_XFF = 'X-Forwarded-For',
77
- // As-User header
78
- HEADER_AS_USER = 'As-User',
79
- // Range of SUCCESS http status codes
80
- HTTP_STATUS_CODE_SUCCESS_BLOCK_RANGE = [
81
- 200,
82
- 299
83
- ];
84
-
43
+ // The Authorization header label
44
+ var HEADER_AUTHORIZATION = 'Authorization',
45
+ // Prefix our token with this string in the Authorization header
46
+ HEADER_AUTHORIZATION_PREFIX = 'Bearer ',
47
+ // The 'BoxApi' header label
48
+ HEADER_BOXAPI = 'BoxApi',
49
+ // The XFF header label - Used to give the API better information for uploads, rate-limiting, etc.
50
+ HEADER_XFF = 'X-Forwarded-For',
51
+ // As-User header
52
+ HEADER_AS_USER = 'As-User',
53
+ // Range of SUCCESS http status codes
54
+ HTTP_STATUS_CODE_SUCCESS_BLOCK_RANGE = [200, 299];
85
55
  /**
86
56
  * Build the 'Authorization' Header for the API
87
57
  *
@@ -90,31 +60,26 @@ var HEADER_AUTHORIZATION = 'Authorization',
90
60
  * @private
91
61
  */
92
62
  function buildAuthorizationHeader(accessToken) {
93
- return HEADER_AUTHORIZATION_PREFIX + accessToken;
63
+ return HEADER_AUTHORIZATION_PREFIX + accessToken;
94
64
  }
95
-
96
65
  /**
97
66
  * Returns true iff the response is a 401 UNAUTHORIZED that is caused by an expired access token.
98
67
  * @param {APIRequest~ResponseObject} response - The response returned by an APIRequestManager request
99
68
  * @returns {boolean} - true iff the response is a 401 UNAUTHORIZED caused by an expired access token
100
69
  * @private
101
70
  */
102
- function isUnauthorizedDueToExpiredAccessToken(response) {
103
- // There are three cases to consider:
104
- // 1) The response body is a Buffer. This indicates that the request was malformed (i.e. malformed url) so return false.
105
- // 2) The status code is UNAUTHORIZED and the response body is an empty object or null. This indicates that the access tokens are expired, so return true.
106
- // 3) The status code is UNAUTHORIZED and the response body is a non-empty object. This indicates that the 401 was returned for some reason other
107
- // than expired tokens, so return false.
108
-
109
- if (Buffer.isBuffer(response.body)) {
110
- return false;
111
- }
112
-
113
- var isResponseStatusCodeUnauthorized = response.statusCode === httpStatusCodes.UNAUTHORIZED,
114
- isResponseBodyEmpty = !response.body || Object.getOwnPropertyNames(response.body).length === 0;
115
- return isResponseStatusCodeUnauthorized && isResponseBodyEmpty;
71
+ function isUnauthorizedDueToExpiredAccessToken(response /* FIXME */) {
72
+ // There are three cases to consider:
73
+ // 1) The response body is a Buffer. This indicates that the request was malformed (i.e. malformed url) so return false.
74
+ // 2) The status code is UNAUTHORIZED and the response body is an empty object or null. This indicates that the access tokens are expired, so return true.
75
+ // 3) The status code is UNAUTHORIZED and the response body is a non-empty object. This indicates that the 401 was returned for some reason other
76
+ // than expired tokens, so return false.
77
+ if (Buffer.isBuffer(response.body)) {
78
+ return false;
79
+ }
80
+ var isResponseStatusCodeUnauthorized = response.statusCode === httpStatusCodes.UNAUTHORIZED, isResponseBodyEmpty = !response.body || Object.getOwnPropertyNames(response.body).length === 0;
81
+ return isResponseStatusCodeUnauthorized && isResponseBodyEmpty;
116
82
  }
117
-
118
83
  /**
119
84
  * Returns a full URL. If the url argument begins with http:// or https://, then url is simply returned.
120
85
  * Otherwise, the defaultBasePath is prepended to url and returned.
@@ -125,12 +90,11 @@ function isUnauthorizedDueToExpiredAccessToken(response) {
125
90
  * @private
126
91
  */
127
92
  function getFullURL(defaultBasePath, url) {
128
- if (/^https?:\/\//.test(url)) {
129
- return url;
130
- }
131
- return defaultBasePath + url;
93
+ if (/^https?:\/\//.test(url)) {
94
+ return url;
95
+ }
96
+ return defaultBasePath + url;
132
97
  }
133
-
134
98
  /**
135
99
  * Create a valid request object for the Batch API from a standard request
136
100
  * params object
@@ -139,17 +103,14 @@ function getFullURL(defaultBasePath, url) {
139
103
  * @private
140
104
  */
141
105
  function formatRequestForBatch(params) {
142
-
143
- var relativePath = params.url.replace(/^http.*?\/\d\.\d\//, '/');
144
-
145
- return {
146
- method: params.method,
147
- relative_url: relativePath + (params.qs ? `?${qs.stringify(params.qs)}` : ''),
148
- body: params.body,
149
- headers: params.headers
150
- };
106
+ var relativePath = params.url.replace(/^http.*?\/\d\.\d\//, '/');
107
+ return {
108
+ method: params.method,
109
+ relative_url: relativePath + (params.qs ? "?" + qs.stringify(params.qs) : ''),
110
+ body: params.body,
111
+ headers: params.headers,
112
+ };
151
113
  }
152
-
153
114
  /**
154
115
  * Format a Batch API response object into a standard request response
155
116
  * for use in response handling
@@ -157,201 +118,513 @@ function formatRequestForBatch(params) {
157
118
  * @returns {Object} The standard response object
158
119
  * @private
159
120
  */
160
- function formatResponseForBatch(response) {
161
-
162
- return {
163
- statusCode: response.status,
164
- headers: response.headers,
165
- body: response.response
166
- };
121
+ function formatResponseForBatch(response /* FIXME */) {
122
+ return {
123
+ statusCode: response.status,
124
+ headers: response.headers,
125
+ body: response.response,
126
+ };
167
127
  }
168
-
169
128
  /**
170
129
  * Construct the X-Box-UA header to send analytics identifiers
171
130
  * @param {Object} [client] Analytics client information
172
131
  * @returns {string} The header value
173
132
  */
174
- function constructBoxUAHeader(client) {
175
-
176
- var analyticsIdentifiers = {
177
- agent: `box-node-sdk/${pkg.version}`,
178
- env: `Node/${process.version.replace('v', '')}`
179
- };
180
-
181
- if (client) {
182
- analyticsIdentifiers.client = `${client.name}/${client.version}`;
183
- }
184
-
185
- return Object.keys(analyticsIdentifiers).map(k => `${k}=${analyticsIdentifiers[k]}`)
186
- .join('; ');
187
- }
188
-
189
- /**
190
- * The BoxClient can make API calls on behalf of a valid API Session. It is responsible
191
- * for formatting the requests and handling the response. Its goal is to deliver
192
- * sensible results to the user.
193
- *
194
- * @param {APISession} apiSession An initialized API Session, used to get/revoke tokens and handle
195
- * unauthorized responses from the API.
196
- * @param {Config} config The SDK configuration options
197
- * @param {APIRequestManager} requestManager The API Request Manager
198
- * @constructor
199
- */
200
- function BoxClient(apiSession, config, requestManager) {
201
- // the API Session used by the client for authentication
202
- this._session = apiSession;
203
-
204
- // Attach a request manager instance for making requests
205
- this._requestManager = requestManager;
206
-
207
- // An object of custom headers to apply to every request. Modified via BoxClient.setCustomHeader().
208
- this._customHeaders = {};
209
- // Attach the configured properties
210
- this._baseURL = util.format('%s/%s', config.apiRootURL, config.apiVersion);
211
- this._uploadBaseURL = util.format('%s/%s', config.uploadAPIRootURL, config.apiVersion);
212
- this._uploadRequestTimeoutMS = config.uploadRequestTimeoutMS;
213
- this._useIterators = config.iterators;
214
- this._analyticsClient = config.analyticsClient;
215
-
216
- // Attach API Resource Managers
217
- this.users = new Users(this);
218
- this.files = new Files(this);
219
- this.folders = new Folders(this);
220
- this.comments = new Comments(this);
221
- this.collaborations = new Collaborations(this);
222
- this.groups = new Groups(this);
223
- this.sharedItems = new SharedItems(this);
224
- this.metadata = new Metadata(this);
225
- this.collections = new Collections(this);
226
- this.events = new Events(this);
227
- this.search = new Search(this);
228
- this.tasks = new Tasks(this);
229
- this.trash = new Trash(this);
230
- this.enterprise = new Enterprise(this);
231
- this.legalHoldPolicies = new LegalHoldPolicies(this);
232
- this.weblinks = new WebLinks(this);
233
- this.retentionPolicies = new RetentionPolicies(this);
234
- this.devicePins = new DevicePins(this);
235
- this.webhooks = new Webhooks(this);
236
- this.recentItems = new RecentItems(this);
237
- this.collaborationWhitelist = new CollaborationWhitelist(this);
238
- this.termsOfService = new TermsOfService(this);
239
- this.storagePolicies = new StoragePolicies(this);
240
-
241
- // Array of requests when in batch mode, null otherwise
242
- this._batch = null;
133
+ function constructBoxUAHeader(client /* FIXME */) {
134
+ var analyticsIdentifiers = {
135
+ agent: "box-node-sdk/" + pkg.version,
136
+ env: "Node/" + process.version.replace('v', ''),
137
+ };
138
+ if (client) {
139
+ analyticsIdentifiers.client = client.name + "/" + client.version;
140
+ }
141
+ return Object.keys(analyticsIdentifiers)
142
+ .map(function (k) { return k + "=" + analyticsIdentifiers[k]; })
143
+ .join('; ');
243
144
  }
244
-
245
- /**
246
- * Returns an object containing the given headers as well as other headers (like the authorization header and
247
- * custom headers) that should be included in a request.
248
- * @param {?Object} callerHeaders - headers that the caller wishes to include in the request. This method will not
249
- * override these headers with its own. Thus, if all the headers that this method was planning to add are already
250
- * specified here, this method will return an object with exactly the same headers.
251
- * @param {string} accessToken - the access token that will be used to make the request
252
- * @returns {Object} - a new object with the headers needed for the request
253
- * @private
254
- */
255
- BoxClient.prototype._createHeadersForRequest = function(callerHeaders, accessToken) {
256
- var headers = {};
257
-
258
- // 'Authorization' - contains your valid access token for authorization
259
- headers[HEADER_AUTHORIZATION] = buildAuthorizationHeader(accessToken);
260
-
261
- // We copy our own custom headers (XFF, BoxApi, etc.) before copying over the caller-specified headers so that
262
- // the caller-specified headers will take precedence.
263
- Object.assign(headers, this._customHeaders, callerHeaders);
264
-
265
- // Add analytics headers last so they cannot be overwritten
266
- Object.assign(headers, { 'X-Box-UA': constructBoxUAHeader(this._analyticsClient) });
267
-
268
- return headers;
269
- };
270
-
271
- /**
272
- * Makes an API request to the Box API on behalf of the client. Before executing
273
- * the request, it first ensures the user has usable tokens. Will be called again
274
- * if the request returns a temporary error. Will propogate error if request returns
275
- * a permanent error, or if usable tokens are not available.
276
- *
277
- * @param {Object} params - Request lib params to configure the request
278
- * @param {APIRequest~Callback} [callback] - passed response data
279
- * @returns {Promise} Promise resolving to the response
280
- * @private
281
- */
282
- BoxClient.prototype._makeRequest = function(params, callback) {
283
-
284
- var promise;
285
-
286
- if (this._batch) {
287
-
288
- // eslint-disable-next-line promise/avoid-new
289
- promise = new Promise((resolve, reject) => {
290
- this._batch.push({ params, resolve, reject });
291
- });
292
- } else {
293
-
294
- // Check that tokens are fresh, update if tokens are expired or soon-to-be expired
295
- promise = this._session.getAccessToken(this._tokenOptions)
296
- .then(accessToken => {
297
-
298
- params.headers = this._createHeadersForRequest(params.headers, accessToken);
299
-
300
- if (params.streaming) {
301
- // streaming is specific to the SDK, so delete it from params before continuing
302
- delete params.streaming;
303
- var responseStream = this._requestManager.makeStreamingRequest(params);
304
- // Listen to 'response' event, so we can cleanup the token store in case when the request is unauthorized
305
- // due to expired access token
306
- responseStream.on('response', response => {
307
- if (isUnauthorizedDueToExpiredAccessToken(response)) {
308
-
309
- var expiredTokensError = errors.buildAuthError(response);
310
-
311
- // Give the session a chance to handle the error (ex: a persistent session will clear the token store)
312
- if (this._session.handleExpiredTokensError) {
313
- this._session.handleExpiredTokensError(expiredTokensError);
314
- }
315
- }
316
- });
317
-
318
- return responseStream;
319
- }
320
-
321
- // Make the request to Box, and perform standard response handling
322
- return this._requestManager.makeRequest(params);
323
- });
324
- }
325
-
326
- return promise
327
- .then(response => {
328
-
329
- if (!response.statusCode) {
330
- // Response is not yet complete, and is just a stream that will return the response later
331
- // Just return the stream, since it doesn't need further response handling
332
- return response;
333
- }
334
-
335
- if (isUnauthorizedDueToExpiredAccessToken(response)) {
336
- var expiredTokensError = errors.buildAuthError(response);
337
-
338
- // Give the session a chance to handle the error (ex: a persistent session will clear the token store)
339
- if (this._session.handleExpiredTokensError) {
340
- return this._session.handleExpiredTokensError(expiredTokensError);
341
- }
342
-
343
- throw expiredTokensError;
344
- }
345
-
346
- return response;
347
- })
348
- .asCallback(callback);
349
- };
350
-
145
+ var BoxClient = /** @class */ (function () {
146
+ /**
147
+ * The BoxClient can make API calls on behalf of a valid API Session. It is responsible
148
+ * for formatting the requests and handling the response. Its goal is to deliver
149
+ * sensible results to the user.
150
+ *
151
+ * @param {APISession} apiSession An initialized API Session, used to get/revoke tokens and handle
152
+ * unauthorized responses from the API.
153
+ * @param {Config} config The SDK configuration options
154
+ * @param {APIRequestManager} requestManager The API Request Manager
155
+ * @constructor
156
+ */
157
+ function BoxClient(apiSession, config /* FIXME */, requestManager) {
158
+ /**
159
+ * Puts the client into batch mode, which will queue calls instead of
160
+ * immediately making the API request.
161
+ *
162
+ * DEPRECATED: Batch API is not supported and should not be used; make calls in parallel instead.
163
+ *
164
+ * @returns {BoxClient} Current client object
165
+ */
166
+ this.batch = util.deprecate(function () {
167
+ /* eslint-disable no-invalid-this */
168
+ this._batch = [];
169
+ return this;
170
+ /* eslint-enable no-invalid-this */
171
+ }, 'Batch API is not supported and should not be used; make calls in parallel instead.');
172
+ /**
173
+ * Executes a batch of requests.
174
+ *
175
+ * DEPRECATED: Batch API is not supported and should not be used; make calls in parallel instead.
176
+ *
177
+ * @returns {Promise<Object>} Promise resolving to the collection of batch responses
178
+ */
179
+ this.batchExec = util.deprecate(function (callback) {
180
+ /* eslint-disable no-invalid-this */
181
+ if (!this._batch) {
182
+ return bluebird_1.Promise.reject(new Error('Must start a batch before executing')).asCallback(callback);
183
+ }
184
+ var params = {
185
+ body: {
186
+ requests: this._batch.map(function (batchReq /* FIXME */) {
187
+ return formatRequestForBatch(batchReq.params);
188
+ }),
189
+ },
190
+ };
191
+ var batch = this._batch;
192
+ this._batch = null;
193
+ return this.post('/batch', params)
194
+ .then(function (res /* FIXME */) {
195
+ var responses = res.body.responses;
196
+ responses
197
+ .map(function (x) { return formatResponseForBatch(x); })
198
+ .forEach(function (response, index) {
199
+ batch[index].resolve(response);
200
+ });
201
+ return res.body;
202
+ })
203
+ .catch(function (err) {
204
+ batch.forEach(function (req) { return req.reject(err); });
205
+ throw err;
206
+ })
207
+ .asCallback(callback);
208
+ /* eslint-enable no-invalid-this */
209
+ }, 'Batch API is not supported and should not be used; make calls in parallel instead.');
210
+ // the API Session used by the client for authentication
211
+ this._session = apiSession;
212
+ // Attach a request manager instance for making requests
213
+ this._requestManager = requestManager;
214
+ // An object of custom headers to apply to every request. Modified via BoxClient.setCustomHeader().
215
+ this._customHeaders = {};
216
+ // Attach the configured properties
217
+ this._baseURL = util.format('%s/%s', config.apiRootURL, config.apiVersion);
218
+ this._uploadBaseURL = util.format('%s/%s', config.uploadAPIRootURL, config.apiVersion);
219
+ this._uploadRequestTimeoutMS = config.uploadRequestTimeoutMS;
220
+ this._useIterators = config.iterators;
221
+ this._analyticsClient = config.analyticsClient;
222
+ // Attach API Resource Managers
223
+ this.users = new users_1.default(this);
224
+ this.files = new files_1.default(this);
225
+ this.folders = new folders_1.default(this);
226
+ this.comments = new comments_1.default(this);
227
+ this.collaborations = new collaborations_1.default(this);
228
+ this.groups = new groups_1.default(this);
229
+ this.sharedItems = new shared_items_1.default(this);
230
+ this.metadata = new metadata_1.default(this);
231
+ this.collections = new collections_1.default(this);
232
+ this.events = new events_1.default(this);
233
+ this.search = new search_1.default(this);
234
+ this.tasks = new tasks_1.default(this);
235
+ this.trash = new trash_1.default(this);
236
+ this.enterprise = new enterprise_1.default(this);
237
+ this.legalHoldPolicies = new legal_hold_policies_1.default(this);
238
+ this.weblinks = new web_links_1.default(this);
239
+ this.retentionPolicies = new retention_policies_1.default(this);
240
+ this.devicePins = new device_pins_1.default(this);
241
+ this.webhooks = new webhooks_1.default(this);
242
+ this.recentItems = new recent_items_1.default(this);
243
+ this.collaborationAllowlist = new collaboration_allowlist_1.default(this);
244
+ this.termsOfService = new terms_of_service_1.default(this);
245
+ this.storagePolicies = new storage_policies_1.default(this);
246
+ this.signRequests = new sign_requests_generated_1.default(this);
247
+ // Legacy insensitive language
248
+ this.collaborationWhitelist = this.collaborationAllowlist;
249
+ // Array of requests when in batch mode, null otherwise
250
+ this._batch = null;
251
+ }
252
+ /**
253
+ * Returns an object containing the given headers as well as other headers (like the authorization header and
254
+ * custom headers) that should be included in a request.
255
+ * @param {?Object} callerHeaders - headers that the caller wishes to include in the request. This method will not
256
+ * override these headers with its own. Thus, if all the headers that this method was planning to add are already
257
+ * specified here, this method will return an object with exactly the same headers.
258
+ * @param {string} accessToken - the access token that will be used to make the request
259
+ * @returns {Object} - a new object with the headers needed for the request
260
+ * @private
261
+ */
262
+ BoxClient.prototype._createHeadersForRequest = function (callerHeaders, accessToken) {
263
+ var headers = {};
264
+ // 'Authorization' - contains your valid access token for authorization
265
+ headers[HEADER_AUTHORIZATION] = buildAuthorizationHeader(accessToken);
266
+ // We copy our own custom headers (XFF, BoxApi, etc.) before copying over the caller-specified headers so that
267
+ // the caller-specified headers will take precedence.
268
+ Object.assign(headers, this._customHeaders, callerHeaders);
269
+ // Add analytics headers last so they cannot be overwritten
270
+ Object.assign(headers, {
271
+ 'X-Box-UA': constructBoxUAHeader(this._analyticsClient),
272
+ });
273
+ return headers;
274
+ };
275
+ /**
276
+ * Makes an API request to the Box API on behalf of the client. Before executing
277
+ * the request, it first ensures the user has usable tokens. Will be called again
278
+ * if the request returns a temporary error. Will propogate error if request returns
279
+ * a permanent error, or if usable tokens are not available.
280
+ *
281
+ * @param {Object} params - Request lib params to configure the request
282
+ * @param {APIRequest~Callback} [callback] - passed response data
283
+ * @returns {Promise} Promise resolving to the response
284
+ * @private
285
+ */
286
+ BoxClient.prototype._makeRequest = function (params /* FIXME */, callback) {
287
+ var _this = this;
288
+ var promise;
289
+ if (this._batch) {
290
+ // eslint-disable-next-line promise/avoid-new
291
+ promise = new bluebird_1.Promise(function (resolve, reject) {
292
+ _this._batch.push({ params: params, resolve: resolve, reject: reject });
293
+ });
294
+ }
295
+ else {
296
+ // Check that tokens are fresh, update if tokens are expired or soon-to-be expired
297
+ promise = this._session
298
+ .getAccessToken(this._tokenOptions)
299
+ .then(function (accessToken) {
300
+ params.headers = _this._createHeadersForRequest(params.headers, accessToken);
301
+ if (params.streaming) {
302
+ // streaming is specific to the SDK, so delete it from params before continuing
303
+ delete params.streaming;
304
+ var responseStream = _this._requestManager.makeStreamingRequest(params);
305
+ // Listen to 'response' event, so we can cleanup the token store in case when the request is unauthorized
306
+ // due to expired access token
307
+ responseStream.on('response', function (response /* FIXME */) {
308
+ if (isUnauthorizedDueToExpiredAccessToken(response)) {
309
+ var expiredTokensError = errors.buildAuthError(response);
310
+ // Give the session a chance to handle the error (ex: a persistent session will clear the token store)
311
+ if (_this._session.handleExpiredTokensError) {
312
+ _this._session.handleExpiredTokensError(expiredTokensError);
313
+ }
314
+ }
315
+ });
316
+ return responseStream;
317
+ }
318
+ // Make the request to Box, and perform standard response handling
319
+ return _this._requestManager.makeRequest(params);
320
+ });
321
+ }
322
+ return promise
323
+ .then(function (response /* FIXME */) {
324
+ if (!response.statusCode) {
325
+ // Response is not yet complete, and is just a stream that will return the response later
326
+ // Just return the stream, since it doesn't need further response handling
327
+ return response;
328
+ }
329
+ if (isUnauthorizedDueToExpiredAccessToken(response)) {
330
+ var expiredTokensError = errors.buildAuthError(response);
331
+ // Give the session a chance to handle the error (ex: a persistent session will clear the token store)
332
+ if (_this._session.handleExpiredTokensError) {
333
+ return _this._session.handleExpiredTokensError(expiredTokensError);
334
+ }
335
+ throw expiredTokensError;
336
+ }
337
+ return response;
338
+ })
339
+ .asCallback(callback);
340
+ };
341
+ /**
342
+ * Set a custom header. A custom header is applied to every request for the life of the client. To
343
+ * remove a header, set it's value to null.
344
+ *
345
+ * @param {string} header The name of the custom header to set.
346
+ * @param {*} value The value of the custom header. Set to null to remove the given header.
347
+ * @returns {void}
348
+ */
349
+ BoxClient.prototype.setCustomHeader = function (header, value) {
350
+ if (value) {
351
+ this._customHeaders[header] = value;
352
+ }
353
+ else {
354
+ delete this._customHeaders[header];
355
+ }
356
+ };
357
+ /**
358
+ * Sets the list of requesting IP addresses for the X-Forwarded-For header. Used to give the API
359
+ * better information for uploads, rate-limiting, etc.
360
+ *
361
+ * @param {string[]} ips - Array of IP Addresses
362
+ * @returns {void}
363
+ */
364
+ BoxClient.prototype.setIPs = function (ips) {
365
+ var validIPs = ips.filter(function (ipString) { return isIP(ipString); }).join(', ');
366
+ this.setCustomHeader(HEADER_XFF, validIPs);
367
+ this._tokenOptions = { ip: validIPs };
368
+ };
369
+ /**
370
+ * Sets the shared item context on the API Session. Overwrites any current context.
371
+ *
372
+ * @param {string} url The shared link url
373
+ * @param {?string} password The shared link password, null if no password exists.
374
+ * @returns {void}
375
+ */
376
+ BoxClient.prototype.setSharedContext = function (url, password) {
377
+ var sharedContextAuthHeader = this.buildSharedItemAuthHeader(url, password);
378
+ this.setCustomHeader(HEADER_BOXAPI, sharedContextAuthHeader);
379
+ };
380
+ /**
381
+ * Removes any current shared item context from API Session.
382
+ *
383
+ * @returns {void}
384
+ */
385
+ BoxClient.prototype.revokeSharedContext = function () {
386
+ this.setCustomHeader(HEADER_BOXAPI, null);
387
+ };
388
+ /**
389
+ * Set up the As-User context, which is used by enterprise admins to
390
+ * impersonate their managed users and perform actions on their behalf.
391
+ *
392
+ * @param {string} userID - The ID of the user to impersonate
393
+ * @returns {void}
394
+ */
395
+ BoxClient.prototype.asUser = function (userID) {
396
+ this.setCustomHeader(HEADER_AS_USER, userID);
397
+ };
398
+ /**
399
+ * Revoke the As-User context and return to making calls on behalf of the user
400
+ * who owns the client's access token.
401
+ *
402
+ * @returns {void}
403
+ */
404
+ BoxClient.prototype.asSelf = function () {
405
+ this.setCustomHeader(HEADER_AS_USER, null);
406
+ };
407
+ /**
408
+ * Revokes the client's access tokens. The client will no longer be tied to a user
409
+ * and will be unable to make calls to the API, rendering it effectively useless.
410
+ *
411
+ * @param {Function} [callback] Called after revoking, with an error if one existed
412
+ * @returns {Promise} A promise resolving when the client's access token is revoked
413
+ */
414
+ BoxClient.prototype.revokeTokens = function (callback) {
415
+ return this._session.revokeTokens(this._tokenOptions).asCallback(callback);
416
+ };
417
+ /**
418
+ * Exchange the client access token for one with lower scope
419
+ * @param {string|string[]} scopes The scope(s) requested for the new token
420
+ * @param {string} [resource] The absolute URL of an API resource to scope the new token to
421
+ * @param {Object} [options] - Optional parameters
422
+ * @param {ActorParams} [options.actor] - Optional actor parameters for creating annotator tokens with Token Auth client
423
+ * @param {SharedLinkParams} [options.sharedLink] - Optional shared link parameters for creating tokens using shared links
424
+ * @param {Function} [callback] Called with the new token
425
+ * @returns {Promise<TokenInfo>} A promise resolving to the exchanged token info
426
+ */
427
+ BoxClient.prototype.exchangeToken = function (scopes, resource, options, callback) {
428
+ // Shuffle optional parameters
429
+ if (typeof options === 'function') {
430
+ callback = options;
431
+ options = {};
432
+ }
433
+ var opts = Object.assign({ tokenRequestOptions: this._tokenOptions || null }, options);
434
+ return this._session
435
+ .exchangeToken(scopes, resource, opts)
436
+ .asCallback(callback);
437
+ };
438
+ /**
439
+ * Makes GET request to Box API V2 endpoint
440
+ *
441
+ * @param {string} path - path to a certain API endpoint (ex: /file)
442
+ * @param {?Object} params - object containing parameters for the request, such as query strings and headers
443
+ * @param {APIRequest~Callback} [callback] - passed final API response or err if request failed
444
+ * @returns {void}
445
+ */
446
+ BoxClient.prototype.get = function (path, params, callback) {
447
+ var newParams = merge({}, params || {});
448
+ newParams.method = 'GET';
449
+ newParams.url = getFullURL(this._baseURL, path);
450
+ return this._makeRequest(newParams, callback);
451
+ };
452
+ /**
453
+ * Makes POST request to Box API V2 endpoint
454
+ *
455
+ * @param {string} path - path to a certain API endpoint (ex: /file)
456
+ * @param {?Object} params - object containing parameters for the request, such as query strings and headers
457
+ * @param {APIRequest~Callback} [callback] - passed final API response or err if request failed
458
+ * @returns {void}
459
+ */
460
+ BoxClient.prototype.post = function (path, params, callback) {
461
+ var newParams = merge({}, params || {});
462
+ newParams.method = 'POST';
463
+ newParams.url = getFullURL(this._baseURL, path);
464
+ return this._makeRequest(newParams, callback);
465
+ };
466
+ /**
467
+ * Makes PUT request to Box API V2 endpoint
468
+ *
469
+ * @param {string} path - path to a certain API endpoint (ex: /file)
470
+ * @param {?Object} params - object containing parameters for the request, such as query strings and headers
471
+ * @param {APIRequest~Callback} callback - passed final API response or err if request failed
472
+ * @returns {void}
473
+ */
474
+ BoxClient.prototype.put = function (path, params, callback) {
475
+ var newParams = merge({}, params || {});
476
+ newParams.method = 'PUT';
477
+ newParams.url = getFullURL(this._baseURL, path);
478
+ return this._makeRequest(newParams, callback);
479
+ };
480
+ /**
481
+ * Makes DELETE request to Box API V2 endpoint
482
+ *
483
+ * @param {string} path - path to a certain API endpoint (ex: /file)
484
+ * @param {?Object} params - object containing parameters for the request, such as query strings and headers
485
+ * @param {APIRequest~Callback} callback - passed final API response or err if request failed
486
+ * @returns {void}
487
+ */
488
+ BoxClient.prototype.del = function (path, params, callback) {
489
+ var newParams = merge({}, params || {});
490
+ newParams.method = 'DELETE';
491
+ newParams.url = getFullURL(this._baseURL, path);
492
+ return this._makeRequest(newParams, callback);
493
+ };
494
+ /**
495
+ * Makes an OPTIONS call to a Box API V2 endpoint
496
+ *
497
+ * @param {string} path - Path to an API endpoint (e.g. /files/content)
498
+ * @param {?Object} params - An optional object containing request parameters
499
+ * @param {APIRequest~Callback} callback - Called with API call results, or err if call failed
500
+ * @returns {void}
501
+ */
502
+ BoxClient.prototype.options = function (path, params, callback) {
503
+ var newParams = merge({}, params || {});
504
+ newParams.method = 'OPTIONS';
505
+ newParams.url = getFullURL(this._baseURL, path);
506
+ return this._makeRequest(newParams, callback);
507
+ };
508
+ /**
509
+ * Makes a POST call to a Box API V2 upload endpoint
510
+ * @param {string} path - path to an upload API endpoint
511
+ * @param {?Object} params - an optional object containing request parameters
512
+ * @param {?Object} formData - multipart form data to include in the upload request {@see https://github.com/mikeal/request#multipartform-data-multipart-form-uploads}
513
+ * @param {APIRequest~Callback} callback - called with API call results, or an error if the call failed
514
+ * @returns {void}
515
+ */
516
+ BoxClient.prototype.upload = function (path, params, formData, callback) {
517
+ var defaults = {
518
+ method: 'POST',
519
+ };
520
+ var newParams = merge(defaults, params || {});
521
+ newParams.url = getFullURL(this._uploadBaseURL, path);
522
+ newParams.formData = formData;
523
+ newParams.timeout = this._uploadRequestTimeoutMS;
524
+ return this._makeRequest(newParams, callback);
525
+ };
526
+ /**
527
+ * Build the 'BoxApi' Header used for authenticating access to a shared item
528
+ *
529
+ * @param {string} url The shared link url
530
+ * @param {string} [password] The shared link password
531
+ * @returns {string} A properly formatted 'BoxApi' header
532
+ */
533
+ BoxClient.prototype.buildSharedItemAuthHeader = function (url, password) {
534
+ var encodedURL = encodeURIComponent(url), encodedPassword = encodeURIComponent(password !== null && password !== void 0 ? password : '');
535
+ if (password) {
536
+ return util.format('shared_link=%s&shared_link_password=%s', encodedURL, encodedPassword);
537
+ }
538
+ return util.format('shared_link=%s', encodedURL);
539
+ };
540
+ /**
541
+ * Return a callback that properly handles a successful response code by passing the response
542
+ * body to the original callback. Any request error or unsuccessful response codes are propagated
543
+ * back to the callback as errors. This is the standard behavior of most endpoints.
544
+ *
545
+ * @param {Function} callback The original callback given by the consumer
546
+ * @returns {?APIRequest~Callback} A new callback that processes the response before passing it to the callback.
547
+ */
548
+ BoxClient.prototype.defaultResponseHandler = function (callback) {
549
+ var self = this;
550
+ if (!callback) {
551
+ return null;
552
+ }
553
+ return function (err, response /* FIXME */) {
554
+ // Error with Request
555
+ if (err) {
556
+ callback(err);
557
+ return;
558
+ }
559
+ // Successful Response
560
+ if (response.statusCode >= HTTP_STATUS_CODE_SUCCESS_BLOCK_RANGE[0] &&
561
+ response.statusCode <= HTTP_STATUS_CODE_SUCCESS_BLOCK_RANGE[1]) {
562
+ if (self._useIterators && PagingIterator.isIterable(response)) {
563
+ callback(null, new PagingIterator(response, self));
564
+ return;
565
+ }
566
+ callback(null, response.body);
567
+ return;
568
+ }
569
+ // Unexpected Response
570
+ callback(errors.buildUnexpectedResponseError(response));
571
+ };
572
+ };
573
+ /**
574
+ * Wrap a client method with the default handler for both callback and promise styles
575
+ * @param {Function} method The client method (e.g. client.get)
576
+ * @returns {Function} The wrapped method
577
+ */
578
+ BoxClient.prototype.wrapWithDefaultHandler = function (method) {
579
+ var self = this;
580
+ return function wrappedClientMethod( /* arguments */) {
581
+ // Check if the last argument is a callback
582
+ var lastArg = arguments[arguments.length - 1], callback;
583
+ if (typeof lastArg === 'function') {
584
+ callback = self.defaultResponseHandler(lastArg);
585
+ arguments[arguments.length - 1] = callback;
586
+ }
587
+ var ret = method.apply(self, arguments);
588
+ if (ret instanceof bluebird_1.Promise) {
589
+ ret = ret.then(function (response) {
590
+ if (response.statusCode >= HTTP_STATUS_CODE_SUCCESS_BLOCK_RANGE[0] &&
591
+ response.statusCode <= HTTP_STATUS_CODE_SUCCESS_BLOCK_RANGE[1]) {
592
+ if (self._useIterators && PagingIterator.isIterable(response)) {
593
+ return new PagingIterator(response, self);
594
+ }
595
+ return response.body;
596
+ }
597
+ throw errors.buildUnexpectedResponseError(response);
598
+ });
599
+ }
600
+ if (callback) {
601
+ // If the callback will handle any errors, don't worry about the promise
602
+ ret.suppressUnhandledRejections();
603
+ }
604
+ return ret;
605
+ };
606
+ };
607
+ /**
608
+ * Add a SDK plugin. Warning: This will modify the box-client interface and can override existing properties.
609
+ * @param {string} name Plugin name. Will be accessible via client.<plugin-name>
610
+ * @param {Function} plugin The SDK plugin to add
611
+ * @param {Object} [options] Plugin-specific options
612
+ * @returns {void}
613
+ * @throws Will throw an error if plugin name matches an existing method on box-client
614
+ */
615
+ BoxClient.prototype.plug = function (name, plugin, options) {
616
+ options = options || {};
617
+ if (name in this && typeof this[name] === 'function') {
618
+ throw new Error('You cannot define a plugin that overrides an existing method on the client');
619
+ }
620
+ // Create plugin and export plugin onto client.
621
+ this[name] = plugin(this, options);
622
+ };
623
+ return BoxClient;
624
+ }());
351
625
  // ------------------------------------------------------------------------------
352
626
  // Public
353
627
  // ------------------------------------------------------------------------------
354
-
355
628
  /**
356
629
  * Enum of valid collaboration roles
357
630
  *
@@ -359,16 +632,15 @@ BoxClient.prototype._makeRequest = function(params, callback) {
359
632
  * @enum {CollaborationRole}
360
633
  */
361
634
  BoxClient.prototype.collaborationRoles = {
362
- EDITOR: 'editor',
363
- VIEWER: 'viewer',
364
- PREVIEWER: 'previewer',
365
- UPLOADER: 'uploader',
366
- PREVIEWER_UPLOADER: 'previewer uploader',
367
- VIEWER_UPLOADER: 'viewer uploader',
368
- CO_OWNER: 'co-owner',
369
- OWNER: 'owner'
635
+ EDITOR: 'editor',
636
+ VIEWER: 'viewer',
637
+ PREVIEWER: 'previewer',
638
+ UPLOADER: 'uploader',
639
+ PREVIEWER_UPLOADER: 'previewer uploader',
640
+ VIEWER_UPLOADER: 'viewer uploader',
641
+ CO_OWNER: 'co-owner',
642
+ OWNER: 'owner',
370
643
  };
371
-
372
644
  /**
373
645
  * Enum of Box item types
374
646
  *
@@ -376,10 +648,9 @@ BoxClient.prototype.collaborationRoles = {
376
648
  * @enum {ItemType}
377
649
  */
378
650
  BoxClient.prototype.itemTypes = {
379
- FILE: 'file',
380
- FOLDER: 'folder'
651
+ FILE: 'file',
652
+ FOLDER: 'folder',
381
653
  };
382
-
383
654
  /**
384
655
  * Enum of valid values for setting different access levels. To be used when
385
656
  * creating and editting shared links, upload emails, etc.
@@ -388,417 +659,13 @@ BoxClient.prototype.itemTypes = {
388
659
  * @type {AccessLevel}
389
660
  */
390
661
  BoxClient.prototype.accessLevels = {
391
- OPEN: {access: 'open'},
392
- COLLABORATORS: {access: 'collaborators'},
393
- COMPANY: {access: 'company'},
394
- DEFAULT: {},
395
- DISABLED: null
662
+ OPEN: { access: 'open' },
663
+ COLLABORATORS: { access: 'collaborators' },
664
+ COMPANY: { access: 'company' },
665
+ DEFAULT: {},
666
+ DISABLED: null,
396
667
  };
397
-
398
668
  /** @const {string} */
399
- BoxClient.prototype.CURRENT_USER_ID = Users.prototype.CURRENT_USER_ID;
400
-
401
- /**
402
- * Set a custom header. A custom header is applied to every request for the life of the client. To
403
- * remove a header, set it's value to null.
404
- *
405
- * @param {string} header The name of the custom header to set.
406
- * @param {*} value The value of the custom header. Set to null to remove the given header.
407
- * @returns {void}
408
- */
409
- BoxClient.prototype.setCustomHeader = function(header, value) {
410
- if (value) {
411
- this._customHeaders[header] = value;
412
- } else {
413
- delete this._customHeaders[header];
414
- }
415
- };
416
-
417
- /**
418
- * Sets the list of requesting IP addresses for the X-Forwarded-For header. Used to give the API
419
- * better information for uploads, rate-limiting, etc.
420
- *
421
- * @param {string[]} ips - Array of IP Addresses
422
- * @returns {void}
423
- */
424
- BoxClient.prototype.setIPs = function(ips) {
425
- var validIPs = ips.filter(ipString => isIP(ipString)).join(', ');
426
-
427
- this.setCustomHeader(HEADER_XFF, validIPs);
428
-
429
- this._tokenOptions = {ip: validIPs};
430
- };
431
-
432
- /**
433
- * Sets the shared item context on the API Session. Overwrites any current context.
434
- *
435
- * @param {string} url The shared link url
436
- * @param {?string} password The shared link password, null if no password exists.
437
- * @returns {void}
438
- */
439
- BoxClient.prototype.setSharedContext = function(url, password) {
440
- var sharedContextAuthHeader = this.buildSharedItemAuthHeader(url, password);
441
- this.setCustomHeader(HEADER_BOXAPI, sharedContextAuthHeader);
442
- };
443
-
444
- /**
445
- * Removes any current shared item context from API Session.
446
- *
447
- * @returns {void}
448
- */
449
- BoxClient.prototype.revokeSharedContext = function() {
450
- this.setCustomHeader(HEADER_BOXAPI, null);
451
- };
452
-
453
- /**
454
- * Set up the As-User context, which is used by enterprise admins to
455
- * impersonate their managed users and perform actions on their behalf.
456
- *
457
- * @param {string} userID - The ID of the user to impersonate
458
- * @returns {void}
459
- */
460
- BoxClient.prototype.asUser = function(userID) {
461
-
462
- this.setCustomHeader(HEADER_AS_USER, userID);
463
- };
464
-
465
- /**
466
- * Revoke the As-User context and return to making calls on behalf of the user
467
- * who owns the client's access token.
468
- *
469
- * @returns {void}
470
- */
471
- BoxClient.prototype.asSelf = function() {
472
-
473
- this.setCustomHeader(HEADER_AS_USER, null);
474
- };
475
-
476
- /**
477
- * Revokes the client's access tokens. The client will no longer be tied to a user
478
- * and will be unable to make calls to the API, rendering it effectively useless.
479
- *
480
- * @param {Function} [callback] Called after revoking, with an error if one existed
481
- * @returns {Promise} A promise resolving when the client's access token is revoked
482
- */
483
- BoxClient.prototype.revokeTokens = function(callback) {
484
-
485
- return this._session.revokeTokens(this._tokenOptions)
486
- .asCallback(callback);
487
- };
488
-
489
- /**
490
- * Exchange the client access token for one with lower scope
491
- * @param {string|string[]} scopes The scope(s) requested for the new token
492
- * @param {string} [resource] The absolute URL of an API resource to scope the new token to
493
- * @param {Object} [options] - Optional parameters
494
- * @param {ActorParams} [options.actor] - Optional actor parameters for creating annotator tokens with Token Auth client
495
- * @param {SharedLinkParams} [options.sharedLink] - Optional shared link parameters for creating tokens using shared links
496
- * @param {Function} [callback] Called with the new token
497
- * @returns {Promise<TokenInfo>} A promise resolving to the exchanged token info
498
- */
499
- BoxClient.prototype.exchangeToken = function(scopes, resource, options, callback) {
500
-
501
- // Shuffle optional parameters
502
- if (typeof options === 'function') {
503
- callback = options;
504
- options = {};
505
- }
506
-
507
- var opts = Object.assign({ tokenRequestOptions: this._tokenOptions || null }, options);
508
-
509
- return this._session.exchangeToken(scopes, resource, opts)
510
- .asCallback(callback);
511
- };
512
-
513
- /**
514
- * Makes GET request to Box API V2 endpoint
515
- *
516
- * @param {string} path - path to a certain API endpoint (ex: /file)
517
- * @param {?Object} params - object containing parameters for the request, such as query strings and headers
518
- * @param {APIRequest~Callback} callback - passed final API response or err if request failed
519
- * @returns {void}
520
- */
521
- BoxClient.prototype.get = function(path, params, callback) {
522
- var newParams = merge({}, params || {});
523
- newParams.method = 'GET';
524
- newParams.url = getFullURL(this._baseURL, path);
525
-
526
- return this._makeRequest(newParams, callback);
527
- };
528
-
529
- /**
530
- * Makes POST request to Box API V2 endpoint
531
- *
532
- * @param {string} path - path to a certain API endpoint (ex: /file)
533
- * @param {?Object} params - object containing parameters for the request, such as query strings and headers
534
- * @param {APIRequest~Callback} callback - passed final API response or err if request failed
535
- * @returns {void}
536
- */
537
- BoxClient.prototype.post = function(path, params, callback) {
538
- var newParams = merge({}, params || {});
539
- newParams.method = 'POST';
540
- newParams.url = getFullURL(this._baseURL, path);
541
- return this._makeRequest(newParams, callback);
542
- };
543
-
544
- /**
545
- * Makes PUT request to Box API V2 endpoint
546
- *
547
- * @param {string} path - path to a certain API endpoint (ex: /file)
548
- * @param {?Object} params - object containing parameters for the request, such as query strings and headers
549
- * @param {APIRequest~Callback} callback - passed final API response or err if request failed
550
- * @returns {void}
551
- */
552
- BoxClient.prototype.put = function(path, params, callback) {
553
- var newParams = merge({}, params || {});
554
- newParams.method = 'PUT';
555
- newParams.url = getFullURL(this._baseURL, path);
556
- return this._makeRequest(newParams, callback);
557
- };
558
-
559
- /**
560
- * Makes DELETE request to Box API V2 endpoint
561
- *
562
- * @param {string} path - path to a certain API endpoint (ex: /file)
563
- * @param {?Object} params - object containing parameters for the request, such as query strings and headers
564
- * @param {APIRequest~Callback} callback - passed final API response or err if request failed
565
- * @returns {void}
566
- */
567
- BoxClient.prototype.del = function(path, params, callback) {
568
- var newParams = merge({}, params || {});
569
- newParams.method = 'DELETE';
570
- newParams.url = getFullURL(this._baseURL, path);
571
- return this._makeRequest(newParams, callback);
572
- };
573
-
574
-
575
- /**
576
- * Makes an OPTIONS call to a Box API V2 endpoint
577
- *
578
- * @param {string} path - Path to an API endpoint (e.g. /files/content)
579
- * @param {?Object} params - An optional object containing request parameters
580
- * @param {APIRequest~Callback} callback - Called with API call results, or err if call failed
581
- * @returns {void}
582
- */
583
- BoxClient.prototype.options = function(path, params, callback) {
584
- var newParams = merge({}, params || {});
585
- newParams.method = 'OPTIONS';
586
- newParams.url = getFullURL(this._baseURL, path);
587
-
588
- return this._makeRequest(newParams, callback);
589
- };
590
-
591
- /**
592
- * Makes a POST call to a Box API V2 upload endpoint
593
- * @param {string} path - path to an upload API endpoint
594
- * @param {?Object} params - an optional object containing request parameters
595
- * @param {?Object} formData - multipart form data to include in the upload request {@see https://github.com/mikeal/request#multipartform-data-multipart-form-uploads}
596
- * @param {APIRequest~Callback} callback - called with API call results, or an error if the call failed
597
- * @returns {void}
598
- */
599
- BoxClient.prototype.upload = function(path, params, formData, callback) {
600
-
601
- var defaults = {
602
- method: 'POST'
603
- };
604
- var newParams = merge(defaults, params || {});
605
- newParams.url = getFullURL(this._uploadBaseURL, path);
606
- newParams.formData = formData;
607
- newParams.timeout = this._uploadRequestTimeoutMS;
608
-
609
- return this._makeRequest(newParams, callback);
610
- };
611
-
612
- /**
613
- * Puts the client into batch mode, which will queue calls instead of
614
- * immediately making the API request.
615
- *
616
- * DEPRECATED: Batch API is not supported and should not be used; make calls in parallel instead.
617
- *
618
- * @returns {BoxClient} Current client object
619
- */
620
- BoxClient.prototype.batch = util.deprecate(function() {
621
- /* eslint-disable no-invalid-this */
622
- this._batch = [];
623
- return this;
624
- /* eslint-enable no-invalid-this */
625
- }, 'Batch API is not supported and should not be used; make calls in parallel instead.');
626
-
627
- /**
628
- * Executes a batch of requests.
629
- *
630
- * DEPRECATED: Batch API is not supported and should not be used; make calls in parallel instead.
631
- *
632
- * @returns {Promise<Object>} Promise resolving to the collection of batch responses
633
- */
634
- BoxClient.prototype.batchExec = util.deprecate(function(callback) {
635
- /* eslint-disable no-invalid-this */
636
- if (!this._batch) {
637
- return Promise.reject(new Error('Must start a batch before executing'))
638
- .asCallback(callback);
639
- }
640
-
641
- var params = {
642
- body: {
643
- requests: this._batch.map(batchReq => formatRequestForBatch(batchReq.params))
644
- }
645
- };
646
-
647
- var batch = this._batch;
648
- this._batch = null;
649
- return this.post('/batch', params)
650
- .then(res => {
651
-
652
- var responses = res.body.responses;
653
-
654
- responses.map(x => formatResponseForBatch(x)).forEach((response, index) => {
655
- batch[index].resolve(response);
656
- });
657
-
658
- return res.body;
659
- })
660
- .catch(err => {
661
- batch.forEach(req => req.reject(err));
662
-
663
- throw err;
664
- })
665
- .asCallback(callback);
666
- /* eslint-enable no-invalid-this */
667
- }, 'Batch API is not supported and should not be used; make calls in parallel instead.');
668
-
669
- /**
670
- * Build the 'BoxApi' Header used for authenticating access to a shared item
671
- *
672
- * @param {string} url The shared link url
673
- * @param {string} [password] The shared link password
674
- * @returns {string} A properly formatted 'BoxApi' header
675
- */
676
- BoxClient.prototype.buildSharedItemAuthHeader = function(url, password) {
677
- var encodedURL = encodeURIComponent(url),
678
- encodedPassword = encodeURIComponent(password);
679
-
680
- if (password) {
681
- return util.format('shared_link=%s&shared_link_password=%s', encodedURL, encodedPassword);
682
- }
683
-
684
- return util.format('shared_link=%s', encodedURL);
685
- };
686
-
687
- /**
688
- * Return a callback that properly handles a successful response code by passing the response
689
- * body to the original callback. Any request error or unsuccessful response codes are propagated
690
- * back to the callback as errors. This is the standard behavior of most endpoints.
691
- *
692
- * @param {Function} callback The original callback given by the consumer
693
- * @returns {?APIRequest~Callback} A new callback that processes the response before passing it to the callback.
694
- */
695
- BoxClient.prototype.defaultResponseHandler = function(callback) {
696
-
697
-
698
- var self = this;
699
-
700
- if (!callback) {
701
- return null;
702
- }
703
-
704
-
705
- return function(err, response) {
706
- // Error with Request
707
- if (err) {
708
- callback(err);
709
- return;
710
- }
711
-
712
- // Successful Response
713
- if (response.statusCode >= HTTP_STATUS_CODE_SUCCESS_BLOCK_RANGE[0]
714
- && response.statusCode <= HTTP_STATUS_CODE_SUCCESS_BLOCK_RANGE[1]) {
715
-
716
- if (self._useIterators && PagingIterator.isIterable(response)) {
717
- callback(null, new PagingIterator(response, self));
718
- return;
719
- }
720
-
721
- callback(null, response.body);
722
- return;
723
- }
724
- // Unexpected Response
725
- callback(errors.buildUnexpectedResponseError(response));
726
- };
727
- };
728
-
729
- /**
730
- * Wrap a client method with the default handler for both callback and promise styles
731
- * @param {Function} method The client method (e.g. client.get)
732
- * @returns {Function} The wrapped method
733
- */
734
- BoxClient.prototype.wrapWithDefaultHandler = function(method) {
735
-
736
- var self = this;
737
- return function wrappedClientMethod(/* arguments */) {
738
-
739
- // Check if the last argument is a callback
740
- var lastArg = arguments[arguments.length - 1],
741
- callback;
742
- if (typeof lastArg === 'function') {
743
- callback = self.defaultResponseHandler(lastArg);
744
- arguments[arguments.length - 1] = callback;
745
- }
746
-
747
- var ret = method.apply(self, arguments);
748
-
749
- if (ret instanceof Promise) {
750
-
751
- ret = ret.then(response => {
752
-
753
- if (response.statusCode >= HTTP_STATUS_CODE_SUCCESS_BLOCK_RANGE[0]
754
- && response.statusCode <= HTTP_STATUS_CODE_SUCCESS_BLOCK_RANGE[1]) {
755
-
756
- if (self._useIterators && PagingIterator.isIterable(response)) {
757
- return new PagingIterator(response, self);
758
- }
759
-
760
- return response.body;
761
- }
762
-
763
- throw errors.buildUnexpectedResponseError(response);
764
- });
765
- }
766
-
767
- if (callback) {
768
- // If the callback will handle any errors, don't worry about the promise
769
- ret.suppressUnhandledRejections();
770
- }
771
-
772
- return ret;
773
- };
774
- };
775
-
776
- /**
777
- * Add a SDK plugin. Warning: This will modify the box-client interface and can override existing properties.
778
- * @param {string} name Plugin name. Will be accessible via client.<plugin-name>
779
- * @param {Function} plugin The SDK plugin to add
780
- * @param {Object} [options] Plugin-specific options
781
- * @returns {void}
782
- * @throws Will throw an error if plugin name matches an existing method on box-client
783
- */
784
- BoxClient.prototype.plug = function(name, plugin, options) {
785
- options = options || {};
786
-
787
- if ((name in this) && (typeof this[name] === 'function')) {
788
- throw new Error('You cannot define a plugin that overrides an existing method on the client');
789
- }
790
-
791
- // Create plugin and export plugin onto client.
792
- this[name] = plugin(this, options);
793
- };
794
-
795
-
796
- // ------------------------------------------------------------------------------
797
- // Public
798
- // ------------------------------------------------------------------------------
799
-
800
- /**
801
- * @module box-node-sdk/lib/box-client
802
- * @see {@Link BoxClient}
803
- */
669
+ BoxClient.prototype.CURRENT_USER_ID = users_1.default.prototype.CURRENT_USER_ID;
804
670
  module.exports = BoxClient;
671
+ //# sourceMappingURL=box-client.js.map