@bytescale/sdk 3.0.0-alpha.8 → 3.1.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 (30) hide show
  1. package/README.md +388 -48
  2. package/dist/browser/cjs/main.js +705 -566
  3. package/dist/node/cjs/main.js +622 -240
  4. package/dist/node/esm/main.mjs +622 -240
  5. package/dist/types/index.d.ts +1 -1
  6. package/dist/types/private/AuthSessionState.d.ts +25 -8
  7. package/dist/types/private/EnvChecker.d.ts +1 -1
  8. package/dist/types/private/Mutex.d.ts +1 -1
  9. package/dist/types/private/StreamUtils.d.ts +1 -0
  10. package/dist/types/private/UploadManagerBase.d.ts +6 -1
  11. package/dist/types/private/UploadManagerBrowserWorkerBase.d.ts +19 -0
  12. package/dist/types/private/UploadManagerFetchUtils.d.ts +8 -0
  13. package/dist/types/private/model/AuthManagerInterface.d.ts +22 -5
  14. package/dist/types/private/model/AuthSession.d.ts +2 -2
  15. package/dist/types/private/model/OnPartProgress.d.ts +1 -1
  16. package/dist/types/private/model/UploadSourceProcessed.d.ts +6 -1
  17. package/dist/types/public/browser/AuthManagerBrowser.d.ts +11 -6
  18. package/dist/types/public/browser/UploadManagerBrowser.d.ts +3 -12
  19. package/dist/types/public/node/AuthManagerNode.d.ts +8 -3
  20. package/dist/types/public/shared/CommonTypes.d.ts +0 -1
  21. package/dist/types/public/shared/UrlBuilder.d.ts +10 -12
  22. package/dist/types/public/shared/UrlBuilderTypes.d.ts +0 -6
  23. package/dist/types/public/shared/generated/runtime.d.ts +7 -5
  24. package/dist/types/public/worker/UploadManagerWorker.d.ts +8 -0
  25. package/dist/types/public/worker/index.d.ts +2 -0
  26. package/dist/worker/cjs/main.js +2578 -0
  27. package/dist/worker/esm/main.mjs +2578 -0
  28. package/package.json +7 -4
  29. package/tests/UploadManager.test.ts +0 -7
  30. package/tests/UrlBuilder.test.ts +33 -27
@@ -1,25 +1,3 @@
1
- // ----------------------------------------
2
- // POLYFILL GUIDE:
3
- // ----------------------------------------
4
- //
5
- // "buffer" & "stream" are not required for browser environments.
6
- //
7
- // They are only used when the code detects it's running in Node.js (at runtime).
8
- //
9
- // You may polyfill them with empty objects (for browser environments):
10
- //
11
- // ----------------------------------------
12
- // Webpack:
13
- // {
14
- // resolve: {
15
- // fallback: {
16
- // buffer: false,
17
- // stream: false
18
- // }
19
- // }
20
- // }
21
- // ----------------------------------------
22
- //
23
1
  /******/ (function() { // webpackBootstrap
24
2
  /******/ "use strict";
25
3
  /******/ // The require scope
@@ -80,16 +58,332 @@ __lib_require__.d(__lib_exports__, {
80
58
  "querystring": function() { return /* reexport */ querystring; }
81
59
  });
82
60
 
83
- ;// CONCATENATED MODULE: ./src/private/AuthSessionState.ts
61
+ ;// CONCATENATED MODULE: ./src/private/Mutex.ts
84
62
  function _typeof(obj) { "@babel/helpers - typeof"; return _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; }, _typeof(obj); }
63
+ function _call(body, then, direct) {
64
+ if (direct) {
65
+ return then ? then(body()) : body();
66
+ }
67
+ try {
68
+ var result = Promise.resolve(body());
69
+ return then ? result.then(then) : result;
70
+ } catch (e) {
71
+ return Promise.reject(e);
72
+ }
73
+ }
74
+ function _rethrow(thrown, value) {
75
+ if (thrown) throw value;
76
+ return value;
77
+ }
78
+ function _finallyRethrows(body, finalizer) {
79
+ try {
80
+ var result = body();
81
+ } catch (e) {
82
+ return finalizer(true, e);
83
+ }
84
+ if (result && result.then) {
85
+ return result.then(finalizer.bind(null, false), finalizer.bind(null, true));
86
+ }
87
+ return finalizer(false, result);
88
+ }
89
+ function _await(value, then, direct) {
90
+ if (direct) {
91
+ return then ? then(value) : value;
92
+ }
93
+ if (!value || !value.then) {
94
+ value = Promise.resolve(value);
95
+ }
96
+ return then ? value.then(then) : value;
97
+ }
98
+ function _empty() {}
99
+ function _awaitIgnored(value, direct) {
100
+ if (!direct) {
101
+ return value && value.then ? value.then(_empty) : Promise.resolve();
102
+ }
103
+ }
104
+ function _settle(pact, state, value) {
105
+ if (!pact.s) {
106
+ if (value instanceof _Pact) {
107
+ if (value.s) {
108
+ if (state & 1) {
109
+ state = value.s;
110
+ }
111
+ value = value.v;
112
+ } else {
113
+ value.o = _settle.bind(null, pact, state);
114
+ return;
115
+ }
116
+ }
117
+ if (value && value.then) {
118
+ value.then(_settle.bind(null, pact, state), _settle.bind(null, pact, 2));
119
+ return;
120
+ }
121
+ pact.s = state;
122
+ pact.v = value;
123
+ var observer = pact.o;
124
+ if (observer) {
125
+ observer(pact);
126
+ }
127
+ }
128
+ }
129
+ var _Pact = /*#__PURE__*/function () {
130
+ function _Pact() {}
131
+ _Pact.prototype.then = function (onFulfilled, onRejected) {
132
+ var result = new _Pact();
133
+ var state = this.s;
134
+ if (state) {
135
+ var callback = state & 1 ? onFulfilled : onRejected;
136
+ if (callback) {
137
+ try {
138
+ _settle(result, 1, callback(this.v));
139
+ } catch (e) {
140
+ _settle(result, 2, e);
141
+ }
142
+ return result;
143
+ } else {
144
+ return this;
145
+ }
146
+ }
147
+ this.o = function (_this) {
148
+ try {
149
+ var value = _this.v;
150
+ if (_this.s & 1) {
151
+ _settle(result, 1, onFulfilled ? onFulfilled(value) : value);
152
+ } else if (onRejected) {
153
+ _settle(result, 1, onRejected(value));
154
+ } else {
155
+ _settle(result, 2, value);
156
+ }
157
+ } catch (e) {
158
+ _settle(result, 2, e);
159
+ }
160
+ };
161
+ return result;
162
+ };
163
+ return _Pact;
164
+ }();
165
+ function _isSettledPact(thenable) {
166
+ return thenable instanceof _Pact && thenable.s & 1;
167
+ }
168
+ function _for(test, update, body) {
169
+ var stage;
170
+ for (;;) {
171
+ var shouldContinue = test();
172
+ if (_isSettledPact(shouldContinue)) {
173
+ shouldContinue = shouldContinue.v;
174
+ }
175
+ if (!shouldContinue) {
176
+ return result;
177
+ }
178
+ if (shouldContinue.then) {
179
+ stage = 0;
180
+ break;
181
+ }
182
+ var result = body();
183
+ if (result && result.then) {
184
+ if (_isSettledPact(result)) {
185
+ result = result.s;
186
+ } else {
187
+ stage = 1;
188
+ break;
189
+ }
190
+ }
191
+ if (update) {
192
+ var updateValue = update();
193
+ if (updateValue && updateValue.then && !_isSettledPact(updateValue)) {
194
+ stage = 2;
195
+ break;
196
+ }
197
+ }
198
+ }
199
+ var pact = new _Pact();
200
+ var reject = _settle.bind(null, pact, 2);
201
+ (stage === 0 ? shouldContinue.then(_resumeAfterTest) : stage === 1 ? result.then(_resumeAfterBody) : updateValue.then(_resumeAfterUpdate)).then(void 0, reject);
202
+ return pact;
203
+ function _resumeAfterBody(value) {
204
+ result = value;
205
+ do {
206
+ if (update) {
207
+ updateValue = update();
208
+ if (updateValue && updateValue.then && !_isSettledPact(updateValue)) {
209
+ updateValue.then(_resumeAfterUpdate).then(void 0, reject);
210
+ return;
211
+ }
212
+ }
213
+ shouldContinue = test();
214
+ if (!shouldContinue || _isSettledPact(shouldContinue) && !shouldContinue.v) {
215
+ _settle(pact, 1, result);
216
+ return;
217
+ }
218
+ if (shouldContinue.then) {
219
+ shouldContinue.then(_resumeAfterTest).then(void 0, reject);
220
+ return;
221
+ }
222
+ result = body();
223
+ if (_isSettledPact(result)) {
224
+ result = result.v;
225
+ }
226
+ } while (!result || !result.then);
227
+ result.then(_resumeAfterBody).then(void 0, reject);
228
+ }
229
+ function _resumeAfterTest(shouldContinue) {
230
+ if (shouldContinue) {
231
+ result = body();
232
+ if (result && result.then) {
233
+ result.then(_resumeAfterBody).then(void 0, reject);
234
+ } else {
235
+ _resumeAfterBody(result);
236
+ }
237
+ } else {
238
+ _settle(pact, 1, result);
239
+ }
240
+ }
241
+ function _resumeAfterUpdate() {
242
+ if (shouldContinue = test()) {
243
+ if (shouldContinue.then) {
244
+ shouldContinue.then(_resumeAfterTest).then(void 0, reject);
245
+ } else {
246
+ _resumeAfterTest(shouldContinue);
247
+ }
248
+ } else {
249
+ _settle(pact, 1, result);
250
+ }
251
+ }
252
+ }
253
+ function _continue(value, then) {
254
+ return value && value.then ? value.then(then) : then(value);
255
+ }
256
+ function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
85
257
  function _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, _toPropertyKey(descriptor.key), descriptor); } }
86
258
  function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
87
259
  function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
88
260
  function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
89
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
90
- var AuthSessionState = /*#__PURE__*/_createClass(function AuthSessionState() {
91
- _classCallCheck(this, AuthSessionState);
92
- });
261
+ /**
262
+ * A lightweight mutex. (Other libraries contain too many features and we want to keep size down).
263
+ *
264
+ * Characteristics:
265
+ * - Non-reentrant.
266
+ * - Unfair. (Multiple callers awaiting 'acquire' will be granted the mutex in no order.)
267
+ * - When calling `safe` consecutively with no 'awaits' in-between, the current context will synchronously acquire
268
+ * the mutex every time.
269
+ */
270
+ var Mutex = /*#__PURE__*/function () {
271
+ function Mutex() {
272
+ _classCallCheck(this, Mutex);
273
+ this.mutex = undefined;
274
+ this.resolver = undefined;
275
+ }
276
+ _createClass(Mutex, [{
277
+ key: "safe",
278
+ value: function safe(callback) {
279
+ try {
280
+ var _this2 = this;
281
+ return _await(_this2.acquire(), function () {
282
+ return _finallyRethrows(callback, function (_wasThrown, _result) {
283
+ _this2.release();
284
+ return _rethrow(_wasThrown, _result);
285
+ });
286
+ });
287
+ } catch (e) {
288
+ return Promise.reject(e);
289
+ }
290
+ }
291
+ }, {
292
+ key: "acquire",
293
+ value: function acquire() {
294
+ try {
295
+ var _this4 = this;
296
+ // Loop necessary for when multiple calls are made to 'acquire' before a 'release' is called, else the call to
297
+ // 'release' will resume every caller currently waiting on 'acquire'.
298
+ return _continue(_for(function () {
299
+ return _this4.mutex !== undefined;
300
+ }, void 0, function () {
301
+ return _awaitIgnored(_this4.mutex);
302
+ }), function () {
303
+ _this4.mutex = new Promise(function (resolve) {
304
+ _this4.resolver = resolve;
305
+ });
306
+ });
307
+ } catch (e) {
308
+ return Promise.reject(e);
309
+ }
310
+ }
311
+ }, {
312
+ key: "release",
313
+ value: function release() {
314
+ if (this.resolver === undefined) {
315
+ throw new Error("Unable to release mutex: already released.");
316
+ }
317
+ this.resolver();
318
+ this.resolver = undefined;
319
+ this.mutex = undefined;
320
+ }
321
+ }]);
322
+ return Mutex;
323
+ }();
324
+ ;// CONCATENATED MODULE: ./src/private/AuthSessionState.ts
325
+ function AuthSessionState_typeof(obj) { "@babel/helpers - typeof"; return AuthSessionState_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; }, AuthSessionState_typeof(obj); }
326
+ function AuthSessionState_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
327
+ function AuthSessionState_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, AuthSessionState_toPropertyKey(descriptor.key), descriptor); } }
328
+ function AuthSessionState_createClass(Constructor, protoProps, staticProps) { if (protoProps) AuthSessionState_defineProperties(Constructor.prototype, protoProps); if (staticProps) AuthSessionState_defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
329
+ function AuthSessionState_toPropertyKey(arg) { var key = AuthSessionState_toPrimitive(arg, "string"); return AuthSessionState_typeof(key) === "symbol" ? key : String(key); }
330
+ function AuthSessionState_toPrimitive(input, hint) { if (AuthSessionState_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (AuthSessionState_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
331
+
332
+ /**
333
+ * Maintains a global session state, even across package versions.
334
+ *
335
+ * This is to allow users to start auth sessions via the Bytescale JavaScript SDK, where due to versioning or other
336
+ * bundling issues, the Bytescale Upload Widget has been bundled with a different Bytescale JavaScript SDK. In this
337
+ * scenario, the user wouldn't be able to start an auth session with the Bytescale Upload Widget. Therefore, we use
338
+ * global state (i.e. on the window) to ensure the session state can be shared between the user's instance of the
339
+ * Bytescale JavaScript SDK and the Upload Widget's version of the Bytescale JavaScript SDK.
340
+ *
341
+ * Users also frequently have problems caused by them not keeping track of *Api and *Manager instances correctly, so
342
+ * making this global prevents a lot of common mistakes.
343
+ */
344
+ var AuthSessionState = /*#__PURE__*/function () {
345
+ function AuthSessionState() {
346
+ AuthSessionState_classCallCheck(this, AuthSessionState);
347
+ }
348
+ AuthSessionState_createClass(AuthSessionState, null, [{
349
+ key: "getMutex",
350
+ value:
351
+ /**
352
+ * Called in the browser only.
353
+ */
354
+ function getMutex() {
355
+ var key = AuthSessionState.mutexKey;
356
+ var mutex = window[key];
357
+ if (mutex === undefined) {
358
+ mutex = new Mutex();
359
+ window[key] = mutex;
360
+ }
361
+ return mutex;
362
+ }
363
+ /**
364
+ * Called in the browser only.
365
+ */
366
+ }, {
367
+ key: "setSession",
368
+ value: function setSession(session) {
369
+ window[AuthSessionState.stateKey] = session;
370
+ }
371
+ /**
372
+ * Called in the browser and in Node.js (so we check the env before calling env-specific code).
373
+ */
374
+ }, {
375
+ key: "getSession",
376
+ value: function getSession() {
377
+ if (typeof window === "undefined") {
378
+ return undefined;
379
+ }
380
+ return window[AuthSessionState.stateKey];
381
+ }
382
+ }]);
383
+ return AuthSessionState;
384
+ }();
385
+ AuthSessionState.stateKey = "BytescaleSessionState";
386
+ AuthSessionState.mutexKey = "BytescaleSessionStateMutex";
93
387
  ;// CONCATENATED MODULE: ./src/public/shared/generated/runtime.ts
94
388
  function runtime_typeof(obj) { "@babel/helpers - typeof"; return runtime_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; }, runtime_typeof(obj); }
95
389
  function _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) _setPrototypeOf(subClass, superClass); }
@@ -113,8 +407,8 @@ function _catch(body, recover) {
113
407
  }
114
408
  return result;
115
409
  }
116
- function _empty() {}
117
- function _continue(value, then) {
410
+ function runtime_empty() {}
411
+ function runtime_continue(value, then) {
118
412
  return value && value.then ? value.then(then) : then(value);
119
413
  }
120
414
  function _invoke(body, then) {
@@ -125,7 +419,7 @@ function _invoke(body, then) {
125
419
  return then(result);
126
420
  }
127
421
  function _defineProperty(obj, key, value) { key = runtime_toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
128
- function _await(value, then, direct) {
422
+ function runtime_await(value, then, direct) {
129
423
  if (direct) {
130
424
  return then ? then(value) : value;
131
425
  }
@@ -213,72 +507,30 @@ var BaseAPI = /*#__PURE__*/function () {
213
507
  this.config = config;
214
508
  BytescaleApiClientConfigUtils.validate(config);
215
509
  }
510
+ /**
511
+ * Returns a successful response (2**) else throws an error.
512
+ */
216
513
  runtime_createClass(BaseAPI, [{
217
514
  key: "request",
218
515
  value: function request(context, initOverrides, baseUrlOverride) {
219
516
  try {
220
517
  var _this2 = this;
221
- var _a, _b;
518
+ var _a;
222
519
  var apiKey = _this2.config.apiKey;
223
520
  context.headers["Authorization"] = "Bearer ".concat(apiKey); // authorization-header authentication
224
- if (((_a = AuthSessionState.session) === null || _a === void 0 ? void 0 : _a.accessToken) !== undefined) {
225
- context.headers["Authorization-Token"] = AuthSessionState.session.accessToken;
521
+ var session = AuthSessionState.getSession();
522
+ if ((session === null || session === void 0 ? void 0 : session.accessToken) !== undefined) {
523
+ context.headers["Authorization-Token"] = session.accessToken;
226
524
  }
227
525
  // Key: any possible value for 'baseUrlOverride'
228
526
  // Value: user-overridden value for that base URL from the config.
229
527
  var nonDefaultBasePaths = _defineProperty({}, BytescaleApiClientConfigUtils.defaultCdnUrl, BytescaleApiClientConfigUtils.getCdnUrl(_this2.config));
230
- return _await(_this2.createFetchParams(context, initOverrides, baseUrlOverride === undefined ? undefined : (_b = nonDefaultBasePaths[baseUrlOverride]) !== null && _b !== void 0 ? _b : baseUrlOverride), function (_ref) {
528
+ return runtime_await(_this2.createFetchParams(context, initOverrides, baseUrlOverride === undefined ? undefined : (_a = nonDefaultBasePaths[baseUrlOverride]) !== null && _a !== void 0 ? _a : baseUrlOverride), function (_ref) {
231
529
  var url = _ref.url,
232
530
  init = _ref.init;
233
- return _this2.doFetch(url, init, true);
234
- });
235
- } catch (e) {
236
- return Promise.reject(e);
237
- }
238
- }
239
- /**
240
- * Returns a successful response (2**) else throws an error.
241
- */
242
- }, {
243
- key: "doFetch",
244
- value: function doFetch(url, init, isBytescaleApi) {
245
- try {
246
- var _exit3 = false;
247
- var _this4 = this;
248
- var _a, _b;
249
- var response;
250
- return _continue(_catch(function () {
251
- return _await(BytescaleApiClientConfigUtils.getFetchApi(_this4.config)(url, init), function (_BytescaleApiClientCo) {
252
- response = _BytescaleApiClientCo;
253
- });
254
- }, function (e) {
255
- // Network-level errors, CORS errors, or HTTP-level errors from intermediary services (e.g. AWS or the user's own infrastructure/proxies).
256
- // HTTP-level errors from external services (e.g. AWS or the user's own proxy) will appear as CORS errors as their response headers won't include the appropriate CORS values.
257
- throw new Error(isBytescaleApi ? "Unable to resolve the Bytescale API: ".concat(e.message, " If the problem persists, and your network connection is OK, then please contact support@bytescale.com and provide: (a) time of failed request in UTC (b) screenshot of failed network response header + body (c) screenshot of failed network request header + body (d) browser and OS version.") : "Unable to resolve URL (".concat(url, "): ").concat(e.message));
258
- }), function (_result) {
259
- var _exit2 = false;
260
- if (_exit3) return _result;
261
- return response.status >= 200 && response.status < 300 ? response : _invoke(function () {
262
- if (isBytescaleApi) {
263
- var jsonError = undefined;
264
- return _continue(_catch(function () {
265
- return _await(response.json(), function (_response$json) {
266
- jsonError = _response$json;
267
- });
268
- }, _empty), function () {
269
- if (typeof ((_a = jsonError === null || jsonError === void 0 ? void 0 : jsonError.error) === null || _a === void 0 ? void 0 : _a.code) === "string") {
270
- throw new BytescaleApiError(jsonError);
271
- }
272
- // HTTP-level errors from intermediary services (e.g. AWS or the user's own infrastructure/proxies). On the browser,
273
- // this error is unlikely to be triggered since these errors will masqurade as CORS errors (see above) but in Node.js
274
- // this error will appear from any intermediary service failure.
275
- throw new Error("Unable to connect to the Bytescale API (".concat(response.status, "): please try again."));
276
- });
277
- }
278
- }, function (_result2) {
279
- if (_exit2) return _result2;
280
- throw new Error("Failure status code (".concat(response.status, ") received for request: ").concat((_b = init.method) !== null && _b !== void 0 ? _b : "GET", " ").concat(url));
281
- });
531
+ return BaseAPI.fetch(url, init, Object.assign(Object.assign({}, _this2.config), {
532
+ isBytescaleApi: true
533
+ }));
282
534
  });
283
535
  } catch (e) {
284
536
  return Promise.reject(e);
@@ -301,23 +553,23 @@ var BaseAPI = /*#__PURE__*/function () {
301
553
  key: "createFetchParams",
302
554
  value: function createFetchParams(context, initOverrides, baseUrlOverride) {
303
555
  try {
304
- var _this6 = this;
305
- var url = (baseUrlOverride !== null && baseUrlOverride !== void 0 ? baseUrlOverride : BytescaleApiClientConfigUtils.getApiUrl(_this6.config)) + context.path;
556
+ var _this4 = this;
557
+ var url = (baseUrlOverride !== null && baseUrlOverride !== void 0 ? baseUrlOverride : BytescaleApiClientConfigUtils.getApiUrl(_this4.config)) + context.path;
306
558
  if (context.query !== undefined && Object.keys(context.query).length !== 0) {
307
559
  // only add the querystring to the URL if there are query parameters.
308
560
  // this is done to avoid urls ending with a "?" character which buggy webservers
309
561
  // do not handle correctly sometimes.
310
562
  url += "?" + querystring(context.query);
311
563
  }
312
- var configHeaders = _this6.config.headers;
564
+ var configHeaders = _this4.config.headers;
313
565
  var _Object$assign3 = Object.assign({}, context.headers);
314
- return _await(configHeaders === undefined ? {} : configHeaders(), function (_configHeaders) {
566
+ return runtime_await(configHeaders === undefined ? {} : configHeaders(), function (_configHeaders) {
315
567
  var headers = Object.assign(_Object$assign3, _configHeaders);
316
568
  Object.keys(headers).forEach(function (key) {
317
569
  return headers[key] === undefined ? delete headers[key] : {};
318
570
  });
319
571
  var initOverrideFn = typeof initOverrides === "function" ? initOverrides : function () {
320
- return _await(initOverrides);
572
+ return runtime_await(initOverrides);
321
573
  };
322
574
  var initParams = {
323
575
  method: context.method,
@@ -325,7 +577,7 @@ var BaseAPI = /*#__PURE__*/function () {
325
577
  body: context.body
326
578
  };
327
579
  var _Object$assign2 = Object.assign({}, initParams);
328
- return _await(initOverrideFn({
580
+ return runtime_await(initOverrideFn({
329
581
  init: initParams,
330
582
  context: context
331
583
  }), function (_initOverrideFn) {
@@ -343,6 +595,59 @@ var BaseAPI = /*#__PURE__*/function () {
343
595
  return Promise.reject(e);
344
596
  }
345
597
  }
598
+ }], [{
599
+ key: "fetch",
600
+ value: function fetch(url, init, config) {
601
+ try {
602
+ var _exit3 = false;
603
+ var _a, _b;
604
+ var response;
605
+ return runtime_continue(_catch(function () {
606
+ return runtime_await(BytescaleApiClientConfigUtils.getFetchApi(config)(url, Object.assign(Object.assign({}, init), {
607
+ // This is specifically added to cater for Next.js's Fetch implementation, which caches POST requests...
608
+ //
609
+ // "fetch requests that use the POST method are also automatically cached."
610
+ // - https://nextjs.org/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating#caching-data
611
+ //
612
+ // However, this is probably a good idea, even for all GET requests, as if the user is refreshing a JWT
613
+ // or downloading a file via 'FileApi.downloadFile', then they'll likely want the latest.
614
+ cache: "no-store"
615
+ })), function (_BytescaleApiClientCo) {
616
+ response = _BytescaleApiClientCo;
617
+ });
618
+ }, function (e) {
619
+ // Network-level errors, CORS errors, or HTTP-level errors from intermediary services (e.g. AWS or the user's own infrastructure/proxies).
620
+ // HTTP-level errors from external services (e.g. AWS or the user's own proxy) will appear as CORS errors as their response headers won't include the appropriate CORS values.
621
+ throw new Error(config.isBytescaleApi ? "Unable to resolve the Bytescale API: ".concat(e.message, " If the problem persists, and your network connection is OK, then please contact support@bytescale.com and provide: (a) time of failed request in UTC (b) screenshot of failed network response header + body (c) screenshot of failed network request header + body (d) browser and OS version.") : "Unable to resolve URL (".concat(url, "): ").concat(e.message));
622
+ }), function (_result) {
623
+ var _exit2 = false;
624
+ if (_exit3) return _result;
625
+ return response.status >= 200 && response.status < 300 ? response : _invoke(function () {
626
+ if (config.isBytescaleApi) {
627
+ var jsonError = undefined;
628
+ return runtime_continue(_catch(function () {
629
+ return runtime_await(response.json(), function (_response$json) {
630
+ jsonError = _response$json;
631
+ });
632
+ }, runtime_empty), function () {
633
+ if (typeof ((_a = jsonError === null || jsonError === void 0 ? void 0 : jsonError.error) === null || _a === void 0 ? void 0 : _a.code) === "string") {
634
+ throw new BytescaleApiError(jsonError);
635
+ }
636
+ // HTTP-level errors from intermediary services (e.g. AWS or the user's own infrastructure/proxies). On the browser,
637
+ // this error is unlikely to be triggered since these errors will masqurade as CORS errors (see above) but in Node.js
638
+ // this error will appear from any intermediary service failure.
639
+ throw new Error("Unable to connect to the Bytescale API (".concat(response.status, "): please try again."));
640
+ });
641
+ }
642
+ }, function (_result2) {
643
+ if (_exit2) return _result2;
644
+ throw new Error("Failure status code (".concat(response.status, ") received for request: ").concat((_b = init.method) !== null && _b !== void 0 ? _b : "GET", " ").concat(url));
645
+ });
646
+ });
647
+ } catch (e) {
648
+ return Promise.reject(e);
649
+ }
650
+ }
346
651
  }]);
347
652
  return BaseAPI;
348
653
  }();
@@ -350,11 +655,11 @@ var CancelledError = /*#__PURE__*/function (_Error) {
350
655
  _inherits(CancelledError, _Error);
351
656
  var _super = _createSuper(CancelledError);
352
657
  function CancelledError() {
353
- var _this7;
658
+ var _this5;
354
659
  runtime_classCallCheck(this, CancelledError);
355
- _this7 = _super.call(this, "Operation cancelled by caller.");
356
- _this7.name = "CancelledError";
357
- return _this7;
660
+ _this5 = _super.call(this, "Operation cancelled by caller.");
661
+ _this5.name = "CancelledError";
662
+ return _this5;
358
663
  }
359
664
  return runtime_createClass(CancelledError);
360
665
  }( /*#__PURE__*/_wrapNativeSuper(Error));
@@ -362,13 +667,13 @@ var BytescaleApiError = /*#__PURE__*/function (_Error2) {
362
667
  _inherits(BytescaleApiError, _Error2);
363
668
  var _super2 = _createSuper(BytescaleApiError);
364
669
  function BytescaleApiError(response) {
365
- var _this8;
670
+ var _this6;
366
671
  runtime_classCallCheck(this, BytescaleApiError);
367
- _this8 = _super2.call(this, response.error.message);
368
- _this8.name = "BytescaleApiError";
369
- _this8.errorCode = response.error.code;
370
- _this8.details = response.error.details;
371
- return _this8;
672
+ _this6 = _super2.call(this, response.error.message);
673
+ _this6.name = "BytescaleApiError";
674
+ _this6.errorCode = response.error.code;
675
+ _this6.details = response.error.details;
676
+ return _this6;
372
677
  }
373
678
  return runtime_createClass(BytescaleApiError);
374
679
  }( /*#__PURE__*/_wrapNativeSuper(Error));
@@ -394,8 +699,8 @@ var JSONApiResponse = /*#__PURE__*/function () {
394
699
  key: "value",
395
700
  value: function value() {
396
701
  try {
397
- var _this10 = this;
398
- return _await(_this10.raw.json());
702
+ var _this8 = this;
703
+ return runtime_await(_this8.raw.json());
399
704
  } catch (e) {
400
705
  return Promise.reject(e);
401
706
  }
@@ -411,7 +716,7 @@ var VoidApiResponse = /*#__PURE__*/function () {
411
716
  runtime_createClass(VoidApiResponse, [{
412
717
  key: "value",
413
718
  value: function value() {
414
- return _await(undefined);
719
+ return runtime_await(undefined);
415
720
  }
416
721
  }]);
417
722
  return VoidApiResponse;
@@ -436,8 +741,8 @@ var BinaryResult = /*#__PURE__*/function () {
436
741
  key: "text",
437
742
  value: function text() {
438
743
  try {
439
- var _this12 = this;
440
- return _await(_this12.raw.text());
744
+ var _this10 = this;
745
+ return runtime_await(_this10.raw.text());
441
746
  } catch (e) {
442
747
  return Promise.reject(e);
443
748
  }
@@ -446,8 +751,8 @@ var BinaryResult = /*#__PURE__*/function () {
446
751
  key: "blob",
447
752
  value: function blob() {
448
753
  try {
449
- var _this14 = this;
450
- return _await(_this14.raw.blob());
754
+ var _this12 = this;
755
+ return runtime_await(_this12.raw.blob());
451
756
  } catch (e) {
452
757
  return Promise.reject(e);
453
758
  }
@@ -456,8 +761,8 @@ var BinaryResult = /*#__PURE__*/function () {
456
761
  key: "json",
457
762
  value: function json() {
458
763
  try {
459
- var _this16 = this;
460
- return _await(_this16.raw.json());
764
+ var _this14 = this;
765
+ return runtime_await(_this14.raw.json());
461
766
  } catch (e) {
462
767
  return Promise.reject(e);
463
768
  }
@@ -1382,33 +1687,32 @@ function UrlBuilder_toPrimitive(input, hint) { if (UrlBuilder_typeof(input) !==
1382
1687
 
1383
1688
 
1384
1689
  var UrlBuilder = /*#__PURE__*/function () {
1385
- function UrlBuilder(config) {
1690
+ function UrlBuilder() {
1386
1691
  UrlBuilder_classCallCheck(this, UrlBuilder);
1387
- var _a;
1388
- this.cdnUrl = (_a = config === null || config === void 0 ? void 0 : config.cdnUrl) !== null && _a !== void 0 ? _a : BytescaleApiClientConfigUtils.defaultCdnUrl;
1389
1692
  }
1390
- /**
1391
- * Builds a URL to either a raw file or a transformed file.
1392
- *
1393
- * Example 1) Getting a publicly-accessible raw file URL:
1394
- *
1395
- * new UrlBuilder().url({ accountId: "1234abc", filePath: "/example.jpg" })
1396
- *
1397
- * Example 2) Getting a publicly-accessible image URL, resized to 500x500:
1398
- *
1399
- * new UrlBuilder().url({ accountId: "1234abc", filePath: "/example.jpg", options: { transformation: { type: "image", params: { w: 500, h: 500, fit: "crop" } } } })
1400
- *
1401
- * Example 3) Getting a privately-accessible image URL, resized to 500x500 (requires 'AuthManager.beginAuthSession' to be called before accessing the URL):
1402
- *
1403
- * new UrlBuilder().url({ accountId: "1234abc", filePath: "/example.jpg", options: { transformation: { type: "image", params: { w: 500, h: 500, fit: "crop" } }, auth: true } })
1404
- *
1405
- * Example 4) Getting a publicly-accessible image URL, resized using a transformation preset called "thumbnail" that was created manually in the Bytescale Dashboard:
1406
- *
1407
- * new UrlBuilder().url({ accountId: "1234abc", filePath: "/example.jpg", options: { transformation: { type: "preset", preset: "thumbnail" } } })
1408
- */
1409
- UrlBuilder_createClass(UrlBuilder, [{
1693
+ UrlBuilder_createClass(UrlBuilder, null, [{
1410
1694
  key: "url",
1411
- value: function url(params) {
1695
+ value:
1696
+ /**
1697
+ * Builds a URL to either a raw file or a transformed file.
1698
+ *
1699
+ * Example 1) Getting a publicly-accessible raw file URL:
1700
+ *
1701
+ * new UrlBuilder().url({ accountId: "1234abc", filePath: "/example.jpg" })
1702
+ *
1703
+ * Example 2) Getting a publicly-accessible image URL, resized to 500x500:
1704
+ *
1705
+ * new UrlBuilder().url({ accountId: "1234abc", filePath: "/example.jpg", options: { transformation: { type: "image", params: { w: 500, h: 500, fit: "crop" } } } })
1706
+ *
1707
+ * Example 3) Getting a privately-accessible image URL, resized to 500x500 (requires 'AuthManager.beginAuthSession' to be called before accessing the URL):
1708
+ *
1709
+ * new UrlBuilder().url({ accountId: "1234abc", filePath: "/example.jpg", options: { transformation: { type: "image", params: { w: 500, h: 500, fit: "crop" } }, auth: true } })
1710
+ *
1711
+ * Example 4) Getting a publicly-accessible image URL, resized using a transformation preset called "thumbnail" that was created manually in the Bytescale Dashboard:
1712
+ *
1713
+ * new UrlBuilder().url({ accountId: "1234abc", filePath: "/example.jpg", options: { transformation: { type: "preset", preset: "thumbnail" } } })
1714
+ */
1715
+ function url(params) {
1412
1716
  var _a;
1413
1717
  return ((_a = params.options) === null || _a === void 0 ? void 0 : _a.transformation) === undefined ? this.raw(params) : this.transformation(params, params.options);
1414
1718
  }
@@ -1434,7 +1738,8 @@ var UrlBuilder = /*#__PURE__*/function () {
1434
1738
  }, {
1435
1739
  key: "getBaseUrl",
1436
1740
  value: function getBaseUrl(params, prefix) {
1437
- return "".concat(this.cdnUrl, "/").concat(params.accountId, "/").concat(prefix).concat(params.filePath);
1741
+ var cdnUrl = BytescaleApiClientConfigUtils.defaultCdnUrl;
1742
+ return "".concat(cdnUrl, "/").concat(params.accountId, "/").concat(prefix).concat(params.filePath);
1438
1743
  }
1439
1744
  }, {
1440
1745
  key: "getCommonTransformationQueryParams",
@@ -1529,21 +1834,21 @@ function _invokeIgnored(body) {
1529
1834
  return result.then(UploadManagerBase_empty);
1530
1835
  }
1531
1836
  }
1532
- function _settle(pact, state, value) {
1837
+ function UploadManagerBase_settle(pact, state, value) {
1533
1838
  if (!pact.s) {
1534
- if (value instanceof _Pact) {
1839
+ if (value instanceof UploadManagerBase_Pact) {
1535
1840
  if (value.s) {
1536
1841
  if (state & 1) {
1537
1842
  state = value.s;
1538
1843
  }
1539
1844
  value = value.v;
1540
1845
  } else {
1541
- value.o = _settle.bind(null, pact, state);
1846
+ value.o = UploadManagerBase_settle.bind(null, pact, state);
1542
1847
  return;
1543
1848
  }
1544
1849
  }
1545
1850
  if (value && value.then) {
1546
- value.then(_settle.bind(null, pact, state), _settle.bind(null, pact, 2));
1851
+ value.then(UploadManagerBase_settle.bind(null, pact, state), UploadManagerBase_settle.bind(null, pact, 2));
1547
1852
  return;
1548
1853
  }
1549
1854
  pact.s = state;
@@ -1554,7 +1859,7 @@ function _settle(pact, state, value) {
1554
1859
  }
1555
1860
  }
1556
1861
  }
1557
- var _Pact = /*#__PURE__*/function () {
1862
+ var UploadManagerBase_Pact = /*#__PURE__*/function () {
1558
1863
  function _Pact() {}
1559
1864
  _Pact.prototype.then = function (onFulfilled, onRejected) {
1560
1865
  var result = new _Pact();
@@ -1563,9 +1868,9 @@ var _Pact = /*#__PURE__*/function () {
1563
1868
  var callback = state & 1 ? onFulfilled : onRejected;
1564
1869
  if (callback) {
1565
1870
  try {
1566
- _settle(result, 1, callback(this.v));
1871
+ UploadManagerBase_settle(result, 1, callback(this.v));
1567
1872
  } catch (e) {
1568
- _settle(result, 2, e);
1873
+ UploadManagerBase_settle(result, 2, e);
1569
1874
  }
1570
1875
  return result;
1571
1876
  } else {
@@ -1576,28 +1881,28 @@ var _Pact = /*#__PURE__*/function () {
1576
1881
  try {
1577
1882
  var value = _this.v;
1578
1883
  if (_this.s & 1) {
1579
- _settle(result, 1, onFulfilled ? onFulfilled(value) : value);
1884
+ UploadManagerBase_settle(result, 1, onFulfilled ? onFulfilled(value) : value);
1580
1885
  } else if (onRejected) {
1581
- _settle(result, 1, onRejected(value));
1886
+ UploadManagerBase_settle(result, 1, onRejected(value));
1582
1887
  } else {
1583
- _settle(result, 2, value);
1888
+ UploadManagerBase_settle(result, 2, value);
1584
1889
  }
1585
1890
  } catch (e) {
1586
- _settle(result, 2, e);
1891
+ UploadManagerBase_settle(result, 2, e);
1587
1892
  }
1588
1893
  };
1589
1894
  return result;
1590
1895
  };
1591
1896
  return _Pact;
1592
1897
  }();
1593
- function _isSettledPact(thenable) {
1594
- return thenable instanceof _Pact && thenable.s & 1;
1898
+ function UploadManagerBase_isSettledPact(thenable) {
1899
+ return thenable instanceof UploadManagerBase_Pact && thenable.s & 1;
1595
1900
  }
1596
- function _for(test, update, body) {
1901
+ function UploadManagerBase_for(test, update, body) {
1597
1902
  var stage;
1598
1903
  for (;;) {
1599
1904
  var shouldContinue = test();
1600
- if (_isSettledPact(shouldContinue)) {
1905
+ if (UploadManagerBase_isSettledPact(shouldContinue)) {
1601
1906
  shouldContinue = shouldContinue.v;
1602
1907
  }
1603
1908
  if (!shouldContinue) {
@@ -1609,7 +1914,7 @@ function _for(test, update, body) {
1609
1914
  }
1610
1915
  var result = body();
1611
1916
  if (result && result.then) {
1612
- if (_isSettledPact(result)) {
1917
+ if (UploadManagerBase_isSettledPact(result)) {
1613
1918
  result = result.s;
1614
1919
  } else {
1615
1920
  stage = 1;
@@ -1618,14 +1923,14 @@ function _for(test, update, body) {
1618
1923
  }
1619
1924
  if (update) {
1620
1925
  var updateValue = update();
1621
- if (updateValue && updateValue.then && !_isSettledPact(updateValue)) {
1926
+ if (updateValue && updateValue.then && !UploadManagerBase_isSettledPact(updateValue)) {
1622
1927
  stage = 2;
1623
1928
  break;
1624
1929
  }
1625
1930
  }
1626
1931
  }
1627
- var pact = new _Pact();
1628
- var reject = _settle.bind(null, pact, 2);
1932
+ var pact = new UploadManagerBase_Pact();
1933
+ var reject = UploadManagerBase_settle.bind(null, pact, 2);
1629
1934
  (stage === 0 ? shouldContinue.then(_resumeAfterTest) : stage === 1 ? result.then(_resumeAfterBody) : updateValue.then(_resumeAfterUpdate)).then(void 0, reject);
1630
1935
  return pact;
1631
1936
  function _resumeAfterBody(value) {
@@ -1633,14 +1938,14 @@ function _for(test, update, body) {
1633
1938
  do {
1634
1939
  if (update) {
1635
1940
  updateValue = update();
1636
- if (updateValue && updateValue.then && !_isSettledPact(updateValue)) {
1941
+ if (updateValue && updateValue.then && !UploadManagerBase_isSettledPact(updateValue)) {
1637
1942
  updateValue.then(_resumeAfterUpdate).then(void 0, reject);
1638
1943
  return;
1639
1944
  }
1640
1945
  }
1641
1946
  shouldContinue = test();
1642
- if (!shouldContinue || _isSettledPact(shouldContinue) && !shouldContinue.v) {
1643
- _settle(pact, 1, result);
1947
+ if (!shouldContinue || UploadManagerBase_isSettledPact(shouldContinue) && !shouldContinue.v) {
1948
+ UploadManagerBase_settle(pact, 1, result);
1644
1949
  return;
1645
1950
  }
1646
1951
  if (shouldContinue.then) {
@@ -1648,7 +1953,7 @@ function _for(test, update, body) {
1648
1953
  return;
1649
1954
  }
1650
1955
  result = body();
1651
- if (_isSettledPact(result)) {
1956
+ if (UploadManagerBase_isSettledPact(result)) {
1652
1957
  result = result.v;
1653
1958
  }
1654
1959
  } while (!result || !result.then);
@@ -1663,7 +1968,7 @@ function _for(test, update, body) {
1663
1968
  _resumeAfterBody(result);
1664
1969
  }
1665
1970
  } else {
1666
- _settle(pact, 1, result);
1971
+ UploadManagerBase_settle(pact, 1, result);
1667
1972
  }
1668
1973
  }
1669
1974
  function _resumeAfterUpdate() {
@@ -1674,7 +1979,7 @@ function _for(test, update, body) {
1674
1979
  _resumeAfterTest(shouldContinue);
1675
1980
  }
1676
1981
  } else {
1677
- _settle(pact, 1, result);
1982
+ UploadManagerBase_settle(pact, 1, result);
1678
1983
  }
1679
1984
  }
1680
1985
  }
@@ -1690,7 +1995,7 @@ function UploadManagerBase_iterableToArray(iter) { if (typeof Symbol !== "undefi
1690
1995
  function UploadManagerBase_arrayWithoutHoles(arr) { if (Array.isArray(arr)) return UploadManagerBase_arrayLikeToArray(arr); }
1691
1996
  function UploadManagerBase_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; }
1692
1997
  function UploadManagerBase_empty() {}
1693
- function _awaitIgnored(value, direct) {
1998
+ function UploadManagerBase_awaitIgnored(value, direct) {
1694
1999
  if (!direct) {
1695
2000
  return value && value.then ? value.then(UploadManagerBase_empty) : Promise.resolve();
1696
2001
  }
@@ -1704,11 +2009,11 @@ function UploadManagerBase_await(value, then, direct) {
1704
2009
  }
1705
2010
  return then ? value.then(then) : value;
1706
2011
  }
1707
- function _rethrow(thrown, value) {
2012
+ function UploadManagerBase_rethrow(thrown, value) {
1708
2013
  if (thrown) throw value;
1709
2014
  return value;
1710
2015
  }
1711
- function _finallyRethrows(body, finalizer) {
2016
+ function UploadManagerBase_finallyRethrows(body, finalizer) {
1712
2017
  try {
1713
2018
  var result = body();
1714
2019
  } catch (e) {
@@ -1739,6 +2044,7 @@ var UploadManagerBase = /*#__PURE__*/function () {
1739
2044
  this.defaultMaxConcurrentUploadParts = 4;
1740
2045
  this.intervalMs = 500;
1741
2046
  this.uploadApi = new UploadApi(config);
2047
+ this.accountId = BytescaleApiClientConfigUtils.getAccountId(config);
1742
2048
  }
1743
2049
  UploadManagerBase_createClass(UploadManagerBase, [{
1744
2050
  key: "upload",
@@ -1748,10 +2054,13 @@ var UploadManagerBase = /*#__PURE__*/function () {
1748
2054
  _this2.assertNotCancelled(request);
1749
2055
  var source = _this2.processUploadSource(request.data);
1750
2056
  var preUploadInfo = _this2.getPreUploadInfo(request, source);
1751
- var onProgress = _this2.makeProgressCallback(request, preUploadInfo.size);
2057
+ var bytesTotal = preUploadInfo.size;
2058
+ var makeOnProgressForPart = _this2.makeOnProgressForPartFactory(request, bytesTotal);
1752
2059
  var init = _this2.preUpload(source);
1753
2060
  // Raise initial progress event SYNCHRONOUSLY.
1754
- onProgress(0);
2061
+ if (request.onProgress !== undefined) {
2062
+ request.onProgress(_this2.makeProgressEvent(0, bytesTotal));
2063
+ }
1755
2064
  return UploadManagerBase_await(_this2.beginUpload(request, preUploadInfo), function (uploadInfo) {
1756
2065
  var partCount = uploadInfo.uploadParts.count;
1757
2066
  var parts = UploadManagerBase_toConsumableArray(Array(partCount).keys());
@@ -1759,15 +2068,15 @@ var UploadManagerBase = /*#__PURE__*/function () {
1759
2068
  cancel = _this2$makeCancellati.cancel,
1760
2069
  addCancellationHandler = _this2$makeCancellati.addCancellationHandler;
1761
2070
  var intervalHandle = setInterval(_this2.onIntervalTick(request, cancel), _this2.intervalMs);
1762
- return UploadManagerBase_continue(_finallyRethrows(function () {
2071
+ return UploadManagerBase_continue(UploadManagerBase_finallyRethrows(function () {
1763
2072
  return UploadManagerBase_await(_this2.mapAsync(parts, preUploadInfo.maxConcurrentUploadParts, _async(function (part) {
1764
- return _this2.uploadPart(request, source, part, uploadInfo, onProgress, addCancellationHandler);
2073
+ return _this2.uploadPart(request, source, part, uploadInfo, makeOnProgressForPart(), addCancellationHandler);
1765
2074
  })), function () {
1766
- return _awaitIgnored(_this2.postUpload(init));
2075
+ return UploadManagerBase_awaitIgnored(_this2.postUpload(init));
1767
2076
  });
1768
2077
  }, function (_wasThrown, _result) {
1769
2078
  clearInterval(intervalHandle);
1770
- return _rethrow(_wasThrown, _result);
2079
+ return UploadManagerBase_rethrow(_wasThrown, _result);
1771
2080
  }), function () {
1772
2081
  return uploadInfo.file;
1773
2082
  });
@@ -1817,21 +2126,37 @@ var UploadManagerBase = /*#__PURE__*/function () {
1817
2126
  addCancellationHandler: addCancellationHandler
1818
2127
  };
1819
2128
  }
2129
+ /**
2130
+ * Returns a callback, which when called, returns a callback that can be used by ONE specific part to report its progress.
2131
+ */
1820
2132
  }, {
1821
- key: "makeProgressCallback",
1822
- value: function makeProgressCallback(request, bytesTotal) {
2133
+ key: "makeOnProgressForPartFactory",
2134
+ value: function makeOnProgressForPartFactory(request, bytesTotal) {
2135
+ var _this4 = this;
1823
2136
  var onProgress = request.onProgress;
1824
2137
  if (onProgress === undefined) {
1825
- return function () {};
2138
+ return function () {
2139
+ return function () {};
2140
+ };
1826
2141
  }
1827
2142
  var bytesSent = 0;
1828
- return function (bytesSentDelta) {
1829
- bytesSent += bytesSentDelta;
1830
- onProgress({
1831
- bytesTotal: bytesTotal,
1832
- bytesSent: bytesSent,
1833
- progress: Math.round(bytesSent / bytesTotal * 100)
1834
- });
2143
+ return function () {
2144
+ var bytesSentForPart = 0;
2145
+ return function (bytesSentTotalForPart) {
2146
+ var delta = bytesSentTotalForPart - bytesSentForPart;
2147
+ bytesSentForPart += delta;
2148
+ bytesSent += delta;
2149
+ onProgress(_this4.makeProgressEvent(bytesSent, bytesTotal));
2150
+ };
2151
+ };
2152
+ }
2153
+ }, {
2154
+ key: "makeProgressEvent",
2155
+ value: function makeProgressEvent(bytesSent, bytesTotal) {
2156
+ return {
2157
+ bytesTotal: bytesTotal,
2158
+ bytesSent: bytesSent,
2159
+ progress: Math.round(bytesSent / bytesTotal * 100)
1835
2160
  };
1836
2161
  }
1837
2162
  }, {
@@ -1854,9 +2179,9 @@ var UploadManagerBase = /*#__PURE__*/function () {
1854
2179
  mime = _ref2.mime,
1855
2180
  originalFileName = _ref2.originalFileName;
1856
2181
  try {
1857
- var _this5 = this;
1858
- return UploadManagerBase_await(_this5.uploadApi.beginMultipartUpload({
1859
- accountId: request.accountId,
2182
+ var _this6 = this;
2183
+ return UploadManagerBase_await(_this6.uploadApi.beginMultipartUpload({
2184
+ accountId: _this6.accountId,
1860
2185
  beginMultipartUploadRequest: {
1861
2186
  metadata: request.metadata,
1862
2187
  mime: mime,
@@ -1875,14 +2200,14 @@ var UploadManagerBase = /*#__PURE__*/function () {
1875
2200
  key: "uploadPart",
1876
2201
  value: function uploadPart(request, source, partIndex, uploadInfo, onProgress, addCancellationHandler) {
1877
2202
  try {
1878
- var _this7 = this;
1879
- _this7.assertNotCancelled(request);
1880
- return UploadManagerBase_await(_this7.getUploadPart(request, partIndex, uploadInfo), function (part) {
1881
- _this7.assertNotCancelled(request);
1882
- return UploadManagerBase_await(_this7.putUploadPart(part, source, onProgress, addCancellationHandler), function (etag) {
1883
- _this7.assertNotCancelled(request);
1884
- return _awaitIgnored(_this7.uploadApi.completeUploadPart({
1885
- accountId: request.accountId,
2203
+ var _this8 = this;
2204
+ _this8.assertNotCancelled(request);
2205
+ return UploadManagerBase_await(_this8.getUploadPart(partIndex, uploadInfo), function (part) {
2206
+ _this8.assertNotCancelled(request);
2207
+ return UploadManagerBase_await(_this8.putUploadPart(part, source, onProgress, addCancellationHandler), function (etag) {
2208
+ _this8.assertNotCancelled(request);
2209
+ return UploadManagerBase_awaitIgnored(_this8.uploadApi.completeUploadPart({
2210
+ accountId: _this8.accountId,
1886
2211
  uploadId: uploadInfo.uploadId,
1887
2212
  uploadPartIndex: partIndex,
1888
2213
  completeUploadPartRequest: {
@@ -1902,9 +2227,9 @@ var UploadManagerBase = /*#__PURE__*/function () {
1902
2227
  key: "putUploadPart",
1903
2228
  value: function putUploadPart(part, source, onProgress, addCancellationHandler) {
1904
2229
  try {
1905
- var _this9 = this;
2230
+ var _this10 = this;
1906
2231
  var contentLength = part.range.inclusiveEnd + 1 - part.range.inclusiveStart;
1907
- return UploadManagerBase_await(_this9.doPutUploadPart(part, contentLength, source, onProgress, addCancellationHandler), function (_ref3) {
2232
+ return UploadManagerBase_await(_this10.doPutUploadPart(part, contentLength, source, onProgress, addCancellationHandler), function (_ref3) {
1908
2233
  var status = _ref3.status,
1909
2234
  etag = _ref3.etag;
1910
2235
  if (Math.floor(status / 100) !== 2) {
@@ -1913,6 +2238,8 @@ var UploadManagerBase = /*#__PURE__*/function () {
1913
2238
  if (etag === undefined) {
1914
2239
  throw new Error("No 'etag' response header found in upload part response.");
1915
2240
  }
2241
+ // Always send 100% for part, as some UploadManager implementations either don't report progress, or may not report the last chunk uploaded.
2242
+ onProgress(contentLength);
1916
2243
  return etag;
1917
2244
  });
1918
2245
  } catch (e) {
@@ -1921,15 +2248,15 @@ var UploadManagerBase = /*#__PURE__*/function () {
1921
2248
  }
1922
2249
  }, {
1923
2250
  key: "getUploadPart",
1924
- value: function getUploadPart(request, partIndex, uploadInfo) {
2251
+ value: function getUploadPart(partIndex, uploadInfo) {
1925
2252
  try {
1926
- var _this11 = this;
2253
+ var _this12 = this;
1927
2254
  if (partIndex === 0) {
1928
2255
  return uploadInfo.uploadParts.first;
1929
2256
  }
1930
- return UploadManagerBase_await(_this11.uploadApi.getUploadPart({
2257
+ return UploadManagerBase_await(_this12.uploadApi.getUploadPart({
1931
2258
  uploadId: uploadInfo.uploadId,
1932
- accountId: request.accountId,
2259
+ accountId: _this12.accountId,
1933
2260
  uploadPartIndex: partIndex
1934
2261
  }));
1935
2262
  } catch (e) {
@@ -1953,14 +2280,14 @@ var UploadManagerBase = /*#__PURE__*/function () {
1953
2280
  value: function mapAsync(items, concurrency, callback) {
1954
2281
  try {
1955
2282
  var workQueue = UploadManagerBase_toConsumableArray(items);
1956
- return _awaitIgnored(Promise.all(UploadManagerBase_toConsumableArray(Array(concurrency).keys()).map(_async(function () {
1957
- return _continueIgnored(_for(function () {
2283
+ return UploadManagerBase_awaitIgnored(Promise.all(UploadManagerBase_toConsumableArray(Array(concurrency).keys()).map(_async(function () {
2284
+ return _continueIgnored(UploadManagerBase_for(function () {
1958
2285
  return workQueue.length > 0;
1959
2286
  }, void 0, function () {
1960
2287
  var work = workQueue.shift(); // IMPORTANT: use 'shift' instead of 'pop' to ensure 'items' are processed in order when 'concurrency = 1'.
1961
2288
  return _invokeIgnored(function () {
1962
2289
  if (work !== undefined) {
1963
- return _awaitIgnored(callback(work));
2290
+ return UploadManagerBase_awaitIgnored(callback(work));
1964
2291
  }
1965
2292
  });
1966
2293
  }));
@@ -2000,6 +2327,11 @@ var StreamUtils = /*#__PURE__*/function () {
2000
2327
  StreamUtils.endStream(readable);
2001
2328
  return readable;
2002
2329
  }
2330
+ }, {
2331
+ key: "fromArrayBuffer",
2332
+ value: function fromArrayBuffer(buffer) {
2333
+ return StreamUtils.fromBuffer(Buffer.from(buffer));
2334
+ }
2003
2335
  }, {
2004
2336
  key: "fromBuffer",
2005
2337
  value: function fromBuffer(buffer) {
@@ -2208,6 +2540,62 @@ var NodeChunkedStream = /*#__PURE__*/function () {
2208
2540
  }();
2209
2541
  ;// CONCATENATED MODULE: external "buffer"
2210
2542
  var external_buffer_namespaceObject = require("buffer");
2543
+ ;// CONCATENATED MODULE: ./src/private/UploadManagerFetchUtils.ts
2544
+ function UploadManagerFetchUtils_typeof(obj) { "@babel/helpers - typeof"; return UploadManagerFetchUtils_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; }, UploadManagerFetchUtils_typeof(obj); }
2545
+ function UploadManagerFetchUtils_await(value, then, direct) {
2546
+ if (direct) {
2547
+ return then ? then(value) : value;
2548
+ }
2549
+ if (!value || !value.then) {
2550
+ value = Promise.resolve(value);
2551
+ }
2552
+ return then ? value.then(then) : value;
2553
+ }
2554
+ function UploadManagerFetchUtils_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
2555
+ function UploadManagerFetchUtils_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, UploadManagerFetchUtils_toPropertyKey(descriptor.key), descriptor); } }
2556
+ function UploadManagerFetchUtils_createClass(Constructor, protoProps, staticProps) { if (protoProps) UploadManagerFetchUtils_defineProperties(Constructor.prototype, protoProps); if (staticProps) UploadManagerFetchUtils_defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
2557
+ function UploadManagerFetchUtils_toPropertyKey(arg) { var key = UploadManagerFetchUtils_toPrimitive(arg, "string"); return UploadManagerFetchUtils_typeof(key) === "symbol" ? key : String(key); }
2558
+ function UploadManagerFetchUtils_toPrimitive(input, hint) { if (UploadManagerFetchUtils_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (UploadManagerFetchUtils_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
2559
+
2560
+ var UploadManagerFetchUtils = /*#__PURE__*/function () {
2561
+ function UploadManagerFetchUtils() {
2562
+ UploadManagerFetchUtils_classCallCheck(this, UploadManagerFetchUtils);
2563
+ }
2564
+ UploadManagerFetchUtils_createClass(UploadManagerFetchUtils, null, [{
2565
+ key: "doPutUploadPart",
2566
+ value: function doPutUploadPart(config, part, content, contentLength, addCancellationHandler) {
2567
+ try {
2568
+ var _a;
2569
+ var fetchApi = BytescaleApiClientConfigUtils.getFetchApi(config);
2570
+ // Configure cancellation:
2571
+ var controller = new AbortController();
2572
+ var signal = controller.signal;
2573
+ addCancellationHandler(function () {
2574
+ return controller.abort();
2575
+ });
2576
+ var headers = {
2577
+ // Required to prevent fetch using "Transfer-Encoding: Chunked" when body is a stream.
2578
+ "content-length": contentLength.toString()
2579
+ };
2580
+ return UploadManagerFetchUtils_await(fetchApi(part.uploadUrl, {
2581
+ method: "PUT",
2582
+ headers: headers,
2583
+ body: content,
2584
+ signal: signal,
2585
+ cache: "no-store" // Required for Next.js's Fetch implementation, which caches POST/PUT requests by default.
2586
+ }), function (response) {
2587
+ return {
2588
+ etag: (_a = response.headers.get("etag")) !== null && _a !== void 0 ? _a : undefined,
2589
+ status: response.status
2590
+ };
2591
+ });
2592
+ } catch (e) {
2593
+ return Promise.reject(e);
2594
+ }
2595
+ }
2596
+ }]);
2597
+ return UploadManagerFetchUtils;
2598
+ }();
2211
2599
  ;// CONCATENATED MODULE: ./src/public/node/UploadManagerNode.ts
2212
2600
  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); }
2213
2601
  function UploadManagerNode_empty() {}
@@ -2407,6 +2795,7 @@ function UploadManagerNode_getPrototypeOf(o) { UploadManagerNode_getPrototypeOf
2407
2795
 
2408
2796
 
2409
2797
 
2798
+
2410
2799
  var UploadManager = /*#__PURE__*/function (_UploadManagerBase) {
2411
2800
  UploadManagerNode_inherits(UploadManager, _UploadManagerBase);
2412
2801
  var _super = UploadManagerNode_createSuper(UploadManager);
@@ -2438,13 +2827,19 @@ var UploadManager = /*#__PURE__*/function (_UploadManagerBase) {
2438
2827
  value: data
2439
2828
  };
2440
2829
  }
2830
+ if (data.byteLength !== undefined) {
2831
+ return {
2832
+ type: "ArrayBuffer",
2833
+ value: data
2834
+ };
2835
+ }
2441
2836
  if (data.size !== undefined) {
2442
2837
  return {
2443
2838
  type: "Blob",
2444
2839
  value: data
2445
2840
  };
2446
2841
  }
2447
- throw new Error("Unsupported type for 'data' parameter. Please provide a String, Blob, or Readable (Node.js).");
2842
+ throw new Error("Unsupported type for 'data' parameter. Please provide a String, Blob, Buffer, ArrayBuffer, or ReadableStream (Node.js).");
2448
2843
  }
2449
2844
  }, {
2450
2845
  key: "getPreUploadInfoPartial",
@@ -2453,9 +2848,10 @@ var UploadManager = /*#__PURE__*/function (_UploadManagerBase) {
2453
2848
  case "Blob":
2454
2849
  return this.getBlobInfo(data);
2455
2850
  case "Buffer":
2851
+ case "ArrayBuffer":
2456
2852
  return {
2457
2853
  mime: undefined,
2458
- size: data.value.length,
2854
+ size: data.value.byteLength,
2459
2855
  originalFileName: undefined,
2460
2856
  maxConcurrentUploadParts: undefined
2461
2857
  };
@@ -2506,40 +2902,20 @@ var UploadManager = /*#__PURE__*/function (_UploadManagerBase) {
2506
2902
  value: function doPutUploadPart(part, contentLength, source, onProgress, addCancellationHandler) {
2507
2903
  try {
2508
2904
  var _this2 = this;
2509
- var _a, _b;
2510
- var fetchApi = (_a = _this2.config.fetchApi) !== null && _a !== void 0 ? _a : fetch;
2511
- var headers = {
2512
- // Required to prevent fetch using "Transfer-Encoding: Chunked" when body is a stream.
2513
- "content-length": contentLength.toString()
2514
- };
2515
- // Configure cancellation:
2516
- var controller = new AbortController();
2517
- var signal = controller.signal;
2518
- addCancellationHandler(function () {
2519
- return controller.abort();
2520
- });
2521
2905
  // Report progress:
2522
2906
  var hasWarned = false;
2907
+ var bytesSent = 0;
2523
2908
  return UploadManagerNode_await(_this2.sliceDataForRequest(source, part), function (stream) {
2524
2909
  var streamWithProgress = stream.on("data", function (data) {
2525
- if (data.length !== undefined) {
2526
- onProgress(data.length);
2910
+ if (data.byteLength !== undefined) {
2911
+ bytesSent += data.byteLength;
2912
+ onProgress(bytesSent);
2527
2913
  } else if (!hasWarned) {
2528
2914
  hasWarned = true;
2529
2915
  console.warn("Expected stream to contain buffers, but it did not, so upload progress won't be reported.");
2530
2916
  }
2531
2917
  });
2532
- return UploadManagerNode_await(fetchApi(part.uploadUrl, {
2533
- method: "PUT",
2534
- headers: headers,
2535
- body: _this2.coerceRequestBody(streamWithProgress),
2536
- signal: signal
2537
- }), function (response) {
2538
- return {
2539
- etag: (_b = response.headers.get("etag")) !== null && _b !== void 0 ? _b : undefined,
2540
- status: response.status
2541
- };
2542
- });
2918
+ return UploadManagerNode_await(UploadManagerFetchUtils.doPutUploadPart(_this2.config, part, _this2.coerceRequestBody(streamWithProgress), contentLength, addCancellationHandler));
2543
2919
  });
2544
2920
  } catch (e) {
2545
2921
  return Promise.reject(e);
@@ -2563,12 +2939,14 @@ var UploadManager = /*#__PURE__*/function (_UploadManagerBase) {
2563
2939
  return _switch(data.type, [[function () {
2564
2940
  return "Blob";
2565
2941
  }, function () {
2566
- var _fromBuffer = StreamUtils.fromBuffer,
2567
- _Buffer = Buffer,
2568
- _from = _Buffer.from;
2942
+ var _fromArrayBuffer = StreamUtils.fromArrayBuffer;
2569
2943
  return UploadManagerNode_await(data.value.slice(start, endExclusive).arrayBuffer(), function (_data$value$slice$arr) {
2570
- return _fromBuffer.call(StreamUtils, _from.call(_Buffer, _data$value$slice$arr));
2944
+ return _fromArrayBuffer.call(StreamUtils, _data$value$slice$arr);
2571
2945
  });
2946
+ }], [function () {
2947
+ return "ArrayBuffer";
2948
+ }, function () {
2949
+ return StreamUtils.fromArrayBuffer(data.value.slice(start, endExclusive));
2572
2950
  }], [function () {
2573
2951
  return "Buffer";
2574
2952
  }, function () {
@@ -2599,17 +2977,17 @@ var EnvChecker = /*#__PURE__*/function () {
2599
2977
  EnvChecker_classCallCheck(this, EnvChecker);
2600
2978
  }
2601
2979
  EnvChecker_createClass(EnvChecker, null, [{
2602
- key: "isNodeJs",
2603
- value: function isNodeJs() {
2604
- return typeof process !== "undefined" && process.versions !== undefined && process.versions.node !== undefined;
2980
+ key: "isBrowser",
2981
+ value: function isBrowser() {
2982
+ return typeof window !== "undefined";
2605
2983
  }
2606
2984
  }, {
2607
2985
  key: "methodRequiresBrowser",
2608
2986
  value: function methodRequiresBrowser(methodName) {
2609
- if (EnvChecker.isNodeJs()) {
2610
- return new Error("You must call '".concat(methodName, "' in the browser. (You are currently in Node.js.)"));
2987
+ if (!EnvChecker.isBrowser()) {
2988
+ return new Error("You must call '".concat(methodName, "' in your client-side code. (You have called it in your server-side code.)"));
2611
2989
  }
2612
- return new Error("The '".concat(methodName, "' method cannot be called because you have bundled the Node.js implementation of the Bytescale JavaScript SDK into your client-side code. Please ensure your bundling tool (Webpack, Rollup, etc.) is honouring the \"browser\" field of the \"package.json\" file for this package, as this will allow the browser implementation of the Bytescale JavaScript SDK to be included in your client-side code."));
2990
+ return new Error("The '".concat(methodName, "' method cannot be called because you have bundled a non-browser implementation of the Bytescale JavaScript SDK into your client-side code. Please ensure your bundling tool (Webpack, Rollup, etc.) is honouring the \"browser\" field of the \"package.json\" file for this package, as this will allow the browser implementation of the Bytescale JavaScript SDK to be included in your client-side code."));
2613
2991
  }
2614
2992
  }]);
2615
2993
  return EnvChecker;
@@ -2622,13 +3000,13 @@ function AuthManagerNode_createClass(Constructor, protoProps, staticProps) { if
2622
3000
  function AuthManagerNode_toPropertyKey(arg) { var key = AuthManagerNode_toPrimitive(arg, "string"); return AuthManagerNode_typeof(key) === "symbol" ? key : String(key); }
2623
3001
  function AuthManagerNode_toPrimitive(input, hint) { if (AuthManagerNode_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (AuthManagerNode_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
2624
3002
 
2625
- var AuthManager = /*#__PURE__*/function () {
2626
- function AuthManager() {
2627
- AuthManagerNode_classCallCheck(this, AuthManager);
3003
+ var AuthManagerImpl = /*#__PURE__*/function () {
3004
+ function AuthManagerImpl() {
3005
+ AuthManagerNode_classCallCheck(this, AuthManagerImpl);
2628
3006
  }
2629
- AuthManagerNode_createClass(AuthManager, [{
3007
+ AuthManagerNode_createClass(AuthManagerImpl, [{
2630
3008
  key: "beginAuthSession",
2631
- value: function beginAuthSession(_authUrl, _authHeaders) {
3009
+ value: function beginAuthSession(_params) {
2632
3010
  try {
2633
3011
  throw EnvChecker.methodRequiresBrowser("beginAuthSession");
2634
3012
  } catch (e) {
@@ -2650,8 +3028,12 @@ var AuthManager = /*#__PURE__*/function () {
2650
3028
  return false;
2651
3029
  }
2652
3030
  }]);
2653
- return AuthManager;
3031
+ return AuthManagerImpl;
2654
3032
  }();
3033
+ /**
3034
+ * Alternative way of implementing a static class (i.e. all methods static). We do this so we can use a interface on the class (interfaces can't define static methods).
3035
+ */
3036
+ var AuthManager = new AuthManagerImpl();
2655
3037
  ;// CONCATENATED MODULE: ./src/public/node/index.ts
2656
3038
 
2657
3039