@bytescale/sdk 1.1.0 → 1.2.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 (31) hide show
  1. package/dist/browser/cjs/main.js +379 -1033
  2. package/dist/node/cjs/main.js +810 -825
  3. package/dist/node/esm/main.mjs +816 -805
  4. package/dist/types/generated/runtime.d.ts +0 -15
  5. package/dist/types/index.browser.d.ts +3 -0
  6. package/dist/types/index.node.d.ts +3 -0
  7. package/dist/types/uploads/{ChunkedStream.d.ts → private/NodeChunkedStream.d.ts} +11 -4
  8. package/dist/types/uploads/private/StreamUtils.d.ts +8 -0
  9. package/dist/types/uploads/private/TypeUtils.d.ts +1 -0
  10. package/dist/types/uploads/private/UploadManagerBase.d.ts +43 -0
  11. package/dist/types/uploads/private/model/AddCancellationHandler.d.ts +1 -0
  12. package/dist/types/uploads/private/model/OnPartProgress.d.ts +1 -0
  13. package/dist/types/uploads/private/model/PreUploadInfo.d.ts +6 -0
  14. package/dist/types/uploads/private/model/PutUploadPartResult.d.ts +4 -0
  15. package/dist/types/uploads/private/model/UploadManagerInterface.d.ts +5 -0
  16. package/dist/types/uploads/private/model/UploadSourceProcessed.d.ts +18 -0
  17. package/dist/types/uploads/public/browser/UploadManagerBrowser.d.ts +17 -0
  18. package/dist/types/uploads/public/browser/index.d.ts +1 -0
  19. package/dist/types/uploads/public/node/UploadManagerNode.d.ts +26 -0
  20. package/dist/types/uploads/public/node/index.d.ts +1 -0
  21. package/dist/types/uploads/{UploadModel.d.ts → public/shared/Model.d.ts} +8 -5
  22. package/dist/types/uploads/public/shared/index.d.ts +1 -0
  23. package/package.json +1 -1
  24. package/tests/ChunkedStream.test.ts +3 -3
  25. package/tests/UploadManager.test.ts +1 -1
  26. package/dist/browser/cjs/_70b2.main.js +0 -10
  27. package/dist/browser/cjs/_7392.main.js +0 -10
  28. package/dist/types/index.d.ts +0 -2
  29. package/dist/types/uploads/NodeUtils.d.ts +0 -13
  30. package/dist/types/uploads/UploadManager.d.ts +0 -39
  31. package/dist/types/uploads/index.d.ts +0 -3
@@ -20,53 +20,10 @@
20
20
  // }
21
21
  // ----------------------------------------
22
22
  //
23
- import * as __WEBPACK_EXTERNAL_MODULE_buffer__ from "buffer";
24
23
  import * as __WEBPACK_EXTERNAL_MODULE_stream__ from "stream";
25
- /******/ var __lib_libs__ = ({
26
-
27
- /***/ "buffer":
28
- /***/ (function(lib) {
29
-
30
- var x = y => { var x = {}; __lib_require__.d(x, y); return x; }
31
- var y = x => () => x
32
- lib.exports = __WEBPACK_EXTERNAL_MODULE_buffer__;
33
-
34
- /***/ }),
35
-
36
- /***/ "stream":
37
- /***/ (function(lib) {
38
-
39
- var x = y => { var x = {}; __lib_require__.d(x, y); return x; }
40
- var y = x => () => x
41
- lib.exports = __WEBPACK_EXTERNAL_MODULE_stream__;
42
-
43
- /***/ })
44
-
45
- /******/ });
46
- /************************************************************************/
47
- /******/ // The lib cache
48
- /******/ var __lib_lib_cache__ = {};
49
- /******/
50
- /******/ // The require function
51
- /******/ function __lib_require__(libId) {
52
- /******/ // Check if lib is in cache
53
- /******/ var cachedModule = __lib_lib_cache__[libId];
54
- /******/ if (cachedModule !== undefined) {
55
- /******/ return cachedModule.exports;
56
- /******/ }
57
- /******/ // Create a new lib (and put it into the cache)
58
- /******/ var lib = __lib_lib_cache__[libId] = {
59
- /******/ // no lib.id needed
60
- /******/ // no lib.loaded needed
61
- /******/ exports: {}
62
- /******/ };
63
- /******/
64
- /******/ // Execute the lib function
65
- /******/ __lib_libs__[libId](lib, lib.exports, __lib_require__);
66
- /******/
67
- /******/ // Return the exports of the lib
68
- /******/ return lib.exports;
69
- /******/ }
24
+ import * as __WEBPACK_EXTERNAL_MODULE_buffer__ from "buffer";
25
+ /******/ // The require scope
26
+ /******/ var __lib_require__ = {};
70
27
  /******/
71
28
  /************************************************************************/
72
29
  /******/ /* webpack/runtime/define property getters */
@@ -88,8 +45,6 @@ lib.exports = __WEBPACK_EXTERNAL_MODULE_stream__;
88
45
  /******/
89
46
  /************************************************************************/
90
47
  var __lib_exports__ = {};
91
- // This entry need to be wrapped in an IIFE because it need to be isolated against other libs in the chunk.
92
- !function() {
93
48
 
94
49
  // EXPORTS
95
50
  __lib_require__.d(__lib_exports__, {
@@ -98,14 +53,10 @@ __lib_require__.d(__lib_exports__, {
98
53
  "BinaryResult": function() { return /* reexport */ BinaryResult; },
99
54
  "BytescaleApiError": function() { return /* reexport */ BytescaleApiError; },
100
55
  "CancelledError": function() { return /* reexport */ CancelledError; },
101
- "ChunkedStream": function() { return /* reexport */ ChunkedStream; },
102
- "FetchError": function() { return /* reexport */ FetchError; },
103
56
  "FileApi": function() { return /* reexport */ FileApi; },
104
57
  "FolderApi": function() { return /* reexport */ FolderApi; },
105
58
  "JSONApiResponse": function() { return /* reexport */ JSONApiResponse; },
106
59
  "JobApi": function() { return /* reexport */ JobApi; },
107
- "RequiredError": function() { return /* reexport */ RequiredError; },
108
- "ResponseError": function() { return /* reexport */ ResponseError; },
109
60
  "UploadApi": function() { return /* reexport */ UploadApi; },
110
61
  "UploadManager": function() { return /* reexport */ UploadManager; },
111
62
  "VoidApiResponse": function() { return /* reexport */ VoidApiResponse; },
@@ -205,11 +156,7 @@ var BaseAPI = /*#__PURE__*/function () {
205
156
  });
206
157
  }, function (e) {
207
158
  if (response === undefined) {
208
- if (e instanceof Error) {
209
- throw new FetchError(e, "The request failed and the interceptors did not return an alternative response");
210
- } else {
211
- throw e;
212
- }
159
+ throw e;
213
160
  }
214
161
  }), function (_result) {
215
162
  return _exit ? _result : response;
@@ -244,7 +191,7 @@ var BaseAPI = /*#__PURE__*/function () {
244
191
  }
245
192
  }, function (_result2) {
246
193
  if (_exit2) return _result2;
247
- throw new ResponseError(response, "Response returned an error code");
194
+ throw new Error("Unable to connect to the Bytescale API: please try again.");
248
195
  });
249
196
  });
250
197
  });
@@ -299,7 +246,7 @@ var BaseAPI = /*#__PURE__*/function () {
299
246
  }), function (_initOverrideFn) {
300
247
  var overriddenInit = Object.assign(_Object$assign2, _initOverrideFn);
301
248
  var init = Object.assign(Object.assign({}, overriddenInit), {
302
- body: isFormData(overriddenInit.body) || overriddenInit.body instanceof URLSearchParams || isBlob(overriddenInit.body) ? overriddenInit.body : JSON.stringify(overriddenInit.body)
249
+ body: JSON.stringify(overriddenInit.body)
303
250
  });
304
251
  return {
305
252
  url: url,
@@ -314,12 +261,6 @@ var BaseAPI = /*#__PURE__*/function () {
314
261
  }]);
315
262
  return BaseAPI;
316
263
  }();
317
- function isBlob(value) {
318
- return typeof Blob !== "undefined" && value instanceof Blob;
319
- }
320
- function isFormData(value) {
321
- return typeof FormData !== "undefined" && value instanceof FormData;
322
- }
323
264
  var BytescaleApiError = /*#__PURE__*/function (_Error) {
324
265
  _inherits(BytescaleApiError, _Error);
325
266
  var _super = _createSuper(BytescaleApiError);
@@ -334,45 +275,6 @@ var BytescaleApiError = /*#__PURE__*/function (_Error) {
334
275
  }
335
276
  return _createClass(BytescaleApiError);
336
277
  }( /*#__PURE__*/_wrapNativeSuper(Error));
337
- var ResponseError = /*#__PURE__*/function (_Error2) {
338
- _inherits(ResponseError, _Error2);
339
- var _super2 = _createSuper(ResponseError);
340
- function ResponseError(response, msg) {
341
- var _this7;
342
- _classCallCheck(this, ResponseError);
343
- _this7 = _super2.call(this, msg);
344
- _this7.response = response;
345
- _this7.name = "ResponseError";
346
- return _this7;
347
- }
348
- return _createClass(ResponseError);
349
- }( /*#__PURE__*/_wrapNativeSuper(Error));
350
- var FetchError = /*#__PURE__*/function (_Error3) {
351
- _inherits(FetchError, _Error3);
352
- var _super3 = _createSuper(FetchError);
353
- function FetchError(cause, msg) {
354
- var _this8;
355
- _classCallCheck(this, FetchError);
356
- _this8 = _super3.call(this, msg);
357
- _this8.cause = cause;
358
- _this8.name = "FetchError";
359
- return _this8;
360
- }
361
- return _createClass(FetchError);
362
- }( /*#__PURE__*/_wrapNativeSuper(Error));
363
- var RequiredError = /*#__PURE__*/function (_Error4) {
364
- _inherits(RequiredError, _Error4);
365
- var _super4 = _createSuper(RequiredError);
366
- function RequiredError(field, msg) {
367
- var _this9;
368
- _classCallCheck(this, RequiredError);
369
- _this9 = _super4.call(this, msg);
370
- _this9.field = field;
371
- _this9.name = "RequiredError";
372
- return _this9;
373
- }
374
- return _createClass(RequiredError);
375
- }( /*#__PURE__*/_wrapNativeSuper(Error));
376
278
  function querystring(params) {
377
279
  var prefix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "";
378
280
  return Object.keys(params).map(function (key) {
@@ -415,10 +317,10 @@ var JSONApiResponse = /*#__PURE__*/function () {
415
317
  key: "value",
416
318
  value: function value() {
417
319
  try {
418
- var _this11 = this;
419
- var _transformer2 = _this11.transformer;
420
- return _await(_this11.raw.json(), function (_this10$raw$json) {
421
- return _transformer2.call(_this11, _this10$raw$json);
320
+ var _this8 = this;
321
+ var _transformer2 = _this8.transformer;
322
+ return _await(_this8.raw.json(), function (_this7$raw$json) {
323
+ return _transformer2.call(_this8, _this7$raw$json);
422
324
  });
423
325
  } catch (e) {
424
326
  return Promise.reject(e);
@@ -460,8 +362,8 @@ var BinaryResult = /*#__PURE__*/function () {
460
362
  key: "text",
461
363
  value: function text() {
462
364
  try {
463
- var _this13 = this;
464
- return _await(_this13.raw.text());
365
+ var _this10 = this;
366
+ return _await(_this10.raw.text());
465
367
  } catch (e) {
466
368
  return Promise.reject(e);
467
369
  }
@@ -470,8 +372,8 @@ var BinaryResult = /*#__PURE__*/function () {
470
372
  key: "blob",
471
373
  value: function blob() {
472
374
  try {
473
- var _this15 = this;
474
- return _await(_this15.raw.blob());
375
+ var _this12 = this;
376
+ return _await(_this12.raw.blob());
475
377
  } catch (e) {
476
378
  return Promise.reject(e);
477
379
  }
@@ -480,8 +382,8 @@ var BinaryResult = /*#__PURE__*/function () {
480
382
  key: "json",
481
383
  value: function json() {
482
384
  try {
483
- var _this17 = this;
484
- return _await(_this17.raw.json());
385
+ var _this14 = this;
386
+ return _await(_this14.raw.json());
485
387
  } catch (e) {
486
388
  return Promise.reject(e);
487
389
  }
@@ -1380,312 +1282,40 @@ var UploadApi = /*#__PURE__*/function (_runtime$BaseAPI) {
1380
1282
 
1381
1283
 
1382
1284
 
1383
- ;// CONCATENATED MODULE: ./src/uploads/NodeUtils.ts
1384
- function NodeUtils_typeof(obj) { "@babel/helpers - typeof"; return NodeUtils_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, NodeUtils_typeof(obj); }
1385
- function NodeUtils_await(value, then, direct) {
1386
- if (direct) {
1387
- return then ? then(value) : value;
1388
- }
1389
- if (!value || !value.then) {
1390
- value = Promise.resolve(value);
1391
- }
1392
- return then ? value.then(then) : value;
1393
- }
1394
- function NodeUtils_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
1395
- function NodeUtils_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, NodeUtils_toPropertyKey(descriptor.key), descriptor); } }
1396
- function NodeUtils_createClass(Constructor, protoProps, staticProps) { if (protoProps) NodeUtils_defineProperties(Constructor.prototype, protoProps); if (staticProps) NodeUtils_defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
1397
- function NodeUtils_toPropertyKey(arg) { var key = NodeUtils_toPrimitive(arg, "string"); return NodeUtils_typeof(key) === "symbol" ? key : String(key); }
1398
- function NodeUtils_toPrimitive(input, hint) { if (NodeUtils_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (NodeUtils_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
1399
- /**
1400
- * Provides access to Node.js built-in libraries. Should only be called when we're certain we're running in Node.js.
1401
- *
1402
- * We import lazily to support browsers, which don't have these libs, but also won't call these methods so won't trigger the imports.
1403
- */
1404
- var NodeUtils = /*#__PURE__*/function () {
1405
- function NodeUtils() {
1406
- NodeUtils_classCallCheck(this, NodeUtils);
1407
- }
1408
- NodeUtils_createClass(NodeUtils, null, [{
1409
- key: "createStream",
1410
- value: function createStream() {
1411
- try {
1412
- return NodeUtils_await(Promise.resolve(/* import() */).then(__lib_require__.bind(__lib_require__, "stream")), function (_import) {
1413
- var streamModule = _import["default"];
1414
- var Readable = streamModule.Readable;
1415
- var readable = new Readable();
1416
- readable._read = function () {}; // _read is required but you can noop it
1417
- return readable;
1418
- });
1419
- } catch (e) {
1420
- return Promise.reject(e);
1421
- }
1422
- }
1423
- }, {
1424
- key: "createBlob",
1425
- value: function createBlob(sources, options) {
1426
- try {
1427
- return NodeUtils_await(Promise.resolve(/* import() */).then(__lib_require__.bind(__lib_require__, "buffer")), function (_import2) {
1428
- var bufferModule = _import2["default"];
1429
- var B = bufferModule.Blob;
1430
- return new B(sources, options);
1431
- });
1432
- } catch (e) {
1433
- return Promise.reject(e);
1434
- }
1435
- }
1436
- }]);
1437
- return NodeUtils;
1438
- }();
1439
- ;// CONCATENATED MODULE: ./src/uploads/ChunkedStream.ts
1440
- function ChunkedStream_typeof(obj) { "@babel/helpers - typeof"; return ChunkedStream_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, ChunkedStream_typeof(obj); }
1441
- function ChunkedStream_invoke(body, then) {
1442
- var result = body();
1443
- if (result && result.then) {
1444
- return result.then(then);
1445
- }
1446
- return then(result);
1447
- }
1448
- function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
1449
- function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
1450
- function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
1451
- function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
1452
- function _iterableToArrayLimit(arr, i) { var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; if (null != _i) { var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1; try { if (_x = (_i = _i.call(arr)).next, 0 === i) { if (Object(_i) !== _i) return; _n = !1; } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0) { ; } } catch (err) { _d = !0, _e = err; } finally { try { if (!_n && null != _i["return"] && (_r = _i["return"](), Object(_r) !== _r)) return; } finally { if (_d) throw _e; } } return _arr; } }
1453
- function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
1454
- function ChunkedStream_await(value, then, direct) {
1455
- if (direct) {
1456
- return then ? then(value) : value;
1457
- }
1458
- if (!value || !value.then) {
1459
- value = Promise.resolve(value);
1460
- }
1461
- return then ? value.then(then) : value;
1462
- }
1463
- function ChunkedStream_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
1464
- function ChunkedStream_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, ChunkedStream_toPropertyKey(descriptor.key), descriptor); } }
1465
- function ChunkedStream_createClass(Constructor, protoProps, staticProps) { if (protoProps) ChunkedStream_defineProperties(Constructor.prototype, protoProps); if (staticProps) ChunkedStream_defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
1466
- function ChunkedStream_toPropertyKey(arg) { var key = ChunkedStream_toPrimitive(arg, "string"); return ChunkedStream_typeof(key) === "symbol" ? key : String(key); }
1467
- function ChunkedStream_toPrimitive(input, hint) { if (ChunkedStream_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (ChunkedStream_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
1468
-
1469
- var ChunkedStream = /*#__PURE__*/function () {
1470
- function ChunkedStream(source) {
1471
- ChunkedStream_classCallCheck(this, ChunkedStream);
1472
- this.source = source;
1473
- this.buffer = Buffer.alloc(0);
1474
- this.isSourceFullyConsumed = false; // true if the source stream indicates it has finished.
1475
- this.isFinishedConsuming = false; // true if _we_ indicate we have finished reading all we want from the stream.
1476
- this.resolver = undefined;
1477
- }
1478
- /**
1479
- * If the source stream is larger than the 'size' the user is consuming (i.e. they're only wanting to upload a subset
1480
- * of the stream) then the stream won't be resolved by the 'end' event inside 'runChunkPipeline', so calling this
1481
- * method is necessary.
1482
- */
1483
- ChunkedStream_createClass(ChunkedStream, [{
1484
- key: "finishedConsuming",
1485
- value: function finishedConsuming() {
1486
- this.isFinishedConsuming = true;
1487
- if (this.resolver !== undefined) {
1488
- this.resolver();
1489
- }
1490
- }
1491
- /**
1492
- * Promise resolves when the entire stream has finished processing, or an error occurs.
1493
- * You must call 'take' a sufficient number of times after calling this method in order for this promise to resolve.
1494
- */
1495
- }, {
1496
- key: "runChunkPipeline",
1497
- value: function runChunkPipeline() {
1498
- try {
1499
- var _this2 = this;
1500
- return ChunkedStream_await(new Promise(function (resolve, reject) {
1501
- _this2.resolver = resolve;
1502
- var onError = function onError(error) {
1503
- removeListeners();
1504
- reject(error);
1505
- };
1506
- var onEnd = function onEnd() {
1507
- _this2.isSourceFullyConsumed = true;
1508
- removeListeners();
1509
- resolve();
1510
- };
1511
- var onData = function onData(buffer) {
1512
- try {
1513
- if (_this2.isFinishedConsuming) {
1514
- return;
1515
- }
1516
- if (_this2.consumer === undefined) {
1517
- console.warn("Stream yielded data while paused. The data will be buffered, but excessive buffering can cause memory issues.");
1518
- _this2.buffer = Buffer.concat([_this2.buffer, buffer]);
1519
- return;
1520
- }
1521
- if (_this2.consumer.bytesRemaining <= 0) {
1522
- throw new Error("Consumer requires zero bytes, so should not be consuming from the stream.");
1523
- }
1524
- if (_this2.buffer.byteLength > 0) {
1525
- throw new Error("Buffer was expected to be empty (as it should have been flushed to the consumer when '.take' was called).");
1526
- }
1527
- var splitResult = _this2.splitBuffer(buffer, _this2.consumer.bytesRemaining);
1528
- if (splitResult === undefined) {
1529
- return; // Received empty data.
1530
- }
1531
-
1532
- var _splitResult = _slicedToArray(splitResult, 2),
1533
- consumed = _splitResult[0],
1534
- remaining = _splitResult[1];
1535
- _this2.buffer = remaining;
1536
- _this2.consumer.bytesRemaining -= consumed.byteLength;
1537
- _this2.consumer.stream.push(consumed);
1538
- if (_this2.consumer.bytesRemaining === 0) {
1539
- _this2.finishStream(_this2.consumer.stream);
1540
- _this2.consumer = undefined;
1541
- _this2.source.pause();
1542
- }
1543
- } catch (e) {
1544
- removeListeners();
1545
- reject(e);
1546
- }
1547
- };
1548
- var removeListeners = function removeListeners() {
1549
- _this2.source.removeListener("data", onData);
1550
- _this2.source.removeListener("error", onError);
1551
- _this2.source.removeListener("end", onEnd);
1552
- };
1553
- _this2.source.on("data", onData);
1554
- _this2.source.on("error", onError);
1555
- _this2.source.on("end", onEnd);
1556
- _this2.source.pause(); // Resumed when 'take' is called.
1557
- }));
1558
- } catch (e) {
1559
- return Promise.reject(e);
1560
- }
1561
- }
1562
- /**
1563
- * Only call 'take' after the previously returned stream has been fully consumed.
1564
- */
1565
- }, {
1566
- key: "take",
1567
- value: function take(bytes) {
1568
- try {
1569
- var _exit2 = false;
1570
- var _this4 = this;
1571
- var _a;
1572
- if (_this4.consumer !== undefined) {
1573
- throw new Error("The stream from the previous 'take' call must be fully consumed before calling 'take' again.");
1574
- }
1575
- return ChunkedStream_invoke(function () {
1576
- if (bytes <= 0) {
1577
- _exit2 = true;
1578
- return ChunkedStream_await(_this4.emptyStream());
1579
- }
1580
- }, function (_result) {
1581
- return _exit2 ? _result : ChunkedStream_await(NodeUtils.createStream(), function (readable) {
1582
- var consumedFromBuffer = _this4.consumeFromBuffer(bytes);
1583
- var consumedFromBufferLength = (_a = consumedFromBuffer === null || consumedFromBuffer === void 0 ? void 0 : consumedFromBuffer.length) !== null && _a !== void 0 ? _a : 0;
1584
- var bytesToConsumeFromStream = bytes - consumedFromBufferLength;
1585
- if (consumedFromBuffer !== undefined) {
1586
- readable.push(consumedFromBuffer);
1587
- }
1588
- if (bytesToConsumeFromStream > 0) {
1589
- if (_this4.isSourceFullyConsumed) {
1590
- throw new Error("Stream finished processing earlier than expected. The \"size\" parameter is likely larger than the stream's actual contents.");
1591
- }
1592
- _this4.consumer = {
1593
- bytesRemaining: bytesToConsumeFromStream,
1594
- stream: readable
1595
- };
1596
- _this4.source.resume();
1597
- } else {
1598
- _this4.finishStream(readable);
1599
- }
1600
- return readable;
1601
- });
1602
- });
1603
- } catch (e) {
1604
- return Promise.reject(e);
1605
- }
1606
- }
1607
- }, {
1608
- key: "consumeFromBuffer",
1609
- value: function consumeFromBuffer(bytes) {
1610
- var splitResult = this.splitBuffer(this.buffer, bytes);
1611
- if (splitResult === undefined) {
1612
- return undefined;
1613
- }
1614
- var _splitResult2 = _slicedToArray(splitResult, 2),
1615
- consumed = _splitResult2[0],
1616
- remaining = _splitResult2[1];
1617
- this.buffer = remaining;
1618
- return consumed;
1619
- }
1620
- }, {
1621
- key: "splitBuffer",
1622
- value: function splitBuffer(buffer, maxBytes) {
1623
- if (buffer.byteLength === 0) {
1624
- return undefined;
1625
- }
1626
- var bytesToConsume = Math.min(maxBytes, buffer.byteLength);
1627
- if (bytesToConsume === buffer.byteLength) {
1628
- return [buffer, Buffer.alloc(0)]; // Optimization
1629
- }
1630
-
1631
- var consumed = buffer.subarray(0, bytesToConsume);
1632
- var remaining = buffer.subarray(bytesToConsume);
1633
- return [consumed, remaining];
1634
- }
1635
- }, {
1636
- key: "emptyStream",
1637
- value: function emptyStream() {
1638
- try {
1639
- var _this6 = this;
1640
- return ChunkedStream_await(NodeUtils.createStream(), function (readable) {
1641
- _this6.finishStream(readable);
1642
- return readable;
1643
- });
1644
- } catch (e) {
1645
- return Promise.reject(e);
1646
- }
1647
- }
1648
- }, {
1649
- key: "finishStream",
1650
- value: function finishStream(readable) {
1651
- readable.push(null);
1652
- }
1653
- }]);
1654
- return ChunkedStream;
1655
- }();
1656
- ;// CONCATENATED MODULE: ./src/uploads/UploadModel.ts
1657
- function UploadModel_typeof(obj) { "@babel/helpers - typeof"; return UploadModel_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, UploadModel_typeof(obj); }
1658
- function UploadModel_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, UploadModel_toPropertyKey(descriptor.key), descriptor); } }
1659
- function UploadModel_createClass(Constructor, protoProps, staticProps) { if (protoProps) UploadModel_defineProperties(Constructor.prototype, protoProps); if (staticProps) UploadModel_defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
1660
- function UploadModel_toPropertyKey(arg) { var key = UploadModel_toPrimitive(arg, "string"); return UploadModel_typeof(key) === "symbol" ? key : String(key); }
1661
- function UploadModel_toPrimitive(input, hint) { if (UploadModel_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (UploadModel_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
1662
- function UploadModel_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
1663
- function UploadModel_inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) UploadModel_setPrototypeOf(subClass, superClass); }
1664
- function UploadModel_createSuper(Derived) { var hasNativeReflectConstruct = UploadModel_isNativeReflectConstruct(); return function _createSuperInternal() { var Super = UploadModel_getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = UploadModel_getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return UploadModel_possibleConstructorReturn(this, result); }; }
1665
- function UploadModel_possibleConstructorReturn(self, call) { if (call && (UploadModel_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return UploadModel_assertThisInitialized(self); }
1666
- function UploadModel_assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
1667
- function UploadModel_wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; UploadModel_wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !UploadModel_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return UploadModel_construct(Class, arguments, UploadModel_getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return UploadModel_setPrototypeOf(Wrapper, Class); }; return UploadModel_wrapNativeSuper(Class); }
1668
- function UploadModel_construct(Parent, args, Class) { if (UploadModel_isNativeReflectConstruct()) { UploadModel_construct = Reflect.construct.bind(); } else { UploadModel_construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) UploadModel_setPrototypeOf(instance, Class.prototype); return instance; }; } return UploadModel_construct.apply(null, arguments); }
1669
- function UploadModel_isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
1670
- function UploadModel_isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; }
1671
- function UploadModel_setPrototypeOf(o, p) { UploadModel_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return UploadModel_setPrototypeOf(o, p); }
1672
- function UploadModel_getPrototypeOf(o) { UploadModel_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return UploadModel_getPrototypeOf(o); }
1285
+ ;// CONCATENATED MODULE: ./src/uploads/public/shared/Model.ts
1286
+ function Model_typeof(obj) { "@babel/helpers - typeof"; return Model_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, Model_typeof(obj); }
1287
+ function Model_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, Model_toPropertyKey(descriptor.key), descriptor); } }
1288
+ function Model_createClass(Constructor, protoProps, staticProps) { if (protoProps) Model_defineProperties(Constructor.prototype, protoProps); if (staticProps) Model_defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
1289
+ function Model_toPropertyKey(arg) { var key = Model_toPrimitive(arg, "string"); return Model_typeof(key) === "symbol" ? key : String(key); }
1290
+ function Model_toPrimitive(input, hint) { if (Model_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (Model_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
1291
+ function Model_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
1292
+ function Model_inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) Model_setPrototypeOf(subClass, superClass); }
1293
+ function Model_createSuper(Derived) { var hasNativeReflectConstruct = Model_isNativeReflectConstruct(); return function _createSuperInternal() { var Super = Model_getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = Model_getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return Model_possibleConstructorReturn(this, result); }; }
1294
+ function Model_possibleConstructorReturn(self, call) { if (call && (Model_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return Model_assertThisInitialized(self); }
1295
+ function Model_assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
1296
+ function Model_wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; Model_wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !Model_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return Model_construct(Class, arguments, Model_getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return Model_setPrototypeOf(Wrapper, Class); }; return Model_wrapNativeSuper(Class); }
1297
+ function Model_construct(Parent, args, Class) { if (Model_isNativeReflectConstruct()) { Model_construct = Reflect.construct.bind(); } else { Model_construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) Model_setPrototypeOf(instance, Class.prototype); return instance; }; } return Model_construct.apply(null, arguments); }
1298
+ function Model_isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
1299
+ function Model_isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; }
1300
+ function Model_setPrototypeOf(o, p) { Model_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return Model_setPrototypeOf(o, p); }
1301
+ function Model_getPrototypeOf(o) { Model_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return Model_getPrototypeOf(o); }
1673
1302
  var CancelledError = /*#__PURE__*/function (_Error) {
1674
- UploadModel_inherits(CancelledError, _Error);
1675
- var _super = UploadModel_createSuper(CancelledError);
1676
- function CancelledError(msg) {
1303
+ Model_inherits(CancelledError, _Error);
1304
+ var _super = Model_createSuper(CancelledError);
1305
+ function CancelledError() {
1677
1306
  var _this;
1678
- UploadModel_classCallCheck(this, CancelledError);
1679
- _this = _super.call(this, msg);
1680
- _this.msg = msg;
1307
+ Model_classCallCheck(this, CancelledError);
1308
+ _this = _super.call(this, "Upload cancelled by user.");
1681
1309
  _this.name = "CancelledError";
1682
1310
  return _this;
1683
1311
  }
1684
- return UploadModel_createClass(CancelledError);
1685
- }( /*#__PURE__*/UploadModel_wrapNativeSuper(Error));
1686
- ;// CONCATENATED MODULE: ./src/uploads/UploadManager.ts
1687
- function UploadManager_typeof(obj) { "@babel/helpers - typeof"; return UploadManager_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, UploadManager_typeof(obj); }
1688
- function UploadManager_async(f) {
1312
+ return Model_createClass(CancelledError);
1313
+ }( /*#__PURE__*/Model_wrapNativeSuper(Error));
1314
+ ;// CONCATENATED MODULE: ./src/uploads/public/shared/index.ts
1315
+
1316
+ ;// CONCATENATED MODULE: ./src/uploads/private/UploadManagerBase.ts
1317
+ function UploadManagerBase_typeof(obj) { "@babel/helpers - typeof"; return UploadManagerBase_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, UploadManagerBase_typeof(obj); }
1318
+ function UploadManagerBase_async(f) {
1689
1319
  return function () {
1690
1320
  for (var args = [], i = 0; i < arguments.length; i++) {
1691
1321
  args[i] = arguments[i];
@@ -1697,23 +1327,10 @@ function UploadManager_async(f) {
1697
1327
  }
1698
1328
  };
1699
1329
  }
1700
- function UploadManager_empty() {}
1701
- function _awaitIgnored(value, direct) {
1702
- if (!direct) {
1703
- return value && value.then ? value.then(UploadManager_empty) : Promise.resolve();
1704
- }
1705
- }
1706
- function UploadManager_invoke(body, then) {
1707
- var result = body();
1708
- if (result && result.then) {
1709
- return result.then(then);
1710
- }
1711
- return then(result);
1712
- }
1713
1330
  function _invokeIgnored(body) {
1714
1331
  var result = body();
1715
1332
  if (result && result.then) {
1716
- return result.then(UploadManager_empty);
1333
+ return result.then(UploadManagerBase_empty);
1717
1334
  }
1718
1335
  }
1719
1336
  function _settle(pact, state, value) {
@@ -1867,16 +1484,22 @@ function _for(test, update, body) {
1867
1484
  }
1868
1485
  function _continueIgnored(value) {
1869
1486
  if (value && value.then) {
1870
- return value.then(UploadManager_empty);
1487
+ return value.then(UploadManagerBase_empty);
1871
1488
  }
1872
1489
  }
1873
- function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || UploadManager_unsupportedIterableToArray(arr) || _nonIterableSpread(); }
1490
+ function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
1874
1491
  function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
1875
- function UploadManager_unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return UploadManager_arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return UploadManager_arrayLikeToArray(o, minLen); }
1492
+ function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
1876
1493
  function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
1877
- function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return UploadManager_arrayLikeToArray(arr); }
1878
- function UploadManager_arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
1879
- function UploadManager_await(value, then, direct) {
1494
+ function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
1495
+ function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
1496
+ function UploadManagerBase_empty() {}
1497
+ function _awaitIgnored(value, direct) {
1498
+ if (!direct) {
1499
+ return value && value.then ? value.then(UploadManagerBase_empty) : Promise.resolve();
1500
+ }
1501
+ }
1502
+ function UploadManagerBase_await(value, then, direct) {
1880
1503
  if (direct) {
1881
1504
  return then ? then(value) : value;
1882
1505
  }
@@ -1885,46 +1508,73 @@ function UploadManager_await(value, then, direct) {
1885
1508
  }
1886
1509
  return then ? value.then(then) : value;
1887
1510
  }
1888
- function UploadManager_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
1889
- function UploadManager_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, UploadManager_toPropertyKey(descriptor.key), descriptor); } }
1890
- function UploadManager_createClass(Constructor, protoProps, staticProps) { if (protoProps) UploadManager_defineProperties(Constructor.prototype, protoProps); if (staticProps) UploadManager_defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
1891
- function UploadManager_toPropertyKey(arg) { var key = UploadManager_toPrimitive(arg, "string"); return UploadManager_typeof(key) === "symbol" ? key : String(key); }
1892
- function UploadManager_toPrimitive(input, hint) { if (UploadManager_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (UploadManager_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
1893
-
1894
-
1511
+ function _rethrow(thrown, value) {
1512
+ if (thrown) throw value;
1513
+ return value;
1514
+ }
1515
+ function _finallyRethrows(body, finalizer) {
1516
+ try {
1517
+ var result = body();
1518
+ } catch (e) {
1519
+ return finalizer(true, e);
1520
+ }
1521
+ if (result && result.then) {
1522
+ return result.then(finalizer.bind(null, false), finalizer.bind(null, true));
1523
+ }
1524
+ return finalizer(false, result);
1525
+ }
1526
+ function UploadManagerBase_continue(value, then) {
1527
+ return value && value.then ? value.then(then) : then(value);
1528
+ }
1529
+ function UploadManagerBase_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
1530
+ function UploadManagerBase_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, UploadManagerBase_toPropertyKey(descriptor.key), descriptor); } }
1531
+ function UploadManagerBase_createClass(Constructor, protoProps, staticProps) { if (protoProps) UploadManagerBase_defineProperties(Constructor.prototype, protoProps); if (staticProps) UploadManagerBase_defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
1532
+ function UploadManagerBase_toPropertyKey(arg) { var key = UploadManagerBase_toPrimitive(arg, "string"); return UploadManagerBase_typeof(key) === "symbol" ? key : String(key); }
1533
+ function UploadManagerBase_toPrimitive(input, hint) { if (UploadManagerBase_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (UploadManagerBase_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
1895
1534
 
1896
1535
 
1897
- var UploadManager = /*#__PURE__*/function () {
1898
- function UploadManager(config) {
1899
- UploadManager_classCallCheck(this, UploadManager);
1536
+ /**
1537
+ * Methods common to UploadManagerNode and UploadManagerBrowser.
1538
+ */
1539
+ var UploadManagerBase = /*#__PURE__*/function () {
1540
+ function UploadManagerBase(config) {
1541
+ UploadManagerBase_classCallCheck(this, UploadManagerBase);
1900
1542
  this.config = config;
1901
1543
  this.stringMimeType = "text/plain";
1902
1544
  this.defaultMaxConcurrentUploadParts = 4;
1545
+ this.intervalMs = 500;
1903
1546
  this.uploadApi = new UploadApi(config);
1904
1547
  }
1905
- UploadManager_createClass(UploadManager, [{
1548
+ UploadManagerBase_createClass(UploadManagerBase, [{
1906
1549
  key: "upload",
1907
1550
  value: function upload(request) {
1908
1551
  try {
1909
1552
  var _this2 = this;
1910
- return UploadManager_await(_this2.processUploadSource(request.data), function (data) {
1911
- var chunkedStream = _this2.getChunkedStream(data);
1912
- return UploadManager_await(_this2.beginUpload(request, data), function (uploadInfo) {
1913
- _this2.checkIfCancelled(request);
1914
- var maxConcurrency = _this2.calculateMaxConcurrency(request, data);
1915
- var partCount = uploadInfo.uploadParts.count;
1916
- var parts = _toConsumableArray(Array(partCount).keys());
1917
- var runSourceStreamPump = chunkedStream === null || chunkedStream === void 0 ? void 0 : chunkedStream.runChunkPipeline();
1918
- return UploadManager_await(_this2.mapAsync(parts, maxConcurrency, UploadManager_async(function (part) {
1919
- return _this2.uploadPart(request, data, part, uploadInfo);
1553
+ _this2.assertNotCancelled(request);
1554
+ var source = _this2.processUploadSource(request.data);
1555
+ var preUploadInfo = _this2.getPreUploadInfo(request, source);
1556
+ var onProgress = _this2.makeProgressCallback(request, preUploadInfo.size);
1557
+ var init = _this2.preUpload(source);
1558
+ // Raise initial progress event SYNCHRONOUSLY.
1559
+ onProgress(0);
1560
+ return UploadManagerBase_await(_this2.beginUpload(request, preUploadInfo), function (uploadInfo) {
1561
+ var partCount = uploadInfo.uploadParts.count;
1562
+ var parts = _toConsumableArray(Array(partCount).keys());
1563
+ var _this2$makeCancellati = _this2.makeCancellationMethods(),
1564
+ cancel = _this2$makeCancellati.cancel,
1565
+ addCancellationHandler = _this2$makeCancellati.addCancellationHandler;
1566
+ var intervalHandle = setInterval(_this2.onIntervalTick(request, cancel), _this2.intervalMs);
1567
+ return UploadManagerBase_continue(_finallyRethrows(function () {
1568
+ return UploadManagerBase_await(_this2.mapAsync(parts, preUploadInfo.maxConcurrentUploadParts, UploadManagerBase_async(function (part) {
1569
+ return _this2.uploadPart(request, source, part, uploadInfo, onProgress, addCancellationHandler);
1920
1570
  })), function () {
1921
- if (chunkedStream !== undefined) {
1922
- chunkedStream.finishedConsuming();
1923
- }
1924
- return UploadManager_await(runSourceStreamPump, function () {
1925
- return uploadInfo.file;
1926
- });
1571
+ return _awaitIgnored(_this2.postUpload(init));
1927
1572
  });
1573
+ }, function (_wasThrown, _result) {
1574
+ clearInterval(intervalHandle);
1575
+ return _rethrow(_wasThrown, _result);
1576
+ }), function () {
1577
+ return uploadInfo.file;
1928
1578
  });
1929
1579
  });
1930
1580
  } catch (e) {
@@ -1932,22 +1582,85 @@ var UploadManager = /*#__PURE__*/function () {
1932
1582
  }
1933
1583
  }
1934
1584
  }, {
1935
- key: "checkIfCancelled",
1936
- value: function checkIfCancelled(request) {
1937
- var _a;
1938
- if (((_a = request.cancellationToken) === null || _a === void 0 ? void 0 : _a.isCancelled) === true) {
1939
- throw new CancelledError("Upload cancelled by user.");
1585
+ key: "getBlobInfo",
1586
+ value: function getBlobInfo(_ref) {
1587
+ var _ref$value = _ref.value,
1588
+ name = _ref$value.name,
1589
+ size = _ref$value.size,
1590
+ type = _ref$value.type;
1591
+ return {
1592
+ mime: type,
1593
+ size: size,
1594
+ originalFileName: name,
1595
+ maxConcurrentUploadParts: undefined
1596
+ };
1597
+ }
1598
+ }, {
1599
+ key: "onIntervalTick",
1600
+ value: function onIntervalTick(request, cancel) {
1601
+ var _this3 = this;
1602
+ return function () {
1603
+ if (_this3.isCancelled(request)) {
1604
+ cancel();
1605
+ }
1606
+ };
1607
+ }
1608
+ }, {
1609
+ key: "makeCancellationMethods",
1610
+ value: function makeCancellationMethods() {
1611
+ var cancellationHandlers = [];
1612
+ var addCancellationHandler = function addCancellationHandler(ca) {
1613
+ cancellationHandlers.push(ca);
1614
+ };
1615
+ var cancel = function cancel() {
1616
+ return cancellationHandlers.forEach(function (x) {
1617
+ return x();
1618
+ });
1619
+ };
1620
+ return {
1621
+ cancel: cancel,
1622
+ addCancellationHandler: addCancellationHandler
1623
+ };
1624
+ }
1625
+ }, {
1626
+ key: "makeProgressCallback",
1627
+ value: function makeProgressCallback(request, bytesTotal) {
1628
+ var onProgress = request.onProgress;
1629
+ if (onProgress === undefined) {
1630
+ return function () {};
1631
+ }
1632
+ var bytesSent = 0;
1633
+ return function (bytesSentDelta) {
1634
+ bytesSent += bytesSentDelta;
1635
+ onProgress({
1636
+ bytesTotal: bytesTotal,
1637
+ bytesSent: bytesSent,
1638
+ progress: Math.round(bytesSent / bytesTotal * 100)
1639
+ });
1640
+ };
1641
+ }
1642
+ }, {
1643
+ key: "assertNotCancelled",
1644
+ value: function assertNotCancelled(request) {
1645
+ if (this.isCancelled(request)) {
1646
+ throw new CancelledError();
1940
1647
  }
1941
1648
  }
1649
+ }, {
1650
+ key: "isCancelled",
1651
+ value: function isCancelled(request) {
1652
+ var _a;
1653
+ return ((_a = request.cancellationToken) === null || _a === void 0 ? void 0 : _a.isCancelled) === true;
1654
+ }
1942
1655
  }, {
1943
1656
  key: "beginUpload",
1944
- value: function beginUpload(request, data) {
1657
+ value: function beginUpload(request, _ref2) {
1658
+ var size = _ref2.size,
1659
+ mime = _ref2.mime,
1660
+ originalFileName = _ref2.originalFileName;
1945
1661
  try {
1946
- var _this4 = this;
1947
- var size = _this4.calculateSize(request, data);
1948
- var mime = _this4.calculateMime(request, data);
1949
- var originalFileName = _this4.calculateOriginalFileName(request, data);
1950
- return UploadManager_await(_this4.uploadApi.beginMultipartUpload({
1662
+ var _this5 = this;
1663
+ return UploadManagerBase_await(_this5.uploadApi.beginMultipartUpload({
1951
1664
  accountId: request.accountId,
1952
1665
  beginMultipartUploadRequest: {
1953
1666
  metadata: request.metadata,
@@ -1965,15 +1678,15 @@ var UploadManager = /*#__PURE__*/function () {
1965
1678
  }
1966
1679
  }, {
1967
1680
  key: "uploadPart",
1968
- value: function uploadPart(request, data, partIndex, uploadInfo) {
1681
+ value: function uploadPart(request, source, partIndex, uploadInfo, onProgress, addCancellationHandler) {
1969
1682
  try {
1970
- var _this6 = this;
1971
- _this6.checkIfCancelled(request);
1972
- return UploadManager_await(_this6.getUploadPart(request, partIndex, uploadInfo), function (part) {
1973
- _this6.checkIfCancelled(request);
1974
- return UploadManager_await(_this6.putUploadPart(part, data), function (etag) {
1975
- _this6.checkIfCancelled(request);
1976
- return _awaitIgnored(_this6.uploadApi.completeUploadPart({
1683
+ var _this7 = this;
1684
+ _this7.assertNotCancelled(request);
1685
+ return UploadManagerBase_await(_this7.getUploadPart(request, partIndex, uploadInfo), function (part) {
1686
+ _this7.assertNotCancelled(request);
1687
+ return UploadManagerBase_await(_this7.putUploadPart(part, source, onProgress, addCancellationHandler), function (etag) {
1688
+ _this7.assertNotCancelled(request);
1689
+ return _awaitIgnored(_this7.uploadApi.completeUploadPart({
1977
1690
  accountId: request.accountId,
1978
1691
  uploadId: uploadInfo.uploadId,
1979
1692
  uploadPartIndex: partIndex,
@@ -1992,422 +1705,720 @@ var UploadManager = /*#__PURE__*/function () {
1992
1705
  */
1993
1706
  }, {
1994
1707
  key: "putUploadPart",
1995
- value: function putUploadPart(part, data) {
1708
+ value: function putUploadPart(part, source, onProgress, addCancellationHandler) {
1996
1709
  try {
1997
- var _this8 = this;
1998
- var _a, _b;
1999
- var fetchApi = (_a = _this8.config.fetchApi) !== null && _a !== void 0 ? _a : fetch;
2000
- var headers = {
2001
- // Required to prevent fetch using "Transfer-Encoding: Chunked" when body is a stream.
2002
- "content-length": (part.range.inclusiveEnd + 1 - part.range.inclusiveStart).toString()
2003
- };
2004
- var _part$uploadUrl2 = part.uploadUrl,
2005
- _coerceRequestBody2 = _this8.coerceRequestBody;
2006
- return UploadManager_await(_this8.makeRequestBody(part, data), function (_this7$makeRequestBod) {
2007
- return UploadManager_await(fetchApi(_part$uploadUrl2, {
2008
- method: "PUT",
2009
- headers: headers,
2010
- body: _coerceRequestBody2.call(_this8, _this7$makeRequestBod)
2011
- }), function (response) {
2012
- var _exit = false;
2013
- var etag = (_b = response.headers.get("etag")) !== null && _b !== void 0 ? _b : undefined;
2014
- return UploadManager_invoke(function () {
2015
- if (Math.floor(response.status / 100) !== 2) {
2016
- return UploadManager_await(response.text(), function (_response$text) {
2017
- console.error("Failed to upload part (".concat(response.status, "). Response from server:\n").concat(_response$text));
2018
- throw new Error("Failed to upload part (".concat(response.status, ")."));
2019
- });
2020
- }
2021
- }, function (_result) {
2022
- if (_exit) return _result;
2023
- if (etag === undefined) {
2024
- throw new Error("No 'etag' response header found in upload part response.");
2025
- }
2026
- return etag;
2027
- });
2028
- });
1710
+ var _this9 = this;
1711
+ var contentLength = part.range.inclusiveEnd + 1 - part.range.inclusiveStart;
1712
+ return UploadManagerBase_await(_this9.doPutUploadPart(part, contentLength, source, onProgress, addCancellationHandler), function (_ref3) {
1713
+ var status = _ref3.status,
1714
+ etag = _ref3.etag;
1715
+ if (Math.floor(status / 100) !== 2) {
1716
+ throw new Error("Failed to upload part (".concat(status, ")."));
1717
+ }
1718
+ if (etag === undefined) {
1719
+ throw new Error("No 'etag' response header found in upload part response.");
1720
+ }
1721
+ return etag;
2029
1722
  });
2030
1723
  } catch (e) {
2031
1724
  return Promise.reject(e);
2032
1725
  }
2033
1726
  }
2034
1727
  }, {
2035
- key: "coerceRequestBody",
2036
- value: function coerceRequestBody(data) {
2037
- return data; // node-fetch supports 'NodeJS.ReadableStream'
2038
- }
2039
- }, {
2040
- key: "makeRequestBody",
2041
- value: function makeRequestBody(part, data) {
1728
+ key: "getUploadPart",
1729
+ value: function getUploadPart(request, partIndex, uploadInfo) {
2042
1730
  try {
2043
- var _this10 = this;
2044
- return UploadManager_await(_this10.sliceDataForRequest(data, part), function (slicedData) {
2045
- var isNodeJs = _this10.isNodeJs();
2046
- // node-fetch requires 'NodeJS.ReadableStream' for the body.
2047
- // browser fetch supports blobs and buffers.
2048
- return UploadManager_await(_this10.foldDataRaw(slicedData, {
2049
- ifBuffer: UploadManager_async(function (buffer) {
2050
- return isNodeJs ? _this10.bufferToStream(buffer) : buffer;
2051
- }),
2052
- ifBlob: UploadManager_async(function (blob) {
2053
- var _bufferToStream = isNodeJs && _this10.bufferToStream;
2054
- return UploadManager_await(isNodeJs ? _this10.blobToBuffer(blob) : blob, function (_this10$blobToBuffer) {
2055
- return UploadManager_await(isNodeJs ? _bufferToStream.call(_this10, _this10$blobToBuffer) : _this10$blobToBuffer, void 0, !isNodeJs);
2056
- }, !isNodeJs);
2057
- }),
2058
- ifNodeJsStream: function (stream) {
2059
- return UploadManager_await(stream);
2060
- }
2061
- }));
2062
- });
1731
+ var _this11 = this;
1732
+ if (partIndex === 0) {
1733
+ return uploadInfo.uploadParts.first;
1734
+ }
1735
+ return UploadManagerBase_await(_this11.uploadApi.getUploadPart({
1736
+ uploadId: uploadInfo.uploadId,
1737
+ accountId: request.accountId,
1738
+ uploadPartIndex: partIndex
1739
+ }));
2063
1740
  } catch (e) {
2064
1741
  return Promise.reject(e);
2065
1742
  }
2066
1743
  }
2067
1744
  }, {
2068
- key: "bufferToStream",
2069
- value: function bufferToStream(buffer) {
1745
+ key: "getPreUploadInfo",
1746
+ value: function getPreUploadInfo(request, source) {
1747
+ var _a, _b, _c;
1748
+ var partial = this.getPreUploadInfoPartial(request, source);
1749
+ return {
1750
+ maxConcurrentUploadParts: (_a = partial.maxConcurrentUploadParts) !== null && _a !== void 0 ? _a : this.defaultMaxConcurrentUploadParts,
1751
+ originalFileName: (_b = request.originalFileName) !== null && _b !== void 0 ? _b : partial.originalFileName,
1752
+ mime: (_c = request.mime) !== null && _c !== void 0 ? _c : partial.mime,
1753
+ size: partial.size
1754
+ };
1755
+ }
1756
+ }, {
1757
+ key: "mapAsync",
1758
+ value: function mapAsync(items, concurrency, callback) {
2070
1759
  try {
2071
- return UploadManager_await(NodeUtils.createStream(), function (readable) {
2072
- readable.push(buffer);
2073
- readable.push(null);
2074
- return readable;
2075
- });
1760
+ var workQueue = _toConsumableArray(items);
1761
+ return _awaitIgnored(Promise.all(_toConsumableArray(Array(concurrency).keys()).map(UploadManagerBase_async(function () {
1762
+ return _continueIgnored(_for(function () {
1763
+ return workQueue.length > 0;
1764
+ }, void 0, function () {
1765
+ var work = workQueue.shift(); // IMPORTANT: use 'shift' instead of 'pop' to ensure 'items' are processed in order when 'concurrency = 1'.
1766
+ return _invokeIgnored(function () {
1767
+ if (work !== undefined) {
1768
+ return _awaitIgnored(callback(work));
1769
+ }
1770
+ });
1771
+ }));
1772
+ }))));
2076
1773
  } catch (e) {
2077
1774
  return Promise.reject(e);
2078
1775
  }
2079
1776
  }
1777
+ }]);
1778
+ return UploadManagerBase;
1779
+ }();
1780
+ ;// CONCATENATED MODULE: external "stream"
1781
+ var x = y => { var x = {}; __lib_require__.d(x, y); return x; }
1782
+ var y = x => () => x
1783
+ var external_stream_namespaceObject = x({ ["Readable"]: () => __WEBPACK_EXTERNAL_MODULE_stream__.Readable });
1784
+ ;// CONCATENATED MODULE: ./src/uploads/private/StreamUtils.ts
1785
+ function StreamUtils_typeof(obj) { "@babel/helpers - typeof"; return StreamUtils_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, StreamUtils_typeof(obj); }
1786
+ function StreamUtils_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
1787
+ function StreamUtils_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, StreamUtils_toPropertyKey(descriptor.key), descriptor); } }
1788
+ function StreamUtils_createClass(Constructor, protoProps, staticProps) { if (protoProps) StreamUtils_defineProperties(Constructor.prototype, protoProps); if (staticProps) StreamUtils_defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
1789
+ function StreamUtils_toPropertyKey(arg) { var key = StreamUtils_toPrimitive(arg, "string"); return StreamUtils_typeof(key) === "symbol" ? key : String(key); }
1790
+ function StreamUtils_toPrimitive(input, hint) { if (StreamUtils_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (StreamUtils_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
1791
+
1792
+ var StreamUtils = /*#__PURE__*/function () {
1793
+ function StreamUtils() {
1794
+ StreamUtils_classCallCheck(this, StreamUtils);
1795
+ }
1796
+ StreamUtils_createClass(StreamUtils, null, [{
1797
+ key: "create",
1798
+ value: function create() {
1799
+ var readable = new external_stream_namespaceObject.Readable();
1800
+ readable._read = function () {}; // _read is required but you can noop it
1801
+ return readable;
1802
+ }
1803
+ }, {
1804
+ key: "empty",
1805
+ value: function empty() {
1806
+ var readable = StreamUtils.create();
1807
+ StreamUtils.endStream(readable);
1808
+ return readable;
1809
+ }
1810
+ }, {
1811
+ key: "fromBuffer",
1812
+ value: function fromBuffer(buffer) {
1813
+ var readable = StreamUtils.create();
1814
+ readable.push(buffer);
1815
+ StreamUtils.endStream(readable);
1816
+ return readable;
1817
+ }
1818
+ }, {
1819
+ key: "endStream",
1820
+ value: function endStream(readable) {
1821
+ readable.push(null);
1822
+ }
1823
+ }]);
1824
+ return StreamUtils;
1825
+ }();
1826
+ ;// CONCATENATED MODULE: ./src/uploads/private/NodeChunkedStream.ts
1827
+ function NodeChunkedStream_typeof(obj) { "@babel/helpers - typeof"; return NodeChunkedStream_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, NodeChunkedStream_typeof(obj); }
1828
+ function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || NodeChunkedStream_unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
1829
+ function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
1830
+ function NodeChunkedStream_unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return NodeChunkedStream_arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return NodeChunkedStream_arrayLikeToArray(o, minLen); }
1831
+ function NodeChunkedStream_arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
1832
+ function _iterableToArrayLimit(arr, i) { var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; if (null != _i) { var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1; try { if (_x = (_i = _i.call(arr)).next, 0 === i) { if (Object(_i) !== _i) return; _n = !1; } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0) { ; } } catch (err) { _d = !0, _e = err; } finally { try { if (!_n && null != _i["return"] && (_r = _i["return"](), Object(_r) !== _r)) return; } finally { if (_d) throw _e; } } return _arr; } }
1833
+ function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
1834
+ function NodeChunkedStream_await(value, then, direct) {
1835
+ if (direct) {
1836
+ return then ? then(value) : value;
1837
+ }
1838
+ if (!value || !value.then) {
1839
+ value = Promise.resolve(value);
1840
+ }
1841
+ return then ? value.then(then) : value;
1842
+ }
1843
+ function NodeChunkedStream_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
1844
+ function NodeChunkedStream_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, NodeChunkedStream_toPropertyKey(descriptor.key), descriptor); } }
1845
+ function NodeChunkedStream_createClass(Constructor, protoProps, staticProps) { if (protoProps) NodeChunkedStream_defineProperties(Constructor.prototype, protoProps); if (staticProps) NodeChunkedStream_defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
1846
+ function NodeChunkedStream_toPropertyKey(arg) { var key = NodeChunkedStream_toPrimitive(arg, "string"); return NodeChunkedStream_typeof(key) === "symbol" ? key : String(key); }
1847
+ function NodeChunkedStream_toPrimitive(input, hint) { if (NodeChunkedStream_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (NodeChunkedStream_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
1848
+
1849
+ /**
1850
+ * For Node.js streams only:
1851
+ *
1852
+ * Converts a stream into a stream of streams, where the next stream is requested via '.take(sizeInBytes: number): Stream'
1853
+ *
1854
+ * This allows the source stream to be sequentially read (in serial) as a sequence of sub-streams, for the purpose of
1855
+ * issuing PutObject requests for a multipart upload, whereby each request requires its own stream, but where that stream
1856
+ * needs to be a slice of the source stream.
1857
+ */
1858
+ var NodeChunkedStream = /*#__PURE__*/function () {
1859
+ function NodeChunkedStream(source) {
1860
+ NodeChunkedStream_classCallCheck(this, NodeChunkedStream);
1861
+ this.source = source;
1862
+ this.buffer = Buffer.alloc(0);
1863
+ this.isSourceFullyConsumed = false; // true if the source stream indicates it has finished.
1864
+ this.isFinishedConsuming = false; // true if _we_ indicate we have finished reading all we want from the stream.
1865
+ this.resolver = undefined;
1866
+ }
1867
+ /**
1868
+ * If the source stream is larger than the 'size' the user is consuming (i.e. they're only wanting to upload a subset
1869
+ * of the stream) then the stream won't be resolved by the 'end' event inside 'runChunkPipeline', so calling this
1870
+ * method is necessary.
1871
+ */
1872
+ NodeChunkedStream_createClass(NodeChunkedStream, [{
1873
+ key: "finishedConsuming",
1874
+ value: function finishedConsuming() {
1875
+ this.isFinishedConsuming = true;
1876
+ if (this.resolver !== undefined) {
1877
+ this.resolver();
1878
+ }
1879
+ }
2080
1880
  /**
2081
- * Only expected to be called in Node.js environments, and as such, we can assume 'BlobLike' is not a DOM 'File' object.
1881
+ * Promise resolves when the entire stream has finished processing, or an error occurs.
1882
+ * You must call 'take' a sufficient number of times after calling this method in order for this promise to resolve.
2082
1883
  */
2083
1884
  }, {
2084
- key: "blobToBuffer",
2085
- value: function blobToBuffer(blob) {
1885
+ key: "runChunkPipeline",
1886
+ value: function runChunkPipeline() {
2086
1887
  try {
2087
- var _exit3 = false;
2088
- // DOM Blob and Node.js Blob both have 'arrayBuffer' with the same signature...
2089
- return UploadManager_invoke(function () {
2090
- if (blob.arrayBuffer !== undefined) {
2091
- _exit3 = true;
2092
- var _Buffer2 = Buffer,
2093
- _from2 = _Buffer2.from;
2094
- return UploadManager_await(blob.arrayBuffer(), function (_blob$arrayBuffer) {
2095
- return _from2.call(_Buffer2, _blob$arrayBuffer);
2096
- });
2097
- }
2098
- }, function (_result2) {
2099
- if (_exit3) return _result2;
2100
- throw new Error("The provided 'data' field was treated as a BLOB, but it does not have an 'arrayBuffer' method.");
2101
- });
1888
+ var _this2 = this;
1889
+ return NodeChunkedStream_await(new Promise(function (resolve, reject) {
1890
+ _this2.resolver = resolve;
1891
+ var onError = function onError(error) {
1892
+ removeListeners();
1893
+ reject(error);
1894
+ };
1895
+ var onEnd = function onEnd() {
1896
+ _this2.isSourceFullyConsumed = true;
1897
+ removeListeners();
1898
+ resolve();
1899
+ };
1900
+ var onData = function onData(buffer) {
1901
+ try {
1902
+ if (_this2.isFinishedConsuming) {
1903
+ return;
1904
+ }
1905
+ if (_this2.consumer === undefined) {
1906
+ console.warn("Stream yielded data while paused. The data will be buffered, but excessive buffering can cause memory issues.");
1907
+ _this2.buffer = Buffer.concat([_this2.buffer, buffer]);
1908
+ return;
1909
+ }
1910
+ if (_this2.consumer.bytesRemaining <= 0) {
1911
+ throw new Error("Consumer requires zero bytes, so should not be consuming from the stream.");
1912
+ }
1913
+ if (_this2.buffer.byteLength > 0) {
1914
+ throw new Error("Buffer was expected to be empty (as it should have been flushed to the consumer when '.take' was called).");
1915
+ }
1916
+ var splitResult = _this2.splitBuffer(buffer, _this2.consumer.bytesRemaining);
1917
+ if (splitResult === undefined) {
1918
+ return; // Received empty data.
1919
+ }
1920
+
1921
+ var _splitResult = _slicedToArray(splitResult, 2),
1922
+ consumed = _splitResult[0],
1923
+ remaining = _splitResult[1];
1924
+ _this2.buffer = remaining;
1925
+ _this2.consumer.bytesRemaining -= consumed.byteLength;
1926
+ _this2.consumer.stream.push(consumed);
1927
+ if (_this2.consumer.bytesRemaining === 0) {
1928
+ StreamUtils.endStream(_this2.consumer.stream);
1929
+ _this2.consumer = undefined;
1930
+ _this2.source.pause();
1931
+ }
1932
+ } catch (e) {
1933
+ removeListeners();
1934
+ reject(e);
1935
+ }
1936
+ };
1937
+ var removeListeners = function removeListeners() {
1938
+ _this2.source.removeListener("data", onData);
1939
+ _this2.source.removeListener("error", onError);
1940
+ _this2.source.removeListener("end", onEnd);
1941
+ };
1942
+ _this2.source.on("data", onData);
1943
+ _this2.source.on("error", onError);
1944
+ _this2.source.on("end", onEnd);
1945
+ _this2.source.pause(); // Resumed when 'take' is called.
1946
+ }));
2102
1947
  } catch (e) {
2103
1948
  return Promise.reject(e);
2104
1949
  }
2105
1950
  }
1951
+ /**
1952
+ * Only call 'take' after the previously returned stream has been fully consumed.
1953
+ */
2106
1954
  }, {
2107
- key: "sliceDataForRequest",
2108
- value: function sliceDataForRequest(data, part) {
2109
- try {
2110
- var _this12 = this;
2111
- if (part.range.inclusiveEnd === -1) {
2112
- return "";
1955
+ key: "take",
1956
+ value: function take(bytes) {
1957
+ var _a;
1958
+ if (this.consumer !== undefined) {
1959
+ throw new Error("The stream from the previous 'take' call must be fully consumed before calling 'take' again.");
1960
+ }
1961
+ if (bytes <= 0) {
1962
+ return StreamUtils.empty();
1963
+ }
1964
+ var readable = StreamUtils.create();
1965
+ var consumedFromBuffer = this.consumeFromBuffer(bytes);
1966
+ var consumedFromBufferLength = (_a = consumedFromBuffer === null || consumedFromBuffer === void 0 ? void 0 : consumedFromBuffer.length) !== null && _a !== void 0 ? _a : 0;
1967
+ var bytesToConsumeFromStream = bytes - consumedFromBufferLength;
1968
+ if (consumedFromBuffer !== undefined) {
1969
+ readable.push(consumedFromBuffer);
1970
+ }
1971
+ if (bytesToConsumeFromStream > 0) {
1972
+ if (this.isSourceFullyConsumed) {
1973
+ throw new Error("Stream finished processing earlier than expected. The \"size\" parameter is likely larger than the stream's actual contents.");
2113
1974
  }
2114
- var start = part.range.inclusiveStart;
2115
- var endExclusive = part.range.inclusiveEnd + 1;
2116
- var partSize = endExclusive - start;
2117
- return UploadManager_await(_this12.foldData(data, {
2118
- ifBlob: UploadManager_async(function (blob) {
2119
- return blob.slice(start, endExclusive);
2120
- }),
2121
- ifBuffer: UploadManager_async(function (buffer) {
2122
- return buffer.subarray(start, endExclusive);
2123
- }),
2124
- ifNodeJsStream: UploadManager_async(function (stream) {
2125
- return stream.take(partSize);
2126
- }) // Assumes stream is read using one worker (which it is).
2127
- }));
2128
- } catch (e) {
2129
- return Promise.reject(e);
1975
+ this.consumer = {
1976
+ bytesRemaining: bytesToConsumeFromStream,
1977
+ stream: readable
1978
+ };
1979
+ this.source.resume();
1980
+ } else {
1981
+ StreamUtils.endStream(readable);
2130
1982
  }
1983
+ return readable;
2131
1984
  }
2132
1985
  }, {
2133
- key: "isNodeJs",
2134
- value: function isNodeJs() {
2135
- return typeof process !== "undefined" && process.versions !== undefined && process.versions.node !== undefined;
1986
+ key: "consumeFromBuffer",
1987
+ value: function consumeFromBuffer(bytes) {
1988
+ var splitResult = this.splitBuffer(this.buffer, bytes);
1989
+ if (splitResult === undefined) {
1990
+ return undefined;
1991
+ }
1992
+ var _splitResult2 = _slicedToArray(splitResult, 2),
1993
+ consumed = _splitResult2[0],
1994
+ remaining = _splitResult2[1];
1995
+ this.buffer = remaining;
1996
+ return consumed;
2136
1997
  }
2137
1998
  }, {
2138
- key: "getUploadPart",
2139
- value: function getUploadPart(request, partIndex, uploadInfo) {
2140
- try {
2141
- var _this14 = this;
2142
- if (partIndex === 0) {
2143
- return uploadInfo.uploadParts.first;
2144
- }
2145
- return UploadManager_await(_this14.uploadApi.getUploadPart({
2146
- uploadId: uploadInfo.uploadId,
2147
- accountId: request.accountId,
2148
- uploadPartIndex: partIndex
2149
- }));
2150
- } catch (e) {
2151
- return Promise.reject(e);
1999
+ key: "splitBuffer",
2000
+ value: function splitBuffer(buffer, maxBytes) {
2001
+ if (buffer.byteLength === 0) {
2002
+ return undefined;
2152
2003
  }
2004
+ var bytesToConsume = Math.min(maxBytes, buffer.byteLength);
2005
+ if (bytesToConsume === buffer.byteLength) {
2006
+ return [buffer, Buffer.alloc(0)]; // Optimization
2007
+ }
2008
+
2009
+ var consumed = buffer.subarray(0, bytesToConsume);
2010
+ var remaining = buffer.subarray(bytesToConsume);
2011
+ return [consumed, remaining];
2153
2012
  }
2154
- }, {
2155
- key: "calculateSize",
2156
- value: function calculateSize(request, data) {
2157
- return this.foldData(data, {
2158
- ifBlob: function ifBlob(blob) {
2159
- return blob.size;
2160
- },
2161
- ifBuffer: function ifBuffer(buffer) {
2162
- return buffer.length;
2163
- },
2164
- ifNodeJsStream: function ifNodeJsStream(_) {
2165
- if (request.size === undefined) {
2166
- throw new Error("You must include the 'size' parameter when using a stream for the 'data' parameter.");
2167
- }
2168
- return request.size;
2013
+ }]);
2014
+ return NodeChunkedStream;
2015
+ }();
2016
+ ;// CONCATENATED MODULE: ./src/uploads/private/TypeUtils.ts
2017
+ function assertUnreachable(x) {
2018
+ throw new Error("Didn't expect to get here: ".concat(JSON.stringify(x)));
2019
+ }
2020
+ ;// CONCATENATED MODULE: external "buffer"
2021
+ var external_buffer_x = y => { var x = {}; __lib_require__.d(x, y); return x; }
2022
+ var external_buffer_y = x => () => x
2023
+ var external_buffer_namespaceObject = external_buffer_x({ ["Blob"]: () => __WEBPACK_EXTERNAL_MODULE_buffer__.Blob });
2024
+ ;// CONCATENATED MODULE: ./src/uploads/public/node/UploadManagerNode.ts
2025
+ function UploadManagerNode_typeof(obj) { "@babel/helpers - typeof"; return UploadManagerNode_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, UploadManagerNode_typeof(obj); }
2026
+ function UploadManagerNode_empty() {}
2027
+ function UploadManagerNode_awaitIgnored(value, direct) {
2028
+ if (!direct) {
2029
+ return value && value.then ? value.then(UploadManagerNode_empty) : Promise.resolve();
2030
+ }
2031
+ }
2032
+ function UploadManagerNode_await(value, then, direct) {
2033
+ if (direct) {
2034
+ return then ? then(value) : value;
2035
+ }
2036
+ if (!value || !value.then) {
2037
+ value = Promise.resolve(value);
2038
+ }
2039
+ return then ? value.then(then) : value;
2040
+ }
2041
+ function UploadManagerNode_settle(pact, state, value) {
2042
+ if (!pact.s) {
2043
+ if (value instanceof UploadManagerNode_Pact) {
2044
+ if (value.s) {
2045
+ if (state & 1) {
2046
+ state = value.s;
2169
2047
  }
2170
- });
2048
+ value = value.v;
2049
+ } else {
2050
+ value.o = UploadManagerNode_settle.bind(null, pact, state);
2051
+ return;
2052
+ }
2171
2053
  }
2172
- }, {
2173
- key: "calculateMime",
2174
- value: function calculateMime(request, data) {
2175
- var _a;
2176
- return (_a = request.mime) !== null && _a !== void 0 ? _a : this.foldData(data, {
2177
- ifBlob: function ifBlob(blob) {
2178
- return blob.type;
2179
- },
2180
- ifBuffer: function ifBuffer(_) {
2181
- return undefined;
2182
- },
2183
- ifNodeJsStream: function ifNodeJsStream(_) {
2184
- return undefined;
2054
+ if (value && value.then) {
2055
+ value.then(UploadManagerNode_settle.bind(null, pact, state), UploadManagerNode_settle.bind(null, pact, 2));
2056
+ return;
2057
+ }
2058
+ pact.s = state;
2059
+ pact.v = value;
2060
+ var observer = pact.o;
2061
+ if (observer) {
2062
+ observer(pact);
2063
+ }
2064
+ }
2065
+ }
2066
+ var UploadManagerNode_Pact = /*#__PURE__*/function () {
2067
+ function _Pact() {}
2068
+ _Pact.prototype.then = function (onFulfilled, onRejected) {
2069
+ var result = new _Pact();
2070
+ var state = this.s;
2071
+ if (state) {
2072
+ var callback = state & 1 ? onFulfilled : onRejected;
2073
+ if (callback) {
2074
+ try {
2075
+ UploadManagerNode_settle(result, 1, callback(this.v));
2076
+ } catch (e) {
2077
+ UploadManagerNode_settle(result, 2, e);
2185
2078
  }
2186
- });
2079
+ return result;
2080
+ } else {
2081
+ return this;
2082
+ }
2187
2083
  }
2188
- }, {
2189
- key: "calculateOriginalFileName",
2190
- value: function calculateOriginalFileName(request, data) {
2191
- var _a;
2192
- return (_a = request.originalFileName) !== null && _a !== void 0 ? _a : this.foldData(data, {
2193
- ifBlob: function ifBlob(blob) {
2194
- return blob.name;
2195
- },
2196
- ifBuffer: function ifBuffer(_) {
2197
- return undefined;
2198
- },
2199
- ifNodeJsStream: function ifNodeJsStream(_) {
2200
- return undefined;
2084
+ this.o = function (_this) {
2085
+ try {
2086
+ var value = _this.v;
2087
+ if (_this.s & 1) {
2088
+ UploadManagerNode_settle(result, 1, onFulfilled ? onFulfilled(value) : value);
2089
+ } else if (onRejected) {
2090
+ UploadManagerNode_settle(result, 1, onRejected(value));
2091
+ } else {
2092
+ UploadManagerNode_settle(result, 2, value);
2201
2093
  }
2202
- });
2094
+ } catch (e) {
2095
+ UploadManagerNode_settle(result, 2, e);
2096
+ }
2097
+ };
2098
+ return result;
2099
+ };
2100
+ return _Pact;
2101
+ }();
2102
+ function _switch(discriminant, cases) {
2103
+ var dispatchIndex = -1;
2104
+ var awaitBody;
2105
+ outer: {
2106
+ for (var i = 0; i < cases.length; i++) {
2107
+ var test = cases[i][0];
2108
+ if (test) {
2109
+ var testValue = test();
2110
+ if (testValue && testValue.then) {
2111
+ break outer;
2112
+ }
2113
+ if (testValue === discriminant) {
2114
+ dispatchIndex = i;
2115
+ break;
2116
+ }
2117
+ } else {
2118
+ // Found the default case, set it as the pending dispatch case
2119
+ dispatchIndex = i;
2120
+ }
2203
2121
  }
2204
- }, {
2205
- key: "calculateMaxConcurrency",
2206
- value: function calculateMaxConcurrency(request, data) {
2207
- var _a;
2208
- return (_a = this.foldData(data, {
2209
- ifBlob: function ifBlob(_) {
2210
- return request.maxConcurrentUploadParts;
2211
- },
2212
- ifBuffer: function ifBuffer(_) {
2213
- return request.maxConcurrentUploadParts;
2214
- },
2215
- ifNodeJsStream: function ifNodeJsStream(_) {
2216
- return 1;
2217
- } // Uploading from a stream concurrently is more complex, as would require buffering parts in memory, so we serialize.
2218
- })) !== null && _a !== void 0 ? _a : this.defaultMaxConcurrentUploadParts;
2122
+ if (dispatchIndex !== -1) {
2123
+ do {
2124
+ var body = cases[dispatchIndex][1];
2125
+ while (!body) {
2126
+ dispatchIndex++;
2127
+ body = cases[dispatchIndex][1];
2128
+ }
2129
+ var result = body();
2130
+ if (result && result.then) {
2131
+ awaitBody = true;
2132
+ break outer;
2133
+ }
2134
+ var fallthroughCheck = cases[dispatchIndex][2];
2135
+ dispatchIndex++;
2136
+ } while (fallthroughCheck && !fallthroughCheck());
2137
+ return result;
2219
2138
  }
2220
- }, {
2221
- key: "getChunkedStream",
2222
- value: function getChunkedStream(data) {
2223
- return this.foldData(data, {
2224
- ifBlob: function ifBlob(_) {
2225
- return undefined;
2226
- },
2227
- ifBuffer: function ifBuffer(_) {
2228
- return undefined;
2229
- },
2230
- ifNodeJsStream: function ifNodeJsStream(x) {
2231
- return x;
2139
+ }
2140
+ var pact = new UploadManagerNode_Pact();
2141
+ var reject = UploadManagerNode_settle.bind(null, pact, 2);
2142
+ (awaitBody ? result.then(_resumeAfterBody) : testValue.then(_resumeAfterTest)).then(void 0, reject);
2143
+ return pact;
2144
+ function _resumeAfterTest(value) {
2145
+ for (;;) {
2146
+ if (value === discriminant) {
2147
+ dispatchIndex = i;
2148
+ break;
2149
+ }
2150
+ if (++i === cases.length) {
2151
+ if (dispatchIndex !== -1) {
2152
+ break;
2153
+ } else {
2154
+ UploadManagerNode_settle(pact, 1, result);
2155
+ return;
2232
2156
  }
2233
- });
2157
+ }
2158
+ test = cases[i][0];
2159
+ if (test) {
2160
+ value = test();
2161
+ if (value && value.then) {
2162
+ value.then(_resumeAfterTest).then(void 0, reject);
2163
+ return;
2164
+ }
2165
+ } else {
2166
+ dispatchIndex = i;
2167
+ }
2234
2168
  }
2235
- }, {
2236
- key: "foldData",
2237
- value: function foldData(data, handle) {
2238
- if (data instanceof ChunkedStream) {
2239
- return handle.ifNodeJsStream(data);
2169
+ do {
2170
+ var body = cases[dispatchIndex][1];
2171
+ while (!body) {
2172
+ dispatchIndex++;
2173
+ body = cases[dispatchIndex][1];
2174
+ }
2175
+ var result = body();
2176
+ if (result && result.then) {
2177
+ result.then(_resumeAfterBody).then(void 0, reject);
2178
+ return;
2179
+ }
2180
+ var fallthroughCheck = cases[dispatchIndex][2];
2181
+ dispatchIndex++;
2182
+ } while (fallthroughCheck && !fallthroughCheck());
2183
+ UploadManagerNode_settle(pact, 1, result);
2184
+ }
2185
+ function _resumeAfterBody(result) {
2186
+ for (;;) {
2187
+ var fallthroughCheck = cases[dispatchIndex][2];
2188
+ if (!fallthroughCheck || fallthroughCheck()) {
2189
+ break;
2190
+ }
2191
+ dispatchIndex++;
2192
+ var body = cases[dispatchIndex][1];
2193
+ while (!body) {
2194
+ dispatchIndex++;
2195
+ body = cases[dispatchIndex][1];
2196
+ }
2197
+ result = body();
2198
+ if (result && result.then) {
2199
+ result.then(_resumeAfterBody).then(void 0, reject);
2200
+ return;
2201
+ }
2202
+ }
2203
+ UploadManagerNode_settle(pact, 1, result);
2204
+ }
2205
+ }
2206
+ function UploadManagerNode_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
2207
+ function UploadManagerNode_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, UploadManagerNode_toPropertyKey(descriptor.key), descriptor); } }
2208
+ function UploadManagerNode_createClass(Constructor, protoProps, staticProps) { if (protoProps) UploadManagerNode_defineProperties(Constructor.prototype, protoProps); if (staticProps) UploadManagerNode_defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
2209
+ function UploadManagerNode_toPropertyKey(arg) { var key = UploadManagerNode_toPrimitive(arg, "string"); return UploadManagerNode_typeof(key) === "symbol" ? key : String(key); }
2210
+ function UploadManagerNode_toPrimitive(input, hint) { if (UploadManagerNode_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (UploadManagerNode_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
2211
+ function UploadManagerNode_inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) UploadManagerNode_setPrototypeOf(subClass, superClass); }
2212
+ function UploadManagerNode_setPrototypeOf(o, p) { UploadManagerNode_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return UploadManagerNode_setPrototypeOf(o, p); }
2213
+ function UploadManagerNode_createSuper(Derived) { var hasNativeReflectConstruct = UploadManagerNode_isNativeReflectConstruct(); return function _createSuperInternal() { var Super = UploadManagerNode_getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = UploadManagerNode_getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return UploadManagerNode_possibleConstructorReturn(this, result); }; }
2214
+ function UploadManagerNode_possibleConstructorReturn(self, call) { if (call && (UploadManagerNode_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return UploadManagerNode_assertThisInitialized(self); }
2215
+ function UploadManagerNode_assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
2216
+ function UploadManagerNode_isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
2217
+ function UploadManagerNode_getPrototypeOf(o) { UploadManagerNode_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return UploadManagerNode_getPrototypeOf(o); }
2218
+
2219
+
2220
+
2221
+
2222
+
2223
+ var UploadManager = /*#__PURE__*/function (_UploadManagerBase) {
2224
+ UploadManagerNode_inherits(UploadManager, _UploadManagerBase);
2225
+ var _super = UploadManagerNode_createSuper(UploadManager);
2226
+ function UploadManager() {
2227
+ UploadManagerNode_classCallCheck(this, UploadManager);
2228
+ return _super.apply(this, arguments);
2229
+ }
2230
+ UploadManagerNode_createClass(UploadManager, [{
2231
+ key: "processUploadSource",
2232
+ value: function processUploadSource(data) {
2233
+ if (typeof data === "string") {
2234
+ // 'Blob' must be from 'buffer' as we're in a node context here, so isn't globally available.
2235
+ return {
2236
+ type: "Blob",
2237
+ value: new external_buffer_namespaceObject.Blob([data], {
2238
+ type: this.stringMimeType
2239
+ })
2240
+ };
2241
+ }
2242
+ if (data.on !== undefined) {
2243
+ return {
2244
+ type: "Stream",
2245
+ value: new NodeChunkedStream(data)
2246
+ };
2240
2247
  }
2241
2248
  if (data.subarray !== undefined) {
2242
- return handle.ifBuffer(data);
2249
+ return {
2250
+ type: "Buffer",
2251
+ value: data
2252
+ };
2243
2253
  }
2244
- if (data.slice !== undefined) {
2245
- return handle.ifBlob(data);
2254
+ if (data.size !== undefined) {
2255
+ return {
2256
+ type: "Blob",
2257
+ value: data
2258
+ };
2246
2259
  }
2247
2260
  throw new Error("Unsupported type for 'data' parameter. Please provide a String, Blob, or Readable (Node.js).");
2248
2261
  }
2249
2262
  }, {
2250
- key: "foldDataRaw",
2251
- value: function foldDataRaw(data, handle) {
2252
- try {
2253
- var _exit8 = false;
2254
- var _this16 = this;
2255
- return UploadManager_invoke(function () {
2256
- if (typeof data === "string") {
2257
- _exit8 = true;
2258
- var _ifBlob2 = handle.ifBlob;
2259
- return UploadManager_await(_this16.stringToBlob(data), function (_this15$stringToBlob) {
2260
- return UploadManager_await(_ifBlob2.call(handle, _this15$stringToBlob));
2261
- });
2263
+ key: "getPreUploadInfoPartial",
2264
+ value: function getPreUploadInfoPartial(request, data) {
2265
+ switch (data.type) {
2266
+ case "Blob":
2267
+ return this.getBlobInfo(data);
2268
+ case "Buffer":
2269
+ return {
2270
+ mime: undefined,
2271
+ size: data.value.length,
2272
+ originalFileName: undefined,
2273
+ maxConcurrentUploadParts: undefined
2274
+ };
2275
+ case "Stream":
2276
+ if (request.size === undefined) {
2277
+ throw new Error("You must include the 'size' parameter when using a stream for the 'data' parameter.");
2262
2278
  }
2263
- }, function (_result3) {
2264
- var _exit5 = false;
2265
- if (_exit8) return _result3;
2266
- return UploadManager_invoke(function () {
2267
- if (data.on !== undefined) {
2268
- _exit5 = true;
2269
- return UploadManager_await(handle.ifNodeJsStream(data));
2270
- }
2271
- }, function (_result4) {
2272
- var _exit6 = false;
2273
- if (_exit5) return _result4;
2274
- return UploadManager_invoke(function () {
2275
- if (data.subarray !== undefined) {
2276
- _exit6 = true;
2277
- return UploadManager_await(handle.ifBuffer(data));
2278
- }
2279
- }, function (_result5) {
2280
- var _exit7 = false;
2281
- if (_exit6) return _result5;
2282
- return UploadManager_invoke(function () {
2283
- if (data.slice !== undefined) {
2284
- _exit7 = true;
2285
- return UploadManager_await(handle.ifBlob(data));
2286
- }
2287
- }, function (_result6) {
2288
- if (_exit7) return _result6;
2289
- throw new Error("Unsupported type for 'data' parameter. Please provide a String, Blob, or Readable (Node.js).");
2290
- });
2291
- });
2292
- });
2293
- });
2294
- } catch (e) {
2295
- return Promise.reject(e);
2279
+ return {
2280
+ mime: undefined,
2281
+ size: request.size,
2282
+ originalFileName: undefined,
2283
+ maxConcurrentUploadParts: 1 // Uploading from a stream concurrently is complex, so we serialize it.
2284
+ };
2285
+
2286
+ default:
2287
+ assertUnreachable(data);
2296
2288
  }
2297
2289
  }
2298
2290
  }, {
2299
- key: "processUploadSource",
2300
- value: function processUploadSource(data) {
2301
- try {
2302
- var _exit10 = false;
2303
- var _this18 = this;
2304
- return UploadManager_invoke(function () {
2305
- if (typeof data === "string") {
2306
- _exit10 = true;
2307
- return UploadManager_await(_this18.stringToBlob(data));
2308
- }
2309
- }, function (_result7) {
2310
- if (_exit10) return _result7;
2311
- if (data.on !== undefined) {
2312
- return new ChunkedStream(data);
2313
- }
2314
- if (data.subarray !== undefined) {
2315
- return data;
2316
- }
2317
- if (data.slice !== undefined) {
2318
- return data;
2319
- }
2320
- throw new Error("Unsupported type for 'data' parameter. Please provide a String, Blob, or Readable (Node.js).");
2321
- });
2322
- } catch (e) {
2323
- return Promise.reject(e);
2291
+ key: "preUpload",
2292
+ value: function preUpload(source) {
2293
+ if (source.type !== "Stream") {
2294
+ return undefined;
2324
2295
  }
2296
+ var chunkedStream = source.value;
2297
+ var chunkedStreamPromise = chunkedStream.runChunkPipeline();
2298
+ return {
2299
+ chunkedStreamPromise: chunkedStreamPromise,
2300
+ chunkedStream: chunkedStream
2301
+ };
2325
2302
  }
2326
2303
  }, {
2327
- key: "stringToBlob",
2328
- value: function stringToBlob(data) {
2304
+ key: "postUpload",
2305
+ value: function postUpload(init) {
2329
2306
  try {
2330
- var _this20 = this;
2331
- var _a;
2332
- var _temp2 = (_a = _this20.globalBlob(data)) !== null && _a !== void 0;
2333
- return UploadManager_await(_temp2 ? _a : _this20.nodeJsBlob(data), void 0, _temp2);
2307
+ if (init === undefined) {
2308
+ return;
2309
+ }
2310
+ init.chunkedStream.finishedConsuming();
2311
+ // Raise any errors from the stream chunking task.
2312
+ return UploadManagerNode_awaitIgnored(init.chunkedStreamPromise);
2334
2313
  } catch (e) {
2335
2314
  return Promise.reject(e);
2336
2315
  }
2337
- } // Supported by browsers & newer versions of Node.js.
2338
- }, {
2339
- key: "globalBlob",
2340
- value: function globalBlob(data) {
2341
- var B = globalThis.Blob;
2342
- if (B === undefined) {
2343
- return undefined;
2344
- }
2345
- return new B([data], {
2346
- type: this.stringMimeType
2347
- });
2348
2316
  }
2349
- // Fallback for Node.js
2350
2317
  }, {
2351
- key: "nodeJsBlob",
2352
- value: function nodeJsBlob(data) {
2318
+ key: "doPutUploadPart",
2319
+ value: function doPutUploadPart(part, contentLength, source, onProgress, addCancellationHandler) {
2353
2320
  try {
2354
- var _this22 = this;
2355
- return UploadManager_await(NodeUtils.createBlob([data], {
2356
- type: _this22.stringMimeType
2357
- }));
2321
+ var _this2 = this;
2322
+ var _a, _b;
2323
+ var fetchApi = (_a = _this2.config.fetchApi) !== null && _a !== void 0 ? _a : fetch;
2324
+ var headers = {
2325
+ // Required to prevent fetch using "Transfer-Encoding: Chunked" when body is a stream.
2326
+ "content-length": contentLength.toString()
2327
+ };
2328
+ // Configure cancellation:
2329
+ var controller = new AbortController();
2330
+ var signal = controller.signal;
2331
+ addCancellationHandler(function () {
2332
+ return controller.abort();
2333
+ });
2334
+ // Report progress:
2335
+ var hasWarned = false;
2336
+ return UploadManagerNode_await(_this2.sliceDataForRequest(source, part), function (stream) {
2337
+ var streamWithProgress = stream.on("data", function (data) {
2338
+ if (data.length !== undefined) {
2339
+ onProgress(data.length);
2340
+ } else if (!hasWarned) {
2341
+ hasWarned = true;
2342
+ console.warn("Expected stream to contain buffers, but it did not, so upload progress won't be reported.");
2343
+ }
2344
+ });
2345
+ return UploadManagerNode_await(fetchApi(part.uploadUrl, {
2346
+ method: "PUT",
2347
+ headers: headers,
2348
+ body: _this2.coerceRequestBody(streamWithProgress),
2349
+ signal: signal
2350
+ }), function (response) {
2351
+ return {
2352
+ etag: (_b = response.headers.get("etag")) !== null && _b !== void 0 ? _b : undefined,
2353
+ status: response.status
2354
+ };
2355
+ });
2356
+ });
2358
2357
  } catch (e) {
2359
2358
  return Promise.reject(e);
2360
2359
  }
2361
2360
  }
2362
2361
  }, {
2363
- key: "mapAsync",
2364
- value: function mapAsync(items, concurrency, callback) {
2362
+ key: "coerceRequestBody",
2363
+ value: function coerceRequestBody(data) {
2364
+ return data; // node-fetch supports 'NodeJS.ReadableStream'
2365
+ }
2366
+ }, {
2367
+ key: "sliceDataForRequest",
2368
+ value: function sliceDataForRequest(data, part) {
2365
2369
  try {
2366
- var workQueue = _toConsumableArray(items);
2367
- return _awaitIgnored(Promise.all(_toConsumableArray(Array(concurrency).keys()).map(UploadManager_async(function () {
2368
- return _continueIgnored(_for(function () {
2369
- return workQueue.length > 0;
2370
- }, void 0, function () {
2371
- var work = workQueue.shift(); // IMPORTANT: use 'shift' instead of 'pop' to ensure 'items' are processed in order when 'concurrency = 1'.
2372
- return _invokeIgnored(function () {
2373
- if (work !== undefined) {
2374
- return _awaitIgnored(callback(work));
2375
- }
2376
- });
2377
- }));
2378
- }))));
2370
+ if (part.range.inclusiveEnd === -1) {
2371
+ return StreamUtils.empty();
2372
+ }
2373
+ var start = part.range.inclusiveStart;
2374
+ var endExclusive = part.range.inclusiveEnd + 1;
2375
+ var partSize = endExclusive - start;
2376
+ return _switch(data.type, [[function () {
2377
+ return "Blob";
2378
+ }, function () {
2379
+ var _fromBuffer = StreamUtils.fromBuffer,
2380
+ _Buffer = Buffer,
2381
+ _from = _Buffer.from;
2382
+ return UploadManagerNode_await(data.value.slice(start, endExclusive).arrayBuffer(), function (_data$value$slice$arr) {
2383
+ return _fromBuffer.call(StreamUtils, _from.call(_Buffer, _data$value$slice$arr));
2384
+ });
2385
+ }], [function () {
2386
+ return "Buffer";
2387
+ }, function () {
2388
+ return StreamUtils.fromBuffer(data.value.subarray(start, endExclusive));
2389
+ }], [function () {
2390
+ return "Stream";
2391
+ }, function () {
2392
+ return data.value.take(partSize);
2393
+ }], [void 0, function () {
2394
+ assertUnreachable(data);
2395
+ }, UploadManagerNode_empty]]);
2379
2396
  } catch (e) {
2380
2397
  return Promise.reject(e);
2381
2398
  }
2382
2399
  }
2383
2400
  }]);
2384
2401
  return UploadManager;
2385
- }();
2386
- ;// CONCATENATED MODULE: ./src/uploads/index.ts
2387
-
2402
+ }(UploadManagerBase);
2403
+ ;// CONCATENATED MODULE: ./src/uploads/public/node/index.ts
2388
2404
 
2389
-
2390
- ;// CONCATENATED MODULE: ./src/index.ts
2405
+ ;// CONCATENATED MODULE: ./src/index.node.ts
2391
2406
  /* tslint:disable */
2392
2407
  /* eslint-disable */
2393
2408
 
2394
2409
 
2395
- }();
2410
+
2396
2411
  var __lib_exports__BASE_PATH = __lib_exports__.BASE_PATH;
2397
2412
  var __lib_exports__BaseAPI = __lib_exports__.BaseAPI;
2398
2413
  var __lib_exports__BinaryResult = __lib_exports__.BinaryResult;
2399
2414
  var __lib_exports__BytescaleApiError = __lib_exports__.BytescaleApiError;
2400
2415
  var __lib_exports__CancelledError = __lib_exports__.CancelledError;
2401
- var __lib_exports__ChunkedStream = __lib_exports__.ChunkedStream;
2402
- var __lib_exports__FetchError = __lib_exports__.FetchError;
2403
2416
  var __lib_exports__FileApi = __lib_exports__.FileApi;
2404
2417
  var __lib_exports__FolderApi = __lib_exports__.FolderApi;
2405
2418
  var __lib_exports__JSONApiResponse = __lib_exports__.JSONApiResponse;
2406
2419
  var __lib_exports__JobApi = __lib_exports__.JobApi;
2407
- var __lib_exports__RequiredError = __lib_exports__.RequiredError;
2408
- var __lib_exports__ResponseError = __lib_exports__.ResponseError;
2409
2420
  var __lib_exports__UploadApi = __lib_exports__.UploadApi;
2410
2421
  var __lib_exports__UploadManager = __lib_exports__.UploadManager;
2411
2422
  var __lib_exports__VoidApiResponse = __lib_exports__.VoidApiResponse;
2412
2423
  var __lib_exports__querystring = __lib_exports__.querystring;
2413
- export { __lib_exports__BASE_PATH as BASE_PATH, __lib_exports__BaseAPI as BaseAPI, __lib_exports__BinaryResult as BinaryResult, __lib_exports__BytescaleApiError as BytescaleApiError, __lib_exports__CancelledError as CancelledError, __lib_exports__ChunkedStream as ChunkedStream, __lib_exports__FetchError as FetchError, __lib_exports__FileApi as FileApi, __lib_exports__FolderApi as FolderApi, __lib_exports__JSONApiResponse as JSONApiResponse, __lib_exports__JobApi as JobApi, __lib_exports__RequiredError as RequiredError, __lib_exports__ResponseError as ResponseError, __lib_exports__UploadApi as UploadApi, __lib_exports__UploadManager as UploadManager, __lib_exports__VoidApiResponse as VoidApiResponse, __lib_exports__querystring as querystring };
2424
+ export { __lib_exports__BASE_PATH as BASE_PATH, __lib_exports__BaseAPI as BaseAPI, __lib_exports__BinaryResult as BinaryResult, __lib_exports__BytescaleApiError as BytescaleApiError, __lib_exports__CancelledError as CancelledError, __lib_exports__FileApi as FileApi, __lib_exports__FolderApi as FolderApi, __lib_exports__JSONApiResponse as JSONApiResponse, __lib_exports__JobApi as JobApi, __lib_exports__UploadApi as UploadApi, __lib_exports__UploadManager as UploadManager, __lib_exports__VoidApiResponse as VoidApiResponse, __lib_exports__querystring as querystring };