@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
@@ -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.");
378
461
  }
379
- if (config.apiKey.trim() !== config.apiKey) {
462
+ if (config.apiKey !== undefined && typeof config.apiKey !== "string") {
463
+ throw new Error("The 'apiKey' config parameter must be a string when provided.");
464
+ }
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, 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, 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,139 +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, 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
- var config = {
3477
- additionalConfig: result.additionalConfig,
3478
- sourceUrlPrefixes: result.sourceUrlPrefixes
3479
- };
3480
- return AuthManagerBrowser_invoke(function () {
3481
- if (session.primaryAuthSwConfig !== undefined) {
3482
- return AuthManagerBrowser_await(_this4.sendMergedServiceWorkerConfig(session, session.primaryAuthSwConfig, config), function () {
3483
- return AuthManagerBrowser_awaitIgnored(_this4.waitForServiceWorker());
3484
- });
3485
- }
3486
- }, function () {
3487
- session.serviceWorkerConfig = config;
3488
- _this4.updateSessionReadiness(session);
3489
- refreshAt = _this4.getServiceWorkerConfigRefreshEpoch(config.additionalConfig);
3490
- });
3491
- });
3492
- }, function (e) {
3493
- ConsoleUtils.warn("Unable to refresh service worker auth config: ".concat(e));
3494
- refreshAt = Date.now() + _this4.retryAuthAfterErrorSeconds * 1000;
3495
- }), function (_result2) {
3496
- if (_exit) return _result2;
3497
- if (refreshAt !== undefined) {
3498
- session.serviceWorkerConfigRefreshHandle = _this4.scheduler.schedule(refreshAt, function () {
3499
- _this4.refreshServiceWorkerConfig(session, params).then(function () {}, function (e) {
3500
- return ConsoleUtils.error("Unexpected error when refreshing service worker auth config: ".concat(e));
3501
- });
3502
- });
3503
- }
3738
+ _this4.updateSessionState(session);
3739
+ return AuthManagerBrowser_rethrow(_wasThrown, _result2);
3504
3740
  });
3505
3741
  }))));
3506
3742
  } catch (e) {
@@ -3508,54 +3744,49 @@ var AuthManagerImpl = /*#__PURE__*/function () {
3508
3744
  }
3509
3745
  }
3510
3746
  }, {
3511
- key: "sendMergedServiceWorkerConfig",
3512
- value: function sendMergedServiceWorkerConfig(session, primaryConfig, serviceWorkerConfig) {
3747
+ key: "sendCurrentServiceWorkerConfig",
3748
+ value: function sendCurrentServiceWorkerConfig(session) {
3513
3749
  try {
3514
3750
  var _this5 = this;
3515
3751
  var _a;
3516
- return AuthManagerBrowser_await(AuthManagerBrowser_awaitIgnored(_this5.sendServiceWorkerConfig(session, [Object.assign(Object.assign({}, primaryConfig), {
3517
- sourceUrlPrefixes: serviceWorkerConfig === null || serviceWorkerConfig === void 0 ? void 0 : serviceWorkerConfig.sourceUrlPrefixes
3518
- })].concat(AuthManagerBrowser_toConsumableArray((_a = serviceWorkerConfig === null || serviceWorkerConfig === void 0 ? void 0 : serviceWorkerConfig.additionalConfig) !== null && _a !== void 0 ? _a : [])))));
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.getCdnUrl(session.params), "/").concat(state.config.accountId, "/")
3765
+ }];
3766
+ });
3767
+ return AuthManagerBrowser_await(AuthManagerBrowser_awaitIgnored(_this5.sendServiceWorkerConfig(session, config, _this5.isV2Params(session.params) ? session.params.urlRewriteRules : undefined)));
3519
3768
  } catch (e) {
3520
3769
  return Promise.reject(e);
3521
3770
  }
3522
3771
  }
3523
- }, {
3524
- key: "getServiceWorkerConfigRefreshEpoch",
3525
- value: function getServiceWorkerConfigRefreshEpoch(config) {
3526
- var earliestExpiry;
3527
- var _iterator = _createForOfIteratorHelper(config),
3528
- _step;
3529
- try {
3530
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
3531
- var entry = _step.value;
3532
- if (entry.expires !== undefined && (earliestExpiry === undefined || entry.expires < earliestExpiry)) {
3533
- earliestExpiry = entry.expires;
3534
- }
3535
- }
3536
- } catch (err) {
3537
- _iterator.e(err);
3538
- } finally {
3539
- _iterator.f();
3540
- }
3541
- return earliestExpiry === undefined ? undefined : earliestExpiry - this.refreshBeforeExpirySeconds * 1000;
3542
- }
3543
3772
  }, {
3544
3773
  key: "sendServiceWorkerConfig",
3545
- value: function sendServiceWorkerConfig(session, config) {
3774
+ value: function sendServiceWorkerConfig(session, config, urlRewriteRules) {
3546
3775
  try {
3547
3776
  var _this6 = this;
3548
3777
  if (session.authServiceWorker === undefined) {
3549
3778
  throw new Error("Service worker configuration cannot be applied because service workers are unavailable.");
3550
3779
  }
3551
- return AuthManagerBrowser_await(_this6.serviceWorkerUtils.sendMessage({
3780
+ return AuthManagerBrowser_await(_this6.serviceWorkerUtils.sendMessage(Object.assign({
3552
3781
  type: "SET_BYTESCALE_AUTH_CONFIG",
3553
3782
  config: config.map(function (entry) {
3554
3783
  return Object.assign(Object.assign({}, entry), {
3555
3784
  urlPrefix: "".concat(entry.sourceUrlPrefixes === undefined ? "" : _this6.sourceScopedUrlPrefixMarker).concat(entry.urlPrefix)
3556
3785
  });
3557
3786
  })
3558
- }, session.authServiceWorker, _this6.serviceWorkerScriptFieldName), function (_this6$serviceWorkerU) {
3787
+ }, urlRewriteRules === undefined ? {} : {
3788
+ urlRewriteRules: urlRewriteRules
3789
+ }), session.authServiceWorker, _this6.serviceWorkerScriptFieldName), function (_this6$serviceWorkerU) {
3559
3790
  session.authServiceWorker = _this6$serviceWorkerU;
3560
3791
  });
3561
3792
  } catch (e) {
@@ -3563,16 +3794,169 @@ var AuthManagerImpl = /*#__PURE__*/function () {
3563
3794
  }
3564
3795
  }
3565
3796
  }, {
3566
- key: "updateSessionReadiness",
3567
- value: function updateSessionReadiness(session) {
3568
- 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.enableCookieAuth !== undefined && typeof config.enableCookieAuth !== "boolean" || config.enableServiceWorkerAuth !== undefined && typeof config.enableServiceWorkerAuth !== "boolean") {
3858
+ throw new Error("Authentication enablement flags must be booleans when provided.");
3859
+ }
3860
+ if (config.sourceUrlPrefixes !== undefined && (!Array.isArray(config.sourceUrlPrefixes) || !config.sourceUrlPrefixes.every(function (prefix) {
3861
+ return typeof prefix === "string";
3862
+ }))) {
3863
+ throw new Error("The 'sourceUrlPrefixes' field must be an array of strings.");
3864
+ }
3865
+ var isManual = typeof config.getAuthorizationToken === "function";
3866
+ var isAutomatic = typeof config.authUrl === "string" && typeof config.authHeaders === "function";
3867
+ if (isManual === isAutomatic || isManual && (config.authUrl !== undefined || config.authHeaders !== undefined)) {
3868
+ throw new Error("Each auth configuration must provide either 'getAuthorizationToken' or both 'authUrl' and 'authHeaders'.");
3869
+ }
3870
+ if (config.enableCookieAuth === true) {
3871
+ if (cookieConfig !== undefined) {
3872
+ throw new Error("Only one auth configuration may enable cookie authentication.");
3873
+ }
3874
+ cookieConfig = config;
3875
+ }
3876
+ if (this.isServiceWorkerEnabled(config)) {
3877
+ var _prefix = "".concat(this.getCdnUrl(params), "/").concat(config.accountId, "/");
3878
+ if (workerConfigsByPrefix.has(_prefix)) {
3879
+ throw new Error("Multiple service-worker auth configurations target the same URL prefix: '".concat(_prefix, "'."));
3880
+ }
3881
+ workerConfigsByPrefix.set(_prefix, config);
3882
+ }
3883
+ }
3884
+ } catch (err) {
3885
+ _iterator2.e(err);
3886
+ } finally {
3887
+ _iterator2.f();
3888
+ }
3889
+ if (cookieConfig !== undefined) {
3890
+ var prefix = "".concat(this.getCdnUrl(params), "/").concat(cookieConfig.accountId, "/");
3891
+ var workerConfig = workerConfigsByPrefix.get(prefix);
3892
+ if (workerConfig !== undefined && workerConfig !== cookieConfig) {
3893
+ throw new Error("Cookie and service-worker authentication cannot target the same account from different configs.");
3894
+ }
3895
+ }
3896
+ if (isV2) {
3897
+ this.validateUrlRewriteRules(params.urlRewriteRules);
3898
+ if (requiresServiceWorker && params.serviceWorkerScript === undefined) {
3899
+ throw new Error("The 'serviceWorkerScript' field is required when service-worker authentication or URL rewriting is enabled.");
3900
+ }
3901
+ if (requiresServiceWorker && !canUseServiceWorkers) {
3902
+ throw new Error("This auth session requires service workers, but this browser does not support them.");
3903
+ }
3904
+ }
3905
+ }
3906
+ }, {
3907
+ key: "validateUrlRewriteRules",
3908
+ value: function validateUrlRewriteRules(rules) {
3909
+ if (rules !== undefined && (!Array.isArray(rules) || !rules.every(function (rule) {
3910
+ return rule !== null && AuthManagerBrowser_typeof(rule) === "object" && typeof rule.fromUrlPrefix === "string" && typeof rule.toUrlPrefix === "string";
3911
+ }))) {
3912
+ throw new Error("The 'urlRewriteRules' field must be an array of URL rewrite rules.");
3913
+ }
3914
+ }
3915
+ }, {
3916
+ key: "updateSessionState",
3917
+ value: function updateSessionState(session) {
3918
+ var _this7 = this;
3919
+ var _a;
3920
+ var configs = (_a = session.authConfigs) !== null && _a !== void 0 ? _a : [];
3921
+ var defaultConfig = configs.find(function (state) {
3922
+ return state.config.authConfigId === undefined;
3923
+ });
3924
+ var exposeLegacyDefault = !this.isV2Params(session.params);
3925
+ session.accessToken = exposeLegacyDefault && defaultConfig !== undefined && this.isConfigUsable(defaultConfig) ? defaultConfig.accessToken : undefined;
3926
+ session.accessTokenRefreshHandle = exposeLegacyDefault ? defaultConfig === null || defaultConfig === void 0 ? void 0 : defaultConfig.refreshHandle : undefined;
3927
+ session.isReady = configs.length > 0 && configs.every(function (state) {
3928
+ return _this7.isConfigUsable(state);
3929
+ }) && (session.authServiceWorker === undefined || session.serviceWorkerConfigured === true);
3930
+ }
3931
+ }, {
3932
+ key: "isConfigUsable",
3933
+ value: function isConfigUsable(state) {
3934
+ return (state === null || state === void 0 ? void 0 : state.accessToken) !== undefined && state.expiresAt !== undefined && state.expiresAt > Date.now();
3935
+ }
3936
+ }, {
3937
+ key: "isServiceWorkerEnabled",
3938
+ value: function isServiceWorkerEnabled(config) {
3939
+ return config.enableServiceWorkerAuth !== false;
3940
+ }
3941
+ }, {
3942
+ key: "isV2Params",
3943
+ value: function isV2Params(params) {
3944
+ return typeof params.authConfigs === "function";
3945
+ }
3946
+ }, {
3947
+ key: "isValidAccountId",
3948
+ value: function isValidAccountId(accountId) {
3949
+ return typeof accountId === "string" && /^[1-9A-HJ-NP-Za-km-z]{7}$/.test(accountId);
3950
+ }
3951
+ }, {
3952
+ key: "shouldSetCookie",
3953
+ value: function shouldSetCookie(session, config) {
3954
+ return this.isV2Params(session.params) ? config.enableCookieAuth === true : session.authServiceWorker === undefined;
3569
3955
  }
3570
3956
  }, {
3571
3957
  key: "waitForServiceWorker",
3572
3958
  value: function waitForServiceWorker() {
3573
3959
  try {
3574
- // Message delivery is asynchronous and has no acknowledgement, so allow the worker time to apply the config before
3575
- // beginAuthSession reports that authenticated requests are ready.
3576
3960
  return AuthManagerBrowser_await(AuthManagerBrowser_awaitIgnored(new Promise(function (resolve) {
3577
3961
  return setTimeout(resolve, 100);
3578
3962
  })));
@@ -3582,8 +3966,8 @@ var AuthManagerImpl = /*#__PURE__*/function () {
3582
3966
  }
3583
3967
  }, {
3584
3968
  key: "getAccessTokenUrl",
3585
- value: function getAccessTokenUrl(params, setCookie) {
3586
- return "".concat(this.getCdnUrl(params), "/api/v1/access_tokens/").concat(params.accountId, "?set-cookie=").concat(setCookie ? "true" : "false");
3969
+ value: function getAccessTokenUrl(options, accountId, setCookie) {
3970
+ return "".concat(BytescaleApiClientConfigUtils.getCdnUrl(options !== null && options !== void 0 ? options : {}), "/api/v1/access_tokens/").concat(accountId, "?set-cookie=").concat(setCookie ? "true" : "false");
3587
3971
  }
3588
3972
  }, {
3589
3973
  key: "getCdnUrl",
@@ -3593,17 +3977,16 @@ var AuthManagerImpl = /*#__PURE__*/function () {
3593
3977
  }
3594
3978
  }, {
3595
3979
  key: "deleteAccessToken",
3596
- value: function deleteAccessToken(params) {
3980
+ value: function deleteAccessToken(options, accountId) {
3597
3981
  try {
3598
- var _this7 = this;
3599
- var _a;
3600
- return AuthManagerBrowser_await(AuthManagerBrowser_awaitIgnored(BaseAPI.fetch(_this7.getAccessTokenUrl(params, true), {
3982
+ var _this8 = this;
3983
+ return AuthManagerBrowser_await(AuthManagerBrowser_awaitIgnored(BaseAPI.fetch(_this8.getAccessTokenUrl(options, accountId, true), {
3601
3984
  method: "DELETE",
3602
3985
  credentials: "include",
3603
3986
  headers: {}
3604
3987
  }, {
3605
3988
  isBytescaleApi: true,
3606
- fetchApi: (_a = params.options) === null || _a === void 0 ? void 0 : _a.fetchApi
3989
+ fetchApi: options === null || options === void 0 ? void 0 : options.fetchApi
3607
3990
  })));
3608
3991
  } catch (e) {
3609
3992
  return Promise.reject(e);
@@ -3611,68 +3994,96 @@ var AuthManagerImpl = /*#__PURE__*/function () {
3611
3994
  }
3612
3995
  }, {
3613
3996
  key: "setAccessToken",
3614
- value: function setAccessToken(params, jwt, setCookie) {
3997
+ value: function setAccessToken(options, accountId, jwt, setCookie) {
3615
3998
  try {
3616
- var _this8 = this;
3617
- var _a;
3999
+ var _this9 = this;
3618
4000
  var request = {
3619
4001
  accessToken: jwt
3620
4002
  };
3621
- return AuthManagerBrowser_await(BaseAPI.fetch(_this8.getAccessTokenUrl(params, setCookie), {
4003
+ return AuthManagerBrowser_await(BaseAPI.fetch(_this9.getAccessTokenUrl(options, accountId, setCookie), {
3622
4004
  method: "PUT",
3623
4005
  credentials: "include",
3624
- headers: AuthManagerBrowser_defineProperty({}, _this8.contentType, _this8.contentTypeJson),
4006
+ headers: AuthManagerBrowser_defineProperty({}, _this9.contentType, _this9.contentTypeJson),
3625
4007
  body: JSON.stringify(request)
3626
4008
  }, {
3627
4009
  isBytescaleApi: true,
3628
- fetchApi: (_a = params.options) === null || _a === void 0 ? void 0 : _a.fetchApi
4010
+ fetchApi: options === null || options === void 0 ? void 0 : options.fetchApi
3629
4011
  }), function (response) {
3630
- return AuthManagerBrowser_await(response.json());
4012
+ return AuthManagerBrowser_await(response.json(), function (result) {
4013
+ if (typeof result.accessToken !== "string" || result.accessToken.length === 0 || typeof result.ttlSeconds !== "number" || !Number.isFinite(result.ttlSeconds) || result.ttlSeconds <= 0) {
4014
+ throw new Error("Bytescale returned an invalid access-token registration response.");
4015
+ }
4016
+ return result;
4017
+ });
3631
4018
  });
3632
4019
  } catch (e) {
3633
4020
  return Promise.reject(e);
3634
4021
  }
3635
4022
  }
3636
4023
  }, {
3637
- key: "getAccessToken",
3638
- value: function getAccessToken(params, headers) {
4024
+ key: "getAuthorizationToken",
4025
+ value: function getAuthorizationToken(params, config) {
3639
4026
  try {
3640
- var _this9 = this;
4027
+ var _exit = false;
4028
+ var _this0 = this;
3641
4029
  var _a, _b;
3642
- var endpointName = "Your auth API endpoint";
3643
- var requiredContentType = _this9.contentTypeText;
3644
- return AuthManagerBrowser_await(BaseAPI.fetch(params.authUrl, {
3645
- method: "GET",
3646
- headers: headers
3647
- }, {
3648
- isBytescaleApi: false,
3649
- fetchApi: (_a = params.options) === null || _a === void 0 ? void 0 : _a.fetchApi
3650
- }), function (result) {
3651
- var actualContentType = (_b = result.headers.get(_this9.contentType)) !== null && _b !== void 0 ? _b : "";
3652
- // Support content types like "text/plain; charset=utf-8" and "text/plain"
3653
- if (actualContentType.split(";")[0] !== requiredContentType) {
3654
- throw new Error("".concat(endpointName, " returned \"").concat(actualContentType, "\" for the ").concat(_this9.contentType, " response header, but the Bytescale SDK requires \"").concat(requiredContentType, "\"."));
4030
+ return AuthManagerBrowser_await(AuthManagerBrowser_invoke(function () {
4031
+ if (typeof config.getAuthorizationToken === "function") {
4032
+ var _validateJwt = _this0.validateJwt;
4033
+ return AuthManagerBrowser_await(config.getAuthorizationToken(), function (_config$getAuthorizat) {
4034
+ var _this0$validateJwt = _validateJwt.call(_this0, _config$getAuthorizat, "The 'getAuthorizationToken' callback");
4035
+ _exit = true;
4036
+ return _this0$validateJwt;
4037
+ });
3655
4038
  }
3656
- return AuthManagerBrowser_await(result.text(), function (jwt) {
3657
- if (jwt.length === 0) {
3658
- throw new Error("".concat(endpointName, " returned an empty string. Please return a valid JWT instead."));
3659
- }
3660
- if (jwt.trim().length !== jwt.length) {
3661
- // Whitespace can be a nightmare to spot/debug, so we fail early here.
3662
- throw new Error("".concat(endpointName, " returned whitespace around the JWT, please remove it."));
3663
- }
3664
- return jwt;
4039
+ }, function (_result3) {
4040
+ if (_exit) return _result3;
4041
+ var endpointName = "Your auth API endpoint";
4042
+ var _fetch = BaseAPI.fetch,
4043
+ _config$authUrl = config.authUrl;
4044
+ return AuthManagerBrowser_await(config.authHeaders(), function (_config$authHeaders) {
4045
+ return AuthManagerBrowser_await(_fetch.call(BaseAPI, _config$authUrl, {
4046
+ method: "GET",
4047
+ headers: _config$authHeaders
4048
+ }, {
4049
+ isBytescaleApi: false,
4050
+ fetchApi: (_a = params.options) === null || _a === void 0 ? void 0 : _a.fetchApi
4051
+ }), function (result) {
4052
+ var actualContentType = (_b = result.headers.get(_this0.contentType)) !== null && _b !== void 0 ? _b : "";
4053
+ if (actualContentType.split(";")[0] !== _this0.contentTypeText) {
4054
+ throw new Error("".concat(endpointName, " returned \"").concat(actualContentType, "\" for the ").concat(_this0.contentType, " response header, but the Bytescale SDK requires \"").concat(_this0.contentTypeText, "\"."));
4055
+ }
4056
+ var _validateJwt2 = _this0.validateJwt;
4057
+ return AuthManagerBrowser_await(result.text(), function (_result$text) {
4058
+ return _validateJwt2.call(_this0, _result$text, endpointName);
4059
+ });
4060
+ });
3665
4061
  });
3666
- });
4062
+ }));
3667
4063
  } catch (e) {
3668
4064
  return Promise.reject(e);
3669
4065
  }
3670
4066
  }
4067
+ }, {
4068
+ key: "validateJwt",
4069
+ value: function validateJwt(jwt, source) {
4070
+ if (typeof jwt !== "string" || jwt.length === 0) {
4071
+ throw new InvalidAuthTokenError("".concat(source, " returned an empty or malformed token. Please return a valid JWT instead."));
4072
+ }
4073
+ if (jwt.trim().length !== jwt.length) {
4074
+ throw new InvalidAuthTokenError("".concat(source, " returned whitespace around the JWT, please remove it."));
4075
+ }
4076
+ var parts = jwt.split(".");
4077
+ if (parts.length !== 3 || parts.some(function (part) {
4078
+ return part.length === 0 || !/^[A-Za-z0-9_-]+$/.test(part);
4079
+ })) {
4080
+ throw new InvalidAuthTokenError("".concat(source, " returned a malformed JWT."));
4081
+ }
4082
+ return jwt;
4083
+ }
3671
4084
  }]);
3672
4085
  }();
3673
- /**
3674
- * 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).
3675
- */
4086
+ /** Alternative to a static class that allows the implementation to satisfy an interface. */
3676
4087
  var AuthManager = new AuthManagerImpl(new ServiceWorkerUtils());
3677
4088
  ;// ./src/public/browser/index.ts
3678
4089