@uploadcare/upload-client 3.1.0 → 4.0.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.
@@ -1,1743 +0,0 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- /*! *****************************************************************************
6
- Copyright (c) Microsoft Corporation. All rights reserved.
7
- Licensed under the Apache License, Version 2.0 (the "License"); you may not use
8
- this file except in compliance with the License. You may obtain a copy of the
9
- License at http://www.apache.org/licenses/LICENSE-2.0
10
-
11
- THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
12
- KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
13
- WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
14
- MERCHANTABLITY OR NON-INFRINGEMENT.
15
-
16
- See the Apache Version 2.0 License for specific language governing permissions
17
- and limitations under the License.
18
- ***************************************************************************** */
19
- /* global Reflect, Promise */
20
-
21
- var extendStatics = function(d, b) {
22
- extendStatics = Object.setPrototypeOf ||
23
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
24
- function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
25
- return extendStatics(d, b);
26
- };
27
-
28
- function __extends(d, b) {
29
- extendStatics(d, b);
30
- function __() { this.constructor = d; }
31
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
32
- }
33
-
34
- var __assign = function() {
35
- __assign = Object.assign || function __assign(t) {
36
- for (var s, i = 1, n = arguments.length; i < n; i++) {
37
- s = arguments[i];
38
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
39
- }
40
- return t;
41
- };
42
- return __assign.apply(this, arguments);
43
- };
44
-
45
- function __spreadArrays() {
46
- for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
47
- for (var r = Array(s), k = 0, i = 0; i < il; i++)
48
- for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
49
- r[k] = a[j];
50
- return r;
51
- }
52
-
53
- var UploadClientError = /** @class */ (function (_super) {
54
- __extends(UploadClientError, _super);
55
- function UploadClientError(message, code, request, response, headers) {
56
- var _this = _super.call(this) || this;
57
- _this.name = 'UploadClientError';
58
- _this.message = message;
59
- _this.code = code;
60
- _this.request = request;
61
- _this.response = response;
62
- _this.headers = headers;
63
- Object.setPrototypeOf(_this, UploadClientError.prototype);
64
- return _this;
65
- }
66
- return UploadClientError;
67
- }(Error));
68
- var cancelError = function (message) {
69
- if (message === void 0) { message = 'Request canceled'; }
70
- var error = new UploadClientError(message);
71
- error.isCancel = true;
72
- return error;
73
- };
74
-
75
- var onCancel = function (signal, callback) {
76
- if (signal) {
77
- if (signal.aborted) {
78
- Promise.resolve().then(callback);
79
- }
80
- else {
81
- signal.addEventListener('abort', function () { return callback(); }, { once: true });
82
- }
83
- }
84
- };
85
-
86
- var request = function (_a) {
87
- var method = _a.method, url = _a.url, data = _a.data, _b = _a.headers, headers = _b === void 0 ? {} : _b, signal = _a.signal, onProgress = _a.onProgress;
88
- return new Promise(function (resolve, reject) {
89
- var xhr = new XMLHttpRequest();
90
- var requestMethod = (method === null || method === void 0 ? void 0 : method.toUpperCase()) || 'GET';
91
- var aborted = false;
92
- xhr.open(requestMethod, url);
93
- if (headers) {
94
- Object.entries(headers).forEach(function (entry) {
95
- var key = entry[0], value = entry[1];
96
- typeof value !== 'undefined' &&
97
- !Array.isArray(value) &&
98
- xhr.setRequestHeader(key, value);
99
- });
100
- }
101
- xhr.responseType = 'text';
102
- onCancel(signal, function () {
103
- aborted = true;
104
- xhr.abort();
105
- reject(cancelError());
106
- });
107
- xhr.onload = function () {
108
- if (xhr.status != 200) {
109
- // analyze HTTP status of the response
110
- reject(new Error("Error " + xhr.status + ": " + xhr.statusText)); // e.g. 404: Not Found
111
- }
112
- else {
113
- var request_1 = {
114
- method: requestMethod,
115
- url: url,
116
- data: data,
117
- headers: headers || undefined,
118
- signal: signal,
119
- onProgress: onProgress
120
- };
121
- // Convert the header string into an array
122
- // of individual headers
123
- var headersArray = xhr
124
- .getAllResponseHeaders()
125
- .trim()
126
- .split(/[\r\n]+/);
127
- // Create a map of header names to values
128
- var responseHeaders_1 = {};
129
- headersArray.forEach(function (line) {
130
- var parts = line.split(': ');
131
- var header = parts.shift();
132
- var value = parts.join(': ');
133
- if (header && typeof header !== 'undefined') {
134
- responseHeaders_1[header] = value;
135
- }
136
- });
137
- var responseData = xhr.response;
138
- var responseStatus = xhr.status;
139
- resolve({
140
- request: request_1,
141
- data: responseData,
142
- headers: responseHeaders_1,
143
- status: responseStatus
144
- });
145
- }
146
- };
147
- xhr.onerror = function () {
148
- if (aborted)
149
- return;
150
- // only triggers if the request couldn't be made at all
151
- reject(new Error('Network error'));
152
- };
153
- if (onProgress && typeof onProgress === 'function') {
154
- xhr.upload.onprogress = function (event) {
155
- if (event.lengthComputable) {
156
- onProgress({
157
- isComputable: true,
158
- value: event.loaded / event.total
159
- });
160
- }
161
- else {
162
- onProgress({ isComputable: false });
163
- }
164
- };
165
- }
166
- if (data) {
167
- xhr.send(data);
168
- }
169
- else {
170
- xhr.send();
171
- }
172
- });
173
- };
174
-
175
- function identity(obj) {
176
- return obj;
177
- }
178
-
179
- var transformFile = identity;
180
- var getFormData = (function () { return new FormData(); });
181
-
182
- /**
183
- * FileData type guard.
184
- */
185
- var isFileData = function (data) {
186
- return (data !== undefined &&
187
- ((typeof Blob !== 'undefined' && data instanceof Blob) ||
188
- (typeof File !== 'undefined' && data instanceof File) ||
189
- (typeof Buffer !== 'undefined' && data instanceof Buffer)));
190
- };
191
- /**
192
- * Uuid type guard.
193
- */
194
- var isUuid = function (data) {
195
- var UUID_REGEX = '[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}';
196
- var regExp = new RegExp(UUID_REGEX);
197
- return !isFileData(data) && regExp.test(data);
198
- };
199
- /**
200
- * Url type guard.
201
- *
202
- * @param {NodeFile | BrowserFile | Url | Uuid} data
203
- */
204
- var isUrl = function (data) {
205
- var URL_REGEX = '^(?:\\w+:)?\\/\\/([^\\s\\.]+\\.\\S{2}|localhost[\\:?\\d]*)\\S*$';
206
- var regExp = new RegExp(URL_REGEX);
207
- return !isFileData(data) && regExp.test(data);
208
- };
209
-
210
- var isSimpleValue = function (value) {
211
- return (typeof value === 'string' ||
212
- typeof value === 'number' ||
213
- typeof value === 'undefined');
214
- };
215
- var isObjectValue = function (value) {
216
- return !!value && typeof value === 'object' && !Array.isArray(value);
217
- };
218
- var isFileValue = function (value) {
219
- return !!value &&
220
- typeof value === 'object' &&
221
- 'data' in value &&
222
- isFileData(value.data);
223
- };
224
- function collectParams(params, inputKey, inputValue) {
225
- if (isFileValue(inputValue)) {
226
- var name_1 = inputValue.name;
227
- var file = transformFile(inputValue.data); // lgtm [js/superfluous-trailing-arguments]
228
- params.push(name_1 ? [inputKey, file, name_1] : [inputKey, file]);
229
- }
230
- else if (isObjectValue(inputValue)) {
231
- for (var _i = 0, _a = Object.entries(inputValue); _i < _a.length; _i++) {
232
- var _b = _a[_i], key = _b[0], value = _b[1];
233
- if (typeof value !== 'undefined') {
234
- params.push([inputKey + "[" + key + "]", String(value)]);
235
- }
236
- }
237
- }
238
- else if (isSimpleValue(inputValue) && inputValue) {
239
- params.push([inputKey, inputValue.toString()]);
240
- }
241
- }
242
- function getFormDataParams(options) {
243
- var params = [];
244
- for (var _i = 0, _a = Object.entries(options); _i < _a.length; _i++) {
245
- var _b = _a[_i], key = _b[0], value = _b[1];
246
- collectParams(params, key, value);
247
- }
248
- return params;
249
- }
250
- function buildFormData(options) {
251
- var formData = getFormData();
252
- var params = getFormDataParams(options);
253
- for (var _i = 0, params_1 = params; _i < params_1.length; _i++) {
254
- var param = params_1[_i];
255
- formData.append.apply(formData, param);
256
- }
257
- return formData;
258
- }
259
-
260
- var serializePair = function (key, value) {
261
- return typeof value !== 'undefined' ? key + "=" + encodeURIComponent(value) : null;
262
- };
263
- // TODO: generalize value transforming logic and use it here and inside `buildFormData`
264
- var createQuery = function (query) {
265
- return Object.entries(query)
266
- .reduce(function (params, _a) {
267
- var key = _a[0], value = _a[1];
268
- var param;
269
- if (typeof value === 'object' && !Array.isArray(value)) {
270
- param = Object.entries(value)
271
- .filter(function (entry) { return typeof entry[1] !== 'undefined'; })
272
- .map(function (entry) {
273
- return serializePair(key + "[" + entry[0] + "]", String(entry[1]));
274
- });
275
- }
276
- else if (Array.isArray(value)) {
277
- param = value.map(function (val) { return serializePair(key + "[]", val); });
278
- }
279
- else {
280
- param = serializePair(key, value);
281
- }
282
- return params.concat(param);
283
- }, [])
284
- .filter(function (x) { return !!x; })
285
- .join('&');
286
- };
287
- var getUrl = function (base, path, query) {
288
- return [
289
- base,
290
- path,
291
- query && Object.keys(query).length > 0 ? '?' : '',
292
- query && createQuery(query)
293
- ]
294
- .filter(Boolean)
295
- .join('');
296
- };
297
-
298
- /*
299
- Settings for future support:
300
- parallelDirectUploads: 10,
301
- */
302
- var defaultSettings = {
303
- baseCDN: 'https://ucarecdn.com',
304
- baseURL: 'https://upload.uploadcare.com',
305
- maxContentLength: 50 * 1024 * 1024,
306
- retryThrottledRequestMaxTimes: 1,
307
- multipartMinFileSize: 25 * 1024 * 1024,
308
- multipartChunkSize: 5 * 1024 * 1024,
309
- multipartMinLastPartSize: 1024 * 1024,
310
- maxConcurrentRequests: 4,
311
- multipartMaxAttempts: 3,
312
- pollingTimeoutMilliseconds: 10000,
313
- pusherKey: '79ae88bd931ea68464d9'
314
- };
315
- var defaultContentType = 'application/octet-stream';
316
- var defaultFilename = 'original';
317
-
318
- var version = '3.1.0';
319
-
320
- /**
321
- * Returns User Agent based on version and settings.
322
- */
323
- function getUserAgent(_a) {
324
- var _b = _a === void 0 ? {} : _a, userAgent = _b.userAgent, _c = _b.publicKey, publicKey = _c === void 0 ? '' : _c, _d = _b.integration, integration = _d === void 0 ? '' : _d;
325
- var libraryName = 'UploadcareUploadClient';
326
- var libraryVersion = version;
327
- var languageName = 'JavaScript';
328
- if (typeof userAgent === 'string') {
329
- return userAgent;
330
- }
331
- if (typeof userAgent === 'function') {
332
- return userAgent({
333
- publicKey: publicKey,
334
- libraryName: libraryName,
335
- libraryVersion: libraryVersion,
336
- languageName: languageName,
337
- integration: integration
338
- });
339
- }
340
- var mainInfo = [libraryName, libraryVersion, publicKey]
341
- .filter(Boolean)
342
- .join('/');
343
- var additionInfo = [languageName, integration].filter(Boolean).join('; ');
344
- return mainInfo + " (" + additionInfo + ")";
345
- }
346
-
347
- var SEPARATOR = /\W|_/g;
348
- /**
349
- * Transforms a string to camelCased.
350
- */
351
- function camelize(text) {
352
- return text
353
- .split(SEPARATOR)
354
- .map(function (word, index) {
355
- return word.charAt(0)[index > 0 ? 'toUpperCase' : 'toLowerCase']() +
356
- word.slice(1);
357
- })
358
- .join('');
359
- }
360
- /**
361
- * Transforms keys of an object to camelCased recursively.
362
- */
363
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
364
- function camelizeKeys(source) {
365
- if (!source || typeof source !== 'object') {
366
- return source;
367
- }
368
- return Object.keys(source).reduce(function (accumulator, key) {
369
- accumulator[camelize(key)] =
370
- typeof source[key] === 'object' ? camelizeKeys(source[key]) : source[key];
371
- return accumulator;
372
- }, {});
373
- }
374
-
375
- /**
376
- * setTimeout as Promise.
377
- *
378
- * @param {number} ms Timeout in milliseconds.
379
- */
380
- var delay = function (ms) {
381
- return new Promise(function (resolve) { return setTimeout(resolve, ms); });
382
- };
383
-
384
- var defaultOptions = {
385
- factor: 2,
386
- time: 100
387
- };
388
- function retrier(fn, options) {
389
- if (options === void 0) { options = defaultOptions; }
390
- var attempts = 0;
391
- function runAttempt(fn) {
392
- var defaultDelayTime = Math.round(options.time * Math.pow(options.factor, attempts));
393
- var retry = function (ms) {
394
- return delay(ms !== null && ms !== void 0 ? ms : defaultDelayTime).then(function () {
395
- attempts += 1;
396
- return runAttempt(fn);
397
- });
398
- };
399
- return fn({
400
- attempt: attempts,
401
- retry: retry
402
- });
403
- }
404
- return runAttempt(fn);
405
- }
406
-
407
- var REQUEST_WAS_THROTTLED_CODE = 'RequestThrottledError';
408
- var DEFAULT_RETRY_AFTER_TIMEOUT = 15000;
409
- function getTimeoutFromThrottledRequest(error) {
410
- var headers = (error || {}).headers;
411
- return ((headers &&
412
- Number.parseInt(headers['x-throttle-wait-seconds']) * 1000) ||
413
- DEFAULT_RETRY_AFTER_TIMEOUT);
414
- }
415
- function retryIfThrottled(fn, retryThrottledMaxTimes) {
416
- return retrier(function (_a) {
417
- var attempt = _a.attempt, retry = _a.retry;
418
- return fn().catch(function (error) {
419
- if ('response' in error &&
420
- (error === null || error === void 0 ? void 0 : error.code) === REQUEST_WAS_THROTTLED_CODE &&
421
- attempt < retryThrottledMaxTimes) {
422
- return retry(getTimeoutFromThrottledRequest(error));
423
- }
424
- throw error;
425
- });
426
- });
427
- }
428
-
429
- function getStoreValue(store) {
430
- return typeof store === 'undefined' ? 'auto' : store ? '1' : '0';
431
- }
432
-
433
- /**
434
- * Performs file uploading request to Uploadcare Upload API.
435
- * Can be canceled and has progress.
436
- */
437
- function base(file, _a) {
438
- var publicKey = _a.publicKey, fileName = _a.fileName, _b = _a.baseURL, baseURL = _b === void 0 ? defaultSettings.baseURL : _b, secureSignature = _a.secureSignature, secureExpire = _a.secureExpire, store = _a.store, signal = _a.signal, onProgress = _a.onProgress, _c = _a.source, source = _c === void 0 ? 'local' : _c, integration = _a.integration, userAgent = _a.userAgent, _d = _a.retryThrottledRequestMaxTimes, retryThrottledRequestMaxTimes = _d === void 0 ? defaultSettings.retryThrottledRequestMaxTimes : _d, metadata = _a.metadata;
439
- return retryIfThrottled(function () {
440
- var _a;
441
- return request({
442
- method: 'POST',
443
- url: getUrl(baseURL, '/base/', {
444
- jsonerrors: 1
445
- }),
446
- headers: {
447
- 'X-UC-User-Agent': getUserAgent({ publicKey: publicKey, integration: integration, userAgent: userAgent })
448
- },
449
- data: buildFormData({
450
- file: {
451
- data: file,
452
- name: (_a = fileName !== null && fileName !== void 0 ? fileName : file.name) !== null && _a !== void 0 ? _a : defaultFilename
453
- },
454
- UPLOADCARE_PUB_KEY: publicKey,
455
- UPLOADCARE_STORE: getStoreValue(store),
456
- signature: secureSignature,
457
- expire: secureExpire,
458
- source: source,
459
- metadata: metadata
460
- }),
461
- signal: signal,
462
- onProgress: onProgress
463
- }).then(function (_a) {
464
- var data = _a.data, headers = _a.headers, request = _a.request;
465
- var response = camelizeKeys(JSON.parse(data));
466
- if ('error' in response) {
467
- throw new UploadClientError(response.error.content, response.error.errorCode, request, response, headers);
468
- }
469
- else {
470
- return response;
471
- }
472
- });
473
- }, retryThrottledRequestMaxTimes);
474
- }
475
-
476
- var TypeEnum;
477
- (function (TypeEnum) {
478
- TypeEnum["Token"] = "token";
479
- TypeEnum["FileInfo"] = "file_info";
480
- })(TypeEnum || (TypeEnum = {}));
481
- /**
482
- * Uploading files from URL.
483
- */
484
- function fromUrl(sourceUrl, _a) {
485
- var publicKey = _a.publicKey, _b = _a.baseURL, baseURL = _b === void 0 ? defaultSettings.baseURL : _b, store = _a.store, fileName = _a.fileName, checkForUrlDuplicates = _a.checkForUrlDuplicates, saveUrlForRecurrentUploads = _a.saveUrlForRecurrentUploads, secureSignature = _a.secureSignature, secureExpire = _a.secureExpire, _c = _a.source, source = _c === void 0 ? 'url' : _c, signal = _a.signal, integration = _a.integration, userAgent = _a.userAgent, _d = _a.retryThrottledRequestMaxTimes, retryThrottledRequestMaxTimes = _d === void 0 ? defaultSettings.retryThrottledRequestMaxTimes : _d, metadata = _a.metadata;
486
- return retryIfThrottled(function () {
487
- return request({
488
- method: 'POST',
489
- headers: {
490
- 'X-UC-User-Agent': getUserAgent({ publicKey: publicKey, integration: integration, userAgent: userAgent })
491
- },
492
- url: getUrl(baseURL, '/from_url/', {
493
- jsonerrors: 1,
494
- pub_key: publicKey,
495
- source_url: sourceUrl,
496
- store: getStoreValue(store),
497
- filename: fileName,
498
- check_URL_duplicates: checkForUrlDuplicates ? 1 : undefined,
499
- save_URL_duplicates: saveUrlForRecurrentUploads ? 1 : undefined,
500
- signature: secureSignature,
501
- expire: secureExpire,
502
- source: source,
503
- metadata: metadata
504
- }),
505
- signal: signal
506
- }).then(function (_a) {
507
- var data = _a.data, headers = _a.headers, request = _a.request;
508
- var response = camelizeKeys(JSON.parse(data));
509
- if ('error' in response) {
510
- throw new UploadClientError(response.error.content, response.error.errorCode, request, response, headers);
511
- }
512
- else {
513
- return response;
514
- }
515
- });
516
- }, retryThrottledRequestMaxTimes);
517
- }
518
-
519
- var Status;
520
- (function (Status) {
521
- Status["Unknown"] = "unknown";
522
- Status["Waiting"] = "waiting";
523
- Status["Progress"] = "progress";
524
- Status["Error"] = "error";
525
- Status["Success"] = "success";
526
- })(Status || (Status = {}));
527
- var isErrorResponse = function (response) {
528
- return 'status' in response && response.status === Status.Error;
529
- };
530
- /**
531
- * Checking upload status and working with file tokens.
532
- */
533
- function fromUrlStatus(token, _a) {
534
- var _b = _a === void 0 ? {} : _a, publicKey = _b.publicKey, _c = _b.baseURL, baseURL = _c === void 0 ? defaultSettings.baseURL : _c, signal = _b.signal, integration = _b.integration, userAgent = _b.userAgent, _d = _b.retryThrottledRequestMaxTimes, retryThrottledRequestMaxTimes = _d === void 0 ? defaultSettings.retryThrottledRequestMaxTimes : _d;
535
- return retryIfThrottled(function () {
536
- return request({
537
- method: 'GET',
538
- headers: publicKey
539
- ? {
540
- 'X-UC-User-Agent': getUserAgent({
541
- publicKey: publicKey,
542
- integration: integration,
543
- userAgent: userAgent
544
- })
545
- }
546
- : undefined,
547
- url: getUrl(baseURL, '/from_url/status/', {
548
- jsonerrors: 1,
549
- token: token
550
- }),
551
- signal: signal
552
- }).then(function (_a) {
553
- var data = _a.data, headers = _a.headers, request = _a.request;
554
- var response = camelizeKeys(JSON.parse(data));
555
- if ('error' in response && !isErrorResponse(response)) {
556
- throw new UploadClientError(response.error.content, undefined, request, response, headers);
557
- }
558
- else {
559
- return response;
560
- }
561
- });
562
- }, retryThrottledRequestMaxTimes);
563
- }
564
-
565
- /**
566
- * Create files group.
567
- */
568
- function group(uuids, _a) {
569
- var publicKey = _a.publicKey, _b = _a.baseURL, baseURL = _b === void 0 ? defaultSettings.baseURL : _b, jsonpCallback = _a.jsonpCallback, secureSignature = _a.secureSignature, secureExpire = _a.secureExpire, signal = _a.signal, source = _a.source, integration = _a.integration, userAgent = _a.userAgent, _c = _a.retryThrottledRequestMaxTimes, retryThrottledRequestMaxTimes = _c === void 0 ? defaultSettings.retryThrottledRequestMaxTimes : _c;
570
- return retryIfThrottled(function () {
571
- return request({
572
- method: 'POST',
573
- headers: {
574
- 'X-UC-User-Agent': getUserAgent({ publicKey: publicKey, integration: integration, userAgent: userAgent })
575
- },
576
- url: getUrl(baseURL, '/group/', {
577
- jsonerrors: 1,
578
- pub_key: publicKey,
579
- files: uuids,
580
- callback: jsonpCallback,
581
- signature: secureSignature,
582
- expire: secureExpire,
583
- source: source
584
- }),
585
- signal: signal
586
- }).then(function (_a) {
587
- var data = _a.data, headers = _a.headers, request = _a.request;
588
- var response = camelizeKeys(JSON.parse(data));
589
- if ('error' in response) {
590
- throw new UploadClientError(response.error.content, response.error.errorCode, request, response, headers);
591
- }
592
- else {
593
- return response;
594
- }
595
- });
596
- }, retryThrottledRequestMaxTimes);
597
- }
598
-
599
- /**
600
- * Get info about group.
601
- */
602
- function groupInfo(id, _a) {
603
- var publicKey = _a.publicKey, _b = _a.baseURL, baseURL = _b === void 0 ? defaultSettings.baseURL : _b, signal = _a.signal, source = _a.source, integration = _a.integration, userAgent = _a.userAgent, _c = _a.retryThrottledRequestMaxTimes, retryThrottledRequestMaxTimes = _c === void 0 ? defaultSettings.retryThrottledRequestMaxTimes : _c;
604
- return retryIfThrottled(function () {
605
- return request({
606
- method: 'GET',
607
- headers: {
608
- 'X-UC-User-Agent': getUserAgent({ publicKey: publicKey, integration: integration, userAgent: userAgent })
609
- },
610
- url: getUrl(baseURL, '/group/info/', {
611
- jsonerrors: 1,
612
- pub_key: publicKey,
613
- group_id: id,
614
- source: source
615
- }),
616
- signal: signal
617
- }).then(function (_a) {
618
- var data = _a.data, headers = _a.headers, request = _a.request;
619
- var response = camelizeKeys(JSON.parse(data));
620
- if ('error' in response) {
621
- throw new UploadClientError(response.error.content, response.error.errorCode, request, response, headers);
622
- }
623
- else {
624
- return response;
625
- }
626
- });
627
- }, retryThrottledRequestMaxTimes);
628
- }
629
-
630
- /**
631
- * Returns a JSON dictionary holding file info.
632
- */
633
- function info(uuid, _a) {
634
- var publicKey = _a.publicKey, _b = _a.baseURL, baseURL = _b === void 0 ? defaultSettings.baseURL : _b, signal = _a.signal, source = _a.source, integration = _a.integration, userAgent = _a.userAgent, _c = _a.retryThrottledRequestMaxTimes, retryThrottledRequestMaxTimes = _c === void 0 ? defaultSettings.retryThrottledRequestMaxTimes : _c;
635
- return retryIfThrottled(function () {
636
- return request({
637
- method: 'GET',
638
- headers: {
639
- 'X-UC-User-Agent': getUserAgent({ publicKey: publicKey, integration: integration, userAgent: userAgent })
640
- },
641
- url: getUrl(baseURL, '/info/', {
642
- jsonerrors: 1,
643
- pub_key: publicKey,
644
- file_id: uuid,
645
- source: source
646
- }),
647
- signal: signal
648
- }).then(function (_a) {
649
- var data = _a.data, headers = _a.headers, request = _a.request;
650
- var response = camelizeKeys(JSON.parse(data));
651
- if ('error' in response) {
652
- throw new UploadClientError(response.error.content, response.error.errorCode, request, response, headers);
653
- }
654
- else {
655
- return response;
656
- }
657
- });
658
- }, retryThrottledRequestMaxTimes);
659
- }
660
-
661
- /**
662
- * Start multipart uploading.
663
- */
664
- function multipartStart(size, _a) {
665
- var publicKey = _a.publicKey, contentType = _a.contentType, fileName = _a.fileName, _b = _a.multipartChunkSize, multipartChunkSize = _b === void 0 ? defaultSettings.multipartChunkSize : _b, _c = _a.baseURL, baseURL = _c === void 0 ? '' : _c, secureSignature = _a.secureSignature, secureExpire = _a.secureExpire, store = _a.store, signal = _a.signal, _d = _a.source, source = _d === void 0 ? 'local' : _d, integration = _a.integration, userAgent = _a.userAgent, _e = _a.retryThrottledRequestMaxTimes, retryThrottledRequestMaxTimes = _e === void 0 ? defaultSettings.retryThrottledRequestMaxTimes : _e, metadata = _a.metadata;
666
- return retryIfThrottled(function () {
667
- return request({
668
- method: 'POST',
669
- url: getUrl(baseURL, '/multipart/start/', { jsonerrors: 1 }),
670
- headers: {
671
- 'X-UC-User-Agent': getUserAgent({ publicKey: publicKey, integration: integration, userAgent: userAgent })
672
- },
673
- data: buildFormData({
674
- filename: fileName !== null && fileName !== void 0 ? fileName : defaultFilename,
675
- size: size,
676
- content_type: contentType !== null && contentType !== void 0 ? contentType : defaultContentType,
677
- part_size: multipartChunkSize,
678
- UPLOADCARE_STORE: getStoreValue(store),
679
- UPLOADCARE_PUB_KEY: publicKey,
680
- signature: secureSignature,
681
- expire: secureExpire,
682
- source: source,
683
- metadata: metadata
684
- }),
685
- signal: signal
686
- }).then(function (_a) {
687
- var data = _a.data, headers = _a.headers, request = _a.request;
688
- var response = camelizeKeys(JSON.parse(data));
689
- if ('error' in response) {
690
- throw new UploadClientError(response.error.content, response.error.errorCode, request, response, headers);
691
- }
692
- else {
693
- // convert to array
694
- response.parts = Object.keys(response.parts).map(function (key) { return response.parts[key]; });
695
- return response;
696
- }
697
- });
698
- }, retryThrottledRequestMaxTimes);
699
- }
700
-
701
- /**
702
- * Complete multipart uploading.
703
- */
704
- function multipartUpload(part, url, _a) {
705
- var signal = _a.signal, onProgress = _a.onProgress;
706
- return request({
707
- method: 'PUT',
708
- url: url,
709
- data: part,
710
- // Upload request can't be non-computable because we always know exact size
711
- onProgress: onProgress,
712
- signal: signal
713
- })
714
- .then(function (result) {
715
- // hack for node ¯\_(ツ)_/¯
716
- if (onProgress)
717
- onProgress({
718
- isComputable: true,
719
- value: 1
720
- });
721
- return result;
722
- })
723
- .then(function (_a) {
724
- var status = _a.status;
725
- return ({ code: status });
726
- });
727
- }
728
-
729
- /**
730
- * Complete multipart uploading.
731
- */
732
- function multipartComplete(uuid, _a) {
733
- var publicKey = _a.publicKey, _b = _a.baseURL, baseURL = _b === void 0 ? defaultSettings.baseURL : _b, _c = _a.source, source = _c === void 0 ? 'local' : _c, signal = _a.signal, integration = _a.integration, userAgent = _a.userAgent, _d = _a.retryThrottledRequestMaxTimes, retryThrottledRequestMaxTimes = _d === void 0 ? defaultSettings.retryThrottledRequestMaxTimes : _d;
734
- return retryIfThrottled(function () {
735
- return request({
736
- method: 'POST',
737
- url: getUrl(baseURL, '/multipart/complete/', { jsonerrors: 1 }),
738
- headers: {
739
- 'X-UC-User-Agent': getUserAgent({ publicKey: publicKey, integration: integration, userAgent: userAgent })
740
- },
741
- data: buildFormData({
742
- uuid: uuid,
743
- UPLOADCARE_PUB_KEY: publicKey,
744
- source: source
745
- }),
746
- signal: signal
747
- }).then(function (_a) {
748
- var data = _a.data, headers = _a.headers, request = _a.request;
749
- var response = camelizeKeys(JSON.parse(data));
750
- if ('error' in response) {
751
- throw new UploadClientError(response.error.content, response.error.errorCode, request, response, headers);
752
- }
753
- else {
754
- return response;
755
- }
756
- });
757
- }, retryThrottledRequestMaxTimes);
758
- }
759
-
760
- var UploadcareFile = /** @class */ (function () {
761
- function UploadcareFile(fileInfo, _a) {
762
- var baseCDN = _a.baseCDN, defaultEffects = _a.defaultEffects, fileName = _a.fileName;
763
- this.name = null;
764
- this.size = null;
765
- this.isStored = null;
766
- this.isImage = null;
767
- this.mimeType = null;
768
- this.cdnUrl = null;
769
- this.cdnUrlModifiers = null;
770
- this.originalUrl = null;
771
- this.originalFilename = null;
772
- this.imageInfo = null;
773
- this.videoInfo = null;
774
- this.contentInfo = null;
775
- this.metadata = null;
776
- var uuid = fileInfo.uuid, s3Bucket = fileInfo.s3Bucket;
777
- var urlBase = s3Bucket
778
- ? "https://" + s3Bucket + ".s3.amazonaws.com/" + uuid + "/" + fileInfo.filename
779
- : baseCDN + "/" + uuid + "/";
780
- var cdnUrlModifiers = defaultEffects ? "-/" + defaultEffects : null;
781
- var cdnUrl = "" + urlBase + (cdnUrlModifiers || '');
782
- var originalUrl = uuid ? urlBase : null;
783
- this.uuid = uuid;
784
- this.name = fileName || fileInfo.filename;
785
- this.size = fileInfo.size;
786
- this.isStored = fileInfo.isStored;
787
- this.isImage = fileInfo.isImage;
788
- this.mimeType = fileInfo.mimeType;
789
- this.cdnUrl = cdnUrl;
790
- this.cdnUrlModifiers = cdnUrlModifiers;
791
- this.originalUrl = originalUrl;
792
- this.originalFilename = fileInfo.originalFilename;
793
- this.imageInfo = camelizeKeys(fileInfo.imageInfo);
794
- this.videoInfo = camelizeKeys(fileInfo.videoInfo);
795
- this.contentInfo = camelizeKeys(fileInfo.contentInfo);
796
- this.metadata = fileInfo.metadata || null;
797
- }
798
- return UploadcareFile;
799
- }());
800
-
801
- var DEFAULT_INTERVAL = 500;
802
- var poll = function (_a) {
803
- var check = _a.check, _b = _a.interval, interval = _b === void 0 ? DEFAULT_INTERVAL : _b, signal = _a.signal;
804
- return new Promise(function (resolve, reject) {
805
- var timeoutId;
806
- onCancel(signal, function () {
807
- timeoutId && clearTimeout(timeoutId);
808
- reject(cancelError('Poll cancelled'));
809
- });
810
- var tick = function () {
811
- try {
812
- Promise.resolve(check(signal))
813
- .then(function (result) {
814
- if (result) {
815
- resolve(result);
816
- }
817
- else {
818
- timeoutId = setTimeout(tick, interval);
819
- }
820
- })
821
- .catch(function (error) { return reject(error); });
822
- }
823
- catch (error) {
824
- reject(error);
825
- }
826
- };
827
- timeoutId = setTimeout(tick, 0);
828
- });
829
- };
830
-
831
- function isReadyPoll(_a) {
832
- var file = _a.file, publicKey = _a.publicKey, baseURL = _a.baseURL, source = _a.source, integration = _a.integration, userAgent = _a.userAgent, retryThrottledRequestMaxTimes = _a.retryThrottledRequestMaxTimes, signal = _a.signal, onProgress = _a.onProgress;
833
- return poll({
834
- check: function (signal) {
835
- return info(file, {
836
- publicKey: publicKey,
837
- baseURL: baseURL,
838
- signal: signal,
839
- source: source,
840
- integration: integration,
841
- userAgent: userAgent,
842
- retryThrottledRequestMaxTimes: retryThrottledRequestMaxTimes
843
- }).then(function (response) {
844
- if (response.isReady) {
845
- return response;
846
- }
847
- onProgress && onProgress({ isComputable: true, value: 1 });
848
- return false;
849
- });
850
- },
851
- signal: signal
852
- });
853
- }
854
-
855
- var uploadFromObject = function (file, _a) {
856
- var publicKey = _a.publicKey, fileName = _a.fileName, baseURL = _a.baseURL, secureSignature = _a.secureSignature, secureExpire = _a.secureExpire, store = _a.store, signal = _a.signal, onProgress = _a.onProgress, source = _a.source, integration = _a.integration, userAgent = _a.userAgent, retryThrottledRequestMaxTimes = _a.retryThrottledRequestMaxTimes, baseCDN = _a.baseCDN, metadata = _a.metadata;
857
- return base(file, {
858
- publicKey: publicKey,
859
- fileName: fileName,
860
- baseURL: baseURL,
861
- secureSignature: secureSignature,
862
- secureExpire: secureExpire,
863
- store: store,
864
- signal: signal,
865
- onProgress: onProgress,
866
- source: source,
867
- integration: integration,
868
- userAgent: userAgent,
869
- retryThrottledRequestMaxTimes: retryThrottledRequestMaxTimes,
870
- metadata: metadata
871
- })
872
- .then(function (_a) {
873
- var file = _a.file;
874
- return isReadyPoll({
875
- file: file,
876
- publicKey: publicKey,
877
- baseURL: baseURL,
878
- source: source,
879
- integration: integration,
880
- userAgent: userAgent,
881
- retryThrottledRequestMaxTimes: retryThrottledRequestMaxTimes,
882
- onProgress: onProgress,
883
- signal: signal
884
- });
885
- })
886
- .then(function (fileInfo) { return new UploadcareFile(fileInfo, { baseCDN: baseCDN }); });
887
- };
888
-
889
- /*globals self, window */
890
-
891
- /*eslint-disable @mysticatea/prettier */
892
- const { AbortController, AbortSignal } =
893
- typeof self !== "undefined" ? self :
894
- typeof window !== "undefined" ? window :
895
- /* otherwise */ undefined;
896
-
897
- var race = function (fns, _a) {
898
- var signal = (_a === void 0 ? {} : _a).signal;
899
- var lastError = null;
900
- var winnerIndex = null;
901
- var controllers = fns.map(function () { return new AbortController(); });
902
- var createStopRaceCallback = function (i) { return function () {
903
- winnerIndex = i;
904
- controllers.forEach(function (controller, index) { return index !== i && controller.abort(); });
905
- }; };
906
- onCancel(signal, function () {
907
- controllers.forEach(function (controller) { return controller.abort(); });
908
- });
909
- return Promise.all(fns.map(function (fn, i) {
910
- var stopRace = createStopRaceCallback(i);
911
- return Promise.resolve()
912
- .then(function () { return fn({ stopRace: stopRace, signal: controllers[i].signal }); })
913
- .then(function (result) {
914
- stopRace();
915
- return result;
916
- })
917
- .catch(function (error) {
918
- lastError = error;
919
- return null;
920
- });
921
- })).then(function (results) {
922
- if (winnerIndex === null) {
923
- throw lastError;
924
- }
925
- else {
926
- return results[winnerIndex];
927
- }
928
- });
929
- };
930
-
931
- var WebSocket = window.WebSocket;
932
-
933
- var Events = /** @class */ (function () {
934
- function Events() {
935
- this.events = Object.create({});
936
- }
937
- Events.prototype.emit = function (event, data) {
938
- var _a;
939
- (_a = this.events[event]) === null || _a === void 0 ? void 0 : _a.forEach(function (fn) { return fn(data); });
940
- };
941
- Events.prototype.on = function (event, callback) {
942
- this.events[event] = this.events[event] || [];
943
- this.events[event].push(callback);
944
- };
945
- Events.prototype.off = function (event, callback) {
946
- if (callback) {
947
- this.events[event] = this.events[event].filter(function (fn) { return fn !== callback; });
948
- }
949
- else {
950
- this.events[event] = [];
951
- }
952
- };
953
- return Events;
954
- }());
955
-
956
- var response = function (type, data) {
957
- if (type === 'success') {
958
- return __assign({ status: Status.Success }, data);
959
- }
960
- if (type === 'progress') {
961
- return __assign({ status: Status.Progress }, data);
962
- }
963
- return __assign({ status: Status.Error }, data);
964
- };
965
- var Pusher = /** @class */ (function () {
966
- function Pusher(pusherKey, disconnectTime) {
967
- if (disconnectTime === void 0) { disconnectTime = 30000; }
968
- this.ws = undefined;
969
- this.queue = [];
970
- this.isConnected = false;
971
- this.subscribers = 0;
972
- this.emmitter = new Events();
973
- this.disconnectTimeoutId = null;
974
- this.key = pusherKey;
975
- this.disconnectTime = disconnectTime;
976
- }
977
- Pusher.prototype.connect = function () {
978
- var _this = this;
979
- this.disconnectTimeoutId && clearTimeout(this.disconnectTimeoutId);
980
- if (!this.isConnected && !this.ws) {
981
- var pusherUrl = "wss://ws.pusherapp.com/app/" + this.key + "?protocol=5&client=js&version=1.12.2";
982
- this.ws = new WebSocket(pusherUrl);
983
- this.ws.addEventListener('error', function (error) {
984
- _this.emmitter.emit('error', new Error(error.message));
985
- });
986
- this.emmitter.on('connected', function () {
987
- _this.isConnected = true;
988
- _this.queue.forEach(function (message) { return _this.send(message.event, message.data); });
989
- _this.queue = [];
990
- });
991
- this.ws.addEventListener('message', function (e) {
992
- var data = JSON.parse(e.data.toString());
993
- switch (data.event) {
994
- case 'pusher:connection_established': {
995
- _this.emmitter.emit('connected', undefined);
996
- break;
997
- }
998
- case 'pusher:ping': {
999
- _this.send('pusher:pong', {});
1000
- break;
1001
- }
1002
- case 'progress':
1003
- case 'success':
1004
- case 'fail': {
1005
- _this.emmitter.emit(data.channel, response(data.event, JSON.parse(data.data)));
1006
- }
1007
- }
1008
- });
1009
- }
1010
- };
1011
- Pusher.prototype.disconnect = function () {
1012
- var _this = this;
1013
- var actualDisconect = function () {
1014
- var _a;
1015
- (_a = _this.ws) === null || _a === void 0 ? void 0 : _a.close();
1016
- _this.ws = undefined;
1017
- _this.isConnected = false;
1018
- };
1019
- if (this.disconnectTime) {
1020
- this.disconnectTimeoutId = setTimeout(function () {
1021
- actualDisconect();
1022
- }, this.disconnectTime);
1023
- }
1024
- else {
1025
- actualDisconect();
1026
- }
1027
- };
1028
- Pusher.prototype.send = function (event, data) {
1029
- var _a;
1030
- var str = JSON.stringify({ event: event, data: data });
1031
- (_a = this.ws) === null || _a === void 0 ? void 0 : _a.send(str);
1032
- };
1033
- Pusher.prototype.subscribe = function (token, handler) {
1034
- this.subscribers += 1;
1035
- this.connect();
1036
- var channel = "task-status-" + token;
1037
- var message = {
1038
- event: 'pusher:subscribe',
1039
- data: { channel: channel }
1040
- };
1041
- this.emmitter.on(channel, handler);
1042
- if (this.isConnected) {
1043
- this.send(message.event, message.data);
1044
- }
1045
- else {
1046
- this.queue.push(message);
1047
- }
1048
- };
1049
- Pusher.prototype.unsubscribe = function (token) {
1050
- this.subscribers -= 1;
1051
- var channel = "task-status-" + token;
1052
- var message = {
1053
- event: 'pusher:unsubscribe',
1054
- data: { channel: channel }
1055
- };
1056
- this.emmitter.off(channel);
1057
- if (this.isConnected) {
1058
- this.send(message.event, message.data);
1059
- }
1060
- else {
1061
- this.queue = this.queue.filter(function (msg) { return msg.data.channel !== channel; });
1062
- }
1063
- if (this.subscribers === 0) {
1064
- this.disconnect();
1065
- }
1066
- };
1067
- Pusher.prototype.onError = function (callback) {
1068
- var _this = this;
1069
- this.emmitter.on('error', callback);
1070
- return function () { return _this.emmitter.off('error', callback); };
1071
- };
1072
- return Pusher;
1073
- }());
1074
- var pusher = null;
1075
- var getPusher = function (key) {
1076
- if (!pusher) {
1077
- // no timeout for nodeJS and 30000 ms for browser
1078
- var disconectTimeout = typeof window === 'undefined' ? 0 : 30000;
1079
- pusher = new Pusher(key, disconectTimeout);
1080
- }
1081
- return pusher;
1082
- };
1083
- var preconnect = function (key) {
1084
- getPusher(key).connect();
1085
- };
1086
-
1087
- function pollStrategy(_a) {
1088
- var token = _a.token, publicKey = _a.publicKey, baseURL = _a.baseURL, integration = _a.integration, userAgent = _a.userAgent, retryThrottledRequestMaxTimes = _a.retryThrottledRequestMaxTimes, onProgress = _a.onProgress, signal = _a.signal;
1089
- return poll({
1090
- check: function (signal) {
1091
- return fromUrlStatus(token, {
1092
- publicKey: publicKey,
1093
- baseURL: baseURL,
1094
- integration: integration,
1095
- userAgent: userAgent,
1096
- retryThrottledRequestMaxTimes: retryThrottledRequestMaxTimes,
1097
- signal: signal
1098
- }).then(function (response) {
1099
- switch (response.status) {
1100
- case Status.Error: {
1101
- return new UploadClientError(response.error, response.errorCode);
1102
- }
1103
- case Status.Waiting: {
1104
- return false;
1105
- }
1106
- case Status.Unknown: {
1107
- return new UploadClientError("Token \"" + token + "\" was not found.");
1108
- }
1109
- case Status.Progress: {
1110
- if (onProgress) {
1111
- if (response.total === 'unknown') {
1112
- onProgress({ isComputable: false });
1113
- }
1114
- else {
1115
- onProgress({
1116
- isComputable: true,
1117
- value: response.done / response.total
1118
- });
1119
- }
1120
- }
1121
- return false;
1122
- }
1123
- case Status.Success: {
1124
- if (onProgress)
1125
- onProgress({
1126
- isComputable: true,
1127
- value: response.done / response.total
1128
- });
1129
- return response;
1130
- }
1131
- default: {
1132
- throw new Error('Unknown status');
1133
- }
1134
- }
1135
- });
1136
- },
1137
- signal: signal
1138
- });
1139
- }
1140
- var pushStrategy = function (_a) {
1141
- var token = _a.token, pusherKey = _a.pusherKey, signal = _a.signal, onProgress = _a.onProgress;
1142
- return new Promise(function (resolve, reject) {
1143
- var pusher = getPusher(pusherKey);
1144
- var unsubErrorHandler = pusher.onError(reject);
1145
- var destroy = function () {
1146
- unsubErrorHandler();
1147
- pusher.unsubscribe(token);
1148
- };
1149
- onCancel(signal, function () {
1150
- destroy();
1151
- reject(cancelError('pusher cancelled'));
1152
- });
1153
- pusher.subscribe(token, function (result) {
1154
- switch (result.status) {
1155
- case Status.Progress: {
1156
- if (onProgress) {
1157
- if (result.total === 'unknown') {
1158
- onProgress({ isComputable: false });
1159
- }
1160
- else {
1161
- onProgress({
1162
- isComputable: true,
1163
- value: result.done / result.total
1164
- });
1165
- }
1166
- }
1167
- break;
1168
- }
1169
- case Status.Success: {
1170
- destroy();
1171
- if (onProgress)
1172
- onProgress({
1173
- isComputable: true,
1174
- value: result.done / result.total
1175
- });
1176
- resolve(result);
1177
- break;
1178
- }
1179
- case Status.Error: {
1180
- destroy();
1181
- reject(new UploadClientError(result.msg, result.error_code));
1182
- }
1183
- }
1184
- });
1185
- });
1186
- };
1187
- var uploadFromUrl = function (sourceUrl, _a) {
1188
- var publicKey = _a.publicKey, fileName = _a.fileName, baseURL = _a.baseURL, baseCDN = _a.baseCDN, checkForUrlDuplicates = _a.checkForUrlDuplicates, saveUrlForRecurrentUploads = _a.saveUrlForRecurrentUploads, secureSignature = _a.secureSignature, secureExpire = _a.secureExpire, store = _a.store, signal = _a.signal, onProgress = _a.onProgress, source = _a.source, integration = _a.integration, userAgent = _a.userAgent, retryThrottledRequestMaxTimes = _a.retryThrottledRequestMaxTimes, _b = _a.pusherKey, pusherKey = _b === void 0 ? defaultSettings.pusherKey : _b, metadata = _a.metadata;
1189
- return Promise.resolve(preconnect(pusherKey))
1190
- .then(function () {
1191
- return fromUrl(sourceUrl, {
1192
- publicKey: publicKey,
1193
- fileName: fileName,
1194
- baseURL: baseURL,
1195
- checkForUrlDuplicates: checkForUrlDuplicates,
1196
- saveUrlForRecurrentUploads: saveUrlForRecurrentUploads,
1197
- secureSignature: secureSignature,
1198
- secureExpire: secureExpire,
1199
- store: store,
1200
- signal: signal,
1201
- source: source,
1202
- integration: integration,
1203
- userAgent: userAgent,
1204
- retryThrottledRequestMaxTimes: retryThrottledRequestMaxTimes,
1205
- metadata: metadata
1206
- });
1207
- })
1208
- .catch(function (error) {
1209
- var pusher = getPusher(pusherKey);
1210
- pusher === null || pusher === void 0 ? void 0 : pusher.disconnect();
1211
- return Promise.reject(error);
1212
- })
1213
- .then(function (urlResponse) {
1214
- if (urlResponse.type === TypeEnum.FileInfo) {
1215
- return urlResponse;
1216
- }
1217
- else {
1218
- return race([
1219
- function (_a) {
1220
- var signal = _a.signal;
1221
- return pollStrategy({
1222
- token: urlResponse.token,
1223
- publicKey: publicKey,
1224
- baseURL: baseURL,
1225
- integration: integration,
1226
- userAgent: userAgent,
1227
- retryThrottledRequestMaxTimes: retryThrottledRequestMaxTimes,
1228
- onProgress: onProgress,
1229
- signal: signal
1230
- });
1231
- },
1232
- function (_a) {
1233
- var signal = _a.signal;
1234
- return pushStrategy({
1235
- token: urlResponse.token,
1236
- pusherKey: pusherKey,
1237
- signal: signal,
1238
- onProgress: onProgress
1239
- });
1240
- }
1241
- ], { signal: signal });
1242
- }
1243
- })
1244
- .then(function (result) {
1245
- if (result instanceof UploadClientError)
1246
- throw result;
1247
- return result;
1248
- })
1249
- .then(function (result) {
1250
- return isReadyPoll({
1251
- file: result.uuid,
1252
- publicKey: publicKey,
1253
- baseURL: baseURL,
1254
- integration: integration,
1255
- userAgent: userAgent,
1256
- retryThrottledRequestMaxTimes: retryThrottledRequestMaxTimes,
1257
- onProgress: onProgress,
1258
- signal: signal
1259
- });
1260
- })
1261
- .then(function (fileInfo) { return new UploadcareFile(fileInfo, { baseCDN: baseCDN }); });
1262
- };
1263
-
1264
- var uploadFromUploaded = function (uuid, _a) {
1265
- var publicKey = _a.publicKey, fileName = _a.fileName, baseURL = _a.baseURL, signal = _a.signal, onProgress = _a.onProgress, source = _a.source, integration = _a.integration, userAgent = _a.userAgent, retryThrottledRequestMaxTimes = _a.retryThrottledRequestMaxTimes, baseCDN = _a.baseCDN;
1266
- return info(uuid, {
1267
- publicKey: publicKey,
1268
- baseURL: baseURL,
1269
- signal: signal,
1270
- source: source,
1271
- integration: integration,
1272
- userAgent: userAgent,
1273
- retryThrottledRequestMaxTimes: retryThrottledRequestMaxTimes
1274
- })
1275
- .then(function (fileInfo) { return new UploadcareFile(fileInfo, { baseCDN: baseCDN, fileName: fileName }); })
1276
- .then(function (result) {
1277
- // hack for node ¯\_(ツ)_/¯
1278
- if (onProgress)
1279
- onProgress({
1280
- isComputable: true,
1281
- value: 1
1282
- });
1283
- return result;
1284
- });
1285
- };
1286
-
1287
- /**
1288
- * Get file size.
1289
- */
1290
- var getFileSize = function (file) {
1291
- return file.length || file.size;
1292
- };
1293
- /**
1294
- * Check if FileData is multipart data.
1295
- */
1296
- var isMultipart = function (fileSize, multipartMinFileSize) {
1297
- if (multipartMinFileSize === void 0) { multipartMinFileSize = defaultSettings.multipartMinFileSize; }
1298
- return fileSize >= multipartMinFileSize;
1299
- };
1300
-
1301
- var sliceChunk = function (file, index, fileSize, chunkSize) {
1302
- var start = chunkSize * index;
1303
- var end = Math.min(start + chunkSize, fileSize);
1304
- return file.slice(start, end);
1305
- };
1306
-
1307
- function prepareChunks(file, fileSize, chunkSize) {
1308
- return function (index) {
1309
- return sliceChunk(file, index, fileSize, chunkSize);
1310
- };
1311
- }
1312
-
1313
- var runWithConcurrency = function (concurrency, tasks) {
1314
- return new Promise(function (resolve, reject) {
1315
- var results = [];
1316
- var rejected = false;
1317
- var settled = tasks.length;
1318
- var forRun = __spreadArrays(tasks);
1319
- var run = function () {
1320
- var index = tasks.length - forRun.length;
1321
- var next = forRun.shift();
1322
- if (next) {
1323
- next()
1324
- .then(function (result) {
1325
- if (rejected)
1326
- return;
1327
- results[index] = result;
1328
- settled -= 1;
1329
- if (settled) {
1330
- run();
1331
- }
1332
- else {
1333
- resolve(results);
1334
- }
1335
- })
1336
- .catch(function (error) {
1337
- rejected = true;
1338
- reject(error);
1339
- });
1340
- }
1341
- };
1342
- for (var i = 0; i < concurrency; i++) {
1343
- run();
1344
- }
1345
- });
1346
- };
1347
-
1348
- var uploadPartWithRetry = function (chunk, url, _a) {
1349
- var publicKey = _a.publicKey, onProgress = _a.onProgress, signal = _a.signal, integration = _a.integration, multipartMaxAttempts = _a.multipartMaxAttempts;
1350
- return retrier(function (_a) {
1351
- var attempt = _a.attempt, retry = _a.retry;
1352
- return multipartUpload(chunk, url, {
1353
- publicKey: publicKey,
1354
- onProgress: onProgress,
1355
- signal: signal,
1356
- integration: integration
1357
- }).catch(function (error) {
1358
- if (attempt < multipartMaxAttempts) {
1359
- return retry();
1360
- }
1361
- throw error;
1362
- });
1363
- });
1364
- };
1365
- var uploadMultipart = function (file, _a) {
1366
- var publicKey = _a.publicKey, fileName = _a.fileName, fileSize = _a.fileSize, baseURL = _a.baseURL, secureSignature = _a.secureSignature, secureExpire = _a.secureExpire, store = _a.store, signal = _a.signal, onProgress = _a.onProgress, source = _a.source, integration = _a.integration, userAgent = _a.userAgent, retryThrottledRequestMaxTimes = _a.retryThrottledRequestMaxTimes, contentType = _a.contentType, _b = _a.multipartChunkSize, multipartChunkSize = _b === void 0 ? defaultSettings.multipartChunkSize : _b, _c = _a.maxConcurrentRequests, maxConcurrentRequests = _c === void 0 ? defaultSettings.maxConcurrentRequests : _c, _d = _a.multipartMaxAttempts, multipartMaxAttempts = _d === void 0 ? defaultSettings.multipartMaxAttempts : _d, baseCDN = _a.baseCDN, metadata = _a.metadata;
1367
- var size = fileSize || getFileSize(file);
1368
- var progressValues;
1369
- var createProgressHandler = function (totalChunks, chunkIdx) {
1370
- if (!onProgress)
1371
- return;
1372
- if (!progressValues) {
1373
- progressValues = Array(totalChunks).fill(0);
1374
- }
1375
- var sum = function (values) {
1376
- return values.reduce(function (sum, next) { return sum + next; }, 0);
1377
- };
1378
- return function (info) {
1379
- if (!info.isComputable) {
1380
- return;
1381
- }
1382
- progressValues[chunkIdx] = info.value;
1383
- onProgress({
1384
- isComputable: true,
1385
- value: sum(progressValues) / totalChunks
1386
- });
1387
- };
1388
- };
1389
- return multipartStart(size, {
1390
- publicKey: publicKey,
1391
- contentType: contentType,
1392
- fileName: fileName !== null && fileName !== void 0 ? fileName : file.name,
1393
- baseURL: baseURL,
1394
- secureSignature: secureSignature,
1395
- secureExpire: secureExpire,
1396
- store: store,
1397
- signal: signal,
1398
- source: source,
1399
- integration: integration,
1400
- userAgent: userAgent,
1401
- retryThrottledRequestMaxTimes: retryThrottledRequestMaxTimes,
1402
- metadata: metadata
1403
- })
1404
- .then(function (_a) {
1405
- var uuid = _a.uuid, parts = _a.parts;
1406
- var getChunk = prepareChunks(file, size, multipartChunkSize);
1407
- return Promise.all([
1408
- uuid,
1409
- runWithConcurrency(maxConcurrentRequests, parts.map(function (url, index) { return function () {
1410
- return uploadPartWithRetry(getChunk(index), url, {
1411
- publicKey: publicKey,
1412
- onProgress: createProgressHandler(parts.length, index),
1413
- signal: signal,
1414
- integration: integration,
1415
- multipartMaxAttempts: multipartMaxAttempts
1416
- });
1417
- }; }))
1418
- ]);
1419
- })
1420
- .then(function (_a) {
1421
- var uuid = _a[0];
1422
- return multipartComplete(uuid, {
1423
- publicKey: publicKey,
1424
- baseURL: baseURL,
1425
- source: source,
1426
- integration: integration,
1427
- userAgent: userAgent,
1428
- retryThrottledRequestMaxTimes: retryThrottledRequestMaxTimes
1429
- });
1430
- })
1431
- .then(function (fileInfo) {
1432
- if (fileInfo.isReady) {
1433
- return fileInfo;
1434
- }
1435
- else {
1436
- return isReadyPoll({
1437
- file: fileInfo.uuid,
1438
- publicKey: publicKey,
1439
- baseURL: baseURL,
1440
- source: source,
1441
- integration: integration,
1442
- userAgent: userAgent,
1443
- retryThrottledRequestMaxTimes: retryThrottledRequestMaxTimes,
1444
- onProgress: onProgress,
1445
- signal: signal
1446
- });
1447
- }
1448
- })
1449
- .then(function (fileInfo) { return new UploadcareFile(fileInfo, { baseCDN: baseCDN }); });
1450
- };
1451
-
1452
- /**
1453
- * Uploads file from provided data.
1454
- */
1455
- function uploadFile(data, _a) {
1456
- var publicKey = _a.publicKey, fileName = _a.fileName, _b = _a.baseURL, baseURL = _b === void 0 ? defaultSettings.baseURL : _b, secureSignature = _a.secureSignature, secureExpire = _a.secureExpire, store = _a.store, signal = _a.signal, onProgress = _a.onProgress, source = _a.source, integration = _a.integration, userAgent = _a.userAgent, retryThrottledRequestMaxTimes = _a.retryThrottledRequestMaxTimes, contentType = _a.contentType, multipartMinFileSize = _a.multipartMinFileSize, multipartChunkSize = _a.multipartChunkSize, multipartMaxAttempts = _a.multipartMaxAttempts, maxConcurrentRequests = _a.maxConcurrentRequests, _c = _a.baseCDN, baseCDN = _c === void 0 ? defaultSettings.baseCDN : _c, checkForUrlDuplicates = _a.checkForUrlDuplicates, saveUrlForRecurrentUploads = _a.saveUrlForRecurrentUploads, pusherKey = _a.pusherKey, metadata = _a.metadata;
1457
- if (isFileData(data)) {
1458
- var fileSize = getFileSize(data);
1459
- if (isMultipart(fileSize, multipartMinFileSize)) {
1460
- return uploadMultipart(data, {
1461
- publicKey: publicKey,
1462
- contentType: contentType,
1463
- multipartChunkSize: multipartChunkSize,
1464
- multipartMaxAttempts: multipartMaxAttempts,
1465
- fileName: fileName,
1466
- baseURL: baseURL,
1467
- secureSignature: secureSignature,
1468
- secureExpire: secureExpire,
1469
- store: store,
1470
- signal: signal,
1471
- onProgress: onProgress,
1472
- source: source,
1473
- integration: integration,
1474
- userAgent: userAgent,
1475
- maxConcurrentRequests: maxConcurrentRequests,
1476
- retryThrottledRequestMaxTimes: retryThrottledRequestMaxTimes,
1477
- baseCDN: baseCDN,
1478
- metadata: metadata
1479
- });
1480
- }
1481
- return uploadFromObject(data, {
1482
- publicKey: publicKey,
1483
- fileName: fileName,
1484
- baseURL: baseURL,
1485
- secureSignature: secureSignature,
1486
- secureExpire: secureExpire,
1487
- store: store,
1488
- signal: signal,
1489
- onProgress: onProgress,
1490
- source: source,
1491
- integration: integration,
1492
- userAgent: userAgent,
1493
- retryThrottledRequestMaxTimes: retryThrottledRequestMaxTimes,
1494
- baseCDN: baseCDN,
1495
- metadata: metadata
1496
- });
1497
- }
1498
- if (isUrl(data)) {
1499
- return uploadFromUrl(data, {
1500
- publicKey: publicKey,
1501
- fileName: fileName,
1502
- baseURL: baseURL,
1503
- baseCDN: baseCDN,
1504
- checkForUrlDuplicates: checkForUrlDuplicates,
1505
- saveUrlForRecurrentUploads: saveUrlForRecurrentUploads,
1506
- secureSignature: secureSignature,
1507
- secureExpire: secureExpire,
1508
- store: store,
1509
- signal: signal,
1510
- onProgress: onProgress,
1511
- source: source,
1512
- integration: integration,
1513
- userAgent: userAgent,
1514
- retryThrottledRequestMaxTimes: retryThrottledRequestMaxTimes,
1515
- pusherKey: pusherKey,
1516
- metadata: metadata
1517
- });
1518
- }
1519
- if (isUuid(data)) {
1520
- return uploadFromUploaded(data, {
1521
- publicKey: publicKey,
1522
- fileName: fileName,
1523
- baseURL: baseURL,
1524
- signal: signal,
1525
- onProgress: onProgress,
1526
- source: source,
1527
- integration: integration,
1528
- userAgent: userAgent,
1529
- retryThrottledRequestMaxTimes: retryThrottledRequestMaxTimes,
1530
- baseCDN: baseCDN
1531
- });
1532
- }
1533
- throw new TypeError("File uploading from \"" + data + "\" is not supported");
1534
- }
1535
-
1536
- var UploadcareGroup = /** @class */ (function () {
1537
- function UploadcareGroup(groupInfo, files) {
1538
- this.storedAt = null;
1539
- this.uuid = groupInfo.id;
1540
- this.filesCount = groupInfo.filesCount;
1541
- this.totalSize = Object.values(groupInfo.files).reduce(function (acc, file) { return acc + file.size; }, 0);
1542
- this.isStored = !!groupInfo.datetimeStored;
1543
- this.isImage = !!Object.values(groupInfo.files).filter(function (file) { return file.isImage; }).length;
1544
- this.cdnUrl = groupInfo.cdnUrl;
1545
- this.files = files;
1546
- this.createdAt = groupInfo.datetimeCreated;
1547
- this.storedAt = groupInfo.datetimeStored;
1548
- }
1549
- return UploadcareGroup;
1550
- }());
1551
-
1552
- /**
1553
- * FileData type guard.
1554
- */
1555
- var isFileDataArray = function (data) {
1556
- for (var _i = 0, data_1 = data; _i < data_1.length; _i++) {
1557
- var item = data_1[_i];
1558
- if (!isFileData(item)) {
1559
- return false;
1560
- }
1561
- }
1562
- return true;
1563
- };
1564
- /**
1565
- * Uuid type guard.
1566
- */
1567
- var isUuidArray = function (data) {
1568
- for (var _i = 0, data_2 = data; _i < data_2.length; _i++) {
1569
- var item = data_2[_i];
1570
- if (!isUuid(item)) {
1571
- return false;
1572
- }
1573
- }
1574
- return true;
1575
- };
1576
- /**
1577
- * Url type guard.
1578
- */
1579
- var isUrlArray = function (data) {
1580
- for (var _i = 0, data_3 = data; _i < data_3.length; _i++) {
1581
- var item = data_3[_i];
1582
- if (!isUrl(item)) {
1583
- return false;
1584
- }
1585
- }
1586
- return true;
1587
- };
1588
-
1589
- function uploadFileGroup(data, _a) {
1590
- var publicKey = _a.publicKey, fileName = _a.fileName, _b = _a.baseURL, baseURL = _b === void 0 ? defaultSettings.baseURL : _b, secureSignature = _a.secureSignature, secureExpire = _a.secureExpire, store = _a.store, signal = _a.signal, onProgress = _a.onProgress, source = _a.source, integration = _a.integration, userAgent = _a.userAgent, retryThrottledRequestMaxTimes = _a.retryThrottledRequestMaxTimes, contentType = _a.contentType, _c = _a.multipartChunkSize, multipartChunkSize = _c === void 0 ? defaultSettings.multipartChunkSize : _c, _d = _a.baseCDN, baseCDN = _d === void 0 ? defaultSettings.baseCDN : _d, jsonpCallback = _a.jsonpCallback, defaultEffects = _a.defaultEffects;
1591
- if (!isFileDataArray(data) && !isUrlArray(data) && !isUuidArray(data)) {
1592
- throw new TypeError("Group uploading from \"" + data + "\" is not supported");
1593
- }
1594
- var progressValues;
1595
- var isStillComputable = true;
1596
- var filesCount = data.length;
1597
- var createProgressHandler = function (size, index) {
1598
- if (!onProgress)
1599
- return;
1600
- if (!progressValues) {
1601
- progressValues = Array(size).fill(0);
1602
- }
1603
- var normalize = function (values) {
1604
- return values.reduce(function (sum, next) { return sum + next; }) / size;
1605
- };
1606
- return function (info) {
1607
- if (!info.isComputable || !isStillComputable) {
1608
- isStillComputable = false;
1609
- onProgress({ isComputable: false });
1610
- return;
1611
- }
1612
- progressValues[index] = info.value;
1613
- onProgress({ isComputable: true, value: normalize(progressValues) });
1614
- };
1615
- };
1616
- return Promise.all(data.map(function (file, index) {
1617
- return uploadFile(file, {
1618
- publicKey: publicKey,
1619
- fileName: fileName,
1620
- baseURL: baseURL,
1621
- secureSignature: secureSignature,
1622
- secureExpire: secureExpire,
1623
- store: store,
1624
- signal: signal,
1625
- onProgress: createProgressHandler(filesCount, index),
1626
- source: source,
1627
- integration: integration,
1628
- userAgent: userAgent,
1629
- retryThrottledRequestMaxTimes: retryThrottledRequestMaxTimes,
1630
- contentType: contentType,
1631
- multipartChunkSize: multipartChunkSize,
1632
- baseCDN: baseCDN
1633
- });
1634
- })).then(function (files) {
1635
- var uuids = files.map(function (file) { return file.uuid; });
1636
- var addDefaultEffects = function (file) {
1637
- var cdnUrlModifiers = defaultEffects ? "-/" + defaultEffects : null;
1638
- var cdnUrl = "" + file.urlBase + (cdnUrlModifiers || '');
1639
- return __assign(__assign({}, file), { cdnUrlModifiers: cdnUrlModifiers,
1640
- cdnUrl: cdnUrl });
1641
- };
1642
- var filesInGroup = defaultEffects ? files.map(addDefaultEffects) : files;
1643
- return group(uuids, {
1644
- publicKey: publicKey,
1645
- baseURL: baseURL,
1646
- jsonpCallback: jsonpCallback,
1647
- secureSignature: secureSignature,
1648
- secureExpire: secureExpire,
1649
- signal: signal,
1650
- source: source,
1651
- integration: integration,
1652
- userAgent: userAgent,
1653
- retryThrottledRequestMaxTimes: retryThrottledRequestMaxTimes
1654
- })
1655
- .then(function (groupInfo) { return new UploadcareGroup(groupInfo, filesInGroup); })
1656
- .then(function (group) {
1657
- onProgress && onProgress({ isComputable: true, value: 1 });
1658
- return group;
1659
- });
1660
- });
1661
- }
1662
-
1663
- /**
1664
- * Populate options with settings.
1665
- */
1666
- var populateOptionsWithSettings = function (options, settings) { return (__assign(__assign({}, settings), options)); };
1667
- var UploadClient = /** @class */ (function () {
1668
- function UploadClient(settings) {
1669
- this.settings = Object.assign({}, defaultSettings, settings);
1670
- }
1671
- UploadClient.prototype.updateSettings = function (newSettings) {
1672
- this.settings = Object.assign(this.settings, newSettings);
1673
- };
1674
- UploadClient.prototype.getSettings = function () {
1675
- return this.settings;
1676
- };
1677
- UploadClient.prototype.base = function (file, options) {
1678
- var settings = this.getSettings();
1679
- return base(file, populateOptionsWithSettings(options, settings));
1680
- };
1681
- UploadClient.prototype.info = function (uuid, options) {
1682
- var settings = this.getSettings();
1683
- return info(uuid, populateOptionsWithSettings(options, settings));
1684
- };
1685
- UploadClient.prototype.fromUrl = function (sourceUrl, options) {
1686
- var settings = this.getSettings();
1687
- return fromUrl(sourceUrl, populateOptionsWithSettings(options, settings));
1688
- };
1689
- UploadClient.prototype.fromUrlStatus = function (token, options) {
1690
- var settings = this.getSettings();
1691
- return fromUrlStatus(token, populateOptionsWithSettings(options, settings));
1692
- };
1693
- UploadClient.prototype.group = function (uuids, options) {
1694
- var settings = this.getSettings();
1695
- return group(uuids, populateOptionsWithSettings(options, settings));
1696
- };
1697
- UploadClient.prototype.groupInfo = function (id, options) {
1698
- var settings = this.getSettings();
1699
- return groupInfo(id, populateOptionsWithSettings(options, settings));
1700
- };
1701
- UploadClient.prototype.multipartStart = function (size, options) {
1702
- var settings = this.getSettings();
1703
- return multipartStart(size, populateOptionsWithSettings(options, settings));
1704
- };
1705
- UploadClient.prototype.multipartUpload = function (part, url, options) {
1706
- var settings = this.getSettings();
1707
- return multipartUpload(part, url, populateOptionsWithSettings(options, settings));
1708
- };
1709
- UploadClient.prototype.multipartComplete = function (uuid, options) {
1710
- var settings = this.getSettings();
1711
- return multipartComplete(uuid, populateOptionsWithSettings(options, settings));
1712
- };
1713
- UploadClient.prototype.uploadFile = function (data, options) {
1714
- var settings = this.getSettings();
1715
- return uploadFile(data, populateOptionsWithSettings(options, settings));
1716
- };
1717
- UploadClient.prototype.uploadFileGroup = function (data, options) {
1718
- var settings = this.getSettings();
1719
- return uploadFileGroup(data, populateOptionsWithSettings(options, settings));
1720
- };
1721
- return UploadClient;
1722
- }());
1723
-
1724
- exports.AbortController = AbortController;
1725
- exports.UploadClient = UploadClient;
1726
- exports.UploadClientError = UploadClientError;
1727
- exports.UploadcareFile = UploadcareFile;
1728
- exports.UploadcareGroup = UploadcareGroup;
1729
- exports.base = base;
1730
- exports.fromUrl = fromUrl;
1731
- exports.fromUrlStatus = fromUrlStatus;
1732
- exports.group = group;
1733
- exports.groupInfo = groupInfo;
1734
- exports.info = info;
1735
- exports.multipartComplete = multipartComplete;
1736
- exports.multipartStart = multipartStart;
1737
- exports.multipartUpload = multipartUpload;
1738
- exports.uploadBase = uploadFromObject;
1739
- exports.uploadFile = uploadFile;
1740
- exports.uploadFileGroup = uploadFileGroup;
1741
- exports.uploadFromUploaded = uploadFromUploaded;
1742
- exports.uploadFromUrl = uploadFromUrl;
1743
- exports.uploadMultipart = uploadMultipart;