@bytescale/sdk 3.58.0 → 3.60.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (29) hide show
  1. package/dist/browser/cjs/main.js +730 -316
  2. package/dist/browser/esm/main.mjs +730 -316
  3. package/dist/node/cjs/main.js +123 -29
  4. package/dist/node/esm/main.mjs +123 -29
  5. package/dist/types/private/AuthSessionState.d.ts +7 -0
  6. package/dist/types/private/UploadManagerBase.d.ts +0 -1
  7. package/dist/types/private/dtos/AuthSwSetConfigDto.d.ts +1 -1
  8. package/dist/types/private/model/AuthManagerInterface.d.ts +1 -105
  9. package/dist/types/private/model/AuthSession.d.ts +12 -5
  10. package/dist/types/private/model/AuthSessionConfig.d.ts +3 -0
  11. package/dist/types/private/model/AuthSessionConfigAuto.d.ts +6 -0
  12. package/dist/types/private/model/AuthSessionConfigBase.d.ts +14 -0
  13. package/dist/types/private/model/AuthSessionConfigManual.d.ts +7 -0
  14. package/dist/types/private/model/BeginAuthSessionParams.d.ts +3 -0
  15. package/dist/types/private/model/BeginAuthSessionParamsOptions.d.ts +2 -0
  16. package/dist/types/private/model/BeginAuthSessionParamsV1.d.ts +11 -0
  17. package/dist/types/private/model/BeginAuthSessionParamsV2.d.ts +16 -0
  18. package/dist/types/private/model/NonEmptyArray.d.ts +1 -0
  19. package/dist/types/private/model/UrlRewriteRule.d.ts +6 -0
  20. package/dist/types/public/browser/AuthManagerBrowser.d.ts +28 -11
  21. package/dist/types/public/node/AuthManagerNode.d.ts +12 -2
  22. package/dist/types/public/shared/generated/runtime.d.ts +13 -6
  23. package/dist/worker/cjs/main.js +123 -29
  24. package/dist/worker/esm/main.mjs +123 -29
  25. package/package.json +1 -1
  26. package/tests/ApiClientAuth.test.ts +222 -0
  27. package/tests/AuthManagerBrowser.test.ts +360 -234
  28. package/tests/AuthServiceWorkerRewrite.test.ts +86 -5
  29. package/tests/UploadManagerAuth.test.ts +156 -0
@@ -210,6 +210,55 @@ var AuthSessionState = /*#__PURE__*/function () {
210
210
  }
211
211
  return window[AuthSessionState.stateKey];
212
212
  }
213
+ /** Resolves request-time auth while remaining compatible with the single-token session used by SDK 3.54.0. */
214
+ }, {
215
+ key: "resolveAuthConfig",
216
+ value: function resolveAuthConfig(authConfigId, requireReadyDefault) {
217
+ if (authConfigId === false) {
218
+ return undefined;
219
+ }
220
+ var session = AuthSessionState.getSession();
221
+ if (session === undefined || !session.isActive) {
222
+ if (typeof authConfigId === "string") {
223
+ throw new Error("No active AuthManager configuration has ID '".concat(authConfigId, "'."));
224
+ }
225
+ return undefined;
226
+ }
227
+ if (Array.isArray(session.authConfigs)) {
228
+ var state = session.authConfigs.find(function (config) {
229
+ return config.config.authConfigId === authConfigId;
230
+ });
231
+ if (state === undefined) {
232
+ if (typeof authConfigId === "string") {
233
+ throw new Error("No active AuthManager configuration has ID '".concat(authConfigId, "'."));
234
+ }
235
+ return undefined;
236
+ }
237
+ if (state.accessToken === undefined || state.expiresAt === undefined || state.expiresAt <= Date.now() || state.jwt === undefined) {
238
+ var isV2Session = typeof session.params.authConfigs === "function";
239
+ if (typeof authConfigId === "string" || requireReadyDefault || isV2Session) {
240
+ throw new Error("AuthManager configuration '".concat(authConfigId !== null && authConfigId !== void 0 ? authConfigId : "default", "' is not ready."));
241
+ }
242
+ return undefined;
243
+ }
244
+ return {
245
+ accessToken: state.accessToken,
246
+ accountId: state.config.accountId,
247
+ jwt: state.jwt
248
+ };
249
+ }
250
+ if (typeof authConfigId === "string") {
251
+ throw new Error("No active AuthManager configuration has ID '".concat(authConfigId, "'."));
252
+ }
253
+ if (session.accessToken === undefined || typeof session.params.accountId !== "string") {
254
+ return undefined;
255
+ }
256
+ return {
257
+ accessToken: session.accessToken,
258
+ accountId: session.params.accountId,
259
+ jwt: undefined
260
+ };
261
+ }
213
262
  }]);
214
263
  }();
215
264
  AuthSessionState.stateKey = "BytescaleSessionState";
@@ -353,12 +402,47 @@ var BytescaleApiClientConfigUtils = /*#__PURE__*/function () {
353
402
  }, {
354
403
  key: "getAccountId",
355
404
  value: function getAccountId(config) {
405
+ return BytescaleApiClientConfigUtils.resolveAuthentication(config).accountId;
406
+ }
407
+ }, {
408
+ key: "resolveAuthentication",
409
+ value: function resolveAuthentication(config) {
410
+ var _a, _b;
411
+ var apiKey = (_a = config.apiKey) !== null && _a !== void 0 ? _a : undefined;
412
+ var authConfig = AuthSessionState.resolveAuthConfig(config.authConfigId, apiKey === undefined);
413
+ var apiKeyAccountId = apiKey === undefined ? undefined : BytescaleApiClientConfigUtils.getApiKeyAccountId(apiKey);
414
+ if (apiKeyAccountId !== undefined && authConfig !== undefined && apiKeyAccountId !== authConfig.accountId) {
415
+ throw new Error("The API key belongs to account '".concat(apiKeyAccountId, "', but AuthManager configuration '").concat((_b = config.authConfigId) !== null && _b !== void 0 ? _b : "default", "' belongs to account '").concat(authConfig.accountId, "'."));
416
+ }
417
+ if (apiKey !== undefined) {
418
+ return {
419
+ accountId: apiKeyAccountId,
420
+ headers: Object.assign({
421
+ Authorization: "Bearer ".concat(apiKey)
422
+ }, authConfig === undefined ? {} : {
423
+ "Authorization-Token": authConfig.accessToken
424
+ })
425
+ };
426
+ }
427
+ if ((authConfig === null || authConfig === void 0 ? void 0 : authConfig.jwt) !== undefined) {
428
+ return {
429
+ accountId: authConfig.accountId,
430
+ headers: {
431
+ Authorization: "Bearer ".concat(authConfig.jwt)
432
+ }
433
+ };
434
+ }
435
+ throw new Error("Please provide an API key via the 'apiKey' config parameter.");
436
+ }
437
+ }, {
438
+ key: "getApiKeyAccountId",
439
+ value: function getApiKeyAccountId(apiKey) {
356
440
  var _a, _b;
357
441
  var accountId;
358
- if (BytescaleApiClientConfigUtils.specialApiKeys.includes(config.apiKey)) {
442
+ if (BytescaleApiClientConfigUtils.specialApiKeys.includes(apiKey)) {
359
443
  accountId = BytescaleApiClientConfigUtils.specialApiKeyAccountId;
360
444
  } else {
361
- accountId = (_b = (_a = config.apiKey.split("_")[1]) === null || _a === void 0 ? void 0 : _a.substr(0, BytescaleApiClientConfigUtils.accountIdLength)) !== null && _b !== void 0 ? _b : "";
445
+ accountId = (_b = (_a = apiKey.split("_")[1]) === null || _a === void 0 ? void 0 : _a.substr(0, BytescaleApiClientConfigUtils.accountIdLength)) !== null && _b !== void 0 ? _b : "";
362
446
  if (accountId.length !== BytescaleApiClientConfigUtils.accountIdLength) {
363
447
  throw new Error("Invalid Bytescale API key.");
364
448
  }
@@ -368,21 +452,24 @@ var BytescaleApiClientConfigUtils = /*#__PURE__*/function () {
368
452
  }, {
369
453
  key: "validate",
370
454
  value: function validate(config) {
371
- var _a;
372
455
  // Defensive programming, for users not using TypeScript. Mainly because this is used by UploadWidget users.
373
456
  if ((config !== null && config !== void 0 ? config : undefined) === undefined) {
374
457
  throw new Error("Config parameter required.");
375
458
  }
376
- if (((_a = config.apiKey) !== null && _a !== void 0 ? _a : undefined) === undefined) {
377
- throw new Error("Please provide an API key via the 'apiKey' config parameter.");
459
+ if (config.authConfigId !== undefined && config.authConfigId !== false && typeof config.authConfigId !== "string") {
460
+ throw new Error("The 'authConfigId' config parameter must be a string, false, or undefined.");
461
+ }
462
+ if (config.apiKey !== undefined && typeof config.apiKey !== "string") {
463
+ throw new Error("The 'apiKey' config parameter must be a string when provided.");
378
464
  }
379
- if (config.apiKey.trim() !== config.apiKey) {
465
+ if (config.apiKey !== undefined && config.apiKey.trim() !== config.apiKey) {
380
466
  // We do not support API keys with whitespace (by trimming ourselves) because otherwise we'd need to support this
381
467
  // everywhere in perpetuity (since removing the trimming would be a breaking change).
382
468
  throw new Error("API key needs trimming (whitespace detected).");
383
469
  }
384
- // This performs futher validation on the API key...
385
- BytescaleApiClientConfigUtils.getAccountId(config);
470
+ if (config.apiKey !== undefined) {
471
+ BytescaleApiClientConfigUtils.getApiKeyAccountId(config.apiKey);
472
+ }
386
473
  }
387
474
  }]);
388
475
  }();
@@ -409,12 +496,7 @@ var BaseAPI = /*#__PURE__*/function () {
409
496
  try {
410
497
  var _this = this;
411
498
  var _a;
412
- var apiKey = _this.config.apiKey;
413
- context.headers["Authorization"] = "Bearer ".concat(apiKey); // authorization-header authentication
414
- var session = AuthSessionState.getSession();
415
- if ((session === null || session === void 0 ? void 0 : session.accessToken) !== undefined) {
416
- context.headers["Authorization-Token"] = session.accessToken;
417
- }
499
+ Object.assign(context.headers, BytescaleApiClientConfigUtils.resolveAuthentication(_this.config).headers);
418
500
  // Key: any possible value for 'baseUrlOverride'
419
501
  // Value: user-overridden value for that base URL from the config.
420
502
  var nonDefaultBasePaths = _defineProperty({}, BytescaleApiClientConfigUtils.defaultCdnUrl, BytescaleApiClientConfigUtils.getCdnUrl(_this.config));
@@ -454,9 +536,21 @@ var BaseAPI = /*#__PURE__*/function () {
454
536
  url += "?" + querystring(context.query);
455
537
  }
456
538
  var configHeaders = _this2.config.headers;
457
- var _Object$assign = Object.assign({}, context.headers);
458
- return runtime_await(runtime_await(configHeaders === undefined ? {} : typeof configHeaders === "function" ? configHeaders() : configHeaders, function (_configHeaders) {
459
- var headers = Object.assign(_Object$assign, configHeaders === undefined ? _configHeaders : _configHeaders);
539
+ return runtime_await(runtime_await(configHeaders === undefined ? {} : typeof configHeaders === "function" ? configHeaders() : configHeaders, function (resolvedConfigHeaders) {
540
+ for (var _i = 0, _Object$keys = Object.keys(resolvedConfigHeaders); _i < _Object$keys.length; _i++) {
541
+ var key = _Object$keys[_i];
542
+ if (key.toLowerCase() === "authorization" || key.toLowerCase() === "authorization-token") {
543
+ for (var _i2 = 0, _Object$keys2 = Object.keys(context.headers); _i2 < _Object$keys2.length; _i2++) {
544
+ var generatedKey = _Object$keys2[_i2];
545
+ if (generatedKey.toLowerCase() === key.toLowerCase()) {
546
+ // Custom auth headers have documented precedence; remove the generated spelling to make that deterministic.
547
+ // eslint-disable-next-line @typescript-eslint/no-dynamic-delete
548
+ delete context.headers[generatedKey];
549
+ }
550
+ }
551
+ }
552
+ }
553
+ var headers = Object.assign(Object.assign({}, context.headers), resolvedConfigHeaders);
460
554
  Object.keys(headers).forEach(function (key) {
461
555
  return headers[key] === undefined ? delete headers[key] : {};
462
556
  });
@@ -468,12 +562,12 @@ var BaseAPI = /*#__PURE__*/function () {
468
562
  headers: headers,
469
563
  body: context.body
470
564
  };
471
- var _Object$assign2 = Object.assign({}, initParams);
565
+ var _Object$assign = Object.assign({}, initParams);
472
566
  return runtime_await(initOverrideFn({
473
567
  init: initParams,
474
568
  context: context
475
569
  }), function (_initOverrideFn) {
476
- var overriddenInit = Object.assign(_Object$assign2, _initOverrideFn);
570
+ var overriddenInit = Object.assign(_Object$assign, _initOverrideFn);
477
571
  var init = Object.assign(Object.assign({}, overriddenInit), {
478
572
  body: JSON.stringify(overriddenInit.body)
479
573
  });
@@ -2098,7 +2192,6 @@ var UploadManagerBase = /*#__PURE__*/function () {
2098
2192
  this.defaultMaxConcurrentUploadParts = 4;
2099
2193
  this.intervalMs = 500;
2100
2194
  this.uploadApi = new UploadApi(config);
2101
- this.accountId = BytescaleApiClientConfigUtils.getAccountId(config);
2102
2195
  }
2103
2196
  return UploadManagerBase_createClass(UploadManagerBase, [{
2104
2197
  key: "upload",
@@ -2106,6 +2199,7 @@ var UploadManagerBase = /*#__PURE__*/function () {
2106
2199
  try {
2107
2200
  var _this = this;
2108
2201
  _this.assertNotCancelled(request);
2202
+ var accountId = BytescaleApiClientConfigUtils.getAccountId(_this.config);
2109
2203
  var source = _this.processUploadSource(request.data);
2110
2204
  var preUploadInfo = _this.getPreUploadInfo(request, source);
2111
2205
  var bytesTotal = preUploadInfo.size;
@@ -2115,7 +2209,7 @@ var UploadManagerBase = /*#__PURE__*/function () {
2115
2209
  if (request.onProgress !== undefined) {
2116
2210
  request.onProgress(_this.makeProgressEvent(0, bytesTotal));
2117
2211
  }
2118
- return UploadManagerBase_await(_this.beginUpload(request, preUploadInfo), function (uploadInfo) {
2212
+ return UploadManagerBase_await(_this.beginUpload(request, preUploadInfo, accountId), function (uploadInfo) {
2119
2213
  var partCount = uploadInfo.uploadParts.count;
2120
2214
  var parts = UploadManagerBase_toConsumableArray(Array(partCount).keys());
2121
2215
  var _this$makeCancellatio = _this.makeCancellationMethods(),
@@ -2125,7 +2219,7 @@ var UploadManagerBase = /*#__PURE__*/function () {
2125
2219
  var uploadedParts;
2126
2220
  return UploadManagerBase_continue(UploadManagerBase_finallyRethrows(function () {
2127
2221
  return UploadManagerBase_await(_this.mapAsync(parts, preUploadInfo.maxConcurrentUploadParts, _async(function (part) {
2128
- return _this.uploadPart(request, source, part, uploadInfo, makeOnProgressForPart(), addCancellationHandler);
2222
+ return _this.uploadPart(request, source, part, uploadInfo, makeOnProgressForPart(), addCancellationHandler, accountId);
2129
2223
  })), function (_this$mapAsync) {
2130
2224
  uploadedParts = _this$mapAsync;
2131
2225
  return UploadManagerBase_awaitIgnored(_this.postUpload(init));
@@ -2237,14 +2331,14 @@ var UploadManagerBase = /*#__PURE__*/function () {
2237
2331
  }
2238
2332
  }, {
2239
2333
  key: "beginUpload",
2240
- value: function beginUpload(request, _ref2) {
2334
+ value: function beginUpload(request, _ref2, accountId) {
2241
2335
  var size = _ref2.size,
2242
2336
  mime = _ref2.mime,
2243
2337
  originalFileName = _ref2.originalFileName;
2244
2338
  try {
2245
2339
  var _this4 = this;
2246
2340
  return UploadManagerBase_await(_this4.uploadApi.beginMultipartUpload({
2247
- accountId: _this4.accountId,
2341
+ accountId: accountId,
2248
2342
  beginMultipartUploadRequest: {
2249
2343
  metadata: request.metadata,
2250
2344
  mime: mime,
@@ -2261,16 +2355,16 @@ var UploadManagerBase = /*#__PURE__*/function () {
2261
2355
  }
2262
2356
  }, {
2263
2357
  key: "uploadPart",
2264
- value: function uploadPart(request, source, partIndex, uploadInfo, onProgress, addCancellationHandler) {
2358
+ value: function uploadPart(request, source, partIndex, uploadInfo, onProgress, addCancellationHandler, accountId) {
2265
2359
  try {
2266
2360
  var _this5 = this;
2267
2361
  _this5.assertNotCancelled(request);
2268
- return UploadManagerBase_await(_this5.getUploadPart(partIndex, uploadInfo), function (part) {
2362
+ return UploadManagerBase_await(_this5.getUploadPart(partIndex, uploadInfo, accountId), function (part) {
2269
2363
  _this5.assertNotCancelled(request);
2270
2364
  return UploadManagerBase_await(_this5.putUploadPart(part, source, onProgress, addCancellationHandler), function (etag) {
2271
2365
  _this5.assertNotCancelled(request);
2272
2366
  return UploadManagerBase_await(_this5.uploadApi.completeUploadPart({
2273
- accountId: _this5.accountId,
2367
+ accountId: accountId,
2274
2368
  uploadId: uploadInfo.uploadId,
2275
2369
  uploadPartIndex: partIndex,
2276
2370
  completeUploadPartRequest: {
@@ -2311,7 +2405,7 @@ var UploadManagerBase = /*#__PURE__*/function () {
2311
2405
  }
2312
2406
  }, {
2313
2407
  key: "getUploadPart",
2314
- value: function getUploadPart(partIndex, uploadInfo) {
2408
+ value: function getUploadPart(partIndex, uploadInfo, accountId) {
2315
2409
  try {
2316
2410
  var _this7 = this;
2317
2411
  if (partIndex === 0) {
@@ -2319,7 +2413,7 @@ var UploadManagerBase = /*#__PURE__*/function () {
2319
2413
  }
2320
2414
  return UploadManagerBase_await(_this7.uploadApi.getUploadPart({
2321
2415
  uploadId: uploadInfo.uploadId,
2322
- accountId: _this7.accountId,
2416
+ accountId: accountId,
2323
2417
  uploadPartIndex: partIndex
2324
2418
  }));
2325
2419
  } catch (e) {
@@ -3156,12 +3250,178 @@ function AuthManagerBrowser_awaitIgnored(value, direct) {
3156
3250
  return value && value.then ? value.then(AuthManagerBrowser_empty) : Promise.resolve();
3157
3251
  }
3158
3252
  }
3159
- function AuthManagerBrowser_invoke(body, then) {
3160
- var result = body();
3253
+ var AuthManagerBrowser_iteratorSymbol = /*#__PURE__*/typeof Symbol !== "undefined" ? Symbol.iterator || (Symbol.iterator = Symbol("Symbol.iterator")) : "@@iterator";
3254
+ function AuthManagerBrowser_settle(pact, state, value) {
3255
+ if (!pact.s) {
3256
+ if (value instanceof AuthManagerBrowser_Pact) {
3257
+ if (value.s) {
3258
+ if (state & 1) {
3259
+ state = value.s;
3260
+ }
3261
+ value = value.v;
3262
+ } else {
3263
+ value.o = AuthManagerBrowser_settle.bind(null, pact, state);
3264
+ return;
3265
+ }
3266
+ }
3267
+ if (value && value.then) {
3268
+ value.then(AuthManagerBrowser_settle.bind(null, pact, state), AuthManagerBrowser_settle.bind(null, pact, 2));
3269
+ return;
3270
+ }
3271
+ pact.s = state;
3272
+ pact.v = value;
3273
+ var observer = pact.o;
3274
+ if (observer) {
3275
+ observer(pact);
3276
+ }
3277
+ }
3278
+ }
3279
+ var AuthManagerBrowser_Pact = /*#__PURE__*/function () {
3280
+ function _Pact() {}
3281
+ _Pact.prototype.then = function (onFulfilled, onRejected) {
3282
+ var result = new _Pact();
3283
+ var state = this.s;
3284
+ if (state) {
3285
+ var callback = state & 1 ? onFulfilled : onRejected;
3286
+ if (callback) {
3287
+ try {
3288
+ AuthManagerBrowser_settle(result, 1, callback(this.v));
3289
+ } catch (e) {
3290
+ AuthManagerBrowser_settle(result, 2, e);
3291
+ }
3292
+ return result;
3293
+ } else {
3294
+ return this;
3295
+ }
3296
+ }
3297
+ this.o = function (_this) {
3298
+ try {
3299
+ var value = _this.v;
3300
+ if (_this.s & 1) {
3301
+ AuthManagerBrowser_settle(result, 1, onFulfilled ? onFulfilled(value) : value);
3302
+ } else if (onRejected) {
3303
+ AuthManagerBrowser_settle(result, 1, onRejected(value));
3304
+ } else {
3305
+ AuthManagerBrowser_settle(result, 2, value);
3306
+ }
3307
+ } catch (e) {
3308
+ AuthManagerBrowser_settle(result, 2, e);
3309
+ }
3310
+ };
3311
+ return result;
3312
+ };
3313
+ return _Pact;
3314
+ }();
3315
+ function AuthManagerBrowser_isSettledPact(thenable) {
3316
+ return thenable instanceof AuthManagerBrowser_Pact && thenable.s & 1;
3317
+ }
3318
+ function AuthManagerBrowser_forTo(array, body, check) {
3319
+ var i = -1,
3320
+ pact,
3321
+ reject;
3322
+ function _cycle(result) {
3323
+ try {
3324
+ while (++i < array.length && (!check || !check())) {
3325
+ result = body(i);
3326
+ if (result && result.then) {
3327
+ if (AuthManagerBrowser_isSettledPact(result)) {
3328
+ result = result.v;
3329
+ } else {
3330
+ result.then(_cycle, reject || (reject = AuthManagerBrowser_settle.bind(null, pact = new AuthManagerBrowser_Pact(), 2)));
3331
+ return;
3332
+ }
3333
+ }
3334
+ }
3335
+ if (pact) {
3336
+ AuthManagerBrowser_settle(pact, 1, result);
3337
+ } else {
3338
+ pact = result;
3339
+ }
3340
+ } catch (e) {
3341
+ AuthManagerBrowser_settle(pact || (pact = new AuthManagerBrowser_Pact()), 2, e);
3342
+ }
3343
+ }
3344
+ _cycle();
3345
+ return pact;
3346
+ }
3347
+ function AuthManagerBrowser_forOf(target, body, check) {
3348
+ if (typeof target[AuthManagerBrowser_iteratorSymbol] === "function") {
3349
+ var _cycle2 = function _cycle(result) {
3350
+ try {
3351
+ while (!(step = iterator.next()).done && (!check || !check())) {
3352
+ result = body(step.value);
3353
+ if (result && result.then) {
3354
+ if (AuthManagerBrowser_isSettledPact(result)) {
3355
+ result = result.v;
3356
+ } else {
3357
+ result.then(_cycle2, reject || (reject = AuthManagerBrowser_settle.bind(null, pact = new AuthManagerBrowser_Pact(), 2)));
3358
+ return;
3359
+ }
3360
+ }
3361
+ }
3362
+ if (pact) {
3363
+ AuthManagerBrowser_settle(pact, 1, result);
3364
+ } else {
3365
+ pact = result;
3366
+ }
3367
+ } catch (e) {
3368
+ AuthManagerBrowser_settle(pact || (pact = new AuthManagerBrowser_Pact()), 2, e);
3369
+ }
3370
+ };
3371
+ var iterator = target[AuthManagerBrowser_iteratorSymbol](),
3372
+ step,
3373
+ pact,
3374
+ reject;
3375
+ _cycle2();
3376
+ if (iterator.return) {
3377
+ var _fixup = function _fixup(value) {
3378
+ try {
3379
+ if (!step.done) {
3380
+ iterator.return();
3381
+ }
3382
+ } catch (e) {}
3383
+ return value;
3384
+ };
3385
+ if (pact && pact.then) {
3386
+ return pact.then(_fixup, function (e) {
3387
+ throw _fixup(e);
3388
+ });
3389
+ }
3390
+ _fixup();
3391
+ }
3392
+ return pact;
3393
+ }
3394
+ // No support for Symbol.iterator
3395
+ if (!("length" in target)) {
3396
+ throw new TypeError("Object is not iterable");
3397
+ }
3398
+ // Handle live collections properly
3399
+ var values = [];
3400
+ for (var i = 0; i < target.length; i++) {
3401
+ values.push(target[i]);
3402
+ }
3403
+ return AuthManagerBrowser_forTo(values, function (i) {
3404
+ return body(values[i]);
3405
+ }, check);
3406
+ }
3407
+ function AuthManagerBrowser_continueIgnored(value) {
3408
+ if (value && value.then) {
3409
+ return value.then(AuthManagerBrowser_empty);
3410
+ }
3411
+ }
3412
+ function AuthManagerBrowser_catch(body, recover) {
3413
+ try {
3414
+ var result = body();
3415
+ } catch (e) {
3416
+ return recover(e);
3417
+ }
3161
3418
  if (result && result.then) {
3162
- return result.then(then);
3419
+ return result.then(void 0, recover);
3163
3420
  }
3164
- return then(result);
3421
+ return result;
3422
+ }
3423
+ function AuthManagerBrowser_continue(value, then) {
3424
+ return value && value.then ? value.then(then) : then(value);
3165
3425
  }
3166
3426
  function AuthManagerBrowser_await(value, then, direct) {
3167
3427
  if (direct) {
@@ -3184,22 +3444,12 @@ function AuthManagerBrowser_async(f) {
3184
3444
  }
3185
3445
  };
3186
3446
  }
3187
- function AuthManagerBrowser_invokeIgnored(body) {
3447
+ function AuthManagerBrowser_invoke(body, then) {
3188
3448
  var result = body();
3189
3449
  if (result && result.then) {
3190
- return result.then(AuthManagerBrowser_empty);
3191
- }
3192
- }
3193
- function AuthManagerBrowser_catch(body, recover) {
3194
- try {
3195
- var result = body();
3196
- } catch (e) {
3197
- return recover(e);
3198
- }
3199
- if (result && result.then) {
3200
- return result.then(void 0, recover);
3450
+ return result.then(then);
3201
3451
  }
3202
- return result;
3452
+ return then(result);
3203
3453
  }
3204
3454
  function AuthManagerBrowser_rethrow(thrown, value) {
3205
3455
  if (thrown) throw value;
@@ -3216,44 +3466,43 @@ function AuthManagerBrowser_finallyRethrows(body, finalizer) {
3216
3466
  }
3217
3467
  return finalizer(false, result);
3218
3468
  }
3219
- function AuthManagerBrowser_continueIgnored(value) {
3220
- if (value && value.then) {
3221
- return value.then(AuthManagerBrowser_empty);
3222
- }
3223
- }
3224
- function AuthManagerBrowser_call(body, then, direct) {
3225
- if (direct) {
3226
- return then ? then(body()) : body();
3227
- }
3228
- try {
3229
- var result = Promise.resolve(body());
3230
- return then ? result.then(then) : result;
3231
- } catch (e) {
3232
- return Promise.reject(e);
3233
- }
3234
- }
3235
- function AuthManagerBrowser_continue(value, then) {
3236
- return value && value.then ? value.then(then) : then(value);
3237
- }
3238
3469
  function AuthManagerBrowser_defineProperty(e, r, t) { return (r = AuthManagerBrowser_toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
3239
- function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = AuthManagerBrowser_unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t.return || t.return(); } finally { if (u) throw o; } } }; }
3240
3470
  function AuthManagerBrowser_toConsumableArray(r) { return AuthManagerBrowser_arrayWithoutHoles(r) || AuthManagerBrowser_iterableToArray(r) || AuthManagerBrowser_unsupportedIterableToArray(r) || AuthManagerBrowser_nonIterableSpread(); }
3241
3471
  function AuthManagerBrowser_nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
3242
- function AuthManagerBrowser_unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return AuthManagerBrowser_arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? AuthManagerBrowser_arrayLikeToArray(r, a) : void 0; } }
3243
3472
  function AuthManagerBrowser_iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); }
3244
3473
  function AuthManagerBrowser_arrayWithoutHoles(r) { if (Array.isArray(r)) return AuthManagerBrowser_arrayLikeToArray(r); }
3474
+ function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = AuthManagerBrowser_unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t.return || t.return(); } finally { if (u) throw o; } } }; }
3475
+ function AuthManagerBrowser_unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return AuthManagerBrowser_arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? AuthManagerBrowser_arrayLikeToArray(r, a) : void 0; } }
3245
3476
  function AuthManagerBrowser_arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
3246
3477
  function AuthManagerBrowser_typeof(o) { "@babel/helpers - typeof"; return AuthManagerBrowser_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, AuthManagerBrowser_typeof(o); }
3247
- function AuthManagerBrowser_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
3248
3478
  function AuthManagerBrowser_defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, AuthManagerBrowser_toPropertyKey(o.key), o); } }
3249
3479
  function AuthManagerBrowser_createClass(e, r, t) { return r && AuthManagerBrowser_defineProperties(e.prototype, r), t && AuthManagerBrowser_defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
3250
3480
  function AuthManagerBrowser_toPropertyKey(t) { var i = AuthManagerBrowser_toPrimitive(t, "string"); return "symbol" == AuthManagerBrowser_typeof(i) ? i : i + ""; }
3251
3481
  function AuthManagerBrowser_toPrimitive(t, r) { if ("object" != AuthManagerBrowser_typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != AuthManagerBrowser_typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
3482
+ function AuthManagerBrowser_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
3483
+ function AuthManagerBrowser_callSuper(t, o, e) { return o = AuthManagerBrowser_getPrototypeOf(o), AuthManagerBrowser_possibleConstructorReturn(t, AuthManagerBrowser_isNativeReflectConstruct() ? Reflect.construct(o, e || [], AuthManagerBrowser_getPrototypeOf(t).constructor) : o.apply(t, e)); }
3484
+ function AuthManagerBrowser_possibleConstructorReturn(t, e) { if (e && ("object" == AuthManagerBrowser_typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return AuthManagerBrowser_assertThisInitialized(t); }
3485
+ function AuthManagerBrowser_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; }
3486
+ function AuthManagerBrowser_inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && AuthManagerBrowser_setPrototypeOf(t, e); }
3487
+ function AuthManagerBrowser_wrapNativeSuper(t) { var r = "function" == typeof Map ? new Map() : void 0; return AuthManagerBrowser_wrapNativeSuper = function _wrapNativeSuper(t) { if (null === t || !AuthManagerBrowser_isNativeFunction(t)) return t; if ("function" != typeof t) throw new TypeError("Super expression must either be null or a function"); if (void 0 !== r) { if (r.has(t)) return r.get(t); r.set(t, Wrapper); } function Wrapper() { return AuthManagerBrowser_construct(t, arguments, AuthManagerBrowser_getPrototypeOf(this).constructor); } return Wrapper.prototype = Object.create(t.prototype, { constructor: { value: Wrapper, enumerable: !1, writable: !0, configurable: !0 } }), AuthManagerBrowser_setPrototypeOf(Wrapper, t); }, AuthManagerBrowser_wrapNativeSuper(t); }
3488
+ function AuthManagerBrowser_construct(t, e, r) { if (AuthManagerBrowser_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments); var o = [null]; o.push.apply(o, e); var p = new (t.bind.apply(t, o))(); return r && AuthManagerBrowser_setPrototypeOf(p, r.prototype), p; }
3489
+ function AuthManagerBrowser_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (AuthManagerBrowser_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
3490
+ function AuthManagerBrowser_isNativeFunction(t) { try { return -1 !== Function.toString.call(t).indexOf("[native code]"); } catch (n) { return "function" == typeof t; } }
3491
+ function AuthManagerBrowser_setPrototypeOf(t, e) { return AuthManagerBrowser_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, AuthManagerBrowser_setPrototypeOf(t, e); }
3492
+ function AuthManagerBrowser_getPrototypeOf(t) { return AuthManagerBrowser_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, AuthManagerBrowser_getPrototypeOf(t); }
3252
3493
 
3253
3494
 
3254
3495
 
3255
3496
 
3256
3497
 
3498
+ var InvalidAuthTokenError = /*#__PURE__*/function (_Error) {
3499
+ function InvalidAuthTokenError() {
3500
+ AuthManagerBrowser_classCallCheck(this, InvalidAuthTokenError);
3501
+ return AuthManagerBrowser_callSuper(this, InvalidAuthTokenError, arguments);
3502
+ }
3503
+ AuthManagerBrowser_inherits(InvalidAuthTokenError, _Error);
3504
+ return AuthManagerBrowser_createClass(InvalidAuthTokenError);
3505
+ }(/*#__PURE__*/AuthManagerBrowser_wrapNativeSuper(Error));
3257
3506
  var AuthManagerImpl = /*#__PURE__*/function () {
3258
3507
  function AuthManagerImpl(serviceWorkerUtils) {
3259
3508
  AuthManagerBrowser_classCallCheck(this, AuthManagerImpl);
@@ -3277,53 +3526,71 @@ var AuthManagerImpl = /*#__PURE__*/function () {
3277
3526
  }, {
3278
3527
  key: "isAuthSessionReady",
3279
3528
  value: function isAuthSessionReady() {
3280
- var _a;
3529
+ var _this = this;
3281
3530
  var session = AuthSessionState.getSession();
3282
- return (_a = session === null || session === void 0 ? void 0 : session.isReady) !== null && _a !== void 0 ? _a : (session === null || session === void 0 ? void 0 : session.accessToken) !== undefined;
3531
+ if (session !== undefined && Array.isArray(session.authConfigs)) {
3532
+ return session.isReady === true && session.authConfigs.every(function (state) {
3533
+ return _this.isConfigUsable(state);
3534
+ });
3535
+ }
3536
+ return (session === null || session === void 0 ? void 0 : session.accessToken) !== undefined;
3283
3537
  }
3284
3538
  }, {
3285
3539
  key: "beginAuthSession",
3286
3540
  value: function beginAuthSession(params) {
3287
3541
  try {
3288
- var _this = this;
3289
- return AuthManagerBrowser_await(_this.authSessionMutex.safe(AuthManagerBrowser_async(function () {
3290
- // We check both 'session' and 'sessionDisposing' here, as we don't want to call 'beginAuthSession' until the session is fully disposed.
3291
- if (_this.isAuthSessionActive()) {
3542
+ var _this2 = this;
3543
+ var _a;
3544
+ return AuthManagerBrowser_await(_this2.authSessionMutex.safe(AuthManagerBrowser_async(function () {
3545
+ var _a, _b;
3546
+ if (_this2.isAuthSessionActive()) {
3292
3547
  throw new Error("Auth session already active. Please call 'await endAuthSession()' and then call 'await beginAuthSession(...)' to start a new auth session.");
3293
3548
  }
3294
- var canUseServiceWorkers = _this.serviceWorkerUtils.canUseServiceWorkers();
3295
- if (params.serviceWorkerConfig !== undefined) {
3296
- if (params.serviceWorkerScript === undefined) {
3297
- throw new Error("The 'serviceWorkerScript' field is required when 'serviceWorkerConfig' is provided.");
3298
- }
3299
- if (!canUseServiceWorkers) {
3300
- throw new Error("The 'serviceWorkerConfig' field requires service workers, but this browser does not support them.");
3301
- }
3549
+ if (Object.prototype.hasOwnProperty.call(params, "authConfigs") && typeof params.authConfigs !== "function") {
3550
+ throw new Error("The 'authConfigs' field must be a callback returning a non-empty array.");
3302
3551
  }
3303
- var newSession = {
3304
- accessToken: undefined,
3305
- accessTokenRefreshHandle: undefined,
3306
- params: params,
3307
- isActive: true,
3308
- isReady: false,
3309
- authServiceWorker: params.serviceWorkerScript !== undefined && canUseServiceWorkers ? {
3310
- serviceWorkerScript: params.serviceWorkerScript,
3311
- type: "Uninitialized"
3312
- } : undefined,
3313
- primaryAuthSwConfig: undefined,
3314
- serviceWorkerConfig: undefined,
3315
- serviceWorkerConfigRefreshHandle: undefined
3316
- };
3317
- AuthSessionState.setSession(newSession);
3318
- return newSession;
3552
+ var isV2 = _this2.isV2Params(params);
3553
+ return AuthManagerBrowser_await(isV2 ? _this2.getV2Configs(params) : [_this2.normalizeV1Config(params)], function (configs) {
3554
+ var canUseServiceWorkers = _this2.serviceWorkerUtils.canUseServiceWorkers();
3555
+ var requiresServiceWorker = configs.some(function (config) {
3556
+ return config !== null && AuthManagerBrowser_typeof(config) === "object" && _this2.isServiceWorkerEnabled(config);
3557
+ }) || isV2 && ((_b = (_a = params.urlRewriteRules) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0) > 0;
3558
+ _this2.validateSessionConfig(params, configs, canUseServiceWorkers, requiresServiceWorker);
3559
+ var newSession = {
3560
+ accessToken: undefined,
3561
+ accessTokenRefreshHandle: undefined,
3562
+ authConfigs: configs.map(function (config) {
3563
+ return {
3564
+ accessToken: undefined,
3565
+ config: config,
3566
+ expiresAt: undefined,
3567
+ jwt: undefined,
3568
+ refreshHandle: undefined
3569
+ };
3570
+ }),
3571
+ authServiceWorker: requiresServiceWorker && params.serviceWorkerScript !== undefined && canUseServiceWorkers ? {
3572
+ serviceWorkerScript: params.serviceWorkerScript,
3573
+ type: "Uninitialized"
3574
+ } : undefined,
3575
+ isActive: true,
3576
+ isReady: false,
3577
+ params: params,
3578
+ serviceWorkerConfigured: false
3579
+ };
3580
+ AuthSessionState.setSession(newSession);
3581
+ return newSession;
3582
+ }, !isV2);
3319
3583
  })), function (session) {
3320
- // IMPORTANT: must be called outside the above, else re-entrant deadlock will occur.
3321
- return AuthManagerBrowser_invoke(function () {
3322
- if (session.params.serviceWorkerConfig !== undefined) {
3323
- return AuthManagerBrowser_awaitIgnored(_this.refreshServiceWorkerConfig(session, session.params));
3324
- }
3325
- }, function () {
3326
- return AuthManagerBrowser_awaitIgnored(_this.refreshAccessToken(session, session.params));
3584
+ return AuthManagerBrowser_catch(function () {
3585
+ return AuthManagerBrowser_continueIgnored(AuthManagerBrowser_forOf((_a = session.authConfigs) !== null && _a !== void 0 ? _a : [], function (config) {
3586
+ return AuthManagerBrowser_awaitIgnored(_this2.refreshAuthConfig(session, config, _this2.isV2Params(session.params)));
3587
+ }));
3588
+ }, function (e) {
3589
+ return AuthManagerBrowser_continue(AuthManagerBrowser_catch(function () {
3590
+ return AuthManagerBrowser_awaitIgnored(_this2.endAuthSession());
3591
+ }, AuthManagerBrowser_empty), function () {
3592
+ throw e;
3593
+ });
3327
3594
  });
3328
3595
  });
3329
3596
  } catch (e) {
@@ -3334,31 +3601,68 @@ var AuthManagerImpl = /*#__PURE__*/function () {
3334
3601
  key: "endAuthSession",
3335
3602
  value: function endAuthSession() {
3336
3603
  try {
3337
- var _this2 = this;
3338
- return AuthManagerBrowser_await(AuthManagerBrowser_awaitIgnored(_this2.authSessionMutex.safe(AuthManagerBrowser_async(function () {
3604
+ var _this3 = this;
3605
+ return AuthManagerBrowser_await(AuthManagerBrowser_awaitIgnored(_this3.authSessionMutex.safe(AuthManagerBrowser_async(function () {
3606
+ var _a, _b, _c;
3339
3607
  var session = AuthSessionState.getSession();
3340
3608
  if (session === undefined) {
3341
3609
  return;
3342
3610
  }
3343
3611
  AuthSessionState.setSession(undefined);
3344
3612
  session.isActive = false;
3345
- if (session.accessTokenRefreshHandle !== undefined) {
3346
- _this2.scheduler.unschedule(session.accessTokenRefreshHandle);
3347
- }
3348
- if (session.serviceWorkerConfigRefreshHandle !== undefined) {
3349
- _this2.scheduler.unschedule(session.serviceWorkerConfigRefreshHandle);
3613
+ if (session.authConfigs === undefined) {
3614
+ if (session.accessTokenRefreshHandle !== undefined) {
3615
+ _this3.scheduler.unschedule(session.accessTokenRefreshHandle);
3616
+ }
3617
+ } else {
3618
+ var _iterator = _createForOfIteratorHelper(session.authConfigs),
3619
+ _step;
3620
+ try {
3621
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
3622
+ var state = _step.value;
3623
+ if (state.refreshHandle !== undefined) {
3624
+ _this3.scheduler.unschedule(state.refreshHandle);
3625
+ }
3626
+ }
3627
+ } catch (err) {
3628
+ _iterator.e(err);
3629
+ } finally {
3630
+ _iterator.f();
3631
+ }
3350
3632
  }
3351
- // AuthSessionState is shared between bundled SDK versions. Service-worker-only sessions from 3.56.0 did not
3352
- // contain an accountId, so allow a newer SDK instance to tear those sessions down without calling this endpoint.
3633
+ var cleanupError;
3634
+ var cookieConfigs = _this3.isV2Params(session.params) ? (_b = (_a = session.authConfigs) === null || _a === void 0 ? void 0 : _a.filter(function (state) {
3635
+ return state.config.enableCookieAuth === true;
3636
+ })) !== null && _b !== void 0 ? _b : [] : (_c = session.authConfigs) !== null && _c !== void 0 ? _c : [];
3637
+ // A 3.54.0 session will not contain authConfigs, but a newer bundle must still be able to end it.
3353
3638
  return AuthManagerBrowser_invoke(function () {
3354
- if (typeof session.params.accountId === "string") {
3355
- return AuthManagerBrowser_awaitIgnored(_this2.deleteAccessToken(session.params));
3639
+ if (session.authConfigs === undefined && typeof session.params.accountId === "string") {
3640
+ return AuthManagerBrowser_continueIgnored(AuthManagerBrowser_catch(function () {
3641
+ return AuthManagerBrowser_awaitIgnored(_this3.deleteAccessToken(session.params.options, _this3.getCdnUrl(session.params), session.params.accountId));
3642
+ }, function (e) {
3643
+ cleanupError = e;
3644
+ }));
3645
+ } else {
3646
+ return AuthManagerBrowser_continueIgnored(AuthManagerBrowser_forOf(cookieConfigs, function (state) {
3647
+ return AuthManagerBrowser_continueIgnored(AuthManagerBrowser_catch(function () {
3648
+ return AuthManagerBrowser_awaitIgnored(_this3.deleteAccessToken(session.params.options, _this3.getConfigCdnUrl(session.params, state.config), state.config.accountId));
3649
+ }, function (e) {
3650
+ cleanupError !== null && cleanupError !== void 0 ? cleanupError : cleanupError = e;
3651
+ }));
3652
+ }));
3356
3653
  }
3357
3654
  }, function () {
3358
- return AuthManagerBrowser_invokeIgnored(function () {
3655
+ return AuthManagerBrowser_invoke(function () {
3359
3656
  if (session.authServiceWorker !== undefined) {
3360
- // Prevent service worker from authorizing subsequent requests.
3361
- return AuthManagerBrowser_awaitIgnored(_this2.sendServiceWorkerConfig(session, []));
3657
+ return AuthManagerBrowser_continueIgnored(AuthManagerBrowser_catch(function () {
3658
+ return AuthManagerBrowser_awaitIgnored(_this3.sendServiceWorkerConfig(session, []));
3659
+ }, function (e) {
3660
+ cleanupError !== null && cleanupError !== void 0 ? cleanupError : cleanupError = e;
3661
+ }));
3662
+ }
3663
+ }, function () {
3664
+ if (cleanupError !== undefined) {
3665
+ throw cleanupError instanceof Error ? cleanupError : new Error(String(cleanupError));
3362
3666
  }
3363
3667
  });
3364
3668
  });
@@ -3368,145 +3672,71 @@ var AuthManagerImpl = /*#__PURE__*/function () {
3368
3672
  }
3369
3673
  }
3370
3674
  }, {
3371
- key: "refreshAccessToken",
3372
- value: function refreshAccessToken(session, params) {
3675
+ key: "refreshAuthConfig",
3676
+ value: function refreshAuthConfig(session, state) {
3677
+ var rejectInvalidInitialToken = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
3373
3678
  try {
3374
- var _this3 = this;
3375
- return AuthManagerBrowser_await(AuthManagerBrowser_awaitIgnored(_this3.authSessionMutex.safe(AuthManagerBrowser_async(function () {
3679
+ var _this4 = this;
3680
+ return AuthManagerBrowser_await(AuthManagerBrowser_awaitIgnored(_this4.authSessionMutex.safe(AuthManagerBrowser_async(function () {
3681
+ var _a;
3376
3682
  if (!session.isActive) {
3377
3683
  return;
3378
3684
  }
3379
- var secondsFromNow = function secondsFromNow(seconds) {
3380
- return Date.now() + seconds * 1000;
3685
+ if (state.refreshHandle !== undefined) {
3686
+ _this4.scheduler.unschedule(state.refreshHandle);
3687
+ }
3688
+ var previous = {
3689
+ accessToken: state.accessToken,
3690
+ expiresAt: state.expiresAt,
3691
+ jwt: state.jwt,
3692
+ serviceWorkerConfigured: session.serviceWorkerConfigured
3381
3693
  };
3382
- var expires = secondsFromNow(_this3.retryAuthAfterErrorSeconds);
3383
- return AuthManagerBrowser_continueIgnored(AuthManagerBrowser_finallyRethrows(function () {
3694
+ var refreshAt = Date.now() + _this4.retryAuthAfterErrorSeconds * 1000;
3695
+ return AuthManagerBrowser_finallyRethrows(function () {
3384
3696
  return AuthManagerBrowser_catch(function () {
3385
- var _getAccessToken = _this3.getAccessToken;
3386
- return AuthManagerBrowser_await(params.authHeaders(), function (_params$authHeaders) {
3387
- return AuthManagerBrowser_await(_getAccessToken.call(_this3, params, _params$authHeaders), function (jwt) {
3388
- // We don't use cookie-based auth if the browser supports service worker-based auth, as using both will cause
3389
- // confusion for us in the future (i.e. we may question "do we need to use both together? was there a reason?").
3390
- // Also: if the user has omitted "allowedOrigins" from their JWT, then service worker-based auth is more secure
3391
- // than cookie-based auth, which is another reason to prevent these cookies from being set unless required.
3392
- var setCookie = session.authServiceWorker === undefined;
3393
- return AuthManagerBrowser_await(_this3.setAccessToken(params, jwt, setCookie), function (setTokenResult) {
3394
- return AuthManagerBrowser_invoke(function () {
3395
- if (session.authServiceWorker !== undefined) {
3396
- var primaryAuthSwConfig = {
3397
- headers: [{
3398
- key: "Authorization",
3399
- value: "Bearer ".concat(jwt)
3400
- }],
3401
- expires: secondsFromNow(setTokenResult.ttlSeconds),
3402
- urlPrefix: "".concat(_this3.getCdnUrl(params), "/").concat(params.accountId, "/")
3403
- };
3404
- // Fail closed until the initial serviceWorkerConfig callback succeeds: without its result, we do not know
3405
- // the source-page restrictions intended for the primary JWT.
3406
- return AuthManagerBrowser_invoke(function () {
3407
- if (params.serviceWorkerConfig === undefined || session.serviceWorkerConfig !== undefined) {
3408
- return AuthManagerBrowser_await(_this3.sendMergedServiceWorkerConfig(session, primaryAuthSwConfig, session.serviceWorkerConfig), function () {
3409
- return AuthManagerBrowser_awaitIgnored(_this3.waitForServiceWorker());
3410
- });
3411
- }
3412
- }, function () {
3413
- session.primaryAuthSwConfig = primaryAuthSwConfig;
3697
+ return AuthManagerBrowser_await(_this4.getAuthorizationToken(session.params, state.config), function (jwt) {
3698
+ var setCookie = _this4.shouldSetCookie(session, state.config);
3699
+ return AuthManagerBrowser_await(_this4.setAccessToken(session.params.options, _this4.getConfigCdnUrl(session.params, state.config), state.config.accountId, jwt, setCookie), function (token) {
3700
+ var expiresAt = Date.now() + token.ttlSeconds * 1000;
3701
+ state.accessToken = token.accessToken;
3702
+ state.expiresAt = expiresAt;
3703
+ state.jwt = jwt;
3704
+ return AuthManagerBrowser_invoke(function () {
3705
+ if (session.authServiceWorker !== undefined && (_this4.isServiceWorkerEnabled(state.config) || session.serviceWorkerConfigured !== true)) {
3706
+ return AuthManagerBrowser_await(_this4.sendCurrentServiceWorkerConfig(session), function () {
3707
+ return AuthManagerBrowser_await(_this4.waitForServiceWorker(), function () {
3708
+ session.serviceWorkerConfigured = true;
3414
3709
  });
3415
- }
3416
- }, function () {
3417
- var desiredTtl = setTokenResult.ttlSeconds - _this3.refreshBeforeExpirySeconds;
3418
- var actualTtl = Math.max(desiredTtl, _this3.minJwtTtlSeconds);
3419
- if (desiredTtl !== actualTtl) {
3420
- ConsoleUtils.warn("JWT expiration is too short: waiting for ".concat(actualTtl, " seconds before refreshing."));
3421
- }
3422
- expires = secondsFromNow(actualTtl);
3423
- // Set this at the end, as it's also used to signal 'isAuthSessionReady', so must be set after configuring the Service Worker, etc.
3424
- session.accessToken = setTokenResult.accessToken;
3425
- _this3.updateSessionReadiness(session);
3426
- });
3710
+ });
3711
+ }
3712
+ }, function () {
3713
+ var desiredTtl = token.ttlSeconds - _this4.refreshBeforeExpirySeconds;
3714
+ var actualTtl = Math.max(desiredTtl, _this4.minJwtTtlSeconds);
3715
+ if (desiredTtl !== actualTtl) {
3716
+ ConsoleUtils.warn("JWT expiration is too short: waiting for ".concat(actualTtl, " seconds before refreshing."));
3717
+ }
3718
+ refreshAt = Date.now() + actualTtl * 1000;
3427
3719
  });
3428
3720
  });
3429
3721
  });
3430
3722
  }, function (e) {
3431
- // Use 'warn' instead of 'error' since this happens frequently, i.e. user goes through a tunnel, and some customers report these errors to systems like Sentry, so we don't want to spam.
3432
- ConsoleUtils.warn("Unable to refresh JWT access token: ".concat(e));
3723
+ state.accessToken = previous.accessToken;
3724
+ state.expiresAt = previous.expiresAt;
3725
+ state.jwt = previous.jwt;
3726
+ session.serviceWorkerConfigured = previous.serviceWorkerConfigured;
3727
+ ConsoleUtils.warn("Unable to refresh JWT access token for auth config '".concat((_a = state.config.authConfigId) !== null && _a !== void 0 ? _a : "default", "': ").concat(e));
3728
+ if (rejectInvalidInitialToken && e instanceof InvalidAuthTokenError) {
3729
+ throw e;
3730
+ }
3433
3731
  });
3434
- }, function (_wasThrown, _result) {
3435
- // 'setTimeout' can be paused (e.g., during hibernation), risking JWT expiration before it triggers. We use a
3436
- // scheduler to check wall-clock time every second and execute the callback at the scheduled time (below).
3437
- session.accessTokenRefreshHandle = _this3.scheduler.schedule(expires, function () {
3438
- _this3.refreshAccessToken(session, params).then(function () {},
3439
- // Should not occur, as this method shouldn't throw errors.
3440
- function (e) {
3732
+ }, function (_wasThrown, _result2) {
3733
+ state.refreshHandle = _this4.scheduler.schedule(refreshAt, function () {
3734
+ _this4.refreshAuthConfig(session, state).then(function () {}, function (e) {
3441
3735
  return ConsoleUtils.error("Unexpected error when refreshing JWT access token: ".concat(e));
3442
3736
  });
3443
3737
  });
3444
- return AuthManagerBrowser_rethrow(_wasThrown, _result);
3445
- }));
3446
- }))));
3447
- } catch (e) {
3448
- return Promise.reject(e);
3449
- }
3450
- }
3451
- }, {
3452
- key: "refreshServiceWorkerConfig",
3453
- value: function refreshServiceWorkerConfig(session, params) {
3454
- try {
3455
- var _this4 = this;
3456
- var getServiceWorkerConfig = params.serviceWorkerConfig;
3457
- if (getServiceWorkerConfig === undefined) {
3458
- return AuthManagerBrowser_await();
3459
- }
3460
- return AuthManagerBrowser_await(AuthManagerBrowser_awaitIgnored(_this4.authSessionMutex.safe(AuthManagerBrowser_async(function () {
3461
- var _exit = false;
3462
- if (!session.isActive) {
3463
- return;
3464
- }
3465
- var refreshAt;
3466
- return AuthManagerBrowser_continue(AuthManagerBrowser_catch(function () {
3467
- return AuthManagerBrowser_call(getServiceWorkerConfig, function (result) {
3468
- if (result === null || AuthManagerBrowser_typeof(result) !== "object" || !Array.isArray(result.additionalConfig)) {
3469
- throw new Error("The 'serviceWorkerConfig' callback must return an object containing 'additionalConfig'.");
3470
- }
3471
- if (result.sourceUrlPrefixes !== undefined && (!Array.isArray(result.sourceUrlPrefixes) || !result.sourceUrlPrefixes.every(function (prefix) {
3472
- return typeof prefix === "string";
3473
- }))) {
3474
- throw new Error("The 'sourceUrlPrefixes' field returned by 'serviceWorkerConfig' must be an array of strings.");
3475
- }
3476
- if (result.urlRewriteRules !== undefined && (!Array.isArray(result.urlRewriteRules) || !result.urlRewriteRules.every(function (rule) {
3477
- return rule !== null && AuthManagerBrowser_typeof(rule) === "object" && typeof rule.fromUrlPrefix === "string" && typeof rule.toUrlPrefix === "string";
3478
- }))) {
3479
- throw new Error("The 'urlRewriteRules' field returned by 'serviceWorkerConfig' must be an array of URL rewrite rules.");
3480
- }
3481
- var config = {
3482
- additionalConfig: result.additionalConfig,
3483
- sourceUrlPrefixes: result.sourceUrlPrefixes,
3484
- urlRewriteRules: result.urlRewriteRules
3485
- };
3486
- return AuthManagerBrowser_invoke(function () {
3487
- if (session.primaryAuthSwConfig !== undefined) {
3488
- return AuthManagerBrowser_await(_this4.sendMergedServiceWorkerConfig(session, session.primaryAuthSwConfig, config), function () {
3489
- return AuthManagerBrowser_awaitIgnored(_this4.waitForServiceWorker());
3490
- });
3491
- }
3492
- }, function () {
3493
- session.serviceWorkerConfig = config;
3494
- _this4.updateSessionReadiness(session);
3495
- refreshAt = _this4.getServiceWorkerConfigRefreshEpoch(config.additionalConfig);
3496
- });
3497
- });
3498
- }, function (e) {
3499
- ConsoleUtils.warn("Unable to refresh service worker auth config: ".concat(e));
3500
- refreshAt = Date.now() + _this4.retryAuthAfterErrorSeconds * 1000;
3501
- }), function (_result2) {
3502
- if (_exit) return _result2;
3503
- if (refreshAt !== undefined) {
3504
- session.serviceWorkerConfigRefreshHandle = _this4.scheduler.schedule(refreshAt, function () {
3505
- _this4.refreshServiceWorkerConfig(session, params).then(function () {}, function (e) {
3506
- return ConsoleUtils.error("Unexpected error when refreshing service worker auth config: ".concat(e));
3507
- });
3508
- });
3509
- }
3738
+ _this4.updateSessionState(session);
3739
+ return AuthManagerBrowser_rethrow(_wasThrown, _result2);
3510
3740
  });
3511
3741
  }))));
3512
3742
  } catch (e) {
@@ -3514,38 +3744,31 @@ var AuthManagerImpl = /*#__PURE__*/function () {
3514
3744
  }
3515
3745
  }
3516
3746
  }, {
3517
- key: "sendMergedServiceWorkerConfig",
3518
- value: function sendMergedServiceWorkerConfig(session, primaryConfig, serviceWorkerConfig) {
3747
+ key: "sendCurrentServiceWorkerConfig",
3748
+ value: function sendCurrentServiceWorkerConfig(session) {
3519
3749
  try {
3520
3750
  var _this5 = this;
3521
3751
  var _a;
3522
- return AuthManagerBrowser_await(AuthManagerBrowser_awaitIgnored(_this5.sendServiceWorkerConfig(session, [Object.assign(Object.assign({}, primaryConfig), {
3523
- sourceUrlPrefixes: serviceWorkerConfig === null || serviceWorkerConfig === void 0 ? void 0 : serviceWorkerConfig.sourceUrlPrefixes
3524
- })].concat(AuthManagerBrowser_toConsumableArray((_a = serviceWorkerConfig === null || serviceWorkerConfig === void 0 ? void 0 : serviceWorkerConfig.additionalConfig) !== null && _a !== void 0 ? _a : [])), serviceWorkerConfig === null || serviceWorkerConfig === void 0 ? void 0 : serviceWorkerConfig.urlRewriteRules)));
3752
+ var now = Date.now();
3753
+ var config = ((_a = session.authConfigs) !== null && _a !== void 0 ? _a : []).flatMap(function (state) {
3754
+ if (!_this5.isServiceWorkerEnabled(state.config) || state.jwt === undefined || state.expiresAt === undefined || state.expiresAt <= now) {
3755
+ return [];
3756
+ }
3757
+ return [{
3758
+ expires: state.expiresAt,
3759
+ headers: [{
3760
+ key: "Authorization",
3761
+ value: "Bearer ".concat(state.jwt)
3762
+ }],
3763
+ sourceUrlPrefixes: state.config.sourceUrlPrefixes,
3764
+ urlPrefix: "".concat(_this5.getConfigCdnUrl(session.params, state.config), "/").concat(state.config.accountId, "/")
3765
+ }];
3766
+ });
3767
+ return AuthManagerBrowser_await(AuthManagerBrowser_awaitIgnored(_this5.sendServiceWorkerConfig(session, config, _this5.isV2Params(session.params) ? session.params.urlRewriteRules : undefined)));
3525
3768
  } catch (e) {
3526
3769
  return Promise.reject(e);
3527
3770
  }
3528
3771
  }
3529
- }, {
3530
- key: "getServiceWorkerConfigRefreshEpoch",
3531
- value: function getServiceWorkerConfigRefreshEpoch(config) {
3532
- var earliestExpiry;
3533
- var _iterator = _createForOfIteratorHelper(config),
3534
- _step;
3535
- try {
3536
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
3537
- var entry = _step.value;
3538
- if (entry.expires !== undefined && (earliestExpiry === undefined || entry.expires < earliestExpiry)) {
3539
- earliestExpiry = entry.expires;
3540
- }
3541
- }
3542
- } catch (err) {
3543
- _iterator.e(err);
3544
- } finally {
3545
- _iterator.f();
3546
- }
3547
- return earliestExpiry === undefined ? undefined : earliestExpiry - this.refreshBeforeExpirySeconds * 1000;
3548
- }
3549
3772
  }, {
3550
3773
  key: "sendServiceWorkerConfig",
3551
3774
  value: function sendServiceWorkerConfig(session, config, urlRewriteRules) {
@@ -3571,16 +3794,172 @@ var AuthManagerImpl = /*#__PURE__*/function () {
3571
3794
  }
3572
3795
  }
3573
3796
  }, {
3574
- key: "updateSessionReadiness",
3575
- value: function updateSessionReadiness(session) {
3576
- session.isReady = session.accessToken !== undefined && (session.params.serviceWorkerConfig === undefined || session.serviceWorkerConfig !== undefined);
3797
+ key: "getV2Configs",
3798
+ value: function getV2Configs(params) {
3799
+ try {
3800
+ return AuthManagerBrowser_await(params.authConfigs(), function (configs) {
3801
+ if (!Array.isArray(configs) || configs.length === 0) {
3802
+ throw new Error("The 'authConfigs' callback must return a non-empty array.");
3803
+ }
3804
+ return configs.map(function (config) {
3805
+ return config === null || AuthManagerBrowser_typeof(config) !== "object" ? config : Object.assign(Object.assign({}, config), {
3806
+ sourceUrlPrefixes: Array.isArray(config.sourceUrlPrefixes) ? AuthManagerBrowser_toConsumableArray(config.sourceUrlPrefixes) : config.sourceUrlPrefixes
3807
+ });
3808
+ });
3809
+ });
3810
+ } catch (e) {
3811
+ return Promise.reject(e);
3812
+ }
3813
+ }
3814
+ }, {
3815
+ key: "normalizeV1Config",
3816
+ value: function normalizeV1Config(params) {
3817
+ return {
3818
+ accountId: params.accountId,
3819
+ authConfigId: undefined,
3820
+ authHeaders: params.authHeaders,
3821
+ authUrl: params.authUrl,
3822
+ enableCookieAuth: params.serviceWorkerScript === undefined,
3823
+ enableServiceWorkerAuth: params.serviceWorkerScript !== undefined
3824
+ };
3825
+ }
3826
+ }, {
3827
+ key: "validateSessionConfig",
3828
+ value: function validateSessionConfig(params, configs, canUseServiceWorkers, requiresServiceWorker) {
3829
+ var isV2 = this.isV2Params(params);
3830
+ if (isV2 && (params.accountId !== undefined || params.authHeaders !== undefined || params.authUrl !== undefined)) {
3831
+ throw new Error("V2 auth sessions must use 'authConfigs' instead of top-level auth fields.");
3832
+ }
3833
+ var ids = new Set();
3834
+ var cookieConfig;
3835
+ var workerConfigsByPrefix = new Map();
3836
+ var _iterator2 = _createForOfIteratorHelper(configs),
3837
+ _step2;
3838
+ try {
3839
+ for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
3840
+ var config = _step2.value;
3841
+ if (config === null || AuthManagerBrowser_typeof(config) !== "object") {
3842
+ throw new Error("Each auth configuration must be an object.");
3843
+ }
3844
+ if (!Object.prototype.hasOwnProperty.call(config, "authConfigId")) {
3845
+ throw new Error("Each auth configuration must explicitly provide 'authConfigId'.");
3846
+ }
3847
+ if (config.authConfigId !== undefined && typeof config.authConfigId !== "string") {
3848
+ throw new Error("The 'authConfigId' field must be a string or undefined.");
3849
+ }
3850
+ if (ids.has(config.authConfigId)) {
3851
+ throw new Error(config.authConfigId === undefined ? "Only one default auth configuration is allowed." : "Duplicate auth configuration ID: '".concat(config.authConfigId, "'."));
3852
+ }
3853
+ ids.add(config.authConfigId);
3854
+ if (isV2 && !this.isValidAccountId(config.accountId)) {
3855
+ throw new Error("Invalid Bytescale account ID: '".concat(String(config.accountId), "'."));
3856
+ }
3857
+ if (config.cdnUrl !== undefined && typeof config.cdnUrl !== "string") {
3858
+ throw new Error("The 'cdnUrl' field must be a string when provided.");
3859
+ }
3860
+ if (config.enableCookieAuth !== undefined && typeof config.enableCookieAuth !== "boolean" || config.enableServiceWorkerAuth !== undefined && typeof config.enableServiceWorkerAuth !== "boolean") {
3861
+ throw new Error("Authentication enablement flags must be booleans when provided.");
3862
+ }
3863
+ if (config.sourceUrlPrefixes !== undefined && (!Array.isArray(config.sourceUrlPrefixes) || !config.sourceUrlPrefixes.every(function (prefix) {
3864
+ return typeof prefix === "string";
3865
+ }))) {
3866
+ throw new Error("The 'sourceUrlPrefixes' field must be an array of strings.");
3867
+ }
3868
+ var isManual = typeof config.getAuthorizationToken === "function";
3869
+ var isAutomatic = typeof config.authUrl === "string" && typeof config.authHeaders === "function";
3870
+ if (isManual === isAutomatic || isManual && (config.authUrl !== undefined || config.authHeaders !== undefined)) {
3871
+ throw new Error("Each auth configuration must provide either 'getAuthorizationToken' or both 'authUrl' and 'authHeaders'.");
3872
+ }
3873
+ if (config.enableCookieAuth === true) {
3874
+ if (cookieConfig !== undefined) {
3875
+ throw new Error("Only one auth configuration may enable cookie authentication.");
3876
+ }
3877
+ cookieConfig = config;
3878
+ }
3879
+ if (this.isServiceWorkerEnabled(config)) {
3880
+ var _prefix = "".concat(this.getConfigCdnUrl(params, config), "/").concat(config.accountId, "/");
3881
+ if (workerConfigsByPrefix.has(_prefix)) {
3882
+ throw new Error("Multiple service-worker auth configurations target the same URL prefix: '".concat(_prefix, "'."));
3883
+ }
3884
+ workerConfigsByPrefix.set(_prefix, config);
3885
+ }
3886
+ }
3887
+ } catch (err) {
3888
+ _iterator2.e(err);
3889
+ } finally {
3890
+ _iterator2.f();
3891
+ }
3892
+ if (cookieConfig !== undefined) {
3893
+ var prefix = "".concat(this.getConfigCdnUrl(params, cookieConfig), "/").concat(cookieConfig.accountId, "/");
3894
+ var workerConfig = workerConfigsByPrefix.get(prefix);
3895
+ if (workerConfig !== undefined && workerConfig !== cookieConfig) {
3896
+ throw new Error("Cookie and service-worker authentication cannot target the same account from different configs.");
3897
+ }
3898
+ }
3899
+ if (isV2) {
3900
+ this.validateUrlRewriteRules(params.urlRewriteRules);
3901
+ if (requiresServiceWorker && params.serviceWorkerScript === undefined) {
3902
+ throw new Error("The 'serviceWorkerScript' field is required when service-worker authentication or URL rewriting is enabled.");
3903
+ }
3904
+ if (requiresServiceWorker && !canUseServiceWorkers) {
3905
+ throw new Error("This auth session requires service workers, but this browser does not support them.");
3906
+ }
3907
+ }
3908
+ }
3909
+ }, {
3910
+ key: "validateUrlRewriteRules",
3911
+ value: function validateUrlRewriteRules(rules) {
3912
+ if (rules !== undefined && (!Array.isArray(rules) || !rules.every(function (rule) {
3913
+ return rule !== null && AuthManagerBrowser_typeof(rule) === "object" && typeof rule.fromUrlPrefix === "string" && typeof rule.toUrlPrefix === "string";
3914
+ }))) {
3915
+ throw new Error("The 'urlRewriteRules' field must be an array of URL rewrite rules.");
3916
+ }
3917
+ }
3918
+ }, {
3919
+ key: "updateSessionState",
3920
+ value: function updateSessionState(session) {
3921
+ var _this7 = this;
3922
+ var _a;
3923
+ var configs = (_a = session.authConfigs) !== null && _a !== void 0 ? _a : [];
3924
+ var defaultConfig = configs.find(function (state) {
3925
+ return state.config.authConfigId === undefined;
3926
+ });
3927
+ var exposeLegacyDefault = !this.isV2Params(session.params);
3928
+ session.accessToken = exposeLegacyDefault && defaultConfig !== undefined && this.isConfigUsable(defaultConfig) ? defaultConfig.accessToken : undefined;
3929
+ session.accessTokenRefreshHandle = exposeLegacyDefault ? defaultConfig === null || defaultConfig === void 0 ? void 0 : defaultConfig.refreshHandle : undefined;
3930
+ session.isReady = configs.length > 0 && configs.every(function (state) {
3931
+ return _this7.isConfigUsable(state);
3932
+ }) && (session.authServiceWorker === undefined || session.serviceWorkerConfigured === true);
3933
+ }
3934
+ }, {
3935
+ key: "isConfigUsable",
3936
+ value: function isConfigUsable(state) {
3937
+ return (state === null || state === void 0 ? void 0 : state.accessToken) !== undefined && state.expiresAt !== undefined && state.expiresAt > Date.now();
3938
+ }
3939
+ }, {
3940
+ key: "isServiceWorkerEnabled",
3941
+ value: function isServiceWorkerEnabled(config) {
3942
+ return config.enableServiceWorkerAuth !== false;
3943
+ }
3944
+ }, {
3945
+ key: "isV2Params",
3946
+ value: function isV2Params(params) {
3947
+ return typeof params.authConfigs === "function";
3948
+ }
3949
+ }, {
3950
+ key: "isValidAccountId",
3951
+ value: function isValidAccountId(accountId) {
3952
+ return typeof accountId === "string" && /^[1-9A-HJ-NP-Za-km-z]{7}$/.test(accountId);
3953
+ }
3954
+ }, {
3955
+ key: "shouldSetCookie",
3956
+ value: function shouldSetCookie(session, config) {
3957
+ return this.isV2Params(session.params) ? config.enableCookieAuth === true : session.authServiceWorker === undefined;
3577
3958
  }
3578
3959
  }, {
3579
3960
  key: "waitForServiceWorker",
3580
3961
  value: function waitForServiceWorker() {
3581
3962
  try {
3582
- // Message delivery is asynchronous and has no acknowledgement, so allow the worker time to apply the config before
3583
- // beginAuthSession reports that authenticated requests are ready.
3584
3963
  return AuthManagerBrowser_await(AuthManagerBrowser_awaitIgnored(new Promise(function (resolve) {
3585
3964
  return setTimeout(resolve, 100);
3586
3965
  })));
@@ -3590,8 +3969,8 @@ var AuthManagerImpl = /*#__PURE__*/function () {
3590
3969
  }
3591
3970
  }, {
3592
3971
  key: "getAccessTokenUrl",
3593
- value: function getAccessTokenUrl(params, setCookie) {
3594
- return "".concat(this.getCdnUrl(params), "/api/v1/access_tokens/").concat(params.accountId, "?set-cookie=").concat(setCookie ? "true" : "false");
3972
+ value: function getAccessTokenUrl(cdnUrl, accountId, setCookie) {
3973
+ return "".concat(cdnUrl, "/api/v1/access_tokens/").concat(accountId, "?set-cookie=").concat(setCookie ? "true" : "false");
3595
3974
  }
3596
3975
  }, {
3597
3976
  key: "getCdnUrl",
@@ -3599,19 +3978,26 @@ var AuthManagerImpl = /*#__PURE__*/function () {
3599
3978
  var _a;
3600
3979
  return BytescaleApiClientConfigUtils.getCdnUrl((_a = params.options) !== null && _a !== void 0 ? _a : {});
3601
3980
  }
3981
+ }, {
3982
+ key: "getConfigCdnUrl",
3983
+ value: function getConfigCdnUrl(params, config) {
3984
+ var _a, _b;
3985
+ return BytescaleApiClientConfigUtils.getCdnUrl({
3986
+ cdnUrl: (_a = config.cdnUrl) !== null && _a !== void 0 ? _a : (_b = params.options) === null || _b === void 0 ? void 0 : _b.cdnUrl
3987
+ });
3988
+ }
3602
3989
  }, {
3603
3990
  key: "deleteAccessToken",
3604
- value: function deleteAccessToken(params) {
3991
+ value: function deleteAccessToken(options, cdnUrl, accountId) {
3605
3992
  try {
3606
- var _this7 = this;
3607
- var _a;
3608
- return AuthManagerBrowser_await(AuthManagerBrowser_awaitIgnored(BaseAPI.fetch(_this7.getAccessTokenUrl(params, true), {
3993
+ var _this8 = this;
3994
+ return AuthManagerBrowser_await(AuthManagerBrowser_awaitIgnored(BaseAPI.fetch(_this8.getAccessTokenUrl(cdnUrl, accountId, true), {
3609
3995
  method: "DELETE",
3610
3996
  credentials: "include",
3611
3997
  headers: {}
3612
3998
  }, {
3613
3999
  isBytescaleApi: true,
3614
- fetchApi: (_a = params.options) === null || _a === void 0 ? void 0 : _a.fetchApi
4000
+ fetchApi: options === null || options === void 0 ? void 0 : options.fetchApi
3615
4001
  })));
3616
4002
  } catch (e) {
3617
4003
  return Promise.reject(e);
@@ -3619,68 +4005,96 @@ var AuthManagerImpl = /*#__PURE__*/function () {
3619
4005
  }
3620
4006
  }, {
3621
4007
  key: "setAccessToken",
3622
- value: function setAccessToken(params, jwt, setCookie) {
4008
+ value: function setAccessToken(options, cdnUrl, accountId, jwt, setCookie) {
3623
4009
  try {
3624
- var _this8 = this;
3625
- var _a;
4010
+ var _this9 = this;
3626
4011
  var request = {
3627
4012
  accessToken: jwt
3628
4013
  };
3629
- return AuthManagerBrowser_await(BaseAPI.fetch(_this8.getAccessTokenUrl(params, setCookie), {
4014
+ return AuthManagerBrowser_await(BaseAPI.fetch(_this9.getAccessTokenUrl(cdnUrl, accountId, setCookie), {
3630
4015
  method: "PUT",
3631
4016
  credentials: "include",
3632
- headers: AuthManagerBrowser_defineProperty({}, _this8.contentType, _this8.contentTypeJson),
4017
+ headers: AuthManagerBrowser_defineProperty({}, _this9.contentType, _this9.contentTypeJson),
3633
4018
  body: JSON.stringify(request)
3634
4019
  }, {
3635
4020
  isBytescaleApi: true,
3636
- fetchApi: (_a = params.options) === null || _a === void 0 ? void 0 : _a.fetchApi
4021
+ fetchApi: options === null || options === void 0 ? void 0 : options.fetchApi
3637
4022
  }), function (response) {
3638
- return AuthManagerBrowser_await(response.json());
4023
+ return AuthManagerBrowser_await(response.json(), function (result) {
4024
+ if (typeof result.accessToken !== "string" || result.accessToken.length === 0 || typeof result.ttlSeconds !== "number" || !Number.isFinite(result.ttlSeconds) || result.ttlSeconds <= 0) {
4025
+ throw new Error("Bytescale returned an invalid access-token registration response.");
4026
+ }
4027
+ return result;
4028
+ });
3639
4029
  });
3640
4030
  } catch (e) {
3641
4031
  return Promise.reject(e);
3642
4032
  }
3643
4033
  }
3644
4034
  }, {
3645
- key: "getAccessToken",
3646
- value: function getAccessToken(params, headers) {
4035
+ key: "getAuthorizationToken",
4036
+ value: function getAuthorizationToken(params, config) {
3647
4037
  try {
3648
- var _this9 = this;
4038
+ var _exit = false;
4039
+ var _this0 = this;
3649
4040
  var _a, _b;
3650
- var endpointName = "Your auth API endpoint";
3651
- var requiredContentType = _this9.contentTypeText;
3652
- return AuthManagerBrowser_await(BaseAPI.fetch(params.authUrl, {
3653
- method: "GET",
3654
- headers: headers
3655
- }, {
3656
- isBytescaleApi: false,
3657
- fetchApi: (_a = params.options) === null || _a === void 0 ? void 0 : _a.fetchApi
3658
- }), function (result) {
3659
- var actualContentType = (_b = result.headers.get(_this9.contentType)) !== null && _b !== void 0 ? _b : "";
3660
- // Support content types like "text/plain; charset=utf-8" and "text/plain"
3661
- if (actualContentType.split(";")[0] !== requiredContentType) {
3662
- throw new Error("".concat(endpointName, " returned \"").concat(actualContentType, "\" for the ").concat(_this9.contentType, " response header, but the Bytescale SDK requires \"").concat(requiredContentType, "\"."));
4041
+ return AuthManagerBrowser_await(AuthManagerBrowser_invoke(function () {
4042
+ if (typeof config.getAuthorizationToken === "function") {
4043
+ var _validateJwt = _this0.validateJwt;
4044
+ return AuthManagerBrowser_await(config.getAuthorizationToken(), function (_config$getAuthorizat) {
4045
+ var _this0$validateJwt = _validateJwt.call(_this0, _config$getAuthorizat, "The 'getAuthorizationToken' callback");
4046
+ _exit = true;
4047
+ return _this0$validateJwt;
4048
+ });
3663
4049
  }
3664
- return AuthManagerBrowser_await(result.text(), function (jwt) {
3665
- if (jwt.length === 0) {
3666
- throw new Error("".concat(endpointName, " returned an empty string. Please return a valid JWT instead."));
3667
- }
3668
- if (jwt.trim().length !== jwt.length) {
3669
- // Whitespace can be a nightmare to spot/debug, so we fail early here.
3670
- throw new Error("".concat(endpointName, " returned whitespace around the JWT, please remove it."));
3671
- }
3672
- return jwt;
4050
+ }, function (_result3) {
4051
+ if (_exit) return _result3;
4052
+ var endpointName = "Your auth API endpoint";
4053
+ var _fetch = BaseAPI.fetch,
4054
+ _config$authUrl = config.authUrl;
4055
+ return AuthManagerBrowser_await(config.authHeaders(), function (_config$authHeaders) {
4056
+ return AuthManagerBrowser_await(_fetch.call(BaseAPI, _config$authUrl, {
4057
+ method: "GET",
4058
+ headers: _config$authHeaders
4059
+ }, {
4060
+ isBytescaleApi: false,
4061
+ fetchApi: (_a = params.options) === null || _a === void 0 ? void 0 : _a.fetchApi
4062
+ }), function (result) {
4063
+ var actualContentType = (_b = result.headers.get(_this0.contentType)) !== null && _b !== void 0 ? _b : "";
4064
+ if (actualContentType.split(";")[0] !== _this0.contentTypeText) {
4065
+ throw new Error("".concat(endpointName, " returned \"").concat(actualContentType, "\" for the ").concat(_this0.contentType, " response header, but the Bytescale SDK requires \"").concat(_this0.contentTypeText, "\"."));
4066
+ }
4067
+ var _validateJwt2 = _this0.validateJwt;
4068
+ return AuthManagerBrowser_await(result.text(), function (_result$text) {
4069
+ return _validateJwt2.call(_this0, _result$text, endpointName);
4070
+ });
4071
+ });
3673
4072
  });
3674
- });
4073
+ }));
3675
4074
  } catch (e) {
3676
4075
  return Promise.reject(e);
3677
4076
  }
3678
4077
  }
4078
+ }, {
4079
+ key: "validateJwt",
4080
+ value: function validateJwt(jwt, source) {
4081
+ if (typeof jwt !== "string" || jwt.length === 0) {
4082
+ throw new InvalidAuthTokenError("".concat(source, " returned an empty or malformed token. Please return a valid JWT instead."));
4083
+ }
4084
+ if (jwt.trim().length !== jwt.length) {
4085
+ throw new InvalidAuthTokenError("".concat(source, " returned whitespace around the JWT, please remove it."));
4086
+ }
4087
+ var parts = jwt.split(".");
4088
+ if (parts.length !== 3 || parts.some(function (part) {
4089
+ return part.length === 0 || !/^[A-Za-z0-9_-]+$/.test(part);
4090
+ })) {
4091
+ throw new InvalidAuthTokenError("".concat(source, " returned a malformed JWT."));
4092
+ }
4093
+ return jwt;
4094
+ }
3679
4095
  }]);
3680
4096
  }();
3681
- /**
3682
- * 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).
3683
- */
4097
+ /** Alternative to a static class that allows the implementation to satisfy an interface. */
3684
4098
  var AuthManager = new AuthManagerImpl(new ServiceWorkerUtils());
3685
4099
  ;// ./src/public/browser/index.ts
3686
4100