@bytescale/sdk 3.17.0 → 3.19.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.
@@ -2394,6 +2394,201 @@ var ConsoleUtils = /*#__PURE__*/function () {
2394
2394
  }]);
2395
2395
  return ConsoleUtils;
2396
2396
  }();
2397
+ ;// CONCATENATED MODULE: ./src/private/ServiceWorkerUtils.ts
2398
+ function ServiceWorkerUtils_typeof(obj) { "@babel/helpers - typeof"; return ServiceWorkerUtils_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, ServiceWorkerUtils_typeof(obj); }
2399
+ function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = ServiceWorkerUtils_unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, 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 normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; }
2400
+ function ServiceWorkerUtils_unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return ServiceWorkerUtils_arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return ServiceWorkerUtils_arrayLikeToArray(o, minLen); }
2401
+ function ServiceWorkerUtils_arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
2402
+ function ServiceWorkerUtils_await(value, then, direct) {
2403
+ if (direct) {
2404
+ return then ? then(value) : value;
2405
+ }
2406
+ if (!value || !value.then) {
2407
+ value = Promise.resolve(value);
2408
+ }
2409
+ return then ? value.then(then) : value;
2410
+ }
2411
+ function ServiceWorkerUtils_catch(body, recover) {
2412
+ try {
2413
+ var result = body();
2414
+ } catch (e) {
2415
+ return recover(e);
2416
+ }
2417
+ if (result && result.then) {
2418
+ return result.then(void 0, recover);
2419
+ }
2420
+ return result;
2421
+ }
2422
+ function ServiceWorkerUtils_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
2423
+ function ServiceWorkerUtils_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, ServiceWorkerUtils_toPropertyKey(descriptor.key), descriptor); } }
2424
+ function ServiceWorkerUtils_createClass(Constructor, protoProps, staticProps) { if (protoProps) ServiceWorkerUtils_defineProperties(Constructor.prototype, protoProps); if (staticProps) ServiceWorkerUtils_defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
2425
+ function ServiceWorkerUtils_toPropertyKey(arg) { var key = ServiceWorkerUtils_toPrimitive(arg, "string"); return ServiceWorkerUtils_typeof(key) === "symbol" ? key : String(key); }
2426
+ function ServiceWorkerUtils_toPrimitive(input, hint) { if (ServiceWorkerUtils_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (ServiceWorkerUtils_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
2427
+
2428
+ var ServiceWorkerUtils = /*#__PURE__*/function () {
2429
+ function ServiceWorkerUtils() {
2430
+ ServiceWorkerUtils_classCallCheck(this, ServiceWorkerUtils);
2431
+ }
2432
+ ServiceWorkerUtils_createClass(ServiceWorkerUtils, [{
2433
+ key: "canUseServiceWorkers",
2434
+ value: function canUseServiceWorkers() {
2435
+ return "serviceWorker" in navigator;
2436
+ }
2437
+ }, {
2438
+ key: "sendMessage",
2439
+ value: function sendMessage(message, config, serviceWorkerScriptFieldName) {
2440
+ try {
2441
+ var _this2 = this;
2442
+ return ServiceWorkerUtils_await(config.serviceWorkerScope !== undefined ? _this2.getActiveServiceWorkerElseRegister(config, message) : _this2.registerServiceWorkerIfSupported(config.serviceWorkerScript, message, serviceWorkerScriptFieldName), function (result) {
2443
+ if (!result.messageSent) {
2444
+ result.serviceWorker.postMessage(message);
2445
+ }
2446
+ return result.config;
2447
+ });
2448
+ } catch (e) {
2449
+ return Promise.reject(e);
2450
+ }
2451
+ }
2452
+ }, {
2453
+ key: "registerServiceWorkerIfSupported",
2454
+ value: function registerServiceWorkerIfSupported(serviceWorkerScript, init, serviceWorkerScriptFieldName) {
2455
+ try {
2456
+ var _this4 = this;
2457
+ if (!serviceWorkerScript.startsWith("/")) {
2458
+ throw new Error("The '".concat(serviceWorkerScriptFieldName, "' field must start with a '/' and reference a script at the root of your website."));
2459
+ }
2460
+ var forwardSlashCount = serviceWorkerScript.split("/").length - 1;
2461
+ if (forwardSlashCount > 1) {
2462
+ ConsoleUtils.warn("The '".concat(serviceWorkerScriptFieldName, "' field should be a root script (e.g. '/script.js'). The Bytescale SDK can only authorize requests originating from webpages that are at the same level as the script or below."));
2463
+ }
2464
+ return ServiceWorkerUtils_await(_this4.registerAuthServiceWorker(serviceWorkerScript, init));
2465
+ } catch (e) {
2466
+ return Promise.reject(e);
2467
+ }
2468
+ }
2469
+ }, {
2470
+ key: "getActiveServiceWorkerElseRegister",
2471
+ value: function getActiveServiceWorkerElseRegister(config, init) {
2472
+ try {
2473
+ var _this6 = this;
2474
+ return ServiceWorkerUtils_await(_this6.getActiveServiceWorker(config.serviceWorkerScope), function (serviceWorker) {
2475
+ return serviceWorker !== undefined ? {
2476
+ serviceWorker: serviceWorker,
2477
+ messageSent: false,
2478
+ config: config
2479
+ } : ServiceWorkerUtils_await(_this6.registerAuthServiceWorker(config.serviceWorkerScript, init));
2480
+ });
2481
+ } catch (e) {
2482
+ return Promise.reject(e);
2483
+ }
2484
+ }
2485
+ /**
2486
+ * Idempotent.
2487
+ *
2488
+ * Only returns once the service worker has been activated.
2489
+ *
2490
+ * We don't need to unregister it: we just need to clear the config when auth ends.
2491
+ */
2492
+ }, {
2493
+ key: "registerAuthServiceWorker",
2494
+ value: function registerAuthServiceWorker(serviceWorkerScript, init) {
2495
+ try {
2496
+ var _this8 = this;
2497
+ return ServiceWorkerUtils_catch(function () {
2498
+ return ServiceWorkerUtils_await(navigator.serviceWorker.register(serviceWorkerScript), function (registration) {
2499
+ return ServiceWorkerUtils_await(_this8.waitForActiveServiceWorker(registration, init), function (_ref) {
2500
+ var serviceWorker = _ref.serviceWorker,
2501
+ messageSent = _ref.messageSent;
2502
+ return {
2503
+ serviceWorker: serviceWorker,
2504
+ messageSent: messageSent,
2505
+ config: {
2506
+ serviceWorkerScript: serviceWorkerScript,
2507
+ serviceWorkerScope: registration.scope
2508
+ }
2509
+ };
2510
+ });
2511
+ });
2512
+ }, function (e) {
2513
+ throw new Error("Failed to install Bytescale Service Worker (SW). ".concat(e.name, ": ").concat(e.message));
2514
+ });
2515
+ } catch (e) {
2516
+ return Promise.reject(e);
2517
+ }
2518
+ }
2519
+ }, {
2520
+ key: "waitForActiveServiceWorker",
2521
+ value: function waitForActiveServiceWorker(registration, init) {
2522
+ try {
2523
+ // If the service worker is already active, return it.
2524
+ if (registration.active !== null) {
2525
+ return {
2526
+ serviceWorker: registration.active,
2527
+ messageSent: false
2528
+ };
2529
+ }
2530
+ // Service worker has not finished installing, which means we've just started installing a new one, so send the INIT
2531
+ // message to it, as it will be waiting for it to complete its install phase.
2532
+ var messageSent;
2533
+ if (registration.installing !== null) {
2534
+ messageSent = true;
2535
+ registration.installing.postMessage(init);
2536
+ } else {
2537
+ messageSent = false;
2538
+ }
2539
+ // Wait for the service worker to become active.
2540
+ return ServiceWorkerUtils_await(new Promise(function (resolve, reject) {
2541
+ var _a, _b;
2542
+ var serviceWorker = (_b = (_a = registration.installing) !== null && _a !== void 0 ? _a : registration.waiting) !== null && _b !== void 0 ? _b : undefined;
2543
+ if (serviceWorker !== undefined) {
2544
+ var stateChangeHandler = function stateChangeHandler(e) {
2545
+ var sw = e.target;
2546
+ if (sw.state === "activated") {
2547
+ serviceWorker.removeEventListener("statechange", stateChangeHandler);
2548
+ resolve({
2549
+ messageSent: messageSent,
2550
+ serviceWorker: sw
2551
+ });
2552
+ }
2553
+ };
2554
+ serviceWorker.addEventListener("statechange", stateChangeHandler);
2555
+ } else {
2556
+ // If there's no installing or waiting service worker, reject.
2557
+ reject(new Error("No service worker is installing or waiting."));
2558
+ }
2559
+ }));
2560
+ } catch (e) {
2561
+ return Promise.reject(e);
2562
+ }
2563
+ }
2564
+ }, {
2565
+ key: "getActiveServiceWorker",
2566
+ value: function getActiveServiceWorker(serviceWorkerScope) {
2567
+ try {
2568
+ return ServiceWorkerUtils_await(navigator.serviceWorker.getRegistrations(), function (registrations) {
2569
+ var _iterator = _createForOfIteratorHelper(registrations),
2570
+ _step;
2571
+ try {
2572
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
2573
+ var registration = _step.value;
2574
+ if (registration.active !== null && registration.scope === serviceWorkerScope) {
2575
+ return registration.active;
2576
+ }
2577
+ }
2578
+ } catch (err) {
2579
+ _iterator.e(err);
2580
+ } finally {
2581
+ _iterator.f();
2582
+ }
2583
+ return undefined;
2584
+ });
2585
+ } catch (e) {
2586
+ return Promise.reject(e);
2587
+ }
2588
+ }
2589
+ }]);
2590
+ return ServiceWorkerUtils;
2591
+ }();
2397
2592
  ;// CONCATENATED MODULE: ./src/public/browser/AuthManagerBrowser.ts
2398
2593
  function AuthManagerBrowser_typeof(obj) { "@babel/helpers - typeof"; return AuthManagerBrowser_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, AuthManagerBrowser_typeof(obj); }
2399
2594
  function AuthManagerBrowser_defineProperty(obj, key, value) { key = AuthManagerBrowser_toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
@@ -2424,6 +2619,19 @@ function AuthManagerBrowser_async(f) {
2424
2619
  }
2425
2620
  };
2426
2621
  }
2622
+ function AuthManagerBrowser_invokeIgnored(body) {
2623
+ var result = body();
2624
+ if (result && result.then) {
2625
+ return result.then(AuthManagerBrowser_empty);
2626
+ }
2627
+ }
2628
+ function AuthManagerBrowser_invoke(body, then) {
2629
+ var result = body();
2630
+ if (result && result.then) {
2631
+ return result.then(then);
2632
+ }
2633
+ return then(result);
2634
+ }
2427
2635
  function AuthManagerBrowser_catch(body, recover) {
2428
2636
  try {
2429
2637
  var result = body();
@@ -2463,9 +2671,12 @@ function AuthManagerBrowser_toPrimitive(input, hint) { if (AuthManagerBrowser_ty
2463
2671
 
2464
2672
 
2465
2673
 
2674
+
2466
2675
  var AuthManagerImpl = /*#__PURE__*/function () {
2467
- function AuthManagerImpl() {
2676
+ function AuthManagerImpl(serviceWorkerUtils) {
2468
2677
  AuthManagerBrowser_classCallCheck(this, AuthManagerImpl);
2678
+ this.serviceWorkerUtils = serviceWorkerUtils;
2679
+ this.serviceWorkerScriptFieldName = "serviceWorkerScript";
2469
2680
  this.contentType = "content-type";
2470
2681
  this.contentTypeJson = "application/json";
2471
2682
  this.contentTypeText = "text/plain";
@@ -2490,17 +2701,18 @@ var AuthManagerImpl = /*#__PURE__*/function () {
2490
2701
  if (_this2.isAuthSessionActive()) {
2491
2702
  throw new Error("Auth session already active. Please call 'await endAuthSession()' and then call 'await beginAuthSession(...)' to start a new auth session.");
2492
2703
  }
2493
- return AuthManagerBrowser_await(_this2.registerAuthServiceWorker(params), function (_this2$registerAuthSe) {
2494
- var newSession = {
2495
- accessToken: undefined,
2496
- accessTokenRefreshHandle: undefined,
2497
- params: params,
2498
- isActive: true,
2499
- authServiceWorker: _this2$registerAuthSe
2500
- };
2501
- AuthSessionState.setSession(newSession);
2502
- return newSession;
2503
- });
2704
+ var newSession = {
2705
+ accessToken: undefined,
2706
+ accessTokenRefreshHandle: undefined,
2707
+ params: params,
2708
+ isActive: true,
2709
+ authServiceWorker: params.serviceWorkerScript !== undefined && _this2.serviceWorkerUtils.canUseServiceWorkers() ? {
2710
+ serviceWorkerScript: params.serviceWorkerScript,
2711
+ serviceWorkerScope: undefined
2712
+ } : undefined
2713
+ };
2714
+ AuthSessionState.setSession(newSession);
2715
+ return newSession;
2504
2716
  })), function (session) {
2505
2717
  // IMPORTANT: must be called outside the above, else re-entrant deadlock will occur.
2506
2718
  return AuthManagerBrowser_awaitIgnored(_this2.refreshAccessToken(session));
@@ -2525,62 +2737,21 @@ var AuthManagerImpl = /*#__PURE__*/function () {
2525
2737
  clearTimeout(session.accessTokenRefreshHandle);
2526
2738
  }
2527
2739
  return AuthManagerBrowser_await(_this4.deleteAccessToken(session.params), function () {
2528
- _this4.setServiceWorkerConfig(session, []); // Prevent service worker from authorizing subsequent requests.
2740
+ return AuthManagerBrowser_invokeIgnored(function () {
2741
+ if (session.authServiceWorker !== undefined) {
2742
+ // Prevent service worker from authorizing subsequent requests.
2743
+ return AuthManagerBrowser_awaitIgnored(_this4.serviceWorkerUtils.sendMessage({
2744
+ type: "SET_BYTESCALE_AUTH_CONFIG",
2745
+ config: []
2746
+ }, session.authServiceWorker, _this4.serviceWorkerScriptFieldName));
2747
+ }
2748
+ });
2529
2749
  });
2530
2750
  })));
2531
2751
  } catch (e) {
2532
2752
  return Promise.reject(e);
2533
2753
  }
2534
2754
  }
2535
- /**
2536
- * Idempotent.
2537
- *
2538
- * Only returns once the service worker has been activated.
2539
- *
2540
- * We don't need to unregister it: we just need to clear the config when auth ends.
2541
- */
2542
- }, {
2543
- key: "registerAuthServiceWorker",
2544
- value: function registerAuthServiceWorker(_ref) {
2545
- var serviceWorkerScript = _ref.serviceWorkerScript;
2546
- try {
2547
- if (serviceWorkerScript === undefined) {
2548
- return undefined;
2549
- }
2550
- var field = "serviceWorkerScript";
2551
- if (!serviceWorkerScript.startsWith("/")) {
2552
- throw new Error("The '".concat(field, "' field must start with a '/' and reference a script at the root of your website."));
2553
- }
2554
- var forwardSlashCount = serviceWorkerScript.split("/").length - 1;
2555
- if (forwardSlashCount > 1) {
2556
- ConsoleUtils.warn("The '".concat(field, "' field should be a root script (e.g. '/bytescale-auth-sw.js'). The Bytescale SDK can only authorize requests originating from webpages that are at the same level as the script or below."));
2557
- }
2558
- return AuthManagerBrowser_catch(function () {
2559
- if ("serviceWorker" in navigator) {
2560
- return AuthManagerBrowser_await(navigator.serviceWorker.register(serviceWorkerScript), function (registration) {
2561
- return registration.active !== null ? registration.active : AuthManagerBrowser_awaitIgnored(new Promise(function (resolve) {
2562
- registration.addEventListener("updatefound", function () {
2563
- var newWorker = registration.installing;
2564
- if (newWorker !== null) {
2565
- newWorker.addEventListener("statechange", function () {
2566
- if (newWorker.state === "activated") {
2567
- resolve(newWorker);
2568
- }
2569
- });
2570
- }
2571
- });
2572
- }));
2573
- }); // Occurs when: (service worker is already registered AND there's been no code changes) OR (service worker was not previously registered).
2574
- } else {
2575
- ConsoleUtils.warn("Service workers not supported by browser. Falling back to Bytescale CDN cookies for auth. These are third-party cookies, which some modern browsers block.");
2576
- }
2577
- }, function (e) {
2578
- throw new Error("Failed to install Bytescale Auth Service Worker (SW). ".concat(e.name, ": ").concat(e.message));
2579
- });
2580
- } catch (e) {
2581
- return Promise.reject(e);
2582
- }
2583
- }
2584
2755
  }, {
2585
2756
  key: "refreshAccessToken",
2586
2757
  value: function refreshAccessToken(session) {
@@ -2601,24 +2772,32 @@ var AuthManagerImpl = /*#__PURE__*/function () {
2601
2772
  // confusion for us in the future (i.e. we may question "do we need to use both together? was there a reason?").
2602
2773
  // Also: if the user has omitted "allowedOrigins" from their JWT, then service worker-based auth is more secure
2603
2774
  // than cookie-based auth, which is another reason to prevent these cookies from being set unless required.
2604
- var setCookie = !_this6.isUsingServiceWorker(session);
2775
+ var setCookie = session.authServiceWorker === undefined;
2605
2776
  return AuthManagerBrowser_await(_this6.setAccessToken(session.params, jwt, setCookie), function (setTokenResult) {
2606
- _this6.setServiceWorkerConfig(session, [{
2607
- headers: [{
2608
- key: "Authorization",
2609
- value: "Bearer ".concat(jwt)
2610
- }],
2611
- expires: Date.now() + setTokenResult.ttlSeconds * 1000,
2612
- urlPrefix: "".concat(_this6.getCdnUrl(session.params), "/").concat(session.params.accountId, "/")
2613
- }]);
2614
- var desiredTtl = setTokenResult.ttlSeconds - _this6.refreshBeforeExpirySeconds;
2615
- timeout = Math.max(desiredTtl, _this6.minJwtTtlSeconds);
2616
- if (desiredTtl !== timeout) {
2617
- ConsoleUtils.warn("JWT expiration is too short: waiting for ".concat(timeout, " seconds before refreshing."));
2618
- }
2619
- // There's no need to print a warning for this: it's OK to silently request the JWT before it expires. Also, this is 24 days in this case!
2620
- timeout = Math.min(timeout, _this6.maxJwtTtlSeconds);
2621
- session.accessToken = setTokenResult.accessToken;
2777
+ return AuthManagerBrowser_invoke(function () {
2778
+ if (session.authServiceWorker !== undefined) {
2779
+ return AuthManagerBrowser_awaitIgnored(_this6.serviceWorkerUtils.sendMessage({
2780
+ type: "SET_BYTESCALE_AUTH_CONFIG",
2781
+ config: [{
2782
+ headers: [{
2783
+ key: "Authorization",
2784
+ value: "Bearer ".concat(jwt)
2785
+ }],
2786
+ expires: Date.now() + setTokenResult.ttlSeconds * 1000,
2787
+ urlPrefix: "".concat(_this6.getCdnUrl(session.params), "/").concat(session.params.accountId, "/")
2788
+ }]
2789
+ }, session.authServiceWorker, _this6.serviceWorkerScriptFieldName));
2790
+ }
2791
+ }, function () {
2792
+ var desiredTtl = setTokenResult.ttlSeconds - _this6.refreshBeforeExpirySeconds;
2793
+ timeout = Math.max(desiredTtl, _this6.minJwtTtlSeconds);
2794
+ if (desiredTtl !== timeout) {
2795
+ ConsoleUtils.warn("JWT expiration is too short: waiting for ".concat(timeout, " seconds before refreshing."));
2796
+ }
2797
+ // There's no need to print a warning for this: it's OK to silently request the JWT before it expires. Also, this is 24 days in this case!
2798
+ timeout = Math.min(timeout, _this6.maxJwtTtlSeconds);
2799
+ session.accessToken = setTokenResult.accessToken;
2800
+ });
2622
2801
  });
2623
2802
  });
2624
2803
  });
@@ -2626,7 +2805,7 @@ var AuthManagerImpl = /*#__PURE__*/function () {
2626
2805
  // 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.
2627
2806
  ConsoleUtils.warn("Unable to refresh JWT access token: ".concat(e));
2628
2807
  });
2629
- }, function (_wasThrown, _result3) {
2808
+ }, function (_wasThrown, _result) {
2630
2809
  session.accessTokenRefreshHandle = window.setTimeout(function () {
2631
2810
  _this6.refreshAccessToken(session).then(function () {},
2632
2811
  // Should not occur, as this method shouldn't throw errors.
@@ -2634,28 +2813,13 @@ var AuthManagerImpl = /*#__PURE__*/function () {
2634
2813
  return ConsoleUtils.error("Unexpected error when refreshing JWT access token: ".concat(e));
2635
2814
  });
2636
2815
  }, timeout * 1000);
2637
- return AuthManagerBrowser_rethrow(_wasThrown, _result3);
2816
+ return AuthManagerBrowser_rethrow(_wasThrown, _result);
2638
2817
  }));
2639
2818
  })));
2640
2819
  } catch (e) {
2641
2820
  return Promise.reject(e);
2642
2821
  }
2643
2822
  }
2644
- }, {
2645
- key: "isUsingServiceWorker",
2646
- value: function isUsingServiceWorker(session) {
2647
- return session.authServiceWorker !== undefined;
2648
- }
2649
- }, {
2650
- key: "setServiceWorkerConfig",
2651
- value: function setServiceWorkerConfig(session, config) {
2652
- var _a;
2653
- var message = {
2654
- type: "SET_CONFIG",
2655
- config: config
2656
- };
2657
- (_a = session.authServiceWorker) === null || _a === void 0 ? void 0 : _a.postMessage(message);
2658
- }
2659
2823
  }, {
2660
2824
  key: "getAccessTokenUrl",
2661
2825
  value: function getAccessTokenUrl(params, setCookie) {
@@ -2750,7 +2914,7 @@ var AuthManagerImpl = /*#__PURE__*/function () {
2750
2914
  /**
2751
2915
  * 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).
2752
2916
  */
2753
- var AuthManager = new AuthManagerImpl();
2917
+ var AuthManager = new AuthManagerImpl(new ServiceWorkerUtils());
2754
2918
  ;// CONCATENATED MODULE: ./src/public/browser/index.ts
2755
2919
 
2756
2920
 
@@ -2379,6 +2379,201 @@ var ConsoleUtils = /*#__PURE__*/function () {
2379
2379
  }]);
2380
2380
  return ConsoleUtils;
2381
2381
  }();
2382
+ ;// CONCATENATED MODULE: ./src/private/ServiceWorkerUtils.ts
2383
+ function ServiceWorkerUtils_typeof(obj) { "@babel/helpers - typeof"; return ServiceWorkerUtils_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, ServiceWorkerUtils_typeof(obj); }
2384
+ function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = ServiceWorkerUtils_unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, 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 normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; }
2385
+ function ServiceWorkerUtils_unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return ServiceWorkerUtils_arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return ServiceWorkerUtils_arrayLikeToArray(o, minLen); }
2386
+ function ServiceWorkerUtils_arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
2387
+ function ServiceWorkerUtils_await(value, then, direct) {
2388
+ if (direct) {
2389
+ return then ? then(value) : value;
2390
+ }
2391
+ if (!value || !value.then) {
2392
+ value = Promise.resolve(value);
2393
+ }
2394
+ return then ? value.then(then) : value;
2395
+ }
2396
+ function ServiceWorkerUtils_catch(body, recover) {
2397
+ try {
2398
+ var result = body();
2399
+ } catch (e) {
2400
+ return recover(e);
2401
+ }
2402
+ if (result && result.then) {
2403
+ return result.then(void 0, recover);
2404
+ }
2405
+ return result;
2406
+ }
2407
+ function ServiceWorkerUtils_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
2408
+ function ServiceWorkerUtils_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, ServiceWorkerUtils_toPropertyKey(descriptor.key), descriptor); } }
2409
+ function ServiceWorkerUtils_createClass(Constructor, protoProps, staticProps) { if (protoProps) ServiceWorkerUtils_defineProperties(Constructor.prototype, protoProps); if (staticProps) ServiceWorkerUtils_defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
2410
+ function ServiceWorkerUtils_toPropertyKey(arg) { var key = ServiceWorkerUtils_toPrimitive(arg, "string"); return ServiceWorkerUtils_typeof(key) === "symbol" ? key : String(key); }
2411
+ function ServiceWorkerUtils_toPrimitive(input, hint) { if (ServiceWorkerUtils_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (ServiceWorkerUtils_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
2412
+
2413
+ var ServiceWorkerUtils = /*#__PURE__*/function () {
2414
+ function ServiceWorkerUtils() {
2415
+ ServiceWorkerUtils_classCallCheck(this, ServiceWorkerUtils);
2416
+ }
2417
+ ServiceWorkerUtils_createClass(ServiceWorkerUtils, [{
2418
+ key: "canUseServiceWorkers",
2419
+ value: function canUseServiceWorkers() {
2420
+ return "serviceWorker" in navigator;
2421
+ }
2422
+ }, {
2423
+ key: "sendMessage",
2424
+ value: function sendMessage(message, config, serviceWorkerScriptFieldName) {
2425
+ try {
2426
+ var _this2 = this;
2427
+ return ServiceWorkerUtils_await(config.serviceWorkerScope !== undefined ? _this2.getActiveServiceWorkerElseRegister(config, message) : _this2.registerServiceWorkerIfSupported(config.serviceWorkerScript, message, serviceWorkerScriptFieldName), function (result) {
2428
+ if (!result.messageSent) {
2429
+ result.serviceWorker.postMessage(message);
2430
+ }
2431
+ return result.config;
2432
+ });
2433
+ } catch (e) {
2434
+ return Promise.reject(e);
2435
+ }
2436
+ }
2437
+ }, {
2438
+ key: "registerServiceWorkerIfSupported",
2439
+ value: function registerServiceWorkerIfSupported(serviceWorkerScript, init, serviceWorkerScriptFieldName) {
2440
+ try {
2441
+ var _this4 = this;
2442
+ if (!serviceWorkerScript.startsWith("/")) {
2443
+ throw new Error("The '".concat(serviceWorkerScriptFieldName, "' field must start with a '/' and reference a script at the root of your website."));
2444
+ }
2445
+ var forwardSlashCount = serviceWorkerScript.split("/").length - 1;
2446
+ if (forwardSlashCount > 1) {
2447
+ ConsoleUtils.warn("The '".concat(serviceWorkerScriptFieldName, "' field should be a root script (e.g. '/script.js'). The Bytescale SDK can only authorize requests originating from webpages that are at the same level as the script or below."));
2448
+ }
2449
+ return ServiceWorkerUtils_await(_this4.registerAuthServiceWorker(serviceWorkerScript, init));
2450
+ } catch (e) {
2451
+ return Promise.reject(e);
2452
+ }
2453
+ }
2454
+ }, {
2455
+ key: "getActiveServiceWorkerElseRegister",
2456
+ value: function getActiveServiceWorkerElseRegister(config, init) {
2457
+ try {
2458
+ var _this6 = this;
2459
+ return ServiceWorkerUtils_await(_this6.getActiveServiceWorker(config.serviceWorkerScope), function (serviceWorker) {
2460
+ return serviceWorker !== undefined ? {
2461
+ serviceWorker: serviceWorker,
2462
+ messageSent: false,
2463
+ config: config
2464
+ } : ServiceWorkerUtils_await(_this6.registerAuthServiceWorker(config.serviceWorkerScript, init));
2465
+ });
2466
+ } catch (e) {
2467
+ return Promise.reject(e);
2468
+ }
2469
+ }
2470
+ /**
2471
+ * Idempotent.
2472
+ *
2473
+ * Only returns once the service worker has been activated.
2474
+ *
2475
+ * We don't need to unregister it: we just need to clear the config when auth ends.
2476
+ */
2477
+ }, {
2478
+ key: "registerAuthServiceWorker",
2479
+ value: function registerAuthServiceWorker(serviceWorkerScript, init) {
2480
+ try {
2481
+ var _this8 = this;
2482
+ return ServiceWorkerUtils_catch(function () {
2483
+ return ServiceWorkerUtils_await(navigator.serviceWorker.register(serviceWorkerScript), function (registration) {
2484
+ return ServiceWorkerUtils_await(_this8.waitForActiveServiceWorker(registration, init), function (_ref) {
2485
+ var serviceWorker = _ref.serviceWorker,
2486
+ messageSent = _ref.messageSent;
2487
+ return {
2488
+ serviceWorker: serviceWorker,
2489
+ messageSent: messageSent,
2490
+ config: {
2491
+ serviceWorkerScript: serviceWorkerScript,
2492
+ serviceWorkerScope: registration.scope
2493
+ }
2494
+ };
2495
+ });
2496
+ });
2497
+ }, function (e) {
2498
+ throw new Error("Failed to install Bytescale Service Worker (SW). ".concat(e.name, ": ").concat(e.message));
2499
+ });
2500
+ } catch (e) {
2501
+ return Promise.reject(e);
2502
+ }
2503
+ }
2504
+ }, {
2505
+ key: "waitForActiveServiceWorker",
2506
+ value: function waitForActiveServiceWorker(registration, init) {
2507
+ try {
2508
+ // If the service worker is already active, return it.
2509
+ if (registration.active !== null) {
2510
+ return {
2511
+ serviceWorker: registration.active,
2512
+ messageSent: false
2513
+ };
2514
+ }
2515
+ // Service worker has not finished installing, which means we've just started installing a new one, so send the INIT
2516
+ // message to it, as it will be waiting for it to complete its install phase.
2517
+ var messageSent;
2518
+ if (registration.installing !== null) {
2519
+ messageSent = true;
2520
+ registration.installing.postMessage(init);
2521
+ } else {
2522
+ messageSent = false;
2523
+ }
2524
+ // Wait for the service worker to become active.
2525
+ return ServiceWorkerUtils_await(new Promise(function (resolve, reject) {
2526
+ var _a, _b;
2527
+ var serviceWorker = (_b = (_a = registration.installing) !== null && _a !== void 0 ? _a : registration.waiting) !== null && _b !== void 0 ? _b : undefined;
2528
+ if (serviceWorker !== undefined) {
2529
+ var stateChangeHandler = function stateChangeHandler(e) {
2530
+ var sw = e.target;
2531
+ if (sw.state === "activated") {
2532
+ serviceWorker.removeEventListener("statechange", stateChangeHandler);
2533
+ resolve({
2534
+ messageSent: messageSent,
2535
+ serviceWorker: sw
2536
+ });
2537
+ }
2538
+ };
2539
+ serviceWorker.addEventListener("statechange", stateChangeHandler);
2540
+ } else {
2541
+ // If there's no installing or waiting service worker, reject.
2542
+ reject(new Error("No service worker is installing or waiting."));
2543
+ }
2544
+ }));
2545
+ } catch (e) {
2546
+ return Promise.reject(e);
2547
+ }
2548
+ }
2549
+ }, {
2550
+ key: "getActiveServiceWorker",
2551
+ value: function getActiveServiceWorker(serviceWorkerScope) {
2552
+ try {
2553
+ return ServiceWorkerUtils_await(navigator.serviceWorker.getRegistrations(), function (registrations) {
2554
+ var _iterator = _createForOfIteratorHelper(registrations),
2555
+ _step;
2556
+ try {
2557
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
2558
+ var registration = _step.value;
2559
+ if (registration.active !== null && registration.scope === serviceWorkerScope) {
2560
+ return registration.active;
2561
+ }
2562
+ }
2563
+ } catch (err) {
2564
+ _iterator.e(err);
2565
+ } finally {
2566
+ _iterator.f();
2567
+ }
2568
+ return undefined;
2569
+ });
2570
+ } catch (e) {
2571
+ return Promise.reject(e);
2572
+ }
2573
+ }
2574
+ }]);
2575
+ return ServiceWorkerUtils;
2576
+ }();
2382
2577
  ;// CONCATENATED MODULE: ./src/public/browser/AuthManagerBrowser.ts
2383
2578
  function AuthManagerBrowser_typeof(obj) { "@babel/helpers - typeof"; return AuthManagerBrowser_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, AuthManagerBrowser_typeof(obj); }
2384
2579
  function AuthManagerBrowser_defineProperty(obj, key, value) { key = AuthManagerBrowser_toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
@@ -2409,6 +2604,19 @@ function AuthManagerBrowser_async(f) {
2409
2604
  }
2410
2605
  };
2411
2606
  }
2607
+ function AuthManagerBrowser_invokeIgnored(body) {
2608
+ var result = body();
2609
+ if (result && result.then) {
2610
+ return result.then(AuthManagerBrowser_empty);
2611
+ }
2612
+ }
2613
+ function AuthManagerBrowser_invoke(body, then) {
2614
+ var result = body();
2615
+ if (result && result.then) {
2616
+ return result.then(then);
2617
+ }
2618
+ return then(result);
2619
+ }
2412
2620
  function AuthManagerBrowser_catch(body, recover) {
2413
2621
  try {
2414
2622
  var result = body();
@@ -2448,9 +2656,12 @@ function AuthManagerBrowser_toPrimitive(input, hint) { if (AuthManagerBrowser_ty
2448
2656
 
2449
2657
 
2450
2658
 
2659
+
2451
2660
  var AuthManagerImpl = /*#__PURE__*/function () {
2452
- function AuthManagerImpl() {
2661
+ function AuthManagerImpl(serviceWorkerUtils) {
2453
2662
  AuthManagerBrowser_classCallCheck(this, AuthManagerImpl);
2663
+ this.serviceWorkerUtils = serviceWorkerUtils;
2664
+ this.serviceWorkerScriptFieldName = "serviceWorkerScript";
2454
2665
  this.contentType = "content-type";
2455
2666
  this.contentTypeJson = "application/json";
2456
2667
  this.contentTypeText = "text/plain";
@@ -2475,17 +2686,18 @@ var AuthManagerImpl = /*#__PURE__*/function () {
2475
2686
  if (_this2.isAuthSessionActive()) {
2476
2687
  throw new Error("Auth session already active. Please call 'await endAuthSession()' and then call 'await beginAuthSession(...)' to start a new auth session.");
2477
2688
  }
2478
- return AuthManagerBrowser_await(_this2.registerAuthServiceWorker(params), function (_this2$registerAuthSe) {
2479
- var newSession = {
2480
- accessToken: undefined,
2481
- accessTokenRefreshHandle: undefined,
2482
- params: params,
2483
- isActive: true,
2484
- authServiceWorker: _this2$registerAuthSe
2485
- };
2486
- AuthSessionState.setSession(newSession);
2487
- return newSession;
2488
- });
2689
+ var newSession = {
2690
+ accessToken: undefined,
2691
+ accessTokenRefreshHandle: undefined,
2692
+ params: params,
2693
+ isActive: true,
2694
+ authServiceWorker: params.serviceWorkerScript !== undefined && _this2.serviceWorkerUtils.canUseServiceWorkers() ? {
2695
+ serviceWorkerScript: params.serviceWorkerScript,
2696
+ serviceWorkerScope: undefined
2697
+ } : undefined
2698
+ };
2699
+ AuthSessionState.setSession(newSession);
2700
+ return newSession;
2489
2701
  })), function (session) {
2490
2702
  // IMPORTANT: must be called outside the above, else re-entrant deadlock will occur.
2491
2703
  return AuthManagerBrowser_awaitIgnored(_this2.refreshAccessToken(session));
@@ -2510,62 +2722,21 @@ var AuthManagerImpl = /*#__PURE__*/function () {
2510
2722
  clearTimeout(session.accessTokenRefreshHandle);
2511
2723
  }
2512
2724
  return AuthManagerBrowser_await(_this4.deleteAccessToken(session.params), function () {
2513
- _this4.setServiceWorkerConfig(session, []); // Prevent service worker from authorizing subsequent requests.
2725
+ return AuthManagerBrowser_invokeIgnored(function () {
2726
+ if (session.authServiceWorker !== undefined) {
2727
+ // Prevent service worker from authorizing subsequent requests.
2728
+ return AuthManagerBrowser_awaitIgnored(_this4.serviceWorkerUtils.sendMessage({
2729
+ type: "SET_BYTESCALE_AUTH_CONFIG",
2730
+ config: []
2731
+ }, session.authServiceWorker, _this4.serviceWorkerScriptFieldName));
2732
+ }
2733
+ });
2514
2734
  });
2515
2735
  })));
2516
2736
  } catch (e) {
2517
2737
  return Promise.reject(e);
2518
2738
  }
2519
2739
  }
2520
- /**
2521
- * Idempotent.
2522
- *
2523
- * Only returns once the service worker has been activated.
2524
- *
2525
- * We don't need to unregister it: we just need to clear the config when auth ends.
2526
- */
2527
- }, {
2528
- key: "registerAuthServiceWorker",
2529
- value: function registerAuthServiceWorker(_ref) {
2530
- var serviceWorkerScript = _ref.serviceWorkerScript;
2531
- try {
2532
- if (serviceWorkerScript === undefined) {
2533
- return undefined;
2534
- }
2535
- var field = "serviceWorkerScript";
2536
- if (!serviceWorkerScript.startsWith("/")) {
2537
- throw new Error("The '".concat(field, "' field must start with a '/' and reference a script at the root of your website."));
2538
- }
2539
- var forwardSlashCount = serviceWorkerScript.split("/").length - 1;
2540
- if (forwardSlashCount > 1) {
2541
- ConsoleUtils.warn("The '".concat(field, "' field should be a root script (e.g. '/bytescale-auth-sw.js'). The Bytescale SDK can only authorize requests originating from webpages that are at the same level as the script or below."));
2542
- }
2543
- return AuthManagerBrowser_catch(function () {
2544
- if ("serviceWorker" in navigator) {
2545
- return AuthManagerBrowser_await(navigator.serviceWorker.register(serviceWorkerScript), function (registration) {
2546
- return registration.active !== null ? registration.active : AuthManagerBrowser_awaitIgnored(new Promise(function (resolve) {
2547
- registration.addEventListener("updatefound", function () {
2548
- var newWorker = registration.installing;
2549
- if (newWorker !== null) {
2550
- newWorker.addEventListener("statechange", function () {
2551
- if (newWorker.state === "activated") {
2552
- resolve(newWorker);
2553
- }
2554
- });
2555
- }
2556
- });
2557
- }));
2558
- }); // Occurs when: (service worker is already registered AND there's been no code changes) OR (service worker was not previously registered).
2559
- } else {
2560
- ConsoleUtils.warn("Service workers not supported by browser. Falling back to Bytescale CDN cookies for auth. These are third-party cookies, which some modern browsers block.");
2561
- }
2562
- }, function (e) {
2563
- throw new Error("Failed to install Bytescale Auth Service Worker (SW). ".concat(e.name, ": ").concat(e.message));
2564
- });
2565
- } catch (e) {
2566
- return Promise.reject(e);
2567
- }
2568
- }
2569
2740
  }, {
2570
2741
  key: "refreshAccessToken",
2571
2742
  value: function refreshAccessToken(session) {
@@ -2586,24 +2757,32 @@ var AuthManagerImpl = /*#__PURE__*/function () {
2586
2757
  // confusion for us in the future (i.e. we may question "do we need to use both together? was there a reason?").
2587
2758
  // Also: if the user has omitted "allowedOrigins" from their JWT, then service worker-based auth is more secure
2588
2759
  // than cookie-based auth, which is another reason to prevent these cookies from being set unless required.
2589
- var setCookie = !_this6.isUsingServiceWorker(session);
2760
+ var setCookie = session.authServiceWorker === undefined;
2590
2761
  return AuthManagerBrowser_await(_this6.setAccessToken(session.params, jwt, setCookie), function (setTokenResult) {
2591
- _this6.setServiceWorkerConfig(session, [{
2592
- headers: [{
2593
- key: "Authorization",
2594
- value: "Bearer ".concat(jwt)
2595
- }],
2596
- expires: Date.now() + setTokenResult.ttlSeconds * 1000,
2597
- urlPrefix: "".concat(_this6.getCdnUrl(session.params), "/").concat(session.params.accountId, "/")
2598
- }]);
2599
- var desiredTtl = setTokenResult.ttlSeconds - _this6.refreshBeforeExpirySeconds;
2600
- timeout = Math.max(desiredTtl, _this6.minJwtTtlSeconds);
2601
- if (desiredTtl !== timeout) {
2602
- ConsoleUtils.warn("JWT expiration is too short: waiting for ".concat(timeout, " seconds before refreshing."));
2603
- }
2604
- // There's no need to print a warning for this: it's OK to silently request the JWT before it expires. Also, this is 24 days in this case!
2605
- timeout = Math.min(timeout, _this6.maxJwtTtlSeconds);
2606
- session.accessToken = setTokenResult.accessToken;
2762
+ return AuthManagerBrowser_invoke(function () {
2763
+ if (session.authServiceWorker !== undefined) {
2764
+ return AuthManagerBrowser_awaitIgnored(_this6.serviceWorkerUtils.sendMessage({
2765
+ type: "SET_BYTESCALE_AUTH_CONFIG",
2766
+ config: [{
2767
+ headers: [{
2768
+ key: "Authorization",
2769
+ value: "Bearer ".concat(jwt)
2770
+ }],
2771
+ expires: Date.now() + setTokenResult.ttlSeconds * 1000,
2772
+ urlPrefix: "".concat(_this6.getCdnUrl(session.params), "/").concat(session.params.accountId, "/")
2773
+ }]
2774
+ }, session.authServiceWorker, _this6.serviceWorkerScriptFieldName));
2775
+ }
2776
+ }, function () {
2777
+ var desiredTtl = setTokenResult.ttlSeconds - _this6.refreshBeforeExpirySeconds;
2778
+ timeout = Math.max(desiredTtl, _this6.minJwtTtlSeconds);
2779
+ if (desiredTtl !== timeout) {
2780
+ ConsoleUtils.warn("JWT expiration is too short: waiting for ".concat(timeout, " seconds before refreshing."));
2781
+ }
2782
+ // There's no need to print a warning for this: it's OK to silently request the JWT before it expires. Also, this is 24 days in this case!
2783
+ timeout = Math.min(timeout, _this6.maxJwtTtlSeconds);
2784
+ session.accessToken = setTokenResult.accessToken;
2785
+ });
2607
2786
  });
2608
2787
  });
2609
2788
  });
@@ -2611,7 +2790,7 @@ var AuthManagerImpl = /*#__PURE__*/function () {
2611
2790
  // 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.
2612
2791
  ConsoleUtils.warn("Unable to refresh JWT access token: ".concat(e));
2613
2792
  });
2614
- }, function (_wasThrown, _result3) {
2793
+ }, function (_wasThrown, _result) {
2615
2794
  session.accessTokenRefreshHandle = window.setTimeout(function () {
2616
2795
  _this6.refreshAccessToken(session).then(function () {},
2617
2796
  // Should not occur, as this method shouldn't throw errors.
@@ -2619,28 +2798,13 @@ var AuthManagerImpl = /*#__PURE__*/function () {
2619
2798
  return ConsoleUtils.error("Unexpected error when refreshing JWT access token: ".concat(e));
2620
2799
  });
2621
2800
  }, timeout * 1000);
2622
- return AuthManagerBrowser_rethrow(_wasThrown, _result3);
2801
+ return AuthManagerBrowser_rethrow(_wasThrown, _result);
2623
2802
  }));
2624
2803
  })));
2625
2804
  } catch (e) {
2626
2805
  return Promise.reject(e);
2627
2806
  }
2628
2807
  }
2629
- }, {
2630
- key: "isUsingServiceWorker",
2631
- value: function isUsingServiceWorker(session) {
2632
- return session.authServiceWorker !== undefined;
2633
- }
2634
- }, {
2635
- key: "setServiceWorkerConfig",
2636
- value: function setServiceWorkerConfig(session, config) {
2637
- var _a;
2638
- var message = {
2639
- type: "SET_CONFIG",
2640
- config: config
2641
- };
2642
- (_a = session.authServiceWorker) === null || _a === void 0 ? void 0 : _a.postMessage(message);
2643
- }
2644
2808
  }, {
2645
2809
  key: "getAccessTokenUrl",
2646
2810
  value: function getAccessTokenUrl(params, setCookie) {
@@ -2735,7 +2899,7 @@ var AuthManagerImpl = /*#__PURE__*/function () {
2735
2899
  /**
2736
2900
  * 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).
2737
2901
  */
2738
- var AuthManager = new AuthManagerImpl();
2902
+ var AuthManager = new AuthManagerImpl(new ServiceWorkerUtils());
2739
2903
  ;// CONCATENATED MODULE: ./src/public/browser/index.ts
2740
2904
 
2741
2905
 
@@ -0,0 +1,17 @@
1
+ import { ServiceWorkerConfig, ServiceWorkerConfigInitialized } from "./model/ServiceWorkerConfig";
2
+ export declare class ServiceWorkerUtils<TMessage> {
3
+ canUseServiceWorkers(): boolean;
4
+ sendMessage(message: TMessage, config: ServiceWorkerConfig, serviceWorkerScriptFieldName: string): Promise<ServiceWorkerConfigInitialized>;
5
+ private registerServiceWorkerIfSupported;
6
+ private getActiveServiceWorkerElseRegister;
7
+ /**
8
+ * Idempotent.
9
+ *
10
+ * Only returns once the service worker has been activated.
11
+ *
12
+ * We don't need to unregister it: we just need to clear the config when auth ends.
13
+ */
14
+ private registerAuthServiceWorker;
15
+ private waitForActiveServiceWorker;
16
+ private getActiveServiceWorker;
17
+ }
@@ -1,5 +1,11 @@
1
1
  import { AuthSwConfigDto } from "./AuthSwConfigDto";
2
2
  export interface AuthSwSetConfigDto {
3
3
  config: AuthSwConfigDto;
4
- type: "SET_CONFIG";
4
+ /**
5
+ * We use a specific name for this type, since you can only register one service worker per scope, meaning it's
6
+ * possible the user will want to use their own service worker, which means we'll need to support having the Bytescale
7
+ * Auth Service Worker being a component of the user's service worker. Thus, we use a specific name to avoid conflict
8
+ * with the user's events.
9
+ */
10
+ type: "SET_BYTESCALE_AUTH_CONFIG";
5
11
  }
@@ -1,8 +1,9 @@
1
1
  import { BeginAuthSessionParams } from "./AuthManagerInterface";
2
+ import { ServiceWorkerConfig } from "./ServiceWorkerConfig";
2
3
  export interface AuthSession {
3
4
  accessToken: string | undefined;
4
5
  accessTokenRefreshHandle: number | undefined;
5
- authServiceWorker: ServiceWorker | undefined;
6
+ authServiceWorker: ServiceWorkerConfig | undefined;
6
7
  isActive: boolean;
7
8
  params: BeginAuthSessionParams;
8
9
  }
@@ -0,0 +1,9 @@
1
+ export declare type ServiceWorkerConfig = ServiceWorkerConfigUninitialized | ServiceWorkerConfigInitialized;
2
+ export interface ServiceWorkerConfigUninitialized {
3
+ serviceWorkerScope: undefined;
4
+ serviceWorkerScript: string;
5
+ }
6
+ export interface ServiceWorkerConfigInitialized {
7
+ serviceWorkerScope: string;
8
+ serviceWorkerScript: string;
9
+ }
@@ -0,0 +1,6 @@
1
+ import { ServiceWorkerConfigInitialized } from "./ServiceWorkerConfig";
2
+ export interface ServiceWorkerInitStatus {
3
+ config: ServiceWorkerConfigInitialized;
4
+ messageSent: boolean;
5
+ serviceWorker: ServiceWorker;
6
+ }
@@ -1,6 +1,10 @@
1
1
  import { AuthManagerInterface, BeginAuthSessionParams } from "../../private/model/AuthManagerInterface";
2
+ import { AuthSwSetConfigDto } from "../../private/dtos/AuthSwSetConfigDto";
3
+ import { ServiceWorkerUtils } from "../../private/ServiceWorkerUtils";
2
4
  declare class AuthManagerImpl implements AuthManagerInterface {
5
+ private readonly serviceWorkerUtils;
3
6
  private readonly authSessionMutex;
7
+ private readonly serviceWorkerScriptFieldName;
4
8
  private readonly contentType;
5
9
  private readonly contentTypeJson;
6
10
  private readonly contentTypeText;
@@ -8,21 +12,11 @@ declare class AuthManagerImpl implements AuthManagerInterface {
8
12
  private readonly maxJwtTtlSeconds;
9
13
  private readonly retryAuthAfterErrorSeconds;
10
14
  private readonly refreshBeforeExpirySeconds;
11
- constructor();
15
+ constructor(serviceWorkerUtils: ServiceWorkerUtils<AuthSwSetConfigDto>);
12
16
  isAuthSessionActive(): boolean;
13
17
  beginAuthSession(params: BeginAuthSessionParams): Promise<void>;
14
18
  endAuthSession(): Promise<void>;
15
- /**
16
- * Idempotent.
17
- *
18
- * Only returns once the service worker has been activated.
19
- *
20
- * We don't need to unregister it: we just need to clear the config when auth ends.
21
- */
22
- private registerAuthServiceWorker;
23
19
  private refreshAccessToken;
24
- private isUsingServiceWorker;
25
- private setServiceWorkerConfig;
26
20
  private getAccessTokenUrl;
27
21
  private getCdnUrl;
28
22
  private deleteAccessToken;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bytescale/sdk",
3
- "version": "3.17.0",
3
+ "version": "3.19.0",
4
4
  "description": "Bytescale JavaScript SDK",
5
5
  "author": "Bytescale <hello@bytescale.com> (https://www.bytescale.com)",
6
6
  "license": "MIT",