@bytescale/sdk 3.0.0-alpha.2 → 3.0.0-alpha.21

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 (35) hide show
  1. package/README.md +391 -48
  2. package/dist/browser/cjs/main.js +723 -589
  3. package/dist/node/cjs/main.js +640 -263
  4. package/dist/node/esm/main.mjs +640 -263
  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 -11
  22. package/dist/types/public/shared/UrlBuilderTypes.d.ts +65 -71
  23. package/dist/types/public/shared/generated/apis/FileApi.d.ts +104 -3
  24. package/dist/types/public/shared/generated/apis/FolderApi.d.ts +0 -3
  25. package/dist/types/public/shared/generated/apis/JobApi.d.ts +0 -3
  26. package/dist/types/public/shared/generated/apis/UploadApi.d.ts +6 -3
  27. package/dist/types/public/shared/generated/models/index.d.ts +5 -7
  28. package/dist/types/public/shared/generated/runtime.d.ts +7 -5
  29. package/dist/types/public/worker/UploadManagerWorker.d.ts +8 -0
  30. package/dist/types/public/worker/index.d.ts +2 -0
  31. package/dist/worker/cjs/main.js +2578 -0
  32. package/dist/worker/esm/main.mjs +2578 -0
  33. package/package.json +7 -8
  34. package/tests/UploadManager.test.ts +0 -7
  35. package/tests/UrlBuilder.test.ts +60 -59
@@ -58,16 +58,332 @@ __lib_require__.d(__lib_exports__, {
58
58
  "querystring": function() { return /* reexport */ querystring; }
59
59
  });
60
60
 
61
- ;// CONCATENATED MODULE: ./src/private/AuthSessionState.ts
61
+ ;// CONCATENATED MODULE: ./src/private/Mutex.ts
62
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"); } }
63
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); } }
64
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; }
65
259
  function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
66
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); }
67
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
68
- var AuthSessionState = /*#__PURE__*/_createClass(function AuthSessionState() {
69
- _classCallCheck(this, AuthSessionState);
70
- });
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";
71
387
  ;// CONCATENATED MODULE: ./src/public/shared/generated/runtime.ts
72
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); }
73
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); }
@@ -91,8 +407,8 @@ function _catch(body, recover) {
91
407
  }
92
408
  return result;
93
409
  }
94
- function _empty() {}
95
- function _continue(value, then) {
410
+ function runtime_empty() {}
411
+ function runtime_continue(value, then) {
96
412
  return value && value.then ? value.then(then) : then(value);
97
413
  }
98
414
  function _invoke(body, then) {
@@ -103,7 +419,7 @@ function _invoke(body, then) {
103
419
  return then(result);
104
420
  }
105
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; }
106
- function _await(value, then, direct) {
422
+ function runtime_await(value, then, direct) {
107
423
  if (direct) {
108
424
  return then ? then(value) : value;
109
425
  }
@@ -191,72 +507,30 @@ var BaseAPI = /*#__PURE__*/function () {
191
507
  this.config = config;
192
508
  BytescaleApiClientConfigUtils.validate(config);
193
509
  }
510
+ /**
511
+ * Returns a successful response (2**) else throws an error.
512
+ */
194
513
  runtime_createClass(BaseAPI, [{
195
514
  key: "request",
196
515
  value: function request(context, initOverrides, baseUrlOverride) {
197
516
  try {
198
517
  var _this2 = this;
199
- var _a, _b;
518
+ var _a;
200
519
  var apiKey = _this2.config.apiKey;
201
520
  context.headers["Authorization"] = "Bearer ".concat(apiKey); // authorization-header authentication
202
- if (((_a = AuthSessionState.session) === null || _a === void 0 ? void 0 : _a.accessToken) !== undefined) {
203
- 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;
204
524
  }
205
525
  // Key: any possible value for 'baseUrlOverride'
206
526
  // Value: user-overridden value for that base URL from the config.
207
527
  var nonDefaultBasePaths = _defineProperty({}, BytescaleApiClientConfigUtils.defaultCdnUrl, BytescaleApiClientConfigUtils.getCdnUrl(_this2.config));
208
- 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) {
209
529
  var url = _ref.url,
210
530
  init = _ref.init;
211
- return _this2.doFetch(url, init, true);
212
- });
213
- } catch (e) {
214
- return Promise.reject(e);
215
- }
216
- }
217
- /**
218
- * Returns a successful response (2**) else throws an error.
219
- */
220
- }, {
221
- key: "doFetch",
222
- value: function doFetch(url, init, isBytescaleApi) {
223
- try {
224
- var _exit3 = false;
225
- var _this4 = this;
226
- var _a, _b;
227
- var response;
228
- return _continue(_catch(function () {
229
- return _await(BytescaleApiClientConfigUtils.getFetchApi(_this4.config)(url, init), function (_BytescaleApiClientCo) {
230
- response = _BytescaleApiClientCo;
231
- });
232
- }, function (e) {
233
- // Network-level errors, CORS errors, or HTTP-level errors from intermediary services (e.g. AWS or the user's own infrastructure/proxies).
234
- // 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.
235
- 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));
236
- }), function (_result) {
237
- var _exit2 = false;
238
- if (_exit3) return _result;
239
- return response.status >= 200 && response.status < 300 ? response : _invoke(function () {
240
- if (isBytescaleApi) {
241
- var jsonError = undefined;
242
- return _continue(_catch(function () {
243
- return _await(response.json(), function (_response$json) {
244
- jsonError = _response$json;
245
- });
246
- }, _empty), function () {
247
- if (typeof ((_a = jsonError === null || jsonError === void 0 ? void 0 : jsonError.error) === null || _a === void 0 ? void 0 : _a.code) === "string") {
248
- throw new BytescaleApiError(jsonError);
249
- }
250
- // HTTP-level errors from intermediary services (e.g. AWS or the user's own infrastructure/proxies). On the browser,
251
- // this error is unlikely to be triggered since these errors will masqurade as CORS errors (see above) but in Node.js
252
- // this error will appear from any intermediary service failure.
253
- throw new Error("Unable to connect to the Bytescale API (".concat(response.status, "): please try again."));
254
- });
255
- }
256
- }, function (_result2) {
257
- if (_exit2) return _result2;
258
- throw new Error("Failure status code (".concat(response.status, ") received for request: ").concat((_b = init.method) !== null && _b !== void 0 ? _b : "GET", " ").concat(url));
259
- });
531
+ return BaseAPI.fetch(url, init, Object.assign(Object.assign({}, _this2.config), {
532
+ isBytescaleApi: true
533
+ }));
260
534
  });
261
535
  } catch (e) {
262
536
  return Promise.reject(e);
@@ -279,23 +553,23 @@ var BaseAPI = /*#__PURE__*/function () {
279
553
  key: "createFetchParams",
280
554
  value: function createFetchParams(context, initOverrides, baseUrlOverride) {
281
555
  try {
282
- var _this6 = this;
283
- 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;
284
558
  if (context.query !== undefined && Object.keys(context.query).length !== 0) {
285
559
  // only add the querystring to the URL if there are query parameters.
286
560
  // this is done to avoid urls ending with a "?" character which buggy webservers
287
561
  // do not handle correctly sometimes.
288
562
  url += "?" + querystring(context.query);
289
563
  }
290
- var configHeaders = _this6.config.headers;
564
+ var configHeaders = _this4.config.headers;
291
565
  var _Object$assign3 = Object.assign({}, context.headers);
292
- return _await(configHeaders === undefined ? {} : configHeaders(), function (_configHeaders) {
566
+ return runtime_await(configHeaders === undefined ? {} : configHeaders(), function (_configHeaders) {
293
567
  var headers = Object.assign(_Object$assign3, _configHeaders);
294
568
  Object.keys(headers).forEach(function (key) {
295
569
  return headers[key] === undefined ? delete headers[key] : {};
296
570
  });
297
571
  var initOverrideFn = typeof initOverrides === "function" ? initOverrides : function () {
298
- return _await(initOverrides);
572
+ return runtime_await(initOverrides);
299
573
  };
300
574
  var initParams = {
301
575
  method: context.method,
@@ -303,7 +577,7 @@ var BaseAPI = /*#__PURE__*/function () {
303
577
  body: context.body
304
578
  };
305
579
  var _Object$assign2 = Object.assign({}, initParams);
306
- return _await(initOverrideFn({
580
+ return runtime_await(initOverrideFn({
307
581
  init: initParams,
308
582
  context: context
309
583
  }), function (_initOverrideFn) {
@@ -321,6 +595,59 @@ var BaseAPI = /*#__PURE__*/function () {
321
595
  return Promise.reject(e);
322
596
  }
323
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
+ }
324
651
  }]);
325
652
  return BaseAPI;
326
653
  }();
@@ -328,11 +655,11 @@ var CancelledError = /*#__PURE__*/function (_Error) {
328
655
  _inherits(CancelledError, _Error);
329
656
  var _super = _createSuper(CancelledError);
330
657
  function CancelledError() {
331
- var _this7;
658
+ var _this5;
332
659
  runtime_classCallCheck(this, CancelledError);
333
- _this7 = _super.call(this, "Operation cancelled by caller.");
334
- _this7.name = "CancelledError";
335
- return _this7;
660
+ _this5 = _super.call(this, "Operation cancelled by caller.");
661
+ _this5.name = "CancelledError";
662
+ return _this5;
336
663
  }
337
664
  return runtime_createClass(CancelledError);
338
665
  }( /*#__PURE__*/_wrapNativeSuper(Error));
@@ -340,13 +667,13 @@ var BytescaleApiError = /*#__PURE__*/function (_Error2) {
340
667
  _inherits(BytescaleApiError, _Error2);
341
668
  var _super2 = _createSuper(BytescaleApiError);
342
669
  function BytescaleApiError(response) {
343
- var _this8;
670
+ var _this6;
344
671
  runtime_classCallCheck(this, BytescaleApiError);
345
- _this8 = _super2.call(this, response.error.message);
346
- _this8.name = "BytescaleApiError";
347
- _this8.errorCode = response.error.code;
348
- _this8.details = response.error.details;
349
- 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;
350
677
  }
351
678
  return runtime_createClass(BytescaleApiError);
352
679
  }( /*#__PURE__*/_wrapNativeSuper(Error));
@@ -372,8 +699,8 @@ var JSONApiResponse = /*#__PURE__*/function () {
372
699
  key: "value",
373
700
  value: function value() {
374
701
  try {
375
- var _this10 = this;
376
- return _await(_this10.raw.json());
702
+ var _this8 = this;
703
+ return runtime_await(_this8.raw.json());
377
704
  } catch (e) {
378
705
  return Promise.reject(e);
379
706
  }
@@ -389,7 +716,7 @@ var VoidApiResponse = /*#__PURE__*/function () {
389
716
  runtime_createClass(VoidApiResponse, [{
390
717
  key: "value",
391
718
  value: function value() {
392
- return _await(undefined);
719
+ return runtime_await(undefined);
393
720
  }
394
721
  }]);
395
722
  return VoidApiResponse;
@@ -414,8 +741,8 @@ var BinaryResult = /*#__PURE__*/function () {
414
741
  key: "text",
415
742
  value: function text() {
416
743
  try {
417
- var _this12 = this;
418
- return _await(_this12.raw.text());
744
+ var _this10 = this;
745
+ return runtime_await(_this10.raw.text());
419
746
  } catch (e) {
420
747
  return Promise.reject(e);
421
748
  }
@@ -424,8 +751,8 @@ var BinaryResult = /*#__PURE__*/function () {
424
751
  key: "blob",
425
752
  value: function blob() {
426
753
  try {
427
- var _this14 = this;
428
- return _await(_this14.raw.blob());
754
+ var _this12 = this;
755
+ return runtime_await(_this12.raw.blob());
429
756
  } catch (e) {
430
757
  return Promise.reject(e);
431
758
  }
@@ -434,8 +761,8 @@ var BinaryResult = /*#__PURE__*/function () {
434
761
  key: "json",
435
762
  value: function json() {
436
763
  try {
437
- var _this16 = this;
438
- return _await(_this16.raw.json());
764
+ var _this14 = this;
765
+ return runtime_await(_this14.raw.json());
439
766
  } catch (e) {
440
767
  return Promise.reject(e);
441
768
  }
@@ -481,9 +808,6 @@ function FileApi_getPrototypeOf(o) { FileApi_getPrototypeOf = Object.setPrototyp
481
808
  */
482
809
  // @ts-ignore
483
810
 
484
- /**
485
- *
486
- */
487
811
  var FileApi = /*#__PURE__*/function (_runtime$BaseAPI) {
488
812
  FileApi_inherits(FileApi, _runtime$BaseAPI);
489
813
  var _super = FileApi_createSuper(FileApi);
@@ -782,9 +1106,6 @@ function FolderApi_getPrototypeOf(o) { FolderApi_getPrototypeOf = Object.setProt
782
1106
  */
783
1107
  // @ts-ignore
784
1108
 
785
- /**
786
- *
787
- */
788
1109
  var FolderApi = /*#__PURE__*/function (_runtime$BaseAPI) {
789
1110
  FolderApi_inherits(FolderApi, _runtime$BaseAPI);
790
1111
  var _super = FolderApi_createSuper(FolderApi);
@@ -1042,9 +1363,6 @@ function JobApi_getPrototypeOf(o) { JobApi_getPrototypeOf = Object.setPrototypeO
1042
1363
  */
1043
1364
  // @ts-ignore
1044
1365
 
1045
- /**
1046
- *
1047
- */
1048
1366
  var JobApi = /*#__PURE__*/function (_runtime$BaseAPI) {
1049
1367
  JobApi_inherits(JobApi, _runtime$BaseAPI);
1050
1368
  var _super = JobApi_createSuper(JobApi);
@@ -1177,9 +1495,6 @@ function UploadApi_getPrototypeOf(o) { UploadApi_getPrototypeOf = Object.setProt
1177
1495
  */
1178
1496
  // @ts-ignore
1179
1497
 
1180
- /**
1181
- *
1182
- */
1183
1498
  var UploadApi = /*#__PURE__*/function (_runtime$BaseAPI) {
1184
1499
  UploadApi_inherits(UploadApi, _runtime$BaseAPI);
1185
1500
  var _super = UploadApi_createSuper(UploadApi);
@@ -1372,35 +1687,34 @@ function UrlBuilder_toPrimitive(input, hint) { if (UrlBuilder_typeof(input) !==
1372
1687
 
1373
1688
 
1374
1689
  var UrlBuilder = /*#__PURE__*/function () {
1375
- function UrlBuilder(config) {
1690
+ function UrlBuilder() {
1376
1691
  UrlBuilder_classCallCheck(this, UrlBuilder);
1377
- var _a;
1378
- this.cdnUrl = (_a = config === null || config === void 0 ? void 0 : config.cdnUrl) !== null && _a !== void 0 ? _a : BytescaleApiClientConfigUtils.defaultCdnUrl;
1379
1692
  }
1380
- /**
1381
- * Builds a URL to either a raw file or a transformed file.
1382
- *
1383
- * Example 1) Getting a publicly-accessible raw file URL:
1384
- *
1385
- * new UrlBuilder().url({ accountId: "1234abc", filePath: "/example.jpg" })
1386
- *
1387
- * Example 2) Getting a publicly-accessible image URL, resized to 500x500:
1388
- *
1389
- * new UrlBuilder().url({ accountId: "1234abc", filePath: "/example.jpg", options: { transformation: { type: "image", params: { w: 500, h: 500, fit: "crop" } } } })
1390
- *
1391
- * Example 3) Getting a privately-accessible image URL, resized to 500x500 (requires 'AuthManager.beginAuthSession' to be called before accessing the URL):
1392
- *
1393
- * new UrlBuilder().url({ accountId: "1234abc", filePath: "/example.jpg", options: { transformation: { type: "image", params: { w: 500, h: 500, fit: "crop" } }, auth: true } })
1394
- *
1395
- * Example 4) Getting a publicly-accessible image URL, resized using a transformation preset called "thumbnail" that was created manually in the Bytescale Dashboard:
1396
- *
1397
- * new UrlBuilder().url({ accountId: "1234abc", filePath: "/example.jpg", options: { transformation: { type: "preset", preset: "thumbnail" } } })
1398
- */
1399
- UrlBuilder_createClass(UrlBuilder, [{
1693
+ UrlBuilder_createClass(UrlBuilder, null, [{
1400
1694
  key: "url",
1401
- 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) {
1402
1716
  var _a;
1403
- return ((_a = params.options) === null || _a === void 0 ? void 0 : _a.transformation) === undefined ? this.raw(params) : this.transformation(params, params.options.transformation);
1717
+ return ((_a = params.options) === null || _a === void 0 ? void 0 : _a.transformation) === undefined ? this.raw(params) : this.transformation(params, params.options);
1404
1718
  }
1405
1719
  }, {
1406
1720
  key: "raw",
@@ -1414,17 +1728,25 @@ var UrlBuilder = /*#__PURE__*/function () {
1414
1728
  key: "transformation",
1415
1729
  value: function transformation(params, trans) {
1416
1730
  var _a;
1417
- var baseUrl = this.getBaseUrl(params, trans.type === "preset" ? trans.preset : trans.type);
1418
- var transParams = this.getTransformationParams(trans, {
1419
- cachePermanently: "cache_perm"
1420
- });
1731
+ var baseUrl = this.getBaseUrl(params, trans.transformation === "preset" ? trans.transformationPreset : trans.transformation);
1732
+ var transParams = trans.transformation === "preset" ? [] : this.getTransformationParams(trans);
1421
1733
  var commonParams = this.getCommonQueryParams((_a = params.options) !== null && _a !== void 0 ? _a : {});
1422
- return this.addQueryParams(baseUrl, [].concat(_toConsumableArray(commonParams), _toConsumableArray(transParams)));
1734
+ var transCommonParams = this.getCommonTransformationQueryParams(trans);
1735
+ // This format puts "artifact" at the end, which isn't required, but is convention.
1736
+ return this.addQueryParams(baseUrl, [].concat(_toConsumableArray(transParams), _toConsumableArray(commonParams), _toConsumableArray(transCommonParams)));
1423
1737
  }
1424
1738
  }, {
1425
1739
  key: "getBaseUrl",
1426
1740
  value: function getBaseUrl(params, prefix) {
1427
- 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);
1743
+ }
1744
+ }, {
1745
+ key: "getCommonTransformationQueryParams",
1746
+ value: function getCommonTransformationQueryParams(trans) {
1747
+ return this.makeQueryParams(["cachePermanently", "large", "artifact"], {
1748
+ cachePermanently: "cache_perm"
1749
+ })(trans);
1428
1750
  }
1429
1751
  }, {
1430
1752
  key: "getCommonQueryParams",
@@ -1451,8 +1773,9 @@ var UrlBuilder = /*#__PURE__*/function () {
1451
1773
  }
1452
1774
  }, {
1453
1775
  key: "getTransformationParams",
1454
- value: function getTransformationParams(trans, keyRewrites) {
1455
- if (trans.params === undefined) {
1776
+ value: function getTransformationParams(trans) {
1777
+ var params = trans.transformationParams;
1778
+ if (params === undefined) {
1456
1779
  return [];
1457
1780
  }
1458
1781
  var serializeObj = function serializeObj(obj) {
@@ -1460,11 +1783,10 @@ var UrlBuilder = /*#__PURE__*/function () {
1460
1783
  var _ref2 = _slicedToArray(_ref, 2),
1461
1784
  key = _ref2[0],
1462
1785
  value = _ref2[1];
1463
- var _a;
1464
- return [(_a = keyRewrites[key]) !== null && _a !== void 0 ? _a : key, value.toString()];
1786
+ return [key, value.toString()];
1465
1787
  });
1466
1788
  };
1467
- return Array.isArray(trans.params) ? trans.params.flatMap(serializeObj) : serializeObj(trans.params);
1789
+ return Array.isArray(params) ? params.flatMap(serializeObj) : serializeObj(params);
1468
1790
  }
1469
1791
  }, {
1470
1792
  key: "addQueryParams",
@@ -1512,21 +1834,21 @@ function _invokeIgnored(body) {
1512
1834
  return result.then(UploadManagerBase_empty);
1513
1835
  }
1514
1836
  }
1515
- function _settle(pact, state, value) {
1837
+ function UploadManagerBase_settle(pact, state, value) {
1516
1838
  if (!pact.s) {
1517
- if (value instanceof _Pact) {
1839
+ if (value instanceof UploadManagerBase_Pact) {
1518
1840
  if (value.s) {
1519
1841
  if (state & 1) {
1520
1842
  state = value.s;
1521
1843
  }
1522
1844
  value = value.v;
1523
1845
  } else {
1524
- value.o = _settle.bind(null, pact, state);
1846
+ value.o = UploadManagerBase_settle.bind(null, pact, state);
1525
1847
  return;
1526
1848
  }
1527
1849
  }
1528
1850
  if (value && value.then) {
1529
- 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));
1530
1852
  return;
1531
1853
  }
1532
1854
  pact.s = state;
@@ -1537,7 +1859,7 @@ function _settle(pact, state, value) {
1537
1859
  }
1538
1860
  }
1539
1861
  }
1540
- var _Pact = /*#__PURE__*/function () {
1862
+ var UploadManagerBase_Pact = /*#__PURE__*/function () {
1541
1863
  function _Pact() {}
1542
1864
  _Pact.prototype.then = function (onFulfilled, onRejected) {
1543
1865
  var result = new _Pact();
@@ -1546,9 +1868,9 @@ var _Pact = /*#__PURE__*/function () {
1546
1868
  var callback = state & 1 ? onFulfilled : onRejected;
1547
1869
  if (callback) {
1548
1870
  try {
1549
- _settle(result, 1, callback(this.v));
1871
+ UploadManagerBase_settle(result, 1, callback(this.v));
1550
1872
  } catch (e) {
1551
- _settle(result, 2, e);
1873
+ UploadManagerBase_settle(result, 2, e);
1552
1874
  }
1553
1875
  return result;
1554
1876
  } else {
@@ -1559,28 +1881,28 @@ var _Pact = /*#__PURE__*/function () {
1559
1881
  try {
1560
1882
  var value = _this.v;
1561
1883
  if (_this.s & 1) {
1562
- _settle(result, 1, onFulfilled ? onFulfilled(value) : value);
1884
+ UploadManagerBase_settle(result, 1, onFulfilled ? onFulfilled(value) : value);
1563
1885
  } else if (onRejected) {
1564
- _settle(result, 1, onRejected(value));
1886
+ UploadManagerBase_settle(result, 1, onRejected(value));
1565
1887
  } else {
1566
- _settle(result, 2, value);
1888
+ UploadManagerBase_settle(result, 2, value);
1567
1889
  }
1568
1890
  } catch (e) {
1569
- _settle(result, 2, e);
1891
+ UploadManagerBase_settle(result, 2, e);
1570
1892
  }
1571
1893
  };
1572
1894
  return result;
1573
1895
  };
1574
1896
  return _Pact;
1575
1897
  }();
1576
- function _isSettledPact(thenable) {
1577
- return thenable instanceof _Pact && thenable.s & 1;
1898
+ function UploadManagerBase_isSettledPact(thenable) {
1899
+ return thenable instanceof UploadManagerBase_Pact && thenable.s & 1;
1578
1900
  }
1579
- function _for(test, update, body) {
1901
+ function UploadManagerBase_for(test, update, body) {
1580
1902
  var stage;
1581
1903
  for (;;) {
1582
1904
  var shouldContinue = test();
1583
- if (_isSettledPact(shouldContinue)) {
1905
+ if (UploadManagerBase_isSettledPact(shouldContinue)) {
1584
1906
  shouldContinue = shouldContinue.v;
1585
1907
  }
1586
1908
  if (!shouldContinue) {
@@ -1592,7 +1914,7 @@ function _for(test, update, body) {
1592
1914
  }
1593
1915
  var result = body();
1594
1916
  if (result && result.then) {
1595
- if (_isSettledPact(result)) {
1917
+ if (UploadManagerBase_isSettledPact(result)) {
1596
1918
  result = result.s;
1597
1919
  } else {
1598
1920
  stage = 1;
@@ -1601,14 +1923,14 @@ function _for(test, update, body) {
1601
1923
  }
1602
1924
  if (update) {
1603
1925
  var updateValue = update();
1604
- if (updateValue && updateValue.then && !_isSettledPact(updateValue)) {
1926
+ if (updateValue && updateValue.then && !UploadManagerBase_isSettledPact(updateValue)) {
1605
1927
  stage = 2;
1606
1928
  break;
1607
1929
  }
1608
1930
  }
1609
1931
  }
1610
- var pact = new _Pact();
1611
- var reject = _settle.bind(null, pact, 2);
1932
+ var pact = new UploadManagerBase_Pact();
1933
+ var reject = UploadManagerBase_settle.bind(null, pact, 2);
1612
1934
  (stage === 0 ? shouldContinue.then(_resumeAfterTest) : stage === 1 ? result.then(_resumeAfterBody) : updateValue.then(_resumeAfterUpdate)).then(void 0, reject);
1613
1935
  return pact;
1614
1936
  function _resumeAfterBody(value) {
@@ -1616,14 +1938,14 @@ function _for(test, update, body) {
1616
1938
  do {
1617
1939
  if (update) {
1618
1940
  updateValue = update();
1619
- if (updateValue && updateValue.then && !_isSettledPact(updateValue)) {
1941
+ if (updateValue && updateValue.then && !UploadManagerBase_isSettledPact(updateValue)) {
1620
1942
  updateValue.then(_resumeAfterUpdate).then(void 0, reject);
1621
1943
  return;
1622
1944
  }
1623
1945
  }
1624
1946
  shouldContinue = test();
1625
- if (!shouldContinue || _isSettledPact(shouldContinue) && !shouldContinue.v) {
1626
- _settle(pact, 1, result);
1947
+ if (!shouldContinue || UploadManagerBase_isSettledPact(shouldContinue) && !shouldContinue.v) {
1948
+ UploadManagerBase_settle(pact, 1, result);
1627
1949
  return;
1628
1950
  }
1629
1951
  if (shouldContinue.then) {
@@ -1631,7 +1953,7 @@ function _for(test, update, body) {
1631
1953
  return;
1632
1954
  }
1633
1955
  result = body();
1634
- if (_isSettledPact(result)) {
1956
+ if (UploadManagerBase_isSettledPact(result)) {
1635
1957
  result = result.v;
1636
1958
  }
1637
1959
  } while (!result || !result.then);
@@ -1646,7 +1968,7 @@ function _for(test, update, body) {
1646
1968
  _resumeAfterBody(result);
1647
1969
  }
1648
1970
  } else {
1649
- _settle(pact, 1, result);
1971
+ UploadManagerBase_settle(pact, 1, result);
1650
1972
  }
1651
1973
  }
1652
1974
  function _resumeAfterUpdate() {
@@ -1657,7 +1979,7 @@ function _for(test, update, body) {
1657
1979
  _resumeAfterTest(shouldContinue);
1658
1980
  }
1659
1981
  } else {
1660
- _settle(pact, 1, result);
1982
+ UploadManagerBase_settle(pact, 1, result);
1661
1983
  }
1662
1984
  }
1663
1985
  }
@@ -1673,7 +1995,7 @@ function UploadManagerBase_iterableToArray(iter) { if (typeof Symbol !== "undefi
1673
1995
  function UploadManagerBase_arrayWithoutHoles(arr) { if (Array.isArray(arr)) return UploadManagerBase_arrayLikeToArray(arr); }
1674
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; }
1675
1997
  function UploadManagerBase_empty() {}
1676
- function _awaitIgnored(value, direct) {
1998
+ function UploadManagerBase_awaitIgnored(value, direct) {
1677
1999
  if (!direct) {
1678
2000
  return value && value.then ? value.then(UploadManagerBase_empty) : Promise.resolve();
1679
2001
  }
@@ -1687,11 +2009,11 @@ function UploadManagerBase_await(value, then, direct) {
1687
2009
  }
1688
2010
  return then ? value.then(then) : value;
1689
2011
  }
1690
- function _rethrow(thrown, value) {
2012
+ function UploadManagerBase_rethrow(thrown, value) {
1691
2013
  if (thrown) throw value;
1692
2014
  return value;
1693
2015
  }
1694
- function _finallyRethrows(body, finalizer) {
2016
+ function UploadManagerBase_finallyRethrows(body, finalizer) {
1695
2017
  try {
1696
2018
  var result = body();
1697
2019
  } catch (e) {
@@ -1722,6 +2044,7 @@ var UploadManagerBase = /*#__PURE__*/function () {
1722
2044
  this.defaultMaxConcurrentUploadParts = 4;
1723
2045
  this.intervalMs = 500;
1724
2046
  this.uploadApi = new UploadApi(config);
2047
+ this.accountId = BytescaleApiClientConfigUtils.getAccountId(config);
1725
2048
  }
1726
2049
  UploadManagerBase_createClass(UploadManagerBase, [{
1727
2050
  key: "upload",
@@ -1731,10 +2054,13 @@ var UploadManagerBase = /*#__PURE__*/function () {
1731
2054
  _this2.assertNotCancelled(request);
1732
2055
  var source = _this2.processUploadSource(request.data);
1733
2056
  var preUploadInfo = _this2.getPreUploadInfo(request, source);
1734
- var onProgress = _this2.makeProgressCallback(request, preUploadInfo.size);
2057
+ var bytesTotal = preUploadInfo.size;
2058
+ var makeOnProgressForPart = _this2.makeOnProgressForPartFactory(request, bytesTotal);
1735
2059
  var init = _this2.preUpload(source);
1736
2060
  // Raise initial progress event SYNCHRONOUSLY.
1737
- onProgress(0);
2061
+ if (request.onProgress !== undefined) {
2062
+ request.onProgress(_this2.makeProgressEvent(0, bytesTotal));
2063
+ }
1738
2064
  return UploadManagerBase_await(_this2.beginUpload(request, preUploadInfo), function (uploadInfo) {
1739
2065
  var partCount = uploadInfo.uploadParts.count;
1740
2066
  var parts = UploadManagerBase_toConsumableArray(Array(partCount).keys());
@@ -1742,15 +2068,15 @@ var UploadManagerBase = /*#__PURE__*/function () {
1742
2068
  cancel = _this2$makeCancellati.cancel,
1743
2069
  addCancellationHandler = _this2$makeCancellati.addCancellationHandler;
1744
2070
  var intervalHandle = setInterval(_this2.onIntervalTick(request, cancel), _this2.intervalMs);
1745
- return UploadManagerBase_continue(_finallyRethrows(function () {
2071
+ return UploadManagerBase_continue(UploadManagerBase_finallyRethrows(function () {
1746
2072
  return UploadManagerBase_await(_this2.mapAsync(parts, preUploadInfo.maxConcurrentUploadParts, _async(function (part) {
1747
- return _this2.uploadPart(request, source, part, uploadInfo, onProgress, addCancellationHandler);
2073
+ return _this2.uploadPart(request, source, part, uploadInfo, makeOnProgressForPart(), addCancellationHandler);
1748
2074
  })), function () {
1749
- return _awaitIgnored(_this2.postUpload(init));
2075
+ return UploadManagerBase_awaitIgnored(_this2.postUpload(init));
1750
2076
  });
1751
2077
  }, function (_wasThrown, _result) {
1752
2078
  clearInterval(intervalHandle);
1753
- return _rethrow(_wasThrown, _result);
2079
+ return UploadManagerBase_rethrow(_wasThrown, _result);
1754
2080
  }), function () {
1755
2081
  return uploadInfo.file;
1756
2082
  });
@@ -1800,21 +2126,37 @@ var UploadManagerBase = /*#__PURE__*/function () {
1800
2126
  addCancellationHandler: addCancellationHandler
1801
2127
  };
1802
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
+ */
1803
2132
  }, {
1804
- key: "makeProgressCallback",
1805
- value: function makeProgressCallback(request, bytesTotal) {
2133
+ key: "makeOnProgressForPartFactory",
2134
+ value: function makeOnProgressForPartFactory(request, bytesTotal) {
2135
+ var _this4 = this;
1806
2136
  var onProgress = request.onProgress;
1807
2137
  if (onProgress === undefined) {
1808
- return function () {};
2138
+ return function () {
2139
+ return function () {};
2140
+ };
1809
2141
  }
1810
2142
  var bytesSent = 0;
1811
- return function (bytesSentDelta) {
1812
- bytesSent += bytesSentDelta;
1813
- onProgress({
1814
- bytesTotal: bytesTotal,
1815
- bytesSent: bytesSent,
1816
- progress: Math.round(bytesSent / bytesTotal * 100)
1817
- });
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)
1818
2160
  };
1819
2161
  }
1820
2162
  }, {
@@ -1837,9 +2179,9 @@ var UploadManagerBase = /*#__PURE__*/function () {
1837
2179
  mime = _ref2.mime,
1838
2180
  originalFileName = _ref2.originalFileName;
1839
2181
  try {
1840
- var _this5 = this;
1841
- return UploadManagerBase_await(_this5.uploadApi.beginMultipartUpload({
1842
- accountId: request.accountId,
2182
+ var _this6 = this;
2183
+ return UploadManagerBase_await(_this6.uploadApi.beginMultipartUpload({
2184
+ accountId: _this6.accountId,
1843
2185
  beginMultipartUploadRequest: {
1844
2186
  metadata: request.metadata,
1845
2187
  mime: mime,
@@ -1858,14 +2200,14 @@ var UploadManagerBase = /*#__PURE__*/function () {
1858
2200
  key: "uploadPart",
1859
2201
  value: function uploadPart(request, source, partIndex, uploadInfo, onProgress, addCancellationHandler) {
1860
2202
  try {
1861
- var _this7 = this;
1862
- _this7.assertNotCancelled(request);
1863
- return UploadManagerBase_await(_this7.getUploadPart(request, partIndex, uploadInfo), function (part) {
1864
- _this7.assertNotCancelled(request);
1865
- return UploadManagerBase_await(_this7.putUploadPart(part, source, onProgress, addCancellationHandler), function (etag) {
1866
- _this7.assertNotCancelled(request);
1867
- return _awaitIgnored(_this7.uploadApi.completeUploadPart({
1868
- 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,
1869
2211
  uploadId: uploadInfo.uploadId,
1870
2212
  uploadPartIndex: partIndex,
1871
2213
  completeUploadPartRequest: {
@@ -1885,9 +2227,9 @@ var UploadManagerBase = /*#__PURE__*/function () {
1885
2227
  key: "putUploadPart",
1886
2228
  value: function putUploadPart(part, source, onProgress, addCancellationHandler) {
1887
2229
  try {
1888
- var _this9 = this;
2230
+ var _this10 = this;
1889
2231
  var contentLength = part.range.inclusiveEnd + 1 - part.range.inclusiveStart;
1890
- 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) {
1891
2233
  var status = _ref3.status,
1892
2234
  etag = _ref3.etag;
1893
2235
  if (Math.floor(status / 100) !== 2) {
@@ -1896,6 +2238,8 @@ var UploadManagerBase = /*#__PURE__*/function () {
1896
2238
  if (etag === undefined) {
1897
2239
  throw new Error("No 'etag' response header found in upload part response.");
1898
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);
1899
2243
  return etag;
1900
2244
  });
1901
2245
  } catch (e) {
@@ -1904,15 +2248,15 @@ var UploadManagerBase = /*#__PURE__*/function () {
1904
2248
  }
1905
2249
  }, {
1906
2250
  key: "getUploadPart",
1907
- value: function getUploadPart(request, partIndex, uploadInfo) {
2251
+ value: function getUploadPart(partIndex, uploadInfo) {
1908
2252
  try {
1909
- var _this11 = this;
2253
+ var _this12 = this;
1910
2254
  if (partIndex === 0) {
1911
2255
  return uploadInfo.uploadParts.first;
1912
2256
  }
1913
- return UploadManagerBase_await(_this11.uploadApi.getUploadPart({
2257
+ return UploadManagerBase_await(_this12.uploadApi.getUploadPart({
1914
2258
  uploadId: uploadInfo.uploadId,
1915
- accountId: request.accountId,
2259
+ accountId: _this12.accountId,
1916
2260
  uploadPartIndex: partIndex
1917
2261
  }));
1918
2262
  } catch (e) {
@@ -1936,14 +2280,14 @@ var UploadManagerBase = /*#__PURE__*/function () {
1936
2280
  value: function mapAsync(items, concurrency, callback) {
1937
2281
  try {
1938
2282
  var workQueue = UploadManagerBase_toConsumableArray(items);
1939
- return _awaitIgnored(Promise.all(UploadManagerBase_toConsumableArray(Array(concurrency).keys()).map(_async(function () {
1940
- return _continueIgnored(_for(function () {
2283
+ return UploadManagerBase_awaitIgnored(Promise.all(UploadManagerBase_toConsumableArray(Array(concurrency).keys()).map(_async(function () {
2284
+ return _continueIgnored(UploadManagerBase_for(function () {
1941
2285
  return workQueue.length > 0;
1942
2286
  }, void 0, function () {
1943
2287
  var work = workQueue.shift(); // IMPORTANT: use 'shift' instead of 'pop' to ensure 'items' are processed in order when 'concurrency = 1'.
1944
2288
  return _invokeIgnored(function () {
1945
2289
  if (work !== undefined) {
1946
- return _awaitIgnored(callback(work));
2290
+ return UploadManagerBase_awaitIgnored(callback(work));
1947
2291
  }
1948
2292
  });
1949
2293
  }));
@@ -1955,9 +2299,9 @@ var UploadManagerBase = /*#__PURE__*/function () {
1955
2299
  }]);
1956
2300
  return UploadManagerBase;
1957
2301
  }();
1958
- ;// CONCATENATED MODULE: ./src/public/browser/UploadManagerBrowser.ts
1959
- function UploadManagerBrowser_typeof(obj) { "@babel/helpers - typeof"; return UploadManagerBrowser_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; }, UploadManagerBrowser_typeof(obj); }
1960
- function UploadManagerBrowser_await(value, then, direct) {
2302
+ ;// CONCATENATED MODULE: ./src/private/UploadManagerBrowserWorkerBase.ts
2303
+ function UploadManagerBrowserWorkerBase_typeof(obj) { "@babel/helpers - typeof"; return UploadManagerBrowserWorkerBase_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; }, UploadManagerBrowserWorkerBase_typeof(obj); }
2304
+ function UploadManagerBrowserWorkerBase_await(value, then, direct) {
1961
2305
  if (direct) {
1962
2306
  return then ? then(value) : value;
1963
2307
  }
@@ -1966,44 +2310,31 @@ function UploadManagerBrowser_await(value, then, direct) {
1966
2310
  }
1967
2311
  return then ? value.then(then) : value;
1968
2312
  }
1969
- function UploadManagerBrowser_rethrow(thrown, value) {
1970
- if (thrown) throw value;
1971
- return value;
1972
- }
1973
- function UploadManagerBrowser_finallyRethrows(body, finalizer) {
1974
- try {
1975
- var result = body();
1976
- } catch (e) {
1977
- return finalizer(true, e);
1978
- }
1979
- if (result && result.then) {
1980
- return result.then(finalizer.bind(null, false), finalizer.bind(null, true));
1981
- }
1982
- return finalizer(false, result);
1983
- }
1984
- function UploadManagerBrowser_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
1985
- function UploadManagerBrowser_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, UploadManagerBrowser_toPropertyKey(descriptor.key), descriptor); } }
1986
- function UploadManagerBrowser_createClass(Constructor, protoProps, staticProps) { if (protoProps) UploadManagerBrowser_defineProperties(Constructor.prototype, protoProps); if (staticProps) UploadManagerBrowser_defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
1987
- function UploadManagerBrowser_toPropertyKey(arg) { var key = UploadManagerBrowser_toPrimitive(arg, "string"); return UploadManagerBrowser_typeof(key) === "symbol" ? key : String(key); }
1988
- function UploadManagerBrowser_toPrimitive(input, hint) { if (UploadManagerBrowser_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (UploadManagerBrowser_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
1989
- function UploadManagerBrowser_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) UploadManagerBrowser_setPrototypeOf(subClass, superClass); }
1990
- function UploadManagerBrowser_setPrototypeOf(o, p) { UploadManagerBrowser_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return UploadManagerBrowser_setPrototypeOf(o, p); }
1991
- function UploadManagerBrowser_createSuper(Derived) { var hasNativeReflectConstruct = UploadManagerBrowser_isNativeReflectConstruct(); return function _createSuperInternal() { var Super = UploadManagerBrowser_getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = UploadManagerBrowser_getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return UploadManagerBrowser_possibleConstructorReturn(this, result); }; }
1992
- function UploadManagerBrowser_possibleConstructorReturn(self, call) { if (call && (UploadManagerBrowser_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 UploadManagerBrowser_assertThisInitialized(self); }
1993
- function UploadManagerBrowser_assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
1994
- function UploadManagerBrowser_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; } }
1995
- function UploadManagerBrowser_getPrototypeOf(o) { UploadManagerBrowser_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return UploadManagerBrowser_getPrototypeOf(o); }
1996
-
2313
+ function UploadManagerBrowserWorkerBase_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
2314
+ function UploadManagerBrowserWorkerBase_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, UploadManagerBrowserWorkerBase_toPropertyKey(descriptor.key), descriptor); } }
2315
+ function UploadManagerBrowserWorkerBase_createClass(Constructor, protoProps, staticProps) { if (protoProps) UploadManagerBrowserWorkerBase_defineProperties(Constructor.prototype, protoProps); if (staticProps) UploadManagerBrowserWorkerBase_defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
2316
+ function UploadManagerBrowserWorkerBase_toPropertyKey(arg) { var key = UploadManagerBrowserWorkerBase_toPrimitive(arg, "string"); return UploadManagerBrowserWorkerBase_typeof(key) === "symbol" ? key : String(key); }
2317
+ function UploadManagerBrowserWorkerBase_toPrimitive(input, hint) { if (UploadManagerBrowserWorkerBase_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (UploadManagerBrowserWorkerBase_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
2318
+ function UploadManagerBrowserWorkerBase_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) UploadManagerBrowserWorkerBase_setPrototypeOf(subClass, superClass); }
2319
+ function UploadManagerBrowserWorkerBase_setPrototypeOf(o, p) { UploadManagerBrowserWorkerBase_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return UploadManagerBrowserWorkerBase_setPrototypeOf(o, p); }
2320
+ function UploadManagerBrowserWorkerBase_createSuper(Derived) { var hasNativeReflectConstruct = UploadManagerBrowserWorkerBase_isNativeReflectConstruct(); return function _createSuperInternal() { var Super = UploadManagerBrowserWorkerBase_getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = UploadManagerBrowserWorkerBase_getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return UploadManagerBrowserWorkerBase_possibleConstructorReturn(this, result); }; }
2321
+ function UploadManagerBrowserWorkerBase_possibleConstructorReturn(self, call) { if (call && (UploadManagerBrowserWorkerBase_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 UploadManagerBrowserWorkerBase_assertThisInitialized(self); }
2322
+ function UploadManagerBrowserWorkerBase_assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
2323
+ function UploadManagerBrowserWorkerBase_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; } }
2324
+ function UploadManagerBrowserWorkerBase_getPrototypeOf(o) { UploadManagerBrowserWorkerBase_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return UploadManagerBrowserWorkerBase_getPrototypeOf(o); }
1997
2325
 
1998
2326
 
1999
- var UploadManager = /*#__PURE__*/function (_UploadManagerBase) {
2000
- UploadManagerBrowser_inherits(UploadManager, _UploadManagerBase);
2001
- var _super = UploadManagerBrowser_createSuper(UploadManager);
2002
- function UploadManager() {
2003
- UploadManagerBrowser_classCallCheck(this, UploadManager);
2327
+ /**
2328
+ * The "browser" and "worker" runtimes support the same input types, but the former uses XHR and the latter uses Fetch.
2329
+ */
2330
+ var UploadManagerBrowserWorkerBase = /*#__PURE__*/function (_UploadManagerBase) {
2331
+ UploadManagerBrowserWorkerBase_inherits(UploadManagerBrowserWorkerBase, _UploadManagerBase);
2332
+ var _super = UploadManagerBrowserWorkerBase_createSuper(UploadManagerBrowserWorkerBase);
2333
+ function UploadManagerBrowserWorkerBase() {
2334
+ UploadManagerBrowserWorkerBase_classCallCheck(this, UploadManagerBrowserWorkerBase);
2004
2335
  return _super.apply(this, arguments);
2005
2336
  }
2006
- UploadManagerBrowser_createClass(UploadManager, [{
2337
+ UploadManagerBrowserWorkerBase_createClass(UploadManagerBrowserWorkerBase, [{
2007
2338
  key: "processUploadSource",
2008
2339
  value: function processUploadSource(data) {
2009
2340
  if (typeof data === "string") {
@@ -2015,13 +2346,19 @@ var UploadManager = /*#__PURE__*/function (_UploadManagerBase) {
2015
2346
  })
2016
2347
  };
2017
2348
  }
2349
+ if (data.byteLength !== undefined) {
2350
+ return {
2351
+ type: "ArrayBuffer",
2352
+ value: data
2353
+ };
2354
+ }
2018
2355
  if (data.size !== undefined) {
2019
2356
  return {
2020
2357
  type: "Blob",
2021
2358
  value: data
2022
2359
  };
2023
2360
  }
2024
- throw new Error("Unsupported type for 'data' parameter. Please provide a String, Blob, or File object (from a file input element).");
2361
+ throw new Error("Unsupported type for 'data' parameter. Please provide a String, Blob, ArrayBuffer, or File object (from a file input element).");
2025
2362
  }
2026
2363
  }, {
2027
2364
  key: "getPreUploadInfoPartial",
@@ -2029,8 +2366,15 @@ var UploadManager = /*#__PURE__*/function (_UploadManagerBase) {
2029
2366
  switch (data.type) {
2030
2367
  case "Blob":
2031
2368
  return this.getBlobInfo(data);
2369
+ case "ArrayBuffer":
2370
+ return {
2371
+ mime: undefined,
2372
+ size: data.value.byteLength,
2373
+ originalFileName: undefined,
2374
+ maxConcurrentUploadParts: undefined
2375
+ };
2032
2376
  default:
2033
- assertUnreachable(data.type);
2377
+ assertUnreachable(data);
2034
2378
  }
2035
2379
  }
2036
2380
  }, {
@@ -2041,11 +2385,66 @@ var UploadManager = /*#__PURE__*/function (_UploadManagerBase) {
2041
2385
  }, {
2042
2386
  key: "postUpload",
2043
2387
  value: function postUpload(_init) {
2044
- return UploadManagerBrowser_await();
2388
+ return UploadManagerBrowserWorkerBase_await();
2045
2389
  } // NO-OP.
2046
2390
  }, {
2391
+ key: "getRequestBody",
2392
+ value: function getRequestBody(part, blob) {
2393
+ return part.range.inclusiveEnd === -1 ? new Blob() : blob.value.slice(part.range.inclusiveStart, part.range.inclusiveEnd + 1);
2394
+ }
2395
+ }]);
2396
+ return UploadManagerBrowserWorkerBase;
2397
+ }(UploadManagerBase);
2398
+ ;// CONCATENATED MODULE: ./src/public/browser/UploadManagerBrowser.ts
2399
+ function UploadManagerBrowser_typeof(obj) { "@babel/helpers - typeof"; return UploadManagerBrowser_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; }, UploadManagerBrowser_typeof(obj); }
2400
+ function UploadManagerBrowser_await(value, then, direct) {
2401
+ if (direct) {
2402
+ return then ? then(value) : value;
2403
+ }
2404
+ if (!value || !value.then) {
2405
+ value = Promise.resolve(value);
2406
+ }
2407
+ return then ? value.then(then) : value;
2408
+ }
2409
+ function UploadManagerBrowser_rethrow(thrown, value) {
2410
+ if (thrown) throw value;
2411
+ return value;
2412
+ }
2413
+ function UploadManagerBrowser_finallyRethrows(body, finalizer) {
2414
+ try {
2415
+ var result = body();
2416
+ } catch (e) {
2417
+ return finalizer(true, e);
2418
+ }
2419
+ if (result && result.then) {
2420
+ return result.then(finalizer.bind(null, false), finalizer.bind(null, true));
2421
+ }
2422
+ return finalizer(false, result);
2423
+ }
2424
+ function UploadManagerBrowser_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
2425
+ function UploadManagerBrowser_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, UploadManagerBrowser_toPropertyKey(descriptor.key), descriptor); } }
2426
+ function UploadManagerBrowser_createClass(Constructor, protoProps, staticProps) { if (protoProps) UploadManagerBrowser_defineProperties(Constructor.prototype, protoProps); if (staticProps) UploadManagerBrowser_defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
2427
+ function UploadManagerBrowser_toPropertyKey(arg) { var key = UploadManagerBrowser_toPrimitive(arg, "string"); return UploadManagerBrowser_typeof(key) === "symbol" ? key : String(key); }
2428
+ function UploadManagerBrowser_toPrimitive(input, hint) { if (UploadManagerBrowser_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (UploadManagerBrowser_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
2429
+ function UploadManagerBrowser_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) UploadManagerBrowser_setPrototypeOf(subClass, superClass); }
2430
+ function UploadManagerBrowser_setPrototypeOf(o, p) { UploadManagerBrowser_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return UploadManagerBrowser_setPrototypeOf(o, p); }
2431
+ function UploadManagerBrowser_createSuper(Derived) { var hasNativeReflectConstruct = UploadManagerBrowser_isNativeReflectConstruct(); return function _createSuperInternal() { var Super = UploadManagerBrowser_getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = UploadManagerBrowser_getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return UploadManagerBrowser_possibleConstructorReturn(this, result); }; }
2432
+ function UploadManagerBrowser_possibleConstructorReturn(self, call) { if (call && (UploadManagerBrowser_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 UploadManagerBrowser_assertThisInitialized(self); }
2433
+ function UploadManagerBrowser_assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
2434
+ function UploadManagerBrowser_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; } }
2435
+ function UploadManagerBrowser_getPrototypeOf(o) { UploadManagerBrowser_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return UploadManagerBrowser_getPrototypeOf(o); }
2436
+
2437
+
2438
+ var UploadManager = /*#__PURE__*/function (_UploadManagerBrowser) {
2439
+ UploadManagerBrowser_inherits(UploadManager, _UploadManagerBrowser);
2440
+ var _super = UploadManagerBrowser_createSuper(UploadManager);
2441
+ function UploadManager() {
2442
+ UploadManagerBrowser_classCallCheck(this, UploadManager);
2443
+ return _super.apply(this, arguments);
2444
+ }
2445
+ UploadManagerBrowser_createClass(UploadManager, [{
2047
2446
  key: "doPutUploadPart",
2048
- value: function doPutUploadPart(part, contentLength, source, onProgress, addCancellationHandler) {
2447
+ value: function doPutUploadPart(part, _contentLength, source, onProgress, addCancellationHandler) {
2049
2448
  try {
2050
2449
  var _this2 = this;
2051
2450
  var xhr = new XMLHttpRequest();
@@ -2055,23 +2454,15 @@ var UploadManager = /*#__PURE__*/function (_UploadManagerBase) {
2055
2454
  xhr.abort();
2056
2455
  }
2057
2456
  });
2058
- var lastBytesSent = 0;
2059
- var setBytesSent = function setBytesSent(newBytesSent) {
2060
- var delta = newBytesSent - lastBytesSent;
2061
- lastBytesSent = newBytesSent;
2062
- onProgress(delta);
2063
- };
2064
2457
  return UploadManagerBrowser_finallyRethrows(function () {
2065
2458
  return UploadManagerBrowser_await(new Promise(function (resolve, reject) {
2066
2459
  xhr.upload.addEventListener("progress", function (evt) {
2067
2460
  if (evt.lengthComputable) {
2068
- setBytesSent(evt.loaded);
2461
+ onProgress(evt.loaded);
2069
2462
  }
2070
2463
  }, false);
2071
2464
  xhr.addEventListener("load", function () {
2072
2465
  var _a;
2073
- // Ensure we always report the progress of a finished upload as 100%.
2074
- setBytesSent(contentLength);
2075
2466
  var etag = (_a = xhr.getResponseHeader("etag")) !== null && _a !== void 0 ? _a : undefined;
2076
2467
  resolve({
2077
2468
  etag: etag,
@@ -2098,14 +2489,9 @@ var UploadManager = /*#__PURE__*/function (_UploadManagerBase) {
2098
2489
  return Promise.reject(e);
2099
2490
  }
2100
2491
  }
2101
- }, {
2102
- key: "getRequestBody",
2103
- value: function getRequestBody(part, blob) {
2104
- return part.range.inclusiveEnd === -1 ? new Blob() : blob.value.slice(part.range.inclusiveStart, part.range.inclusiveEnd + 1);
2105
- }
2106
2492
  }]);
2107
2493
  return UploadManager;
2108
- }(UploadManagerBase);
2494
+ }(UploadManagerBrowserWorkerBase);
2109
2495
  ;// CONCATENATED MODULE: ./src/private/ConsoleUtils.ts
2110
2496
  function ConsoleUtils_typeof(obj) { "@babel/helpers - typeof"; return ConsoleUtils_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; }, ConsoleUtils_typeof(obj); }
2111
2497
  function ConsoleUtils_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
@@ -2135,269 +2521,6 @@ var ConsoleUtils = /*#__PURE__*/function () {
2135
2521
  }]);
2136
2522
  return ConsoleUtils;
2137
2523
  }();
2138
- ;// CONCATENATED MODULE: ./src/private/Mutex.ts
2139
- function Mutex_typeof(obj) { "@babel/helpers - typeof"; return Mutex_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; }, Mutex_typeof(obj); }
2140
- function _call(body, then, direct) {
2141
- if (direct) {
2142
- return then ? then(body()) : body();
2143
- }
2144
- try {
2145
- var result = Promise.resolve(body());
2146
- return then ? result.then(then) : result;
2147
- } catch (e) {
2148
- return Promise.reject(e);
2149
- }
2150
- }
2151
- function Mutex_rethrow(thrown, value) {
2152
- if (thrown) throw value;
2153
- return value;
2154
- }
2155
- function Mutex_finallyRethrows(body, finalizer) {
2156
- try {
2157
- var result = body();
2158
- } catch (e) {
2159
- return finalizer(true, e);
2160
- }
2161
- if (result && result.then) {
2162
- return result.then(finalizer.bind(null, false), finalizer.bind(null, true));
2163
- }
2164
- return finalizer(false, result);
2165
- }
2166
- function Mutex_await(value, then, direct) {
2167
- if (direct) {
2168
- return then ? then(value) : value;
2169
- }
2170
- if (!value || !value.then) {
2171
- value = Promise.resolve(value);
2172
- }
2173
- return then ? value.then(then) : value;
2174
- }
2175
- function Mutex_empty() {}
2176
- function Mutex_awaitIgnored(value, direct) {
2177
- if (!direct) {
2178
- return value && value.then ? value.then(Mutex_empty) : Promise.resolve();
2179
- }
2180
- }
2181
- function Mutex_settle(pact, state, value) {
2182
- if (!pact.s) {
2183
- if (value instanceof Mutex_Pact) {
2184
- if (value.s) {
2185
- if (state & 1) {
2186
- state = value.s;
2187
- }
2188
- value = value.v;
2189
- } else {
2190
- value.o = Mutex_settle.bind(null, pact, state);
2191
- return;
2192
- }
2193
- }
2194
- if (value && value.then) {
2195
- value.then(Mutex_settle.bind(null, pact, state), Mutex_settle.bind(null, pact, 2));
2196
- return;
2197
- }
2198
- pact.s = state;
2199
- pact.v = value;
2200
- var observer = pact.o;
2201
- if (observer) {
2202
- observer(pact);
2203
- }
2204
- }
2205
- }
2206
- var Mutex_Pact = /*#__PURE__*/function () {
2207
- function _Pact() {}
2208
- _Pact.prototype.then = function (onFulfilled, onRejected) {
2209
- var result = new _Pact();
2210
- var state = this.s;
2211
- if (state) {
2212
- var callback = state & 1 ? onFulfilled : onRejected;
2213
- if (callback) {
2214
- try {
2215
- Mutex_settle(result, 1, callback(this.v));
2216
- } catch (e) {
2217
- Mutex_settle(result, 2, e);
2218
- }
2219
- return result;
2220
- } else {
2221
- return this;
2222
- }
2223
- }
2224
- this.o = function (_this) {
2225
- try {
2226
- var value = _this.v;
2227
- if (_this.s & 1) {
2228
- Mutex_settle(result, 1, onFulfilled ? onFulfilled(value) : value);
2229
- } else if (onRejected) {
2230
- Mutex_settle(result, 1, onRejected(value));
2231
- } else {
2232
- Mutex_settle(result, 2, value);
2233
- }
2234
- } catch (e) {
2235
- Mutex_settle(result, 2, e);
2236
- }
2237
- };
2238
- return result;
2239
- };
2240
- return _Pact;
2241
- }();
2242
- function Mutex_isSettledPact(thenable) {
2243
- return thenable instanceof Mutex_Pact && thenable.s & 1;
2244
- }
2245
- function Mutex_for(test, update, body) {
2246
- var stage;
2247
- for (;;) {
2248
- var shouldContinue = test();
2249
- if (Mutex_isSettledPact(shouldContinue)) {
2250
- shouldContinue = shouldContinue.v;
2251
- }
2252
- if (!shouldContinue) {
2253
- return result;
2254
- }
2255
- if (shouldContinue.then) {
2256
- stage = 0;
2257
- break;
2258
- }
2259
- var result = body();
2260
- if (result && result.then) {
2261
- if (Mutex_isSettledPact(result)) {
2262
- result = result.s;
2263
- } else {
2264
- stage = 1;
2265
- break;
2266
- }
2267
- }
2268
- if (update) {
2269
- var updateValue = update();
2270
- if (updateValue && updateValue.then && !Mutex_isSettledPact(updateValue)) {
2271
- stage = 2;
2272
- break;
2273
- }
2274
- }
2275
- }
2276
- var pact = new Mutex_Pact();
2277
- var reject = Mutex_settle.bind(null, pact, 2);
2278
- (stage === 0 ? shouldContinue.then(_resumeAfterTest) : stage === 1 ? result.then(_resumeAfterBody) : updateValue.then(_resumeAfterUpdate)).then(void 0, reject);
2279
- return pact;
2280
- function _resumeAfterBody(value) {
2281
- result = value;
2282
- do {
2283
- if (update) {
2284
- updateValue = update();
2285
- if (updateValue && updateValue.then && !Mutex_isSettledPact(updateValue)) {
2286
- updateValue.then(_resumeAfterUpdate).then(void 0, reject);
2287
- return;
2288
- }
2289
- }
2290
- shouldContinue = test();
2291
- if (!shouldContinue || Mutex_isSettledPact(shouldContinue) && !shouldContinue.v) {
2292
- Mutex_settle(pact, 1, result);
2293
- return;
2294
- }
2295
- if (shouldContinue.then) {
2296
- shouldContinue.then(_resumeAfterTest).then(void 0, reject);
2297
- return;
2298
- }
2299
- result = body();
2300
- if (Mutex_isSettledPact(result)) {
2301
- result = result.v;
2302
- }
2303
- } while (!result || !result.then);
2304
- result.then(_resumeAfterBody).then(void 0, reject);
2305
- }
2306
- function _resumeAfterTest(shouldContinue) {
2307
- if (shouldContinue) {
2308
- result = body();
2309
- if (result && result.then) {
2310
- result.then(_resumeAfterBody).then(void 0, reject);
2311
- } else {
2312
- _resumeAfterBody(result);
2313
- }
2314
- } else {
2315
- Mutex_settle(pact, 1, result);
2316
- }
2317
- }
2318
- function _resumeAfterUpdate() {
2319
- if (shouldContinue = test()) {
2320
- if (shouldContinue.then) {
2321
- shouldContinue.then(_resumeAfterTest).then(void 0, reject);
2322
- } else {
2323
- _resumeAfterTest(shouldContinue);
2324
- }
2325
- } else {
2326
- Mutex_settle(pact, 1, result);
2327
- }
2328
- }
2329
- }
2330
- function Mutex_continue(value, then) {
2331
- return value && value.then ? value.then(then) : then(value);
2332
- }
2333
- function Mutex_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
2334
- function Mutex_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, Mutex_toPropertyKey(descriptor.key), descriptor); } }
2335
- function Mutex_createClass(Constructor, protoProps, staticProps) { if (protoProps) Mutex_defineProperties(Constructor.prototype, protoProps); if (staticProps) Mutex_defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
2336
- function Mutex_toPropertyKey(arg) { var key = Mutex_toPrimitive(arg, "string"); return Mutex_typeof(key) === "symbol" ? key : String(key); }
2337
- function Mutex_toPrimitive(input, hint) { if (Mutex_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (Mutex_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
2338
- /**
2339
- * A lightweight mutex. (Other libraries contain too many features and we want to keep the size upload-js down).
2340
- *
2341
- * Characteristics:
2342
- * - Non-reentrant.
2343
- * - Unfair. (Multiple callers awaiting 'acquire' will be granted the mutex in no order.)
2344
- * - When calling `safe` consecutively with no 'awaits' in-between, the current context will synchronously acquire
2345
- * the mutex every time.
2346
- */
2347
- var Mutex = /*#__PURE__*/function () {
2348
- function Mutex() {
2349
- Mutex_classCallCheck(this, Mutex);
2350
- this.mutex = undefined;
2351
- this.resolver = undefined;
2352
- }
2353
- Mutex_createClass(Mutex, [{
2354
- key: "safe",
2355
- value: function safe(callback) {
2356
- try {
2357
- var _this2 = this;
2358
- return Mutex_await(_this2.acquire(), function () {
2359
- return Mutex_finallyRethrows(callback, function (_wasThrown, _result) {
2360
- _this2.release();
2361
- return Mutex_rethrow(_wasThrown, _result);
2362
- });
2363
- });
2364
- } catch (e) {
2365
- return Promise.reject(e);
2366
- }
2367
- }
2368
- }, {
2369
- key: "acquire",
2370
- value: function acquire() {
2371
- try {
2372
- var _this4 = this;
2373
- // Loop necessary for when multiple calls are made to 'acquire' before a 'release' is called, else the call to
2374
- // 'release' will resume every caller currently waiting on 'acquire'.
2375
- return Mutex_continue(Mutex_for(function () {
2376
- return _this4.mutex !== undefined;
2377
- }, void 0, function () {
2378
- return Mutex_awaitIgnored(_this4.mutex);
2379
- }), function () {
2380
- _this4.mutex = new Promise(function (resolve) {
2381
- _this4.resolver = resolve;
2382
- });
2383
- });
2384
- } catch (e) {
2385
- return Promise.reject(e);
2386
- }
2387
- }
2388
- }, {
2389
- key: "release",
2390
- value: function release() {
2391
- if (this.resolver === undefined) {
2392
- throw new Error("Unable to release mutex: already released.");
2393
- }
2394
- this.resolver();
2395
- this.resolver = undefined;
2396
- this.mutex = undefined;
2397
- }
2398
- }]);
2399
- return Mutex;
2400
- }();
2401
2524
  ;// CONCATENATED MODULE: ./src/public/browser/AuthManagerBrowser.ts
2402
2525
  function AuthManagerBrowser_typeof(obj) { "@babel/helpers - typeof"; return AuthManagerBrowser_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; }, AuthManagerBrowser_typeof(obj); }
2403
2526
  function AuthManagerBrowser_defineProperty(obj, key, value) { key = AuthManagerBrowser_toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
@@ -2464,63 +2587,47 @@ function AuthManagerBrowser_defineProperties(target, props) { for (var i = 0; i
2464
2587
  function AuthManagerBrowser_createClass(Constructor, protoProps, staticProps) { if (protoProps) AuthManagerBrowser_defineProperties(Constructor.prototype, protoProps); if (staticProps) AuthManagerBrowser_defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
2465
2588
  function AuthManagerBrowser_toPropertyKey(arg) { var key = AuthManagerBrowser_toPrimitive(arg, "string"); return AuthManagerBrowser_typeof(key) === "symbol" ? key : String(key); }
2466
2589
  function AuthManagerBrowser_toPrimitive(input, hint) { if (AuthManagerBrowser_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (AuthManagerBrowser_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
2467
- function AuthManagerBrowser_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) AuthManagerBrowser_setPrototypeOf(subClass, superClass); }
2468
- function AuthManagerBrowser_setPrototypeOf(o, p) { AuthManagerBrowser_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return AuthManagerBrowser_setPrototypeOf(o, p); }
2469
- function AuthManagerBrowser_createSuper(Derived) { var hasNativeReflectConstruct = AuthManagerBrowser_isNativeReflectConstruct(); return function _createSuperInternal() { var Super = AuthManagerBrowser_getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = AuthManagerBrowser_getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return AuthManagerBrowser_possibleConstructorReturn(this, result); }; }
2470
- function AuthManagerBrowser_possibleConstructorReturn(self, call) { if (call && (AuthManagerBrowser_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 AuthManagerBrowser_assertThisInitialized(self); }
2471
- function AuthManagerBrowser_assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
2472
- function AuthManagerBrowser_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; } }
2473
- function AuthManagerBrowser_getPrototypeOf(o) { AuthManagerBrowser_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return AuthManagerBrowser_getPrototypeOf(o); }
2474
2590
 
2475
2591
 
2476
2592
 
2477
-
2478
- var AuthManager = /*#__PURE__*/function (_BaseAPI) {
2479
- AuthManagerBrowser_inherits(AuthManager, _BaseAPI);
2480
- var _super = AuthManagerBrowser_createSuper(AuthManager);
2481
- function AuthManager(config) {
2482
- var _this;
2483
- AuthManagerBrowser_classCallCheck(this, AuthManager);
2484
- _this = _super.call(this, config);
2485
- _this.authSessionMutex = new Mutex();
2486
- _this.contentType = "content-type";
2487
- _this.contentTypeJson = "application/json";
2488
- _this.contentTypeText = "text/plain";
2489
- _this.minJwtTtlSeconds = 10;
2490
- _this.retryAuthAfterErrorSeconds = 5;
2491
- _this.refreshBeforeExpirySeconds = 20;
2492
- var cdnUrl = BytescaleApiClientConfigUtils.getCdnUrl(config);
2493
- var accountId = BytescaleApiClientConfigUtils.getAccountId(config);
2494
- _this.accessTokenUrl = "".concat(cdnUrl, "/api/v1/access_tokens/").concat(accountId);
2495
- return _this;
2496
- }
2497
- AuthManagerBrowser_createClass(AuthManager, [{
2593
+ var AuthManagerImpl = /*#__PURE__*/function () {
2594
+ function AuthManagerImpl() {
2595
+ AuthManagerBrowser_classCallCheck(this, AuthManagerImpl);
2596
+ this.contentType = "content-type";
2597
+ this.contentTypeJson = "application/json";
2598
+ this.contentTypeText = "text/plain";
2599
+ this.minJwtTtlSeconds = 10;
2600
+ this.maxJwtTtlSeconds = 2147483; // Max value for window.setTimeout is 2147483647ms -- if we go over this, the timeout fires immediately.
2601
+ this.retryAuthAfterErrorSeconds = 5;
2602
+ this.refreshBeforeExpirySeconds = 20;
2603
+ this.authSessionMutex = AuthSessionState.getMutex();
2604
+ }
2605
+ AuthManagerBrowser_createClass(AuthManagerImpl, [{
2498
2606
  key: "isAuthSessionActive",
2499
2607
  value: function isAuthSessionActive() {
2500
- return AuthSessionState.session !== undefined;
2608
+ return AuthSessionState.getSession() !== undefined;
2501
2609
  }
2502
2610
  }, {
2503
2611
  key: "beginAuthSession",
2504
- value: function beginAuthSession(authUrl, authHeaders) {
2612
+ value: function beginAuthSession(params) {
2505
2613
  try {
2506
- var _this3 = this;
2614
+ var _this2 = this;
2507
2615
  var newSession = {
2508
2616
  accessToken: undefined,
2509
2617
  accessTokenRefreshHandle: undefined,
2510
- authUrl: authUrl,
2511
- authHeaders: authHeaders,
2618
+ params: params,
2512
2619
  isActive: true
2513
2620
  };
2514
- return AuthManagerBrowser_await(_this3.authSessionMutex.safe(AuthManagerBrowser_async(function () {
2621
+ return AuthManagerBrowser_await(_this2.authSessionMutex.safe(AuthManagerBrowser_async(function () {
2515
2622
  // We check both 'session' and 'sessionDisposing' here, as we don't want to call 'beginAuthSession' until the session is fully disposed.
2516
- if (_this3.isAuthSessionActive()) {
2623
+ if (_this2.isAuthSessionActive()) {
2517
2624
  throw new Error("Auth session already active: see AuthManager.isAuthSessionActive(). Please call 'await endAuthSession()' and then 'await beginAuthSession(...)' if you want to start a new auth session.");
2518
2625
  }
2519
- AuthSessionState.session = newSession;
2626
+ AuthSessionState.setSession(newSession);
2520
2627
  return AuthManagerBrowser_await();
2521
2628
  })), function () {
2522
2629
  // IMPORTANT: must be called outside the above, else re-entrant deadlock will occur.
2523
- return AuthManagerBrowser_awaitIgnored(_this3.refreshAccessToken(newSession));
2630
+ return AuthManagerBrowser_awaitIgnored(_this2.refreshAccessToken(newSession));
2524
2631
  });
2525
2632
  } catch (e) {
2526
2633
  return Promise.reject(e);
@@ -2530,18 +2637,18 @@ var AuthManager = /*#__PURE__*/function (_BaseAPI) {
2530
2637
  key: "endAuthSession",
2531
2638
  value: function endAuthSession() {
2532
2639
  try {
2533
- var _this5 = this;
2534
- return AuthManagerBrowser_awaitIgnored(_this5.authSessionMutex.safe(AuthManagerBrowser_async(function () {
2535
- if (AuthSessionState.session === undefined) {
2640
+ var _this4 = this;
2641
+ return AuthManagerBrowser_awaitIgnored(_this4.authSessionMutex.safe(AuthManagerBrowser_async(function () {
2642
+ var session = AuthSessionState.getSession();
2643
+ if (session === undefined) {
2536
2644
  return;
2537
2645
  }
2538
- var session = AuthSessionState.session;
2539
- AuthSessionState.session = undefined;
2646
+ AuthSessionState.setSession(undefined);
2540
2647
  session.isActive = false;
2541
2648
  if (session.accessTokenRefreshHandle !== undefined) {
2542
2649
  clearTimeout(session.accessTokenRefreshHandle);
2543
2650
  }
2544
- return AuthManagerBrowser_awaitIgnored(_this5.deleteAccessToken());
2651
+ return AuthManagerBrowser_awaitIgnored(_this4.deleteAccessToken(session.params));
2545
2652
  })));
2546
2653
  } catch (e) {
2547
2654
  return Promise.reject(e);
@@ -2551,24 +2658,26 @@ var AuthManager = /*#__PURE__*/function (_BaseAPI) {
2551
2658
  key: "refreshAccessToken",
2552
2659
  value: function refreshAccessToken(session) {
2553
2660
  try {
2554
- var _this7 = this;
2555
- return AuthManagerBrowser_awaitIgnored(_this7.authSessionMutex.safe(AuthManagerBrowser_async(function () {
2661
+ var _this6 = this;
2662
+ return AuthManagerBrowser_awaitIgnored(_this6.authSessionMutex.safe(AuthManagerBrowser_async(function () {
2556
2663
  if (!session.isActive) {
2557
2664
  return;
2558
2665
  }
2559
- var timeout = _this7.retryAuthAfterErrorSeconds;
2666
+ var timeout = _this6.retryAuthAfterErrorSeconds;
2560
2667
  return AuthManagerBrowser_continueIgnored(AuthManagerBrowser_finallyRethrows(function () {
2561
2668
  return AuthManagerBrowser_catch(function () {
2562
- var _getAccessToken = _this7.getAccessToken,
2563
- _session$authUrl = session.authUrl;
2564
- return AuthManagerBrowser_await(session.authHeaders(), function (_session$authHeaders) {
2565
- return AuthManagerBrowser_await(_getAccessToken.call(_this7, _session$authUrl, _session$authHeaders), function (jwt) {
2566
- return AuthManagerBrowser_await(_this7.setAccessToken(jwt), function (setTokenResult) {
2567
- var desiredTtl = setTokenResult.ttlSeconds - _this7.refreshBeforeExpirySeconds;
2568
- timeout = Math.max(desiredTtl, _this7.minJwtTtlSeconds);
2669
+ var _getAccessToken = _this6.getAccessToken,
2670
+ _session$params = session.params;
2671
+ return AuthManagerBrowser_await(session.params.authHeaders(), function (_session$params$authH) {
2672
+ return AuthManagerBrowser_await(_getAccessToken.call(_this6, _session$params, _session$params$authH), function (jwt) {
2673
+ return AuthManagerBrowser_await(_this6.setAccessToken(session.params, jwt), function (setTokenResult) {
2674
+ var desiredTtl = setTokenResult.ttlSeconds - _this6.refreshBeforeExpirySeconds;
2675
+ timeout = Math.max(desiredTtl, _this6.minJwtTtlSeconds);
2569
2676
  if (desiredTtl !== timeout) {
2570
2677
  ConsoleUtils.warn("JWT expiration is too short: waiting for ".concat(timeout, " seconds before refreshing."));
2571
2678
  }
2679
+ // There's need to print a warning for this: it's OK to silently request the JWT before it expires. Also, this is 24 days in this case!
2680
+ timeout = Math.min(timeout, _this6.maxJwtTtlSeconds);
2572
2681
  session.accessToken = setTokenResult.accessToken;
2573
2682
  });
2574
2683
  });
@@ -2579,7 +2688,7 @@ var AuthManager = /*#__PURE__*/function (_BaseAPI) {
2579
2688
  });
2580
2689
  }, function (_wasThrown, _result) {
2581
2690
  session.accessTokenRefreshHandle = window.setTimeout(function () {
2582
- _this7.refreshAccessToken(session).then(function () {}, function (e) {
2691
+ _this6.refreshAccessToken(session).then(function () {}, function (e) {
2583
2692
  return ConsoleUtils.error("Unexpected error when refreshing access token: ".concat(e));
2584
2693
  });
2585
2694
  }, timeout * 1000);
@@ -2590,34 +2699,49 @@ var AuthManager = /*#__PURE__*/function (_BaseAPI) {
2590
2699
  return Promise.reject(e);
2591
2700
  }
2592
2701
  }
2702
+ }, {
2703
+ key: "getAccessTokenUrl",
2704
+ value: function getAccessTokenUrl(params) {
2705
+ var _a;
2706
+ var cdnUrl = BytescaleApiClientConfigUtils.getCdnUrl((_a = params.options) !== null && _a !== void 0 ? _a : {});
2707
+ return "".concat(cdnUrl, "/api/v1/access_tokens/").concat(params.accountId);
2708
+ }
2593
2709
  }, {
2594
2710
  key: "deleteAccessToken",
2595
- value: function deleteAccessToken() {
2711
+ value: function deleteAccessToken(params) {
2596
2712
  try {
2597
- var _this9 = this;
2598
- return AuthManagerBrowser_awaitIgnored(_this9.doFetch(_this9.accessTokenUrl, {
2713
+ var _this8 = this;
2714
+ var _a;
2715
+ return AuthManagerBrowser_awaitIgnored(BaseAPI.fetch(_this8.getAccessTokenUrl(params), {
2599
2716
  method: "DELETE",
2600
2717
  credentials: "include",
2601
2718
  headers: {}
2602
- }, true));
2719
+ }, {
2720
+ isBytescaleApi: true,
2721
+ fetchApi: (_a = params.options) === null || _a === void 0 ? void 0 : _a.fetchApi
2722
+ }));
2603
2723
  } catch (e) {
2604
2724
  return Promise.reject(e);
2605
2725
  }
2606
2726
  }
2607
2727
  }, {
2608
2728
  key: "setAccessToken",
2609
- value: function setAccessToken(jwt) {
2729
+ value: function setAccessToken(params, jwt) {
2610
2730
  try {
2611
- var _this11 = this;
2731
+ var _this10 = this;
2732
+ var _a;
2612
2733
  var request = {
2613
2734
  accessToken: jwt
2614
2735
  };
2615
- return AuthManagerBrowser_await(_this11.doFetch(_this11.accessTokenUrl, {
2736
+ return AuthManagerBrowser_await(BaseAPI.fetch(_this10.getAccessTokenUrl(params), {
2616
2737
  method: "PUT",
2617
2738
  credentials: "include",
2618
- headers: AuthManagerBrowser_defineProperty({}, _this11.contentType, _this11.contentTypeJson),
2739
+ headers: AuthManagerBrowser_defineProperty({}, _this10.contentType, _this10.contentTypeJson),
2619
2740
  body: JSON.stringify(request)
2620
- }, true), function (response) {
2741
+ }, {
2742
+ isBytescaleApi: true,
2743
+ fetchApi: (_a = params.options) === null || _a === void 0 ? void 0 : _a.fetchApi
2744
+ }), function (response) {
2621
2745
  return AuthManagerBrowser_await(response.json());
2622
2746
  });
2623
2747
  } catch (e) {
@@ -2626,17 +2750,23 @@ var AuthManager = /*#__PURE__*/function (_BaseAPI) {
2626
2750
  }
2627
2751
  }, {
2628
2752
  key: "getAccessToken",
2629
- value: function getAccessToken(authUrl, headers) {
2753
+ value: function getAccessToken(params, headers) {
2630
2754
  try {
2631
- var _this13 = this;
2755
+ var _this12 = this;
2756
+ var _a, _b;
2632
2757
  var endpointName = "Your auth API endpoint";
2633
- var requiredContentType = _this13.contentTypeText;
2634
- return AuthManagerBrowser_await(_this13.doFetch(authUrl, {
2758
+ var requiredContentType = _this12.contentTypeText;
2759
+ return AuthManagerBrowser_await(BaseAPI.fetch(params.authUrl, {
2635
2760
  method: "GET",
2636
2761
  headers: headers
2637
- }, false), function (result) {
2638
- if (result.headers.get(_this13.contentType) !== requiredContentType) {
2639
- throw new Error("".concat(endpointName, " returned an unsupported '").concat(_this13.contentType, "' response header: please return '").concat(requiredContentType, "'."));
2762
+ }, {
2763
+ isBytescaleApi: false,
2764
+ fetchApi: (_a = params.options) === null || _a === void 0 ? void 0 : _a.fetchApi
2765
+ }), function (result) {
2766
+ var actualContentType = (_b = result.headers.get(_this12.contentType)) !== null && _b !== void 0 ? _b : "";
2767
+ // Support content types like "text/plain; charset=utf-8" and "text/plain"
2768
+ if (actualContentType.split(";")[0] !== requiredContentType) {
2769
+ throw new Error("".concat(endpointName, " returned \"").concat(actualContentType, "\" for the ").concat(_this12.contentType, " response header, but the Bytescale SDK requires \"").concat(requiredContentType, "\"."));
2640
2770
  }
2641
2771
  return AuthManagerBrowser_await(result.text(), function (jwt) {
2642
2772
  if (jwt.length === 0) {
@@ -2654,8 +2784,12 @@ var AuthManager = /*#__PURE__*/function (_BaseAPI) {
2654
2784
  }
2655
2785
  }
2656
2786
  }]);
2657
- return AuthManager;
2658
- }(BaseAPI);
2787
+ return AuthManagerImpl;
2788
+ }();
2789
+ /**
2790
+ * 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).
2791
+ */
2792
+ var AuthManager = new AuthManagerImpl();
2659
2793
  ;// CONCATENATED MODULE: ./src/public/browser/index.ts
2660
2794
 
2661
2795