@bytescale/sdk 3.55.0 → 3.57.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.
@@ -3156,6 +3156,13 @@ function AuthManagerBrowser_awaitIgnored(value, direct) {
3156
3156
  return value && value.then ? value.then(AuthManagerBrowser_empty) : Promise.resolve();
3157
3157
  }
3158
3158
  }
3159
+ function AuthManagerBrowser_invoke(body, then) {
3160
+ var result = body();
3161
+ if (result && result.then) {
3162
+ return result.then(then);
3163
+ }
3164
+ return then(result);
3165
+ }
3159
3166
  function AuthManagerBrowser_await(value, then, direct) {
3160
3167
  if (direct) {
3161
3168
  return then ? then(value) : value;
@@ -3183,13 +3190,6 @@ function AuthManagerBrowser_invokeIgnored(body) {
3183
3190
  return result.then(AuthManagerBrowser_empty);
3184
3191
  }
3185
3192
  }
3186
- function AuthManagerBrowser_invoke(body, then) {
3187
- var result = body();
3188
- if (result && result.then) {
3189
- return result.then(then);
3190
- }
3191
- return then(result);
3192
- }
3193
3193
  function AuthManagerBrowser_catch(body, recover) {
3194
3194
  try {
3195
3195
  var result = body();
@@ -3221,8 +3221,29 @@ function AuthManagerBrowser_continueIgnored(value) {
3221
3221
  return value.then(AuthManagerBrowser_empty);
3222
3222
  }
3223
3223
  }
3224
- 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); }
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
+ }
3225
3238
  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
+ function AuthManagerBrowser_toConsumableArray(r) { return AuthManagerBrowser_arrayWithoutHoles(r) || AuthManagerBrowser_iterableToArray(r) || AuthManagerBrowser_unsupportedIterableToArray(r) || AuthManagerBrowser_nonIterableSpread(); }
3241
+ 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
+ function AuthManagerBrowser_iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); }
3244
+ function AuthManagerBrowser_arrayWithoutHoles(r) { if (Array.isArray(r)) return AuthManagerBrowser_arrayLikeToArray(r); }
3245
+ 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
+ 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); }
3226
3247
  function AuthManagerBrowser_classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
3227
3248
  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); } }
3228
3249
  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; }
@@ -3257,7 +3278,8 @@ var AuthManagerImpl = /*#__PURE__*/function () {
3257
3278
  key: "isAuthSessionReady",
3258
3279
  value: function isAuthSessionReady() {
3259
3280
  var _a;
3260
- return ((_a = AuthSessionState.getSession()) === null || _a === void 0 ? void 0 : _a.accessToken) !== undefined;
3281
+ 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;
3261
3283
  }
3262
3284
  }, {
3263
3285
  key: "beginAuthSession",
@@ -3269,21 +3291,40 @@ var AuthManagerImpl = /*#__PURE__*/function () {
3269
3291
  if (_this.isAuthSessionActive()) {
3270
3292
  throw new Error("Auth session already active. Please call 'await endAuthSession()' and then call 'await beginAuthSession(...)' to start a new auth session.");
3271
3293
  }
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
+ }
3302
+ }
3272
3303
  var newSession = {
3273
3304
  accessToken: undefined,
3274
3305
  accessTokenRefreshHandle: undefined,
3275
3306
  params: params,
3276
3307
  isActive: true,
3277
- authServiceWorker: params.serviceWorkerScript !== undefined && _this.serviceWorkerUtils.canUseServiceWorkers() ? {
3308
+ isReady: false,
3309
+ authServiceWorker: params.serviceWorkerScript !== undefined && canUseServiceWorkers ? {
3278
3310
  serviceWorkerScript: params.serviceWorkerScript,
3279
3311
  type: "Uninitialized"
3280
- } : undefined
3312
+ } : undefined,
3313
+ primaryAuthSwConfig: undefined,
3314
+ serviceWorkerConfig: undefined,
3315
+ serviceWorkerConfigRefreshHandle: undefined
3281
3316
  };
3282
3317
  AuthSessionState.setSession(newSession);
3283
3318
  return newSession;
3284
3319
  })), function (session) {
3285
3320
  // IMPORTANT: must be called outside the above, else re-entrant deadlock will occur.
3286
- return AuthManagerBrowser_awaitIgnored(_this.refreshAccessToken(session));
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));
3327
+ });
3287
3328
  });
3288
3329
  } catch (e) {
3289
3330
  return Promise.reject(e);
@@ -3304,14 +3345,20 @@ var AuthManagerImpl = /*#__PURE__*/function () {
3304
3345
  if (session.accessTokenRefreshHandle !== undefined) {
3305
3346
  _this2.scheduler.unschedule(session.accessTokenRefreshHandle);
3306
3347
  }
3307
- return AuthManagerBrowser_await(_this2.deleteAccessToken(session.params), function () {
3348
+ if (session.serviceWorkerConfigRefreshHandle !== undefined) {
3349
+ _this2.scheduler.unschedule(session.serviceWorkerConfigRefreshHandle);
3350
+ }
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.
3353
+ return AuthManagerBrowser_invoke(function () {
3354
+ if (typeof session.params.accountId === "string") {
3355
+ return AuthManagerBrowser_awaitIgnored(_this2.deleteAccessToken(session.params));
3356
+ }
3357
+ }, function () {
3308
3358
  return AuthManagerBrowser_invokeIgnored(function () {
3309
3359
  if (session.authServiceWorker !== undefined) {
3310
3360
  // Prevent service worker from authorizing subsequent requests.
3311
- return AuthManagerBrowser_awaitIgnored(_this2.serviceWorkerUtils.sendMessage({
3312
- type: "SET_BYTESCALE_AUTH_CONFIG",
3313
- config: []
3314
- }, session.authServiceWorker, _this2.serviceWorkerScriptFieldName));
3361
+ return AuthManagerBrowser_awaitIgnored(_this2.sendServiceWorkerConfig(session, []));
3315
3362
  }
3316
3363
  });
3317
3364
  });
@@ -3322,7 +3369,7 @@ var AuthManagerImpl = /*#__PURE__*/function () {
3322
3369
  }
3323
3370
  }, {
3324
3371
  key: "refreshAccessToken",
3325
- value: function refreshAccessToken(session) {
3372
+ value: function refreshAccessToken(session, params) {
3326
3373
  try {
3327
3374
  var _this3 = this;
3328
3375
  return AuthManagerBrowser_await(AuthManagerBrowser_awaitIgnored(_this3.authSessionMutex.safe(AuthManagerBrowser_async(function () {
@@ -3335,36 +3382,35 @@ var AuthManagerImpl = /*#__PURE__*/function () {
3335
3382
  var expires = secondsFromNow(_this3.retryAuthAfterErrorSeconds);
3336
3383
  return AuthManagerBrowser_continueIgnored(AuthManagerBrowser_finallyRethrows(function () {
3337
3384
  return AuthManagerBrowser_catch(function () {
3338
- var _getAccessToken = _this3.getAccessToken,
3339
- _session$params = session.params;
3340
- return AuthManagerBrowser_await(session.params.authHeaders(), function (_session$params$authH) {
3341
- return AuthManagerBrowser_await(_getAccessToken.call(_this3, _session$params, _session$params$authH), function (jwt) {
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) {
3342
3388
  // We don't use cookie-based auth if the browser supports service worker-based auth, as using both will cause
3343
3389
  // confusion for us in the future (i.e. we may question "do we need to use both together? was there a reason?").
3344
3390
  // Also: if the user has omitted "allowedOrigins" from their JWT, then service worker-based auth is more secure
3345
3391
  // than cookie-based auth, which is another reason to prevent these cookies from being set unless required.
3346
3392
  var setCookie = session.authServiceWorker === undefined;
3347
- return AuthManagerBrowser_await(_this3.setAccessToken(session.params, jwt, setCookie), function (setTokenResult) {
3393
+ return AuthManagerBrowser_await(_this3.setAccessToken(params, jwt, setCookie), function (setTokenResult) {
3348
3394
  return AuthManagerBrowser_invoke(function () {
3349
3395
  if (session.authServiceWorker !== undefined) {
3350
- return AuthManagerBrowser_await(_this3.serviceWorkerUtils.sendMessage({
3351
- type: "SET_BYTESCALE_AUTH_CONFIG",
3352
- config: [{
3353
- headers: [{
3354
- key: "Authorization",
3355
- value: "Bearer ".concat(jwt)
3356
- }],
3357
- expires: secondsFromNow(setTokenResult.ttlSeconds),
3358
- sourceUrlPrefixes: session.params.sourceUrlPrefixes,
3359
- urlPrefix: "".concat(session.params.sourceUrlPrefixes === undefined ? "" : _this3.sourceScopedUrlPrefixMarker).concat(_this3.getCdnUrl(session.params), "/").concat(session.params.accountId, "/")
3360
- }]
3361
- }, session.authServiceWorker, _this3.serviceWorkerScriptFieldName), function () {
3362
- // Allow time for the service worker to receive and process the message. Since this is asynchronous and not
3363
- // synchronized, we need to wait for a sufficient amount of time to ensure the service worker is ready to
3364
- // authenticate requests, so that after 'beginAuthSession' completes, users can start making requests.
3365
- return AuthManagerBrowser_awaitIgnored(new Promise(function (resolve) {
3366
- return setTimeout(resolve, 100);
3367
- }));
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;
3368
3414
  });
3369
3415
  }
3370
3416
  }, function () {
@@ -3376,6 +3422,7 @@ var AuthManagerImpl = /*#__PURE__*/function () {
3376
3422
  expires = secondsFromNow(actualTtl);
3377
3423
  // Set this at the end, as it's also used to signal 'isAuthSessionReady', so must be set after configuring the Service Worker, etc.
3378
3424
  session.accessToken = setTokenResult.accessToken;
3425
+ _this3.updateSessionReadiness(session);
3379
3426
  });
3380
3427
  });
3381
3428
  });
@@ -3388,7 +3435,7 @@ var AuthManagerImpl = /*#__PURE__*/function () {
3388
3435
  // 'setTimeout' can be paused (e.g., during hibernation), risking JWT expiration before it triggers. We use a
3389
3436
  // scheduler to check wall-clock time every second and execute the callback at the scheduled time (below).
3390
3437
  session.accessTokenRefreshHandle = _this3.scheduler.schedule(expires, function () {
3391
- _this3.refreshAccessToken(session).then(function () {},
3438
+ _this3.refreshAccessToken(session, params).then(function () {},
3392
3439
  // Should not occur, as this method shouldn't throw errors.
3393
3440
  function (e) {
3394
3441
  return ConsoleUtils.error("Unexpected error when refreshing JWT access token: ".concat(e));
@@ -3401,6 +3448,138 @@ var AuthManagerImpl = /*#__PURE__*/function () {
3401
3448
  return Promise.reject(e);
3402
3449
  }
3403
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
+ }
3504
+ });
3505
+ }))));
3506
+ } catch (e) {
3507
+ return Promise.reject(e);
3508
+ }
3509
+ }
3510
+ }, {
3511
+ key: "sendMergedServiceWorkerConfig",
3512
+ value: function sendMergedServiceWorkerConfig(session, primaryConfig, serviceWorkerConfig) {
3513
+ try {
3514
+ var _this5 = this;
3515
+ 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 : [])))));
3519
+ } catch (e) {
3520
+ return Promise.reject(e);
3521
+ }
3522
+ }
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
+ }, {
3544
+ key: "sendServiceWorkerConfig",
3545
+ value: function sendServiceWorkerConfig(session, config) {
3546
+ try {
3547
+ var _this6 = this;
3548
+ if (session.authServiceWorker === undefined) {
3549
+ throw new Error("Service worker configuration cannot be applied because service workers are unavailable.");
3550
+ }
3551
+ return AuthManagerBrowser_await(_this6.serviceWorkerUtils.sendMessage({
3552
+ type: "SET_BYTESCALE_AUTH_CONFIG",
3553
+ config: config.map(function (entry) {
3554
+ return Object.assign(Object.assign({}, entry), {
3555
+ urlPrefix: "".concat(entry.sourceUrlPrefixes === undefined ? "" : _this6.sourceScopedUrlPrefixMarker).concat(entry.urlPrefix)
3556
+ });
3557
+ })
3558
+ }, session.authServiceWorker, _this6.serviceWorkerScriptFieldName), function (_this6$serviceWorkerU) {
3559
+ session.authServiceWorker = _this6$serviceWorkerU;
3560
+ });
3561
+ } catch (e) {
3562
+ return Promise.reject(e);
3563
+ }
3564
+ }
3565
+ }, {
3566
+ key: "updateSessionReadiness",
3567
+ value: function updateSessionReadiness(session) {
3568
+ session.isReady = session.accessToken !== undefined && (session.params.serviceWorkerConfig === undefined || session.serviceWorkerConfig !== undefined);
3569
+ }
3570
+ }, {
3571
+ key: "waitForServiceWorker",
3572
+ value: function waitForServiceWorker() {
3573
+ 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
+ return AuthManagerBrowser_await(AuthManagerBrowser_awaitIgnored(new Promise(function (resolve) {
3577
+ return setTimeout(resolve, 100);
3578
+ })));
3579
+ } catch (e) {
3580
+ return Promise.reject(e);
3581
+ }
3582
+ }
3404
3583
  }, {
3405
3584
  key: "getAccessTokenUrl",
3406
3585
  value: function getAccessTokenUrl(params, setCookie) {
@@ -3416,9 +3595,9 @@ var AuthManagerImpl = /*#__PURE__*/function () {
3416
3595
  key: "deleteAccessToken",
3417
3596
  value: function deleteAccessToken(params) {
3418
3597
  try {
3419
- var _this4 = this;
3598
+ var _this7 = this;
3420
3599
  var _a;
3421
- return AuthManagerBrowser_await(AuthManagerBrowser_awaitIgnored(BaseAPI.fetch(_this4.getAccessTokenUrl(params, true), {
3600
+ return AuthManagerBrowser_await(AuthManagerBrowser_awaitIgnored(BaseAPI.fetch(_this7.getAccessTokenUrl(params, true), {
3422
3601
  method: "DELETE",
3423
3602
  credentials: "include",
3424
3603
  headers: {}
@@ -3434,15 +3613,15 @@ var AuthManagerImpl = /*#__PURE__*/function () {
3434
3613
  key: "setAccessToken",
3435
3614
  value: function setAccessToken(params, jwt, setCookie) {
3436
3615
  try {
3437
- var _this5 = this;
3616
+ var _this8 = this;
3438
3617
  var _a;
3439
3618
  var request = {
3440
3619
  accessToken: jwt
3441
3620
  };
3442
- return AuthManagerBrowser_await(BaseAPI.fetch(_this5.getAccessTokenUrl(params, setCookie), {
3621
+ return AuthManagerBrowser_await(BaseAPI.fetch(_this8.getAccessTokenUrl(params, setCookie), {
3443
3622
  method: "PUT",
3444
3623
  credentials: "include",
3445
- headers: AuthManagerBrowser_defineProperty({}, _this5.contentType, _this5.contentTypeJson),
3624
+ headers: AuthManagerBrowser_defineProperty({}, _this8.contentType, _this8.contentTypeJson),
3446
3625
  body: JSON.stringify(request)
3447
3626
  }, {
3448
3627
  isBytescaleApi: true,
@@ -3458,10 +3637,10 @@ var AuthManagerImpl = /*#__PURE__*/function () {
3458
3637
  key: "getAccessToken",
3459
3638
  value: function getAccessToken(params, headers) {
3460
3639
  try {
3461
- var _this6 = this;
3640
+ var _this9 = this;
3462
3641
  var _a, _b;
3463
3642
  var endpointName = "Your auth API endpoint";
3464
- var requiredContentType = _this6.contentTypeText;
3643
+ var requiredContentType = _this9.contentTypeText;
3465
3644
  return AuthManagerBrowser_await(BaseAPI.fetch(params.authUrl, {
3466
3645
  method: "GET",
3467
3646
  headers: headers
@@ -3469,10 +3648,10 @@ var AuthManagerImpl = /*#__PURE__*/function () {
3469
3648
  isBytescaleApi: false,
3470
3649
  fetchApi: (_a = params.options) === null || _a === void 0 ? void 0 : _a.fetchApi
3471
3650
  }), function (result) {
3472
- var actualContentType = (_b = result.headers.get(_this6.contentType)) !== null && _b !== void 0 ? _b : "";
3651
+ var actualContentType = (_b = result.headers.get(_this9.contentType)) !== null && _b !== void 0 ? _b : "";
3473
3652
  // Support content types like "text/plain; charset=utf-8" and "text/plain"
3474
3653
  if (actualContentType.split(";")[0] !== requiredContentType) {
3475
- throw new Error("".concat(endpointName, " returned \"").concat(actualContentType, "\" for the ").concat(_this6.contentType, " response header, but the Bytescale SDK requires \"").concat(requiredContentType, "\"."));
3654
+ throw new Error("".concat(endpointName, " returned \"").concat(actualContentType, "\" for the ").concat(_this9.contentType, " response header, but the Bytescale SDK requires \"").concat(requiredContentType, "\"."));
3476
3655
  }
3477
3656
  return AuthManagerBrowser_await(result.text(), function (jwt) {
3478
3657
  if (jwt.length === 0) {
@@ -1,7 +1,11 @@
1
1
  import { AuthSwHeaderDto } from "./AuthSwHeaderDto";
2
2
  export interface AuthSwConfigEntryDto {
3
+ /** Epoch time in milliseconds. Omit the value to keep the entry until the config is replaced. */
3
4
  expires: number | undefined;
5
+ /** Headers to add to matching requests. */
4
6
  headers: AuthSwHeaderDto[];
7
+ /** Optional page or iframe URL prefixes. An empty array matches no clients. */
5
8
  sourceUrlPrefixes?: string[];
9
+ /** Request URL prefix. Use the actual URL; AuthManager applies any internal compatibility marker. */
6
10
  urlPrefix: string;
7
11
  }
@@ -1,4 +1,18 @@
1
1
  import { BytescaleApiClientConfig } from "../../public/shared";
2
+ import { AuthSwConfigEntryDto } from "../dtos/AuthSwConfigEntryDto";
3
+ export interface AuthManagerServiceWorkerConfig {
4
+ /**
5
+ * Additional download-only service-worker authorization rules.
6
+ * An empty array clears all additional rules.
7
+ */
8
+ additionalConfig: AuthSwConfigEntryDto[];
9
+ /**
10
+ * Restricts the primary JWT to pages and iframes whose URL starts with one of these prefixes.
11
+ * An empty array matches no clients. Omit this field to preserve the existing service-worker behavior.
12
+ * History API changes do not update the matched client URL.
13
+ */
14
+ sourceUrlPrefixes?: string[];
15
+ }
2
16
  export interface BeginAuthSessionParams {
3
17
  /**
4
18
  * The account ID to authorize requests for.
@@ -18,6 +32,18 @@ export interface BeginAuthSessionParams {
18
32
  * Optional configuration.
19
33
  */
20
34
  options?: Pick<BytescaleApiClientConfig, "fetchApi" | "cdnUrl">;
35
+ /**
36
+ * Returns configuration for service-worker authorization. The primary JWT returned by `authUrl` is restricted using
37
+ * `sourceUrlPrefixes`; `additionalConfig` contains download-only rules and never authenticates SDK API operations.
38
+ * Called when the session begins and again 20 seconds before the earliest additional entry expires. Entries without
39
+ * an expiry do not trigger a refresh.
40
+ *
41
+ * Requires `serviceWorkerScript` and browser service-worker support. Additional rules cannot use the CDN cookie
42
+ * fallback.
43
+ *
44
+ * IMPORTANT: do not call 'AuthManager.beginAuthSession' or 'AuthManager.endAuthSession' inside this callback, as this will cause a deadlock.
45
+ */
46
+ serviceWorkerConfig?: () => Promise<AuthManagerServiceWorkerConfig>;
21
47
  /**
22
48
  * Enables support for modern browsers that block third-party cookies (like Safari).
23
49
  *
@@ -64,17 +90,14 @@ export interface BeginAuthSessionParams {
64
90
  * script must be hosted on your website's domain in the root directory.
65
91
  */
66
92
  serviceWorkerScript?: string;
67
- /**
68
- * Restricts service-worker authorization to pages and iframes whose URL starts with one of these prefixes.
69
- * An empty array matches no clients. Omit this field to preserve the existing service-worker behavior.
70
- * Applies only with `serviceWorkerScript`; History API changes do not update the matched client URL.
71
- */
72
- sourceUrlPrefixes?: string[];
73
93
  }
74
94
  export interface AuthManagerInterface {
75
95
  /**
76
96
  * Begins a JWT auth session with the Bytescale API and Bytescale CDN.
77
97
  *
98
+ * The primary JWT authenticates Bytescale API operations and downloads for `accountId`. Optional additional
99
+ * service-worker rules authenticate downloads only.
100
+ *
78
101
  * Specifically, calling this method will cause the SDK to periodically acquire a JWT from your JWT endpoint. The SDK will then automatically include this JWT in all subsequent Bytescale API requests (via the 'authorization-token' request header) and also in all Bytescale CDN download requests (via a session cookie, or an 'authorization' header if service workers are being used).
79
102
  *
80
103
  * You can only call this method if 'isAuthSessionActive() === false', else an error will be returned.
@@ -1,9 +1,14 @@
1
- import { BeginAuthSessionParams } from "./AuthManagerInterface";
1
+ import { AuthManagerServiceWorkerConfig, BeginAuthSessionParams } from "./AuthManagerInterface";
2
+ import { AuthSwConfigEntryDto } from "../dtos/AuthSwConfigEntryDto";
2
3
  import { ServiceWorkerConfig } from "./ServiceWorkerConfig";
3
4
  export interface AuthSession {
4
5
  accessToken: string | undefined;
5
6
  accessTokenRefreshHandle: number | undefined;
6
7
  authServiceWorker: ServiceWorkerConfig | undefined;
7
8
  isActive: boolean;
9
+ isReady?: boolean;
8
10
  params: BeginAuthSessionParams;
11
+ primaryAuthSwConfig: AuthSwConfigEntryDto | undefined;
12
+ serviceWorkerConfig: AuthManagerServiceWorkerConfig | undefined;
13
+ serviceWorkerConfigRefreshHandle: number | undefined;
9
14
  }
@@ -1,6 +1,9 @@
1
1
  import { AuthManagerInterface, BeginAuthSessionParams } from "../../private/model/AuthManagerInterface";
2
2
  import { AuthSwSetConfigDto } from "../../private/dtos/AuthSwSetConfigDto";
3
3
  import { ServiceWorkerUtils } from "../../private/ServiceWorkerUtils";
4
+ export type { AuthSwConfigEntryDto } from "../../private/dtos/AuthSwConfigEntryDto";
5
+ export type { AuthSwHeaderDto } from "../../private/dtos/AuthSwHeaderDto";
6
+ export type { AuthManagerServiceWorkerConfig, BeginAuthSessionParams } from "../../private/model/AuthManagerInterface";
4
7
  declare class AuthManagerImpl implements AuthManagerInterface {
5
8
  private readonly serviceWorkerUtils;
6
9
  private readonly authSessionMutex;
@@ -19,6 +22,12 @@ declare class AuthManagerImpl implements AuthManagerInterface {
19
22
  beginAuthSession(params: BeginAuthSessionParams): Promise<void>;
20
23
  endAuthSession(): Promise<void>;
21
24
  private refreshAccessToken;
25
+ private refreshServiceWorkerConfig;
26
+ private sendMergedServiceWorkerConfig;
27
+ private getServiceWorkerConfigRefreshEpoch;
28
+ private sendServiceWorkerConfig;
29
+ private updateSessionReadiness;
30
+ private waitForServiceWorker;
22
31
  private getAccessTokenUrl;
23
32
  private getCdnUrl;
24
33
  private deleteAccessToken;
@@ -29,4 +38,3 @@ declare class AuthManagerImpl implements AuthManagerInterface {
29
38
  * 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).
30
39
  */
31
40
  export declare const AuthManager: AuthManagerImpl;
32
- export {};
@@ -1,4 +1,7 @@
1
1
  import { AuthManagerInterface, BeginAuthSessionParams } from "../../private/model/AuthManagerInterface";
2
+ export type { AuthSwConfigEntryDto } from "../../private/dtos/AuthSwConfigEntryDto";
3
+ export type { AuthSwHeaderDto } from "../../private/dtos/AuthSwHeaderDto";
4
+ export type { AuthManagerServiceWorkerConfig, BeginAuthSessionParams } from "../../private/model/AuthManagerInterface";
2
5
  declare class AuthManagerImpl implements AuthManagerInterface {
3
6
  beginAuthSession(_params: BeginAuthSessionParams): Promise<void>;
4
7
  endAuthSession(): Promise<void>;
@@ -9,4 +12,3 @@ declare class AuthManagerImpl implements AuthManagerInterface {
9
12
  * 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).
10
13
  */
11
14
  export declare const AuthManager: AuthManagerImpl;
12
- export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bytescale/sdk",
3
- "version": "3.55.0",
3
+ "version": "3.57.0",
4
4
  "description": "Bytescale JavaScript SDK",
5
5
  "author": "Bytescale <hello@bytescale.com> (https://www.bytescale.com)",
6
6
  "license": "MIT",