@bytescale/sdk 3.57.0 → 3.59.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 +724 -313
  2. package/dist/browser/esm/main.mjs +724 -313
  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 +2 -0
  8. package/dist/types/private/model/AuthManagerInterface.d.ts +1 -93
  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 +12 -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 +27 -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 +312 -192
  28. package/tests/AuthServiceWorkerRewrite.test.ts +337 -0
  29. package/tests/UploadManagerAuth.test.ts +156 -0
@@ -250,6 +250,55 @@ var AuthSessionState = /*#__PURE__*/function () {
250
250
  }
251
251
  return window[AuthSessionState.stateKey];
252
252
  }
253
+ /** Resolves request-time auth while remaining compatible with the single-token session used by SDK 3.54.0. */
254
+ }, {
255
+ key: "resolveAuthConfig",
256
+ value: function resolveAuthConfig(authConfigId, requireReadyDefault) {
257
+ if (authConfigId === false) {
258
+ return undefined;
259
+ }
260
+ var session = AuthSessionState.getSession();
261
+ if (session === undefined || !session.isActive) {
262
+ if (typeof authConfigId === "string") {
263
+ throw new Error("No active AuthManager configuration has ID '".concat(authConfigId, "'."));
264
+ }
265
+ return undefined;
266
+ }
267
+ if (Array.isArray(session.authConfigs)) {
268
+ var state = session.authConfigs.find(function (config) {
269
+ return config.config.authConfigId === authConfigId;
270
+ });
271
+ if (state === undefined) {
272
+ if (typeof authConfigId === "string") {
273
+ throw new Error("No active AuthManager configuration has ID '".concat(authConfigId, "'."));
274
+ }
275
+ return undefined;
276
+ }
277
+ if (state.accessToken === undefined || state.expiresAt === undefined || state.expiresAt <= Date.now() || state.jwt === undefined) {
278
+ var isV2Session = typeof session.params.authConfigs === "function";
279
+ if (typeof authConfigId === "string" || requireReadyDefault || isV2Session) {
280
+ throw new Error("AuthManager configuration '".concat(authConfigId !== null && authConfigId !== void 0 ? authConfigId : "default", "' is not ready."));
281
+ }
282
+ return undefined;
283
+ }
284
+ return {
285
+ accessToken: state.accessToken,
286
+ accountId: state.config.accountId,
287
+ jwt: state.jwt
288
+ };
289
+ }
290
+ if (typeof authConfigId === "string") {
291
+ throw new Error("No active AuthManager configuration has ID '".concat(authConfigId, "'."));
292
+ }
293
+ if (session.accessToken === undefined || typeof session.params.accountId !== "string") {
294
+ return undefined;
295
+ }
296
+ return {
297
+ accessToken: session.accessToken,
298
+ accountId: session.params.accountId,
299
+ jwt: undefined
300
+ };
301
+ }
253
302
  }]);
254
303
  }();
255
304
  AuthSessionState.stateKey = "BytescaleSessionState";
@@ -393,12 +442,47 @@ var BytescaleApiClientConfigUtils = /*#__PURE__*/function () {
393
442
  }, {
394
443
  key: "getAccountId",
395
444
  value: function getAccountId(config) {
445
+ return BytescaleApiClientConfigUtils.resolveAuthentication(config).accountId;
446
+ }
447
+ }, {
448
+ key: "resolveAuthentication",
449
+ value: function resolveAuthentication(config) {
450
+ var _a, _b;
451
+ var apiKey = (_a = config.apiKey) !== null && _a !== void 0 ? _a : undefined;
452
+ var authConfig = AuthSessionState.resolveAuthConfig(config.authConfigId, apiKey === undefined);
453
+ var apiKeyAccountId = apiKey === undefined ? undefined : BytescaleApiClientConfigUtils.getApiKeyAccountId(apiKey);
454
+ if (apiKeyAccountId !== undefined && authConfig !== undefined && apiKeyAccountId !== authConfig.accountId) {
455
+ 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, "'."));
456
+ }
457
+ if (apiKey !== undefined) {
458
+ return {
459
+ accountId: apiKeyAccountId,
460
+ headers: Object.assign({
461
+ Authorization: "Bearer ".concat(apiKey)
462
+ }, authConfig === undefined ? {} : {
463
+ "Authorization-Token": authConfig.accessToken
464
+ })
465
+ };
466
+ }
467
+ if ((authConfig === null || authConfig === void 0 ? void 0 : authConfig.jwt) !== undefined) {
468
+ return {
469
+ accountId: authConfig.accountId,
470
+ headers: {
471
+ Authorization: "Bearer ".concat(authConfig.jwt)
472
+ }
473
+ };
474
+ }
475
+ throw new Error("Please provide an API key via the 'apiKey' config parameter.");
476
+ }
477
+ }, {
478
+ key: "getApiKeyAccountId",
479
+ value: function getApiKeyAccountId(apiKey) {
396
480
  var _a, _b;
397
481
  var accountId;
398
- if (BytescaleApiClientConfigUtils.specialApiKeys.includes(config.apiKey)) {
482
+ if (BytescaleApiClientConfigUtils.specialApiKeys.includes(apiKey)) {
399
483
  accountId = BytescaleApiClientConfigUtils.specialApiKeyAccountId;
400
484
  } else {
401
- accountId = (_b = (_a = config.apiKey.split("_")[1]) === null || _a === void 0 ? void 0 : _a.substr(0, BytescaleApiClientConfigUtils.accountIdLength)) !== null && _b !== void 0 ? _b : "";
485
+ accountId = (_b = (_a = apiKey.split("_")[1]) === null || _a === void 0 ? void 0 : _a.substr(0, BytescaleApiClientConfigUtils.accountIdLength)) !== null && _b !== void 0 ? _b : "";
402
486
  if (accountId.length !== BytescaleApiClientConfigUtils.accountIdLength) {
403
487
  throw new Error("Invalid Bytescale API key.");
404
488
  }
@@ -408,21 +492,24 @@ var BytescaleApiClientConfigUtils = /*#__PURE__*/function () {
408
492
  }, {
409
493
  key: "validate",
410
494
  value: function validate(config) {
411
- var _a;
412
495
  // Defensive programming, for users not using TypeScript. Mainly because this is used by UploadWidget users.
413
496
  if ((config !== null && config !== void 0 ? config : undefined) === undefined) {
414
497
  throw new Error("Config parameter required.");
415
498
  }
416
- if (((_a = config.apiKey) !== null && _a !== void 0 ? _a : undefined) === undefined) {
417
- throw new Error("Please provide an API key via the 'apiKey' config parameter.");
499
+ if (config.authConfigId !== undefined && config.authConfigId !== false && typeof config.authConfigId !== "string") {
500
+ throw new Error("The 'authConfigId' config parameter must be a string, false, or undefined.");
418
501
  }
419
- if (config.apiKey.trim() !== config.apiKey) {
502
+ if (config.apiKey !== undefined && typeof config.apiKey !== "string") {
503
+ throw new Error("The 'apiKey' config parameter must be a string when provided.");
504
+ }
505
+ if (config.apiKey !== undefined && config.apiKey.trim() !== config.apiKey) {
420
506
  // We do not support API keys with whitespace (by trimming ourselves) because otherwise we'd need to support this
421
507
  // everywhere in perpetuity (since removing the trimming would be a breaking change).
422
508
  throw new Error("API key needs trimming (whitespace detected).");
423
509
  }
424
- // This performs futher validation on the API key...
425
- BytescaleApiClientConfigUtils.getAccountId(config);
510
+ if (config.apiKey !== undefined) {
511
+ BytescaleApiClientConfigUtils.getApiKeyAccountId(config.apiKey);
512
+ }
426
513
  }
427
514
  }]);
428
515
  }();
@@ -449,12 +536,7 @@ var BaseAPI = /*#__PURE__*/function () {
449
536
  try {
450
537
  var _this = this;
451
538
  var _a;
452
- var apiKey = _this.config.apiKey;
453
- context.headers["Authorization"] = "Bearer ".concat(apiKey); // authorization-header authentication
454
- var session = AuthSessionState.getSession();
455
- if ((session === null || session === void 0 ? void 0 : session.accessToken) !== undefined) {
456
- context.headers["Authorization-Token"] = session.accessToken;
457
- }
539
+ Object.assign(context.headers, BytescaleApiClientConfigUtils.resolveAuthentication(_this.config).headers);
458
540
  // Key: any possible value for 'baseUrlOverride'
459
541
  // Value: user-overridden value for that base URL from the config.
460
542
  var nonDefaultBasePaths = _defineProperty({}, BytescaleApiClientConfigUtils.defaultCdnUrl, BytescaleApiClientConfigUtils.getCdnUrl(_this.config));
@@ -494,9 +576,21 @@ var BaseAPI = /*#__PURE__*/function () {
494
576
  url += "?" + querystring(context.query);
495
577
  }
496
578
  var configHeaders = _this2.config.headers;
497
- var _Object$assign = Object.assign({}, context.headers);
498
- return runtime_await(runtime_await(configHeaders === undefined ? {} : typeof configHeaders === "function" ? configHeaders() : configHeaders, function (_configHeaders) {
499
- var headers = Object.assign(_Object$assign, configHeaders === undefined ? _configHeaders : _configHeaders);
579
+ return runtime_await(runtime_await(configHeaders === undefined ? {} : typeof configHeaders === "function" ? configHeaders() : configHeaders, function (resolvedConfigHeaders) {
580
+ for (var _i = 0, _Object$keys = Object.keys(resolvedConfigHeaders); _i < _Object$keys.length; _i++) {
581
+ var key = _Object$keys[_i];
582
+ if (key.toLowerCase() === "authorization" || key.toLowerCase() === "authorization-token") {
583
+ for (var _i2 = 0, _Object$keys2 = Object.keys(context.headers); _i2 < _Object$keys2.length; _i2++) {
584
+ var generatedKey = _Object$keys2[_i2];
585
+ if (generatedKey.toLowerCase() === key.toLowerCase()) {
586
+ // Custom auth headers have documented precedence; remove the generated spelling to make that deterministic.
587
+ // eslint-disable-next-line @typescript-eslint/no-dynamic-delete
588
+ delete context.headers[generatedKey];
589
+ }
590
+ }
591
+ }
592
+ }
593
+ var headers = Object.assign(Object.assign({}, context.headers), resolvedConfigHeaders);
500
594
  Object.keys(headers).forEach(function (key) {
501
595
  return headers[key] === undefined ? delete headers[key] : {};
502
596
  });
@@ -508,12 +602,12 @@ var BaseAPI = /*#__PURE__*/function () {
508
602
  headers: headers,
509
603
  body: context.body
510
604
  };
511
- var _Object$assign2 = Object.assign({}, initParams);
605
+ var _Object$assign = Object.assign({}, initParams);
512
606
  return runtime_await(initOverrideFn({
513
607
  init: initParams,
514
608
  context: context
515
609
  }), function (_initOverrideFn) {
516
- var overriddenInit = Object.assign(_Object$assign2, _initOverrideFn);
610
+ var overriddenInit = Object.assign(_Object$assign, _initOverrideFn);
517
611
  var init = Object.assign(Object.assign({}, overriddenInit), {
518
612
  body: JSON.stringify(overriddenInit.body)
519
613
  });
@@ -2138,7 +2232,6 @@ var UploadManagerBase = /*#__PURE__*/function () {
2138
2232
  this.defaultMaxConcurrentUploadParts = 4;
2139
2233
  this.intervalMs = 500;
2140
2234
  this.uploadApi = new UploadApi(config);
2141
- this.accountId = BytescaleApiClientConfigUtils.getAccountId(config);
2142
2235
  }
2143
2236
  return UploadManagerBase_createClass(UploadManagerBase, [{
2144
2237
  key: "upload",
@@ -2146,6 +2239,7 @@ var UploadManagerBase = /*#__PURE__*/function () {
2146
2239
  try {
2147
2240
  var _this = this;
2148
2241
  _this.assertNotCancelled(request);
2242
+ var accountId = BytescaleApiClientConfigUtils.getAccountId(_this.config);
2149
2243
  var source = _this.processUploadSource(request.data);
2150
2244
  var preUploadInfo = _this.getPreUploadInfo(request, source);
2151
2245
  var bytesTotal = preUploadInfo.size;
@@ -2155,7 +2249,7 @@ var UploadManagerBase = /*#__PURE__*/function () {
2155
2249
  if (request.onProgress !== undefined) {
2156
2250
  request.onProgress(_this.makeProgressEvent(0, bytesTotal));
2157
2251
  }
2158
- return UploadManagerBase_await(_this.beginUpload(request, preUploadInfo), function (uploadInfo) {
2252
+ return UploadManagerBase_await(_this.beginUpload(request, preUploadInfo, accountId), function (uploadInfo) {
2159
2253
  var partCount = uploadInfo.uploadParts.count;
2160
2254
  var parts = UploadManagerBase_toConsumableArray(Array(partCount).keys());
2161
2255
  var _this$makeCancellatio = _this.makeCancellationMethods(),
@@ -2165,7 +2259,7 @@ var UploadManagerBase = /*#__PURE__*/function () {
2165
2259
  var uploadedParts;
2166
2260
  return UploadManagerBase_continue(UploadManagerBase_finallyRethrows(function () {
2167
2261
  return UploadManagerBase_await(_this.mapAsync(parts, preUploadInfo.maxConcurrentUploadParts, _async(function (part) {
2168
- return _this.uploadPart(request, source, part, uploadInfo, makeOnProgressForPart(), addCancellationHandler);
2262
+ return _this.uploadPart(request, source, part, uploadInfo, makeOnProgressForPart(), addCancellationHandler, accountId);
2169
2263
  })), function (_this$mapAsync) {
2170
2264
  uploadedParts = _this$mapAsync;
2171
2265
  return UploadManagerBase_awaitIgnored(_this.postUpload(init));
@@ -2277,14 +2371,14 @@ var UploadManagerBase = /*#__PURE__*/function () {
2277
2371
  }
2278
2372
  }, {
2279
2373
  key: "beginUpload",
2280
- value: function beginUpload(request, _ref2) {
2374
+ value: function beginUpload(request, _ref2, accountId) {
2281
2375
  var size = _ref2.size,
2282
2376
  mime = _ref2.mime,
2283
2377
  originalFileName = _ref2.originalFileName;
2284
2378
  try {
2285
2379
  var _this4 = this;
2286
2380
  return UploadManagerBase_await(_this4.uploadApi.beginMultipartUpload({
2287
- accountId: _this4.accountId,
2381
+ accountId: accountId,
2288
2382
  beginMultipartUploadRequest: {
2289
2383
  metadata: request.metadata,
2290
2384
  mime: mime,
@@ -2301,16 +2395,16 @@ var UploadManagerBase = /*#__PURE__*/function () {
2301
2395
  }
2302
2396
  }, {
2303
2397
  key: "uploadPart",
2304
- value: function uploadPart(request, source, partIndex, uploadInfo, onProgress, addCancellationHandler) {
2398
+ value: function uploadPart(request, source, partIndex, uploadInfo, onProgress, addCancellationHandler, accountId) {
2305
2399
  try {
2306
2400
  var _this5 = this;
2307
2401
  _this5.assertNotCancelled(request);
2308
- return UploadManagerBase_await(_this5.getUploadPart(partIndex, uploadInfo), function (part) {
2402
+ return UploadManagerBase_await(_this5.getUploadPart(partIndex, uploadInfo, accountId), function (part) {
2309
2403
  _this5.assertNotCancelled(request);
2310
2404
  return UploadManagerBase_await(_this5.putUploadPart(part, source, onProgress, addCancellationHandler), function (etag) {
2311
2405
  _this5.assertNotCancelled(request);
2312
2406
  return UploadManagerBase_await(_this5.uploadApi.completeUploadPart({
2313
- accountId: _this5.accountId,
2407
+ accountId: accountId,
2314
2408
  uploadId: uploadInfo.uploadId,
2315
2409
  uploadPartIndex: partIndex,
2316
2410
  completeUploadPartRequest: {
@@ -2351,7 +2445,7 @@ var UploadManagerBase = /*#__PURE__*/function () {
2351
2445
  }
2352
2446
  }, {
2353
2447
  key: "getUploadPart",
2354
- value: function getUploadPart(partIndex, uploadInfo) {
2448
+ value: function getUploadPart(partIndex, uploadInfo, accountId) {
2355
2449
  try {
2356
2450
  var _this7 = this;
2357
2451
  if (partIndex === 0) {
@@ -2359,7 +2453,7 @@ var UploadManagerBase = /*#__PURE__*/function () {
2359
2453
  }
2360
2454
  return UploadManagerBase_await(_this7.uploadApi.getUploadPart({
2361
2455
  uploadId: uploadInfo.uploadId,
2362
- accountId: _this7.accountId,
2456
+ accountId: accountId,
2363
2457
  uploadPartIndex: partIndex
2364
2458
  }));
2365
2459
  } catch (e) {
@@ -3196,12 +3290,178 @@ function AuthManagerBrowser_awaitIgnored(value, direct) {
3196
3290
  return value && value.then ? value.then(AuthManagerBrowser_empty) : Promise.resolve();
3197
3291
  }
3198
3292
  }
3199
- function AuthManagerBrowser_invoke(body, then) {
3200
- var result = body();
3293
+ var AuthManagerBrowser_iteratorSymbol = /*#__PURE__*/typeof Symbol !== "undefined" ? Symbol.iterator || (Symbol.iterator = Symbol("Symbol.iterator")) : "@@iterator";
3294
+ function AuthManagerBrowser_settle(pact, state, value) {
3295
+ if (!pact.s) {
3296
+ if (value instanceof AuthManagerBrowser_Pact) {
3297
+ if (value.s) {
3298
+ if (state & 1) {
3299
+ state = value.s;
3300
+ }
3301
+ value = value.v;
3302
+ } else {
3303
+ value.o = AuthManagerBrowser_settle.bind(null, pact, state);
3304
+ return;
3305
+ }
3306
+ }
3307
+ if (value && value.then) {
3308
+ value.then(AuthManagerBrowser_settle.bind(null, pact, state), AuthManagerBrowser_settle.bind(null, pact, 2));
3309
+ return;
3310
+ }
3311
+ pact.s = state;
3312
+ pact.v = value;
3313
+ var observer = pact.o;
3314
+ if (observer) {
3315
+ observer(pact);
3316
+ }
3317
+ }
3318
+ }
3319
+ var AuthManagerBrowser_Pact = /*#__PURE__*/function () {
3320
+ function _Pact() {}
3321
+ _Pact.prototype.then = function (onFulfilled, onRejected) {
3322
+ var result = new _Pact();
3323
+ var state = this.s;
3324
+ if (state) {
3325
+ var callback = state & 1 ? onFulfilled : onRejected;
3326
+ if (callback) {
3327
+ try {
3328
+ AuthManagerBrowser_settle(result, 1, callback(this.v));
3329
+ } catch (e) {
3330
+ AuthManagerBrowser_settle(result, 2, e);
3331
+ }
3332
+ return result;
3333
+ } else {
3334
+ return this;
3335
+ }
3336
+ }
3337
+ this.o = function (_this) {
3338
+ try {
3339
+ var value = _this.v;
3340
+ if (_this.s & 1) {
3341
+ AuthManagerBrowser_settle(result, 1, onFulfilled ? onFulfilled(value) : value);
3342
+ } else if (onRejected) {
3343
+ AuthManagerBrowser_settle(result, 1, onRejected(value));
3344
+ } else {
3345
+ AuthManagerBrowser_settle(result, 2, value);
3346
+ }
3347
+ } catch (e) {
3348
+ AuthManagerBrowser_settle(result, 2, e);
3349
+ }
3350
+ };
3351
+ return result;
3352
+ };
3353
+ return _Pact;
3354
+ }();
3355
+ function AuthManagerBrowser_isSettledPact(thenable) {
3356
+ return thenable instanceof AuthManagerBrowser_Pact && thenable.s & 1;
3357
+ }
3358
+ function AuthManagerBrowser_forTo(array, body, check) {
3359
+ var i = -1,
3360
+ pact,
3361
+ reject;
3362
+ function _cycle(result) {
3363
+ try {
3364
+ while (++i < array.length && (!check || !check())) {
3365
+ result = body(i);
3366
+ if (result && result.then) {
3367
+ if (AuthManagerBrowser_isSettledPact(result)) {
3368
+ result = result.v;
3369
+ } else {
3370
+ result.then(_cycle, reject || (reject = AuthManagerBrowser_settle.bind(null, pact = new AuthManagerBrowser_Pact(), 2)));
3371
+ return;
3372
+ }
3373
+ }
3374
+ }
3375
+ if (pact) {
3376
+ AuthManagerBrowser_settle(pact, 1, result);
3377
+ } else {
3378
+ pact = result;
3379
+ }
3380
+ } catch (e) {
3381
+ AuthManagerBrowser_settle(pact || (pact = new AuthManagerBrowser_Pact()), 2, e);
3382
+ }
3383
+ }
3384
+ _cycle();
3385
+ return pact;
3386
+ }
3387
+ function AuthManagerBrowser_forOf(target, body, check) {
3388
+ if (typeof target[AuthManagerBrowser_iteratorSymbol] === "function") {
3389
+ var _cycle2 = function _cycle(result) {
3390
+ try {
3391
+ while (!(step = iterator.next()).done && (!check || !check())) {
3392
+ result = body(step.value);
3393
+ if (result && result.then) {
3394
+ if (AuthManagerBrowser_isSettledPact(result)) {
3395
+ result = result.v;
3396
+ } else {
3397
+ result.then(_cycle2, reject || (reject = AuthManagerBrowser_settle.bind(null, pact = new AuthManagerBrowser_Pact(), 2)));
3398
+ return;
3399
+ }
3400
+ }
3401
+ }
3402
+ if (pact) {
3403
+ AuthManagerBrowser_settle(pact, 1, result);
3404
+ } else {
3405
+ pact = result;
3406
+ }
3407
+ } catch (e) {
3408
+ AuthManagerBrowser_settle(pact || (pact = new AuthManagerBrowser_Pact()), 2, e);
3409
+ }
3410
+ };
3411
+ var iterator = target[AuthManagerBrowser_iteratorSymbol](),
3412
+ step,
3413
+ pact,
3414
+ reject;
3415
+ _cycle2();
3416
+ if (iterator.return) {
3417
+ var _fixup = function _fixup(value) {
3418
+ try {
3419
+ if (!step.done) {
3420
+ iterator.return();
3421
+ }
3422
+ } catch (e) {}
3423
+ return value;
3424
+ };
3425
+ if (pact && pact.then) {
3426
+ return pact.then(_fixup, function (e) {
3427
+ throw _fixup(e);
3428
+ });
3429
+ }
3430
+ _fixup();
3431
+ }
3432
+ return pact;
3433
+ }
3434
+ // No support for Symbol.iterator
3435
+ if (!("length" in target)) {
3436
+ throw new TypeError("Object is not iterable");
3437
+ }
3438
+ // Handle live collections properly
3439
+ var values = [];
3440
+ for (var i = 0; i < target.length; i++) {
3441
+ values.push(target[i]);
3442
+ }
3443
+ return AuthManagerBrowser_forTo(values, function (i) {
3444
+ return body(values[i]);
3445
+ }, check);
3446
+ }
3447
+ function AuthManagerBrowser_continueIgnored(value) {
3448
+ if (value && value.then) {
3449
+ return value.then(AuthManagerBrowser_empty);
3450
+ }
3451
+ }
3452
+ function AuthManagerBrowser_catch(body, recover) {
3453
+ try {
3454
+ var result = body();
3455
+ } catch (e) {
3456
+ return recover(e);
3457
+ }
3201
3458
  if (result && result.then) {
3202
- return result.then(then);
3459
+ return result.then(void 0, recover);
3203
3460
  }
3204
- return then(result);
3461
+ return result;
3462
+ }
3463
+ function AuthManagerBrowser_continue(value, then) {
3464
+ return value && value.then ? value.then(then) : then(value);
3205
3465
  }
3206
3466
  function AuthManagerBrowser_await(value, then, direct) {
3207
3467
  if (direct) {
@@ -3224,22 +3484,12 @@ function AuthManagerBrowser_async(f) {
3224
3484
  }
3225
3485
  };
3226
3486
  }
3227
- function AuthManagerBrowser_invokeIgnored(body) {
3487
+ function AuthManagerBrowser_invoke(body, then) {
3228
3488
  var result = body();
3229
3489
  if (result && result.then) {
3230
- return result.then(AuthManagerBrowser_empty);
3231
- }
3232
- }
3233
- function AuthManagerBrowser_catch(body, recover) {
3234
- try {
3235
- var result = body();
3236
- } catch (e) {
3237
- return recover(e);
3238
- }
3239
- if (result && result.then) {
3240
- return result.then(void 0, recover);
3490
+ return result.then(then);
3241
3491
  }
3242
- return result;
3492
+ return then(result);
3243
3493
  }
3244
3494
  function AuthManagerBrowser_rethrow(thrown, value) {
3245
3495
  if (thrown) throw value;
@@ -3256,44 +3506,43 @@ function AuthManagerBrowser_finallyRethrows(body, finalizer) {
3256
3506
  }
3257
3507
  return finalizer(false, result);
3258
3508
  }
3259
- function AuthManagerBrowser_continueIgnored(value) {
3260
- if (value && value.then) {
3261
- return value.then(AuthManagerBrowser_empty);
3262
- }
3263
- }
3264
- function AuthManagerBrowser_call(body, then, direct) {
3265
- if (direct) {
3266
- return then ? then(body()) : body();
3267
- }
3268
- try {
3269
- var result = Promise.resolve(body());
3270
- return then ? result.then(then) : result;
3271
- } catch (e) {
3272
- return Promise.reject(e);
3273
- }
3274
- }
3275
- function AuthManagerBrowser_continue(value, then) {
3276
- return value && value.then ? value.then(then) : then(value);
3277
- }
3278
3509
  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; }
3279
- 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; } } }; }
3280
3510
  function AuthManagerBrowser_toConsumableArray(r) { return AuthManagerBrowser_arrayWithoutHoles(r) || AuthManagerBrowser_iterableToArray(r) || AuthManagerBrowser_unsupportedIterableToArray(r) || AuthManagerBrowser_nonIterableSpread(); }
3281
3511
  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."); }
3282
- 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; } }
3283
3512
  function AuthManagerBrowser_iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); }
3284
3513
  function AuthManagerBrowser_arrayWithoutHoles(r) { if (Array.isArray(r)) return AuthManagerBrowser_arrayLikeToArray(r); }
3514
+ 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; } } }; }
3515
+ 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; } }
3285
3516
  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; }
3286
3517
  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); }
3287
- function AuthManagerBrowser_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
3288
3518
  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); } }
3289
3519
  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; }
3290
3520
  function AuthManagerBrowser_toPropertyKey(t) { var i = AuthManagerBrowser_toPrimitive(t, "string"); return "symbol" == AuthManagerBrowser_typeof(i) ? i : i + ""; }
3291
3521
  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); }
3522
+ function AuthManagerBrowser_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
3523
+ 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)); }
3524
+ 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); }
3525
+ function AuthManagerBrowser_assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; }
3526
+ 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); }
3527
+ 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); }
3528
+ 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; }
3529
+ function AuthManagerBrowser_isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (AuthManagerBrowser_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
3530
+ function AuthManagerBrowser_isNativeFunction(t) { try { return -1 !== Function.toString.call(t).indexOf("[native code]"); } catch (n) { return "function" == typeof t; } }
3531
+ 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); }
3532
+ function AuthManagerBrowser_getPrototypeOf(t) { return AuthManagerBrowser_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, AuthManagerBrowser_getPrototypeOf(t); }
3292
3533
 
3293
3534
 
3294
3535
 
3295
3536
 
3296
3537
 
3538
+ var InvalidAuthTokenError = /*#__PURE__*/function (_Error) {
3539
+ function InvalidAuthTokenError() {
3540
+ AuthManagerBrowser_classCallCheck(this, InvalidAuthTokenError);
3541
+ return AuthManagerBrowser_callSuper(this, InvalidAuthTokenError, arguments);
3542
+ }
3543
+ AuthManagerBrowser_inherits(InvalidAuthTokenError, _Error);
3544
+ return AuthManagerBrowser_createClass(InvalidAuthTokenError);
3545
+ }(/*#__PURE__*/AuthManagerBrowser_wrapNativeSuper(Error));
3297
3546
  var AuthManagerImpl = /*#__PURE__*/function () {
3298
3547
  function AuthManagerImpl(serviceWorkerUtils) {
3299
3548
  AuthManagerBrowser_classCallCheck(this, AuthManagerImpl);
@@ -3317,53 +3566,71 @@ var AuthManagerImpl = /*#__PURE__*/function () {
3317
3566
  }, {
3318
3567
  key: "isAuthSessionReady",
3319
3568
  value: function isAuthSessionReady() {
3320
- var _a;
3569
+ var _this = this;
3321
3570
  var session = AuthSessionState.getSession();
3322
- 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;
3571
+ if (session !== undefined && Array.isArray(session.authConfigs)) {
3572
+ return session.isReady === true && session.authConfigs.every(function (state) {
3573
+ return _this.isConfigUsable(state);
3574
+ });
3575
+ }
3576
+ return (session === null || session === void 0 ? void 0 : session.accessToken) !== undefined;
3323
3577
  }
3324
3578
  }, {
3325
3579
  key: "beginAuthSession",
3326
3580
  value: function beginAuthSession(params) {
3327
3581
  try {
3328
- var _this = this;
3329
- return AuthManagerBrowser_await(_this.authSessionMutex.safe(AuthManagerBrowser_async(function () {
3330
- // We check both 'session' and 'sessionDisposing' here, as we don't want to call 'beginAuthSession' until the session is fully disposed.
3331
- if (_this.isAuthSessionActive()) {
3582
+ var _this2 = this;
3583
+ var _a;
3584
+ return AuthManagerBrowser_await(_this2.authSessionMutex.safe(AuthManagerBrowser_async(function () {
3585
+ var _a, _b;
3586
+ if (_this2.isAuthSessionActive()) {
3332
3587
  throw new Error("Auth session already active. Please call 'await endAuthSession()' and then call 'await beginAuthSession(...)' to start a new auth session.");
3333
3588
  }
3334
- var canUseServiceWorkers = _this.serviceWorkerUtils.canUseServiceWorkers();
3335
- if (params.serviceWorkerConfig !== undefined) {
3336
- if (params.serviceWorkerScript === undefined) {
3337
- throw new Error("The 'serviceWorkerScript' field is required when 'serviceWorkerConfig' is provided.");
3338
- }
3339
- if (!canUseServiceWorkers) {
3340
- throw new Error("The 'serviceWorkerConfig' field requires service workers, but this browser does not support them.");
3341
- }
3589
+ if (Object.prototype.hasOwnProperty.call(params, "authConfigs") && typeof params.authConfigs !== "function") {
3590
+ throw new Error("The 'authConfigs' field must be a callback returning a non-empty array.");
3342
3591
  }
3343
- var newSession = {
3344
- accessToken: undefined,
3345
- accessTokenRefreshHandle: undefined,
3346
- params: params,
3347
- isActive: true,
3348
- isReady: false,
3349
- authServiceWorker: params.serviceWorkerScript !== undefined && canUseServiceWorkers ? {
3350
- serviceWorkerScript: params.serviceWorkerScript,
3351
- type: "Uninitialized"
3352
- } : undefined,
3353
- primaryAuthSwConfig: undefined,
3354
- serviceWorkerConfig: undefined,
3355
- serviceWorkerConfigRefreshHandle: undefined
3356
- };
3357
- AuthSessionState.setSession(newSession);
3358
- return newSession;
3592
+ var isV2 = _this2.isV2Params(params);
3593
+ return AuthManagerBrowser_await(isV2 ? _this2.getV2Configs(params) : [_this2.normalizeV1Config(params)], function (configs) {
3594
+ var canUseServiceWorkers = _this2.serviceWorkerUtils.canUseServiceWorkers();
3595
+ var requiresServiceWorker = configs.some(function (config) {
3596
+ return config !== null && AuthManagerBrowser_typeof(config) === "object" && _this2.isServiceWorkerEnabled(config);
3597
+ }) || isV2 && ((_b = (_a = params.urlRewriteRules) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0) > 0;
3598
+ _this2.validateSessionConfig(params, configs, canUseServiceWorkers, requiresServiceWorker);
3599
+ var newSession = {
3600
+ accessToken: undefined,
3601
+ accessTokenRefreshHandle: undefined,
3602
+ authConfigs: configs.map(function (config) {
3603
+ return {
3604
+ accessToken: undefined,
3605
+ config: config,
3606
+ expiresAt: undefined,
3607
+ jwt: undefined,
3608
+ refreshHandle: undefined
3609
+ };
3610
+ }),
3611
+ authServiceWorker: requiresServiceWorker && params.serviceWorkerScript !== undefined && canUseServiceWorkers ? {
3612
+ serviceWorkerScript: params.serviceWorkerScript,
3613
+ type: "Uninitialized"
3614
+ } : undefined,
3615
+ isActive: true,
3616
+ isReady: false,
3617
+ params: params,
3618
+ serviceWorkerConfigured: false
3619
+ };
3620
+ AuthSessionState.setSession(newSession);
3621
+ return newSession;
3622
+ }, !isV2);
3359
3623
  })), function (session) {
3360
- // IMPORTANT: must be called outside the above, else re-entrant deadlock will occur.
3361
- return AuthManagerBrowser_invoke(function () {
3362
- if (session.params.serviceWorkerConfig !== undefined) {
3363
- return AuthManagerBrowser_awaitIgnored(_this.refreshServiceWorkerConfig(session, session.params));
3364
- }
3365
- }, function () {
3366
- return AuthManagerBrowser_awaitIgnored(_this.refreshAccessToken(session, session.params));
3624
+ return AuthManagerBrowser_catch(function () {
3625
+ return AuthManagerBrowser_continueIgnored(AuthManagerBrowser_forOf((_a = session.authConfigs) !== null && _a !== void 0 ? _a : [], function (config) {
3626
+ return AuthManagerBrowser_awaitIgnored(_this2.refreshAuthConfig(session, config, _this2.isV2Params(session.params)));
3627
+ }));
3628
+ }, function (e) {
3629
+ return AuthManagerBrowser_continue(AuthManagerBrowser_catch(function () {
3630
+ return AuthManagerBrowser_awaitIgnored(_this2.endAuthSession());
3631
+ }, AuthManagerBrowser_empty), function () {
3632
+ throw e;
3633
+ });
3367
3634
  });
3368
3635
  });
3369
3636
  } catch (e) {
@@ -3374,31 +3641,68 @@ var AuthManagerImpl = /*#__PURE__*/function () {
3374
3641
  key: "endAuthSession",
3375
3642
  value: function endAuthSession() {
3376
3643
  try {
3377
- var _this2 = this;
3378
- return AuthManagerBrowser_await(AuthManagerBrowser_awaitIgnored(_this2.authSessionMutex.safe(AuthManagerBrowser_async(function () {
3644
+ var _this3 = this;
3645
+ return AuthManagerBrowser_await(AuthManagerBrowser_awaitIgnored(_this3.authSessionMutex.safe(AuthManagerBrowser_async(function () {
3646
+ var _a, _b, _c;
3379
3647
  var session = AuthSessionState.getSession();
3380
3648
  if (session === undefined) {
3381
3649
  return;
3382
3650
  }
3383
3651
  AuthSessionState.setSession(undefined);
3384
3652
  session.isActive = false;
3385
- if (session.accessTokenRefreshHandle !== undefined) {
3386
- _this2.scheduler.unschedule(session.accessTokenRefreshHandle);
3387
- }
3388
- if (session.serviceWorkerConfigRefreshHandle !== undefined) {
3389
- _this2.scheduler.unschedule(session.serviceWorkerConfigRefreshHandle);
3653
+ if (session.authConfigs === undefined) {
3654
+ if (session.accessTokenRefreshHandle !== undefined) {
3655
+ _this3.scheduler.unschedule(session.accessTokenRefreshHandle);
3656
+ }
3657
+ } else {
3658
+ var _iterator = _createForOfIteratorHelper(session.authConfigs),
3659
+ _step;
3660
+ try {
3661
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
3662
+ var state = _step.value;
3663
+ if (state.refreshHandle !== undefined) {
3664
+ _this3.scheduler.unschedule(state.refreshHandle);
3665
+ }
3666
+ }
3667
+ } catch (err) {
3668
+ _iterator.e(err);
3669
+ } finally {
3670
+ _iterator.f();
3671
+ }
3390
3672
  }
3391
- // AuthSessionState is shared between bundled SDK versions. Service-worker-only sessions from 3.56.0 did not
3392
- // contain an accountId, so allow a newer SDK instance to tear those sessions down without calling this endpoint.
3673
+ var cleanupError;
3674
+ var cookieConfigs = _this3.isV2Params(session.params) ? (_b = (_a = session.authConfigs) === null || _a === void 0 ? void 0 : _a.filter(function (state) {
3675
+ return state.config.enableCookieAuth === true;
3676
+ })) !== null && _b !== void 0 ? _b : [] : (_c = session.authConfigs) !== null && _c !== void 0 ? _c : [];
3677
+ // A 3.54.0 session will not contain authConfigs, but a newer bundle must still be able to end it.
3393
3678
  return AuthManagerBrowser_invoke(function () {
3394
- if (typeof session.params.accountId === "string") {
3395
- return AuthManagerBrowser_awaitIgnored(_this2.deleteAccessToken(session.params));
3679
+ if (session.authConfigs === undefined && typeof session.params.accountId === "string") {
3680
+ return AuthManagerBrowser_continueIgnored(AuthManagerBrowser_catch(function () {
3681
+ return AuthManagerBrowser_awaitIgnored(_this3.deleteAccessToken(session.params.options, session.params.accountId));
3682
+ }, function (e) {
3683
+ cleanupError = e;
3684
+ }));
3685
+ } else {
3686
+ return AuthManagerBrowser_continueIgnored(AuthManagerBrowser_forOf(cookieConfigs, function (state) {
3687
+ return AuthManagerBrowser_continueIgnored(AuthManagerBrowser_catch(function () {
3688
+ return AuthManagerBrowser_awaitIgnored(_this3.deleteAccessToken(session.params.options, state.config.accountId));
3689
+ }, function (e) {
3690
+ cleanupError !== null && cleanupError !== void 0 ? cleanupError : cleanupError = e;
3691
+ }));
3692
+ }));
3396
3693
  }
3397
3694
  }, function () {
3398
- return AuthManagerBrowser_invokeIgnored(function () {
3695
+ return AuthManagerBrowser_invoke(function () {
3399
3696
  if (session.authServiceWorker !== undefined) {
3400
- // Prevent service worker from authorizing subsequent requests.
3401
- return AuthManagerBrowser_awaitIgnored(_this2.sendServiceWorkerConfig(session, []));
3697
+ return AuthManagerBrowser_continueIgnored(AuthManagerBrowser_catch(function () {
3698
+ return AuthManagerBrowser_awaitIgnored(_this3.sendServiceWorkerConfig(session, []));
3699
+ }, function (e) {
3700
+ cleanupError !== null && cleanupError !== void 0 ? cleanupError : cleanupError = e;
3701
+ }));
3702
+ }
3703
+ }, function () {
3704
+ if (cleanupError !== undefined) {
3705
+ throw cleanupError instanceof Error ? cleanupError : new Error(String(cleanupError));
3402
3706
  }
3403
3707
  });
3404
3708
  });
@@ -3408,139 +3712,71 @@ var AuthManagerImpl = /*#__PURE__*/function () {
3408
3712
  }
3409
3713
  }
3410
3714
  }, {
3411
- key: "refreshAccessToken",
3412
- value: function refreshAccessToken(session, params) {
3715
+ key: "refreshAuthConfig",
3716
+ value: function refreshAuthConfig(session, state) {
3717
+ var rejectInvalidInitialToken = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
3413
3718
  try {
3414
- var _this3 = this;
3415
- return AuthManagerBrowser_await(AuthManagerBrowser_awaitIgnored(_this3.authSessionMutex.safe(AuthManagerBrowser_async(function () {
3719
+ var _this4 = this;
3720
+ return AuthManagerBrowser_await(AuthManagerBrowser_awaitIgnored(_this4.authSessionMutex.safe(AuthManagerBrowser_async(function () {
3721
+ var _a;
3416
3722
  if (!session.isActive) {
3417
3723
  return;
3418
3724
  }
3419
- var secondsFromNow = function secondsFromNow(seconds) {
3420
- return Date.now() + seconds * 1000;
3725
+ if (state.refreshHandle !== undefined) {
3726
+ _this4.scheduler.unschedule(state.refreshHandle);
3727
+ }
3728
+ var previous = {
3729
+ accessToken: state.accessToken,
3730
+ expiresAt: state.expiresAt,
3731
+ jwt: state.jwt,
3732
+ serviceWorkerConfigured: session.serviceWorkerConfigured
3421
3733
  };
3422
- var expires = secondsFromNow(_this3.retryAuthAfterErrorSeconds);
3423
- return AuthManagerBrowser_continueIgnored(AuthManagerBrowser_finallyRethrows(function () {
3734
+ var refreshAt = Date.now() + _this4.retryAuthAfterErrorSeconds * 1000;
3735
+ return AuthManagerBrowser_finallyRethrows(function () {
3424
3736
  return AuthManagerBrowser_catch(function () {
3425
- var _getAccessToken = _this3.getAccessToken;
3426
- return AuthManagerBrowser_await(params.authHeaders(), function (_params$authHeaders) {
3427
- return AuthManagerBrowser_await(_getAccessToken.call(_this3, params, _params$authHeaders), function (jwt) {
3428
- // We don't use cookie-based auth if the browser supports service worker-based auth, as using both will cause
3429
- // confusion for us in the future (i.e. we may question "do we need to use both together? was there a reason?").
3430
- // Also: if the user has omitted "allowedOrigins" from their JWT, then service worker-based auth is more secure
3431
- // than cookie-based auth, which is another reason to prevent these cookies from being set unless required.
3432
- var setCookie = session.authServiceWorker === undefined;
3433
- return AuthManagerBrowser_await(_this3.setAccessToken(params, jwt, setCookie), function (setTokenResult) {
3434
- return AuthManagerBrowser_invoke(function () {
3435
- if (session.authServiceWorker !== undefined) {
3436
- var primaryAuthSwConfig = {
3437
- headers: [{
3438
- key: "Authorization",
3439
- value: "Bearer ".concat(jwt)
3440
- }],
3441
- expires: secondsFromNow(setTokenResult.ttlSeconds),
3442
- urlPrefix: "".concat(_this3.getCdnUrl(params), "/").concat(params.accountId, "/")
3443
- };
3444
- // Fail closed until the initial serviceWorkerConfig callback succeeds: without its result, we do not know
3445
- // the source-page restrictions intended for the primary JWT.
3446
- return AuthManagerBrowser_invoke(function () {
3447
- if (params.serviceWorkerConfig === undefined || session.serviceWorkerConfig !== undefined) {
3448
- return AuthManagerBrowser_await(_this3.sendMergedServiceWorkerConfig(session, primaryAuthSwConfig, session.serviceWorkerConfig), function () {
3449
- return AuthManagerBrowser_awaitIgnored(_this3.waitForServiceWorker());
3450
- });
3451
- }
3452
- }, function () {
3453
- session.primaryAuthSwConfig = primaryAuthSwConfig;
3737
+ return AuthManagerBrowser_await(_this4.getAuthorizationToken(session.params, state.config), function (jwt) {
3738
+ var setCookie = _this4.shouldSetCookie(session, state.config);
3739
+ return AuthManagerBrowser_await(_this4.setAccessToken(session.params.options, state.config.accountId, jwt, setCookie), function (token) {
3740
+ var expiresAt = Date.now() + token.ttlSeconds * 1000;
3741
+ state.accessToken = token.accessToken;
3742
+ state.expiresAt = expiresAt;
3743
+ state.jwt = jwt;
3744
+ return AuthManagerBrowser_invoke(function () {
3745
+ if (session.authServiceWorker !== undefined && (_this4.isServiceWorkerEnabled(state.config) || session.serviceWorkerConfigured !== true)) {
3746
+ return AuthManagerBrowser_await(_this4.sendCurrentServiceWorkerConfig(session), function () {
3747
+ return AuthManagerBrowser_await(_this4.waitForServiceWorker(), function () {
3748
+ session.serviceWorkerConfigured = true;
3454
3749
  });
3455
- }
3456
- }, function () {
3457
- var desiredTtl = setTokenResult.ttlSeconds - _this3.refreshBeforeExpirySeconds;
3458
- var actualTtl = Math.max(desiredTtl, _this3.minJwtTtlSeconds);
3459
- if (desiredTtl !== actualTtl) {
3460
- ConsoleUtils.warn("JWT expiration is too short: waiting for ".concat(actualTtl, " seconds before refreshing."));
3461
- }
3462
- expires = secondsFromNow(actualTtl);
3463
- // Set this at the end, as it's also used to signal 'isAuthSessionReady', so must be set after configuring the Service Worker, etc.
3464
- session.accessToken = setTokenResult.accessToken;
3465
- _this3.updateSessionReadiness(session);
3466
- });
3750
+ });
3751
+ }
3752
+ }, function () {
3753
+ var desiredTtl = token.ttlSeconds - _this4.refreshBeforeExpirySeconds;
3754
+ var actualTtl = Math.max(desiredTtl, _this4.minJwtTtlSeconds);
3755
+ if (desiredTtl !== actualTtl) {
3756
+ ConsoleUtils.warn("JWT expiration is too short: waiting for ".concat(actualTtl, " seconds before refreshing."));
3757
+ }
3758
+ refreshAt = Date.now() + actualTtl * 1000;
3467
3759
  });
3468
3760
  });
3469
3761
  });
3470
3762
  }, function (e) {
3471
- // 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.
3472
- ConsoleUtils.warn("Unable to refresh JWT access token: ".concat(e));
3763
+ state.accessToken = previous.accessToken;
3764
+ state.expiresAt = previous.expiresAt;
3765
+ state.jwt = previous.jwt;
3766
+ session.serviceWorkerConfigured = previous.serviceWorkerConfigured;
3767
+ ConsoleUtils.warn("Unable to refresh JWT access token for auth config '".concat((_a = state.config.authConfigId) !== null && _a !== void 0 ? _a : "default", "': ").concat(e));
3768
+ if (rejectInvalidInitialToken && e instanceof InvalidAuthTokenError) {
3769
+ throw e;
3770
+ }
3473
3771
  });
3474
- }, function (_wasThrown, _result) {
3475
- // 'setTimeout' can be paused (e.g., during hibernation), risking JWT expiration before it triggers. We use a
3476
- // scheduler to check wall-clock time every second and execute the callback at the scheduled time (below).
3477
- session.accessTokenRefreshHandle = _this3.scheduler.schedule(expires, function () {
3478
- _this3.refreshAccessToken(session, params).then(function () {},
3479
- // Should not occur, as this method shouldn't throw errors.
3480
- function (e) {
3772
+ }, function (_wasThrown, _result2) {
3773
+ state.refreshHandle = _this4.scheduler.schedule(refreshAt, function () {
3774
+ _this4.refreshAuthConfig(session, state).then(function () {}, function (e) {
3481
3775
  return ConsoleUtils.error("Unexpected error when refreshing JWT access token: ".concat(e));
3482
3776
  });
3483
3777
  });
3484
- return AuthManagerBrowser_rethrow(_wasThrown, _result);
3485
- }));
3486
- }))));
3487
- } catch (e) {
3488
- return Promise.reject(e);
3489
- }
3490
- }
3491
- }, {
3492
- key: "refreshServiceWorkerConfig",
3493
- value: function refreshServiceWorkerConfig(session, params) {
3494
- try {
3495
- var _this4 = this;
3496
- var getServiceWorkerConfig = params.serviceWorkerConfig;
3497
- if (getServiceWorkerConfig === undefined) {
3498
- return AuthManagerBrowser_await();
3499
- }
3500
- return AuthManagerBrowser_await(AuthManagerBrowser_awaitIgnored(_this4.authSessionMutex.safe(AuthManagerBrowser_async(function () {
3501
- var _exit = false;
3502
- if (!session.isActive) {
3503
- return;
3504
- }
3505
- var refreshAt;
3506
- return AuthManagerBrowser_continue(AuthManagerBrowser_catch(function () {
3507
- return AuthManagerBrowser_call(getServiceWorkerConfig, function (result) {
3508
- if (result === null || AuthManagerBrowser_typeof(result) !== "object" || !Array.isArray(result.additionalConfig)) {
3509
- throw new Error("The 'serviceWorkerConfig' callback must return an object containing 'additionalConfig'.");
3510
- }
3511
- if (result.sourceUrlPrefixes !== undefined && (!Array.isArray(result.sourceUrlPrefixes) || !result.sourceUrlPrefixes.every(function (prefix) {
3512
- return typeof prefix === "string";
3513
- }))) {
3514
- throw new Error("The 'sourceUrlPrefixes' field returned by 'serviceWorkerConfig' must be an array of strings.");
3515
- }
3516
- var config = {
3517
- additionalConfig: result.additionalConfig,
3518
- sourceUrlPrefixes: result.sourceUrlPrefixes
3519
- };
3520
- return AuthManagerBrowser_invoke(function () {
3521
- if (session.primaryAuthSwConfig !== undefined) {
3522
- return AuthManagerBrowser_await(_this4.sendMergedServiceWorkerConfig(session, session.primaryAuthSwConfig, config), function () {
3523
- return AuthManagerBrowser_awaitIgnored(_this4.waitForServiceWorker());
3524
- });
3525
- }
3526
- }, function () {
3527
- session.serviceWorkerConfig = config;
3528
- _this4.updateSessionReadiness(session);
3529
- refreshAt = _this4.getServiceWorkerConfigRefreshEpoch(config.additionalConfig);
3530
- });
3531
- });
3532
- }, function (e) {
3533
- ConsoleUtils.warn("Unable to refresh service worker auth config: ".concat(e));
3534
- refreshAt = Date.now() + _this4.retryAuthAfterErrorSeconds * 1000;
3535
- }), function (_result2) {
3536
- if (_exit) return _result2;
3537
- if (refreshAt !== undefined) {
3538
- session.serviceWorkerConfigRefreshHandle = _this4.scheduler.schedule(refreshAt, function () {
3539
- _this4.refreshServiceWorkerConfig(session, params).then(function () {}, function (e) {
3540
- return ConsoleUtils.error("Unexpected error when refreshing service worker auth config: ".concat(e));
3541
- });
3542
- });
3543
- }
3778
+ _this4.updateSessionState(session);
3779
+ return AuthManagerBrowser_rethrow(_wasThrown, _result2);
3544
3780
  });
3545
3781
  }))));
3546
3782
  } catch (e) {
@@ -3548,54 +3784,49 @@ var AuthManagerImpl = /*#__PURE__*/function () {
3548
3784
  }
3549
3785
  }
3550
3786
  }, {
3551
- key: "sendMergedServiceWorkerConfig",
3552
- value: function sendMergedServiceWorkerConfig(session, primaryConfig, serviceWorkerConfig) {
3787
+ key: "sendCurrentServiceWorkerConfig",
3788
+ value: function sendCurrentServiceWorkerConfig(session) {
3553
3789
  try {
3554
3790
  var _this5 = this;
3555
3791
  var _a;
3556
- return AuthManagerBrowser_await(AuthManagerBrowser_awaitIgnored(_this5.sendServiceWorkerConfig(session, [Object.assign(Object.assign({}, primaryConfig), {
3557
- sourceUrlPrefixes: serviceWorkerConfig === null || serviceWorkerConfig === void 0 ? void 0 : serviceWorkerConfig.sourceUrlPrefixes
3558
- })].concat(AuthManagerBrowser_toConsumableArray((_a = serviceWorkerConfig === null || serviceWorkerConfig === void 0 ? void 0 : serviceWorkerConfig.additionalConfig) !== null && _a !== void 0 ? _a : [])))));
3792
+ var now = Date.now();
3793
+ var config = ((_a = session.authConfigs) !== null && _a !== void 0 ? _a : []).flatMap(function (state) {
3794
+ if (!_this5.isServiceWorkerEnabled(state.config) || state.jwt === undefined || state.expiresAt === undefined || state.expiresAt <= now) {
3795
+ return [];
3796
+ }
3797
+ return [{
3798
+ expires: state.expiresAt,
3799
+ headers: [{
3800
+ key: "Authorization",
3801
+ value: "Bearer ".concat(state.jwt)
3802
+ }],
3803
+ sourceUrlPrefixes: state.config.sourceUrlPrefixes,
3804
+ urlPrefix: "".concat(_this5.getCdnUrl(session.params), "/").concat(state.config.accountId, "/")
3805
+ }];
3806
+ });
3807
+ return AuthManagerBrowser_await(AuthManagerBrowser_awaitIgnored(_this5.sendServiceWorkerConfig(session, config, _this5.isV2Params(session.params) ? session.params.urlRewriteRules : undefined)));
3559
3808
  } catch (e) {
3560
3809
  return Promise.reject(e);
3561
3810
  }
3562
3811
  }
3563
- }, {
3564
- key: "getServiceWorkerConfigRefreshEpoch",
3565
- value: function getServiceWorkerConfigRefreshEpoch(config) {
3566
- var earliestExpiry;
3567
- var _iterator = _createForOfIteratorHelper(config),
3568
- _step;
3569
- try {
3570
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
3571
- var entry = _step.value;
3572
- if (entry.expires !== undefined && (earliestExpiry === undefined || entry.expires < earliestExpiry)) {
3573
- earliestExpiry = entry.expires;
3574
- }
3575
- }
3576
- } catch (err) {
3577
- _iterator.e(err);
3578
- } finally {
3579
- _iterator.f();
3580
- }
3581
- return earliestExpiry === undefined ? undefined : earliestExpiry - this.refreshBeforeExpirySeconds * 1000;
3582
- }
3583
3812
  }, {
3584
3813
  key: "sendServiceWorkerConfig",
3585
- value: function sendServiceWorkerConfig(session, config) {
3814
+ value: function sendServiceWorkerConfig(session, config, urlRewriteRules) {
3586
3815
  try {
3587
3816
  var _this6 = this;
3588
3817
  if (session.authServiceWorker === undefined) {
3589
3818
  throw new Error("Service worker configuration cannot be applied because service workers are unavailable.");
3590
3819
  }
3591
- return AuthManagerBrowser_await(_this6.serviceWorkerUtils.sendMessage({
3820
+ return AuthManagerBrowser_await(_this6.serviceWorkerUtils.sendMessage(Object.assign({
3592
3821
  type: "SET_BYTESCALE_AUTH_CONFIG",
3593
3822
  config: config.map(function (entry) {
3594
3823
  return Object.assign(Object.assign({}, entry), {
3595
3824
  urlPrefix: "".concat(entry.sourceUrlPrefixes === undefined ? "" : _this6.sourceScopedUrlPrefixMarker).concat(entry.urlPrefix)
3596
3825
  });
3597
3826
  })
3598
- }, session.authServiceWorker, _this6.serviceWorkerScriptFieldName), function (_this6$serviceWorkerU) {
3827
+ }, urlRewriteRules === undefined ? {} : {
3828
+ urlRewriteRules: urlRewriteRules
3829
+ }), session.authServiceWorker, _this6.serviceWorkerScriptFieldName), function (_this6$serviceWorkerU) {
3599
3830
  session.authServiceWorker = _this6$serviceWorkerU;
3600
3831
  });
3601
3832
  } catch (e) {
@@ -3603,16 +3834,169 @@ var AuthManagerImpl = /*#__PURE__*/function () {
3603
3834
  }
3604
3835
  }
3605
3836
  }, {
3606
- key: "updateSessionReadiness",
3607
- value: function updateSessionReadiness(session) {
3608
- session.isReady = session.accessToken !== undefined && (session.params.serviceWorkerConfig === undefined || session.serviceWorkerConfig !== undefined);
3837
+ key: "getV2Configs",
3838
+ value: function getV2Configs(params) {
3839
+ try {
3840
+ return AuthManagerBrowser_await(params.authConfigs(), function (configs) {
3841
+ if (!Array.isArray(configs) || configs.length === 0) {
3842
+ throw new Error("The 'authConfigs' callback must return a non-empty array.");
3843
+ }
3844
+ return configs.map(function (config) {
3845
+ return config === null || AuthManagerBrowser_typeof(config) !== "object" ? config : Object.assign(Object.assign({}, config), {
3846
+ sourceUrlPrefixes: Array.isArray(config.sourceUrlPrefixes) ? AuthManagerBrowser_toConsumableArray(config.sourceUrlPrefixes) : config.sourceUrlPrefixes
3847
+ });
3848
+ });
3849
+ });
3850
+ } catch (e) {
3851
+ return Promise.reject(e);
3852
+ }
3853
+ }
3854
+ }, {
3855
+ key: "normalizeV1Config",
3856
+ value: function normalizeV1Config(params) {
3857
+ return {
3858
+ accountId: params.accountId,
3859
+ authConfigId: undefined,
3860
+ authHeaders: params.authHeaders,
3861
+ authUrl: params.authUrl,
3862
+ enableCookieAuth: params.serviceWorkerScript === undefined,
3863
+ enableServiceWorkerAuth: params.serviceWorkerScript !== undefined
3864
+ };
3865
+ }
3866
+ }, {
3867
+ key: "validateSessionConfig",
3868
+ value: function validateSessionConfig(params, configs, canUseServiceWorkers, requiresServiceWorker) {
3869
+ var isV2 = this.isV2Params(params);
3870
+ if (isV2 && (params.accountId !== undefined || params.authHeaders !== undefined || params.authUrl !== undefined)) {
3871
+ throw new Error("V2 auth sessions must use 'authConfigs' instead of top-level auth fields.");
3872
+ }
3873
+ var ids = new Set();
3874
+ var cookieConfig;
3875
+ var workerConfigsByPrefix = new Map();
3876
+ var _iterator2 = _createForOfIteratorHelper(configs),
3877
+ _step2;
3878
+ try {
3879
+ for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
3880
+ var config = _step2.value;
3881
+ if (config === null || AuthManagerBrowser_typeof(config) !== "object") {
3882
+ throw new Error("Each auth configuration must be an object.");
3883
+ }
3884
+ if (!Object.prototype.hasOwnProperty.call(config, "authConfigId")) {
3885
+ throw new Error("Each auth configuration must explicitly provide 'authConfigId'.");
3886
+ }
3887
+ if (config.authConfigId !== undefined && typeof config.authConfigId !== "string") {
3888
+ throw new Error("The 'authConfigId' field must be a string or undefined.");
3889
+ }
3890
+ if (ids.has(config.authConfigId)) {
3891
+ throw new Error(config.authConfigId === undefined ? "Only one default auth configuration is allowed." : "Duplicate auth configuration ID: '".concat(config.authConfigId, "'."));
3892
+ }
3893
+ ids.add(config.authConfigId);
3894
+ if (isV2 && !this.isValidAccountId(config.accountId)) {
3895
+ throw new Error("Invalid Bytescale account ID: '".concat(String(config.accountId), "'."));
3896
+ }
3897
+ if (config.enableCookieAuth !== undefined && typeof config.enableCookieAuth !== "boolean" || config.enableServiceWorkerAuth !== undefined && typeof config.enableServiceWorkerAuth !== "boolean") {
3898
+ throw new Error("Authentication enablement flags must be booleans when provided.");
3899
+ }
3900
+ if (config.sourceUrlPrefixes !== undefined && (!Array.isArray(config.sourceUrlPrefixes) || !config.sourceUrlPrefixes.every(function (prefix) {
3901
+ return typeof prefix === "string";
3902
+ }))) {
3903
+ throw new Error("The 'sourceUrlPrefixes' field must be an array of strings.");
3904
+ }
3905
+ var isManual = typeof config.getAuthorizationToken === "function";
3906
+ var isAutomatic = typeof config.authUrl === "string" && typeof config.authHeaders === "function";
3907
+ if (isManual === isAutomatic || isManual && (config.authUrl !== undefined || config.authHeaders !== undefined)) {
3908
+ throw new Error("Each auth configuration must provide either 'getAuthorizationToken' or both 'authUrl' and 'authHeaders'.");
3909
+ }
3910
+ if (config.enableCookieAuth === true) {
3911
+ if (cookieConfig !== undefined) {
3912
+ throw new Error("Only one auth configuration may enable cookie authentication.");
3913
+ }
3914
+ cookieConfig = config;
3915
+ }
3916
+ if (this.isServiceWorkerEnabled(config)) {
3917
+ var _prefix = "".concat(this.getCdnUrl(params), "/").concat(config.accountId, "/");
3918
+ if (workerConfigsByPrefix.has(_prefix)) {
3919
+ throw new Error("Multiple service-worker auth configurations target the same URL prefix: '".concat(_prefix, "'."));
3920
+ }
3921
+ workerConfigsByPrefix.set(_prefix, config);
3922
+ }
3923
+ }
3924
+ } catch (err) {
3925
+ _iterator2.e(err);
3926
+ } finally {
3927
+ _iterator2.f();
3928
+ }
3929
+ if (cookieConfig !== undefined) {
3930
+ var prefix = "".concat(this.getCdnUrl(params), "/").concat(cookieConfig.accountId, "/");
3931
+ var workerConfig = workerConfigsByPrefix.get(prefix);
3932
+ if (workerConfig !== undefined && workerConfig !== cookieConfig) {
3933
+ throw new Error("Cookie and service-worker authentication cannot target the same account from different configs.");
3934
+ }
3935
+ }
3936
+ if (isV2) {
3937
+ this.validateUrlRewriteRules(params.urlRewriteRules);
3938
+ if (requiresServiceWorker && params.serviceWorkerScript === undefined) {
3939
+ throw new Error("The 'serviceWorkerScript' field is required when service-worker authentication or URL rewriting is enabled.");
3940
+ }
3941
+ if (requiresServiceWorker && !canUseServiceWorkers) {
3942
+ throw new Error("This auth session requires service workers, but this browser does not support them.");
3943
+ }
3944
+ }
3945
+ }
3946
+ }, {
3947
+ key: "validateUrlRewriteRules",
3948
+ value: function validateUrlRewriteRules(rules) {
3949
+ if (rules !== undefined && (!Array.isArray(rules) || !rules.every(function (rule) {
3950
+ return rule !== null && AuthManagerBrowser_typeof(rule) === "object" && typeof rule.fromUrlPrefix === "string" && typeof rule.toUrlPrefix === "string";
3951
+ }))) {
3952
+ throw new Error("The 'urlRewriteRules' field must be an array of URL rewrite rules.");
3953
+ }
3954
+ }
3955
+ }, {
3956
+ key: "updateSessionState",
3957
+ value: function updateSessionState(session) {
3958
+ var _this7 = this;
3959
+ var _a;
3960
+ var configs = (_a = session.authConfigs) !== null && _a !== void 0 ? _a : [];
3961
+ var defaultConfig = configs.find(function (state) {
3962
+ return state.config.authConfigId === undefined;
3963
+ });
3964
+ var exposeLegacyDefault = !this.isV2Params(session.params);
3965
+ session.accessToken = exposeLegacyDefault && defaultConfig !== undefined && this.isConfigUsable(defaultConfig) ? defaultConfig.accessToken : undefined;
3966
+ session.accessTokenRefreshHandle = exposeLegacyDefault ? defaultConfig === null || defaultConfig === void 0 ? void 0 : defaultConfig.refreshHandle : undefined;
3967
+ session.isReady = configs.length > 0 && configs.every(function (state) {
3968
+ return _this7.isConfigUsable(state);
3969
+ }) && (session.authServiceWorker === undefined || session.serviceWorkerConfigured === true);
3970
+ }
3971
+ }, {
3972
+ key: "isConfigUsable",
3973
+ value: function isConfigUsable(state) {
3974
+ return (state === null || state === void 0 ? void 0 : state.accessToken) !== undefined && state.expiresAt !== undefined && state.expiresAt > Date.now();
3975
+ }
3976
+ }, {
3977
+ key: "isServiceWorkerEnabled",
3978
+ value: function isServiceWorkerEnabled(config) {
3979
+ return config.enableServiceWorkerAuth !== false;
3980
+ }
3981
+ }, {
3982
+ key: "isV2Params",
3983
+ value: function isV2Params(params) {
3984
+ return typeof params.authConfigs === "function";
3985
+ }
3986
+ }, {
3987
+ key: "isValidAccountId",
3988
+ value: function isValidAccountId(accountId) {
3989
+ return typeof accountId === "string" && /^[1-9A-HJ-NP-Za-km-z]{7}$/.test(accountId);
3990
+ }
3991
+ }, {
3992
+ key: "shouldSetCookie",
3993
+ value: function shouldSetCookie(session, config) {
3994
+ return this.isV2Params(session.params) ? config.enableCookieAuth === true : session.authServiceWorker === undefined;
3609
3995
  }
3610
3996
  }, {
3611
3997
  key: "waitForServiceWorker",
3612
3998
  value: function waitForServiceWorker() {
3613
3999
  try {
3614
- // Message delivery is asynchronous and has no acknowledgement, so allow the worker time to apply the config before
3615
- // beginAuthSession reports that authenticated requests are ready.
3616
4000
  return AuthManagerBrowser_await(AuthManagerBrowser_awaitIgnored(new Promise(function (resolve) {
3617
4001
  return setTimeout(resolve, 100);
3618
4002
  })));
@@ -3622,8 +4006,8 @@ var AuthManagerImpl = /*#__PURE__*/function () {
3622
4006
  }
3623
4007
  }, {
3624
4008
  key: "getAccessTokenUrl",
3625
- value: function getAccessTokenUrl(params, setCookie) {
3626
- return "".concat(this.getCdnUrl(params), "/api/v1/access_tokens/").concat(params.accountId, "?set-cookie=").concat(setCookie ? "true" : "false");
4009
+ value: function getAccessTokenUrl(options, accountId, setCookie) {
4010
+ return "".concat(BytescaleApiClientConfigUtils.getCdnUrl(options !== null && options !== void 0 ? options : {}), "/api/v1/access_tokens/").concat(accountId, "?set-cookie=").concat(setCookie ? "true" : "false");
3627
4011
  }
3628
4012
  }, {
3629
4013
  key: "getCdnUrl",
@@ -3633,17 +4017,16 @@ var AuthManagerImpl = /*#__PURE__*/function () {
3633
4017
  }
3634
4018
  }, {
3635
4019
  key: "deleteAccessToken",
3636
- value: function deleteAccessToken(params) {
4020
+ value: function deleteAccessToken(options, accountId) {
3637
4021
  try {
3638
- var _this7 = this;
3639
- var _a;
3640
- return AuthManagerBrowser_await(AuthManagerBrowser_awaitIgnored(BaseAPI.fetch(_this7.getAccessTokenUrl(params, true), {
4022
+ var _this8 = this;
4023
+ return AuthManagerBrowser_await(AuthManagerBrowser_awaitIgnored(BaseAPI.fetch(_this8.getAccessTokenUrl(options, accountId, true), {
3641
4024
  method: "DELETE",
3642
4025
  credentials: "include",
3643
4026
  headers: {}
3644
4027
  }, {
3645
4028
  isBytescaleApi: true,
3646
- fetchApi: (_a = params.options) === null || _a === void 0 ? void 0 : _a.fetchApi
4029
+ fetchApi: options === null || options === void 0 ? void 0 : options.fetchApi
3647
4030
  })));
3648
4031
  } catch (e) {
3649
4032
  return Promise.reject(e);
@@ -3651,68 +4034,96 @@ var AuthManagerImpl = /*#__PURE__*/function () {
3651
4034
  }
3652
4035
  }, {
3653
4036
  key: "setAccessToken",
3654
- value: function setAccessToken(params, jwt, setCookie) {
4037
+ value: function setAccessToken(options, accountId, jwt, setCookie) {
3655
4038
  try {
3656
- var _this8 = this;
3657
- var _a;
4039
+ var _this9 = this;
3658
4040
  var request = {
3659
4041
  accessToken: jwt
3660
4042
  };
3661
- return AuthManagerBrowser_await(BaseAPI.fetch(_this8.getAccessTokenUrl(params, setCookie), {
4043
+ return AuthManagerBrowser_await(BaseAPI.fetch(_this9.getAccessTokenUrl(options, accountId, setCookie), {
3662
4044
  method: "PUT",
3663
4045
  credentials: "include",
3664
- headers: AuthManagerBrowser_defineProperty({}, _this8.contentType, _this8.contentTypeJson),
4046
+ headers: AuthManagerBrowser_defineProperty({}, _this9.contentType, _this9.contentTypeJson),
3665
4047
  body: JSON.stringify(request)
3666
4048
  }, {
3667
4049
  isBytescaleApi: true,
3668
- fetchApi: (_a = params.options) === null || _a === void 0 ? void 0 : _a.fetchApi
4050
+ fetchApi: options === null || options === void 0 ? void 0 : options.fetchApi
3669
4051
  }), function (response) {
3670
- return AuthManagerBrowser_await(response.json());
4052
+ return AuthManagerBrowser_await(response.json(), function (result) {
4053
+ if (typeof result.accessToken !== "string" || result.accessToken.length === 0 || typeof result.ttlSeconds !== "number" || !Number.isFinite(result.ttlSeconds) || result.ttlSeconds <= 0) {
4054
+ throw new Error("Bytescale returned an invalid access-token registration response.");
4055
+ }
4056
+ return result;
4057
+ });
3671
4058
  });
3672
4059
  } catch (e) {
3673
4060
  return Promise.reject(e);
3674
4061
  }
3675
4062
  }
3676
4063
  }, {
3677
- key: "getAccessToken",
3678
- value: function getAccessToken(params, headers) {
4064
+ key: "getAuthorizationToken",
4065
+ value: function getAuthorizationToken(params, config) {
3679
4066
  try {
3680
- var _this9 = this;
4067
+ var _exit = false;
4068
+ var _this0 = this;
3681
4069
  var _a, _b;
3682
- var endpointName = "Your auth API endpoint";
3683
- var requiredContentType = _this9.contentTypeText;
3684
- return AuthManagerBrowser_await(BaseAPI.fetch(params.authUrl, {
3685
- method: "GET",
3686
- headers: headers
3687
- }, {
3688
- isBytescaleApi: false,
3689
- fetchApi: (_a = params.options) === null || _a === void 0 ? void 0 : _a.fetchApi
3690
- }), function (result) {
3691
- var actualContentType = (_b = result.headers.get(_this9.contentType)) !== null && _b !== void 0 ? _b : "";
3692
- // Support content types like "text/plain; charset=utf-8" and "text/plain"
3693
- if (actualContentType.split(";")[0] !== requiredContentType) {
3694
- throw new Error("".concat(endpointName, " returned \"").concat(actualContentType, "\" for the ").concat(_this9.contentType, " response header, but the Bytescale SDK requires \"").concat(requiredContentType, "\"."));
4070
+ return AuthManagerBrowser_await(AuthManagerBrowser_invoke(function () {
4071
+ if (typeof config.getAuthorizationToken === "function") {
4072
+ var _validateJwt = _this0.validateJwt;
4073
+ return AuthManagerBrowser_await(config.getAuthorizationToken(), function (_config$getAuthorizat) {
4074
+ var _this0$validateJwt = _validateJwt.call(_this0, _config$getAuthorizat, "The 'getAuthorizationToken' callback");
4075
+ _exit = true;
4076
+ return _this0$validateJwt;
4077
+ });
3695
4078
  }
3696
- return AuthManagerBrowser_await(result.text(), function (jwt) {
3697
- if (jwt.length === 0) {
3698
- throw new Error("".concat(endpointName, " returned an empty string. Please return a valid JWT instead."));
3699
- }
3700
- if (jwt.trim().length !== jwt.length) {
3701
- // Whitespace can be a nightmare to spot/debug, so we fail early here.
3702
- throw new Error("".concat(endpointName, " returned whitespace around the JWT, please remove it."));
3703
- }
3704
- return jwt;
4079
+ }, function (_result3) {
4080
+ if (_exit) return _result3;
4081
+ var endpointName = "Your auth API endpoint";
4082
+ var _fetch = BaseAPI.fetch,
4083
+ _config$authUrl = config.authUrl;
4084
+ return AuthManagerBrowser_await(config.authHeaders(), function (_config$authHeaders) {
4085
+ return AuthManagerBrowser_await(_fetch.call(BaseAPI, _config$authUrl, {
4086
+ method: "GET",
4087
+ headers: _config$authHeaders
4088
+ }, {
4089
+ isBytescaleApi: false,
4090
+ fetchApi: (_a = params.options) === null || _a === void 0 ? void 0 : _a.fetchApi
4091
+ }), function (result) {
4092
+ var actualContentType = (_b = result.headers.get(_this0.contentType)) !== null && _b !== void 0 ? _b : "";
4093
+ if (actualContentType.split(";")[0] !== _this0.contentTypeText) {
4094
+ throw new Error("".concat(endpointName, " returned \"").concat(actualContentType, "\" for the ").concat(_this0.contentType, " response header, but the Bytescale SDK requires \"").concat(_this0.contentTypeText, "\"."));
4095
+ }
4096
+ var _validateJwt2 = _this0.validateJwt;
4097
+ return AuthManagerBrowser_await(result.text(), function (_result$text) {
4098
+ return _validateJwt2.call(_this0, _result$text, endpointName);
4099
+ });
4100
+ });
3705
4101
  });
3706
- });
4102
+ }));
3707
4103
  } catch (e) {
3708
4104
  return Promise.reject(e);
3709
4105
  }
3710
4106
  }
4107
+ }, {
4108
+ key: "validateJwt",
4109
+ value: function validateJwt(jwt, source) {
4110
+ if (typeof jwt !== "string" || jwt.length === 0) {
4111
+ throw new InvalidAuthTokenError("".concat(source, " returned an empty or malformed token. Please return a valid JWT instead."));
4112
+ }
4113
+ if (jwt.trim().length !== jwt.length) {
4114
+ throw new InvalidAuthTokenError("".concat(source, " returned whitespace around the JWT, please remove it."));
4115
+ }
4116
+ var parts = jwt.split(".");
4117
+ if (parts.length !== 3 || parts.some(function (part) {
4118
+ return part.length === 0 || !/^[A-Za-z0-9_-]+$/.test(part);
4119
+ })) {
4120
+ throw new InvalidAuthTokenError("".concat(source, " returned a malformed JWT."));
4121
+ }
4122
+ return jwt;
4123
+ }
3711
4124
  }]);
3712
4125
  }();
3713
- /**
3714
- * 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).
3715
- */
4126
+ /** Alternative to a static class that allows the implementation to satisfy an interface. */
3716
4127
  var AuthManager = new AuthManagerImpl(new ServiceWorkerUtils());
3717
4128
  ;// ./src/public/browser/index.ts
3718
4129