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