@codenkay/video-nsgplayer-core 5.1.0 → 5.3.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.
package/dist/index.js CHANGED
@@ -12,9 +12,13 @@ var PlayerErrorCode = /* @__PURE__ */ ((PlayerErrorCode2) => {
12
12
  PlayerErrorCode2["PLAYBACK_ERROR"] = "PLAYBACK_ERROR";
13
13
  PlayerErrorCode2["UNSUPPORTED_BROWSER"] = "UNSUPPORTED_BROWSER";
14
14
  PlayerErrorCode2["AUTOPLAY_BLOCKED"] = "AUTOPLAY_BLOCKED";
15
+ PlayerErrorCode2["PLATFORM_IN_USE"] = "PLATFORM_IN_USE";
16
+ PlayerErrorCode2["PLAYBACK_NOT_READY"] = "PLAYBACK_NOT_READY";
15
17
  PlayerErrorCode2["UNKNOWN"] = "UNKNOWN";
16
18
  return PlayerErrorCode2;
17
19
  })(PlayerErrorCode || {});
20
+ var PLATFORM_IN_USE = "PLATFORM_IN_USE";
21
+ var PLAYBACK_NOT_READY = "PLAYBACK_NOT_READY";
18
22
  function createPlayerError(code, message, options) {
19
23
  return {
20
24
  code,
@@ -146,7 +150,8 @@ var AuthManager = class {
146
150
 
147
151
  // src/config/defaults.ts
148
152
  var PLAYBACK_RATES = [0.5, 0.75, 1, 1.25, 1.5, 2];
149
- var PACKAGE_VERSION = "3.0.3";
153
+ var DEFAULT_PLAYBACK_REFRESH_INTERVAL_MS = 45e3;
154
+ var PACKAGE_VERSION = "5.3.0";
150
155
  var DEFAULT_PLAYER_BEHAVIOR = {
151
156
  autoplay: true,
152
157
  startMuted: true,
@@ -218,7 +223,12 @@ var DEFAULT_PLAYER_CONFIG = {
218
223
  enableWorker: true,
219
224
  // VOD + AES-128: LL mode causes ABR thrash → bufferAppendError on MSE.
220
225
  lowLatencyMode: false,
221
- backBufferLength: 90,
226
+ // Match a smooth encrypted VOD: 30s forward target, 60s ceiling,
227
+ // 20MB cap, and a short back buffer so MSE does not stall when full.
228
+ backBufferLength: 30,
229
+ maxBufferLength: 30,
230
+ maxMaxBufferLength: 60,
231
+ maxBufferSize: 20 * 1024 * 1024,
222
232
  fatalRecoveryLimit: 3
223
233
  }
224
234
  },
@@ -243,7 +253,8 @@ var SKIP_DEEP_SCAN_KEYS = /* @__PURE__ */ new Set([
243
253
  "refreshsource",
244
254
  "keyproxyurlbuilder",
245
255
  "mediaproxyurlbuilder",
246
- "getkeyaccesstoken"
256
+ "getkeyaccesstoken",
257
+ "onnativeauthupdate"
247
258
  ]);
248
259
  var SECRET_SCAN_MAX_DEPTH = 32;
249
260
  function isPlainObject(value) {
@@ -330,7 +341,10 @@ function mergePlayerConfig(partial) {
330
341
  mediaProxyUrlBuilder: partial?.streaming?.mediaProxyUrlBuilder,
331
342
  keyProxyUrlBuilder: partial?.streaming?.keyProxyUrlBuilder,
332
343
  getKeyAccessToken: partial?.streaming?.getKeyAccessToken,
333
- keyProxyMaxFailures: partial?.streaming?.keyProxyMaxFailures
344
+ keyProxyMaxFailures: partial?.streaming?.keyProxyMaxFailures,
345
+ useAppexHlsProfile: partial?.streaming?.useAppexHlsProfile,
346
+ nativeSessionMode: partial?.streaming?.nativeSessionMode,
347
+ onNativeAuthUpdate: partial?.streaming?.onNativeAuthUpdate
334
348
  },
335
349
  logging: { ...DEFAULT_PLAYER_CONFIG.logging, ...partial?.logging },
336
350
  debug: { ...DEFAULT_PLAYER_CONFIG.debug, ...partial?.debug },
@@ -636,6 +650,7 @@ var RefreshManager = class {
636
650
  constructor(options) {
637
651
  this.options = options;
638
652
  this.timer = null;
653
+ this.intervalTimer = null;
639
654
  this.coalesceTimer = null;
640
655
  this.inFlight = false;
641
656
  this.consecutiveFailures = 0;
@@ -644,6 +659,7 @@ var RefreshManager = class {
644
659
  }
645
660
  start(initialExpiresAt) {
646
661
  this.schedule(initialExpiresAt);
662
+ this.armInterval();
647
663
  }
648
664
  requestRenew(reason = "frag_error") {
649
665
  if (this.stopped || this.options.isDestroyed()) return;
@@ -659,8 +675,10 @@ var RefreshManager = class {
659
675
  stop() {
660
676
  this.stopped = true;
661
677
  if (this.timer) clearTimeout(this.timer);
678
+ if (this.intervalTimer) clearTimeout(this.intervalTimer);
662
679
  if (this.coalesceTimer) clearTimeout(this.coalesceTimer);
663
680
  this.timer = null;
681
+ this.intervalTimer = null;
664
682
  this.coalesceTimer = null;
665
683
  }
666
684
  schedule(expiresAt) {
@@ -674,13 +692,25 @@ var RefreshManager = class {
674
692
  void this.renew("proactive");
675
693
  }, delay);
676
694
  }
695
+ /** Rotate the token on a fixed cadence. The loader reads the store live. */
696
+ armInterval() {
697
+ const interval = this.options.refreshIntervalMs;
698
+ if (!interval || interval < 5e3 || this.stopped) return;
699
+ if (this.intervalTimer) clearTimeout(this.intervalTimer);
700
+ this.intervalTimer = setTimeout(() => {
701
+ this.intervalTimer = null;
702
+ if (this.stopped) return;
703
+ void this.renew("proactive");
704
+ this.armInterval();
705
+ }, interval);
706
+ }
677
707
  async renew(reason) {
678
708
  if (this.stopped || this.options.isDestroyed() || this.inFlight) {
679
709
  if (this.inFlight) this.pendingReason = reason;
680
710
  return;
681
711
  }
682
712
  this.inFlight = true;
683
- this.options.onRenewing?.();
713
+ this.options.onRenewing?.(reason);
684
714
  try {
685
715
  await this.options.authManager.ensureToken({
686
716
  reason: reason === "proactive" ? "expiring" : "unauthorized",
@@ -691,7 +721,7 @@ var RefreshManager = class {
691
721
  reason: reason === "proactive" ? "expiring" : reason === "manual" ? "manual" : "auth_error"
692
722
  });
693
723
  this.consecutiveFailures = 0;
694
- this.options.onRenewed?.(source.expiresAt);
724
+ this.options.onRenewed?.(source.expiresAt, reason);
695
725
  this.schedule(source.expiresAt);
696
726
  this.options.logger.debug("Playback source renewed", { reason });
697
727
  } catch (error) {
@@ -789,6 +819,26 @@ function isSameOriginHttpUrl(value, baseOrigin) {
789
819
  }
790
820
  }
791
821
 
822
+ // src/config/hlsProfiles.ts
823
+ function hlsConfig(isLive = false) {
824
+ return {
825
+ maxBufferLength: isLive ? 24 : 60,
826
+ maxMaxBufferLength: isLive ? 40 : 120,
827
+ maxBufferSize: 32 * 1024 * 1024,
828
+ backBufferLength: 30,
829
+ startLevel: 0,
830
+ abrEwmaDefaultEstimate: 5e5,
831
+ abrBandWidthFactor: 0.7,
832
+ abrBandWidthUpFactor: 0.55,
833
+ maxStarvationDelay: 2,
834
+ lowLatencyMode: false,
835
+ liveSyncDurationCount: 4,
836
+ liveMaxLatencyDurationCount: 8,
837
+ maxLiveSyncPlaybackRate: 1.1
838
+ };
839
+ }
840
+ var appexHlsConfig = hlsConfig;
841
+
792
842
  // src/streaming/authParamsLoader.ts
793
843
  var ENC_KEY_PATH_RE = /enc\.key$/i;
794
844
  var BUILTIN_LOADER_NAMES = /* @__PURE__ */ new Set(["XhrLoader", "FetchLoader"]);
@@ -1338,7 +1388,7 @@ var HlsEngine = class {
1338
1388
  const {
1339
1389
  videoEl,
1340
1390
  authParams,
1341
- hlsConfig,
1391
+ hlsConfig: hlsConfig2,
1342
1392
  callbacks,
1343
1393
  videoId,
1344
1394
  keyProxyUrlBuilder,
@@ -1351,27 +1401,29 @@ var HlsEngine = class {
1351
1401
  getKeyAccessToken,
1352
1402
  keyProxyMaxFailures: this.options.keyProxyMaxFailures
1353
1403
  });
1354
- const enableWorker = hlsConfig.enableWorker && !isGeckoBrowser();
1355
- if (hlsConfig.enableWorker && !enableWorker) {
1404
+ const enableWorker = hlsConfig2.enableWorker && !isGeckoBrowser();
1405
+ if (hlsConfig2.enableWorker && !enableWorker) {
1356
1406
  this.options.logger.warn(
1357
1407
  "Disabling hls.js worker on Firefox to avoid MSE bufferAppendError"
1358
1408
  );
1359
1409
  }
1410
+ const startPosition = this.options.startPosition;
1360
1411
  this.hls = new Hls({
1361
1412
  enableWorker,
1362
1413
  // LL mode on short encrypted VOD drives aggressive ABR thrash → MSE errors.
1363
- lowLatencyMode: hlsConfig.lowLatencyMode,
1364
- backBufferLength: hlsConfig.backBufferLength,
1365
- // Stabilize ABR: avoid first-frag-only bandwidth test that immediately
1366
- // hops levels on single-segment Appextech VODs (HAR showed truncated
1367
- // 720p body vs Content-Length during level switches).
1414
+ lowLatencyMode: hlsConfig2.lowLatencyMode,
1415
+ backBufferLength: hlsConfig2.backBufferLength,
1416
+ maxBufferLength: hlsConfig2.maxBufferLength,
1417
+ maxMaxBufferLength: hlsConfig2.maxMaxBufferLength,
1418
+ maxBufferSize: hlsConfig2.maxBufferSize,
1419
+ startPosition: typeof startPosition === "number" && startPosition > 0 ? startPosition : -1,
1420
+ // A first-fragment bandwidth probe on short encrypted VODs truncates
1421
+ // the body and immediately hops levels. ABR itself stays on hls.js
1422
+ // defaults so a long VOD is not held on the lowest rung.
1368
1423
  testBandwidth: false,
1369
- abrEwmaDefaultEstimate: 5e5,
1370
- abrBandWidthFactor: 0.8,
1371
- abrBandWidthUpFactor: 0.5,
1372
- maxStarvationDelay: 4,
1373
- capLevelToPlayerSize: true,
1374
1424
  startLevel: -1,
1425
+ // Opt-in Appextech profile (buffers, ABR, live sync). Wins for its keys.
1426
+ ...this.options.useAppexHlsProfile ? appexHlsConfig(Boolean(this.options.isLive)) : {},
1375
1427
  loader
1376
1428
  });
1377
1429
  this.hls.attachMedia(videoEl);
@@ -1410,7 +1462,7 @@ var HlsEngine = class {
1410
1462
  }
1411
1463
  handleHlsError(Hls, data) {
1412
1464
  if (this.destroyed) return;
1413
- const { callbacks, hlsConfig } = this.options;
1465
+ const { callbacks, hlsConfig: hlsConfig2 } = this.options;
1414
1466
  const status = data.response?.code;
1415
1467
  const authFailure = isAuthHttpStatus(status);
1416
1468
  if (data.details === Hls.ErrorDetails.KEY_LOAD_ERROR) {
@@ -1442,7 +1494,7 @@ var HlsEngine = class {
1442
1494
  }
1443
1495
  if (data.type === Hls.ErrorTypes.NETWORK_ERROR) {
1444
1496
  this.networkRecoveryCount += 1;
1445
- if (this.networkRecoveryCount <= hlsConfig.fatalRecoveryLimit) {
1497
+ if (this.networkRecoveryCount <= hlsConfig2.fatalRecoveryLimit) {
1446
1498
  if (authFailure) {
1447
1499
  callbacks.onAuthRecoveryNeeded?.("fatal_network");
1448
1500
  }
@@ -1452,7 +1504,7 @@ var HlsEngine = class {
1452
1504
  }
1453
1505
  if (data.type === Hls.ErrorTypes.MEDIA_ERROR) {
1454
1506
  this.mediaRecoveryCount += 1;
1455
- if (this.mediaRecoveryCount > hlsConfig.fatalRecoveryLimit) {
1507
+ if (this.mediaRecoveryCount > hlsConfig2.fatalRecoveryLimit) {
1456
1508
  callbacks.onFatalError?.(data.details || "Fatal HLS error");
1457
1509
  return;
1458
1510
  }
@@ -1478,35 +1530,35 @@ var HlsEngine = class {
1478
1530
  }
1479
1531
  }
1480
1532
  clampStartPosition(raw, videoEl) {
1481
- let t = Math.max(0, raw);
1533
+ const t = Math.max(0, raw);
1482
1534
  const duration = videoEl.duration;
1483
1535
  if (Number.isFinite(duration) && duration > 0) {
1484
- t = Math.min(t, Math.max(0, duration - 0.35));
1485
- }
1486
- if (videoEl.seekable.length > 0) {
1487
- const end = videoEl.seekable.end(videoEl.seekable.length - 1);
1488
- if (Number.isFinite(end)) {
1489
- t = Math.min(t, end);
1490
- }
1536
+ return Math.min(t, Math.max(0, duration - 0.35));
1491
1537
  }
1492
1538
  return t;
1493
1539
  }
1494
1540
  async applyStartPositionOnly() {
1495
1541
  if (this.destroyed || this.startPositionApplied) return;
1496
1542
  const { videoEl, startPosition } = this.options;
1543
+ if (typeof startPosition !== "number" || startPosition <= 0) {
1544
+ this.startPositionApplied = true;
1545
+ return;
1546
+ }
1547
+ const durationKnown = Number.isFinite(videoEl.duration) && videoEl.duration > 0;
1548
+ if (!durationKnown) {
1549
+ videoEl.addEventListener(
1550
+ "loadedmetadata",
1551
+ () => {
1552
+ void this.applyStartPositionOnly();
1553
+ },
1554
+ { once: true }
1555
+ );
1556
+ return;
1557
+ }
1497
1558
  this.startPositionApplied = true;
1498
- if (typeof startPosition !== "number" || startPosition <= 0) return;
1499
- const seek = () => {
1500
- if (this.destroyed) return;
1501
- try {
1502
- videoEl.currentTime = this.clampStartPosition(startPosition, videoEl);
1503
- } catch {
1504
- }
1505
- };
1506
- if (videoEl.seekable.length > 0 || Number.isFinite(videoEl.duration)) {
1507
- seek();
1508
- } else {
1509
- videoEl.addEventListener("loadedmetadata", seek, { once: true });
1559
+ try {
1560
+ videoEl.currentTime = this.clampStartPosition(startPosition, videoEl);
1561
+ } catch {
1510
1562
  }
1511
1563
  }
1512
1564
  async applyAutoplayOnly() {
@@ -1550,12 +1602,43 @@ var HlsEngine = class {
1550
1602
  });
1551
1603
  }
1552
1604
  updateAuthParams() {
1553
- if (this.supportMode === "native" && this.options.videoEl) {
1554
- const time = this.options.videoEl.currentTime;
1555
- const wasPaused = this.options.videoEl.paused;
1556
- this.options.videoEl.src = this.playbackRequestUrl(this.options.playbackUrl);
1557
- this.options.videoEl.currentTime = time;
1558
- if (!wasPaused) void this.options.videoEl.play();
1605
+ if (this.supportMode !== "native" || !this.options.videoEl) return;
1606
+ if (this.options.nativeSessionMode) {
1607
+ void this.updateNativeAuthParams(this.options.authParams.toRecord());
1608
+ return;
1609
+ }
1610
+ const time = this.options.videoEl.currentTime;
1611
+ const wasPaused = this.options.videoEl.paused;
1612
+ this.options.videoEl.src = this.playbackRequestUrl(this.options.playbackUrl);
1613
+ this.options.videoEl.currentTime = time;
1614
+ if (!wasPaused) void this.options.videoEl.play();
1615
+ }
1616
+ /**
1617
+ * Native HLS: apply new auth parameters without replacing `video.src`.
1618
+ *
1619
+ * With `nativeSessionMode`, `onNativeAuthUpdate` receives the params and the
1620
+ * current request URL so the BFF session/cookie can be renewed; the element
1621
+ * keeps playing. Without it this method is a no-op unless a callback exists,
1622
+ * because rewriting `video.src` would restart the stream (use
1623
+ * `updateAuthParams()` for that reload path).
1624
+ *
1625
+ * Returns true when a callback handled the update.
1626
+ */
1627
+ async updateNativeAuthParams(params) {
1628
+ if (this.destroyed || this.supportMode !== "native") return false;
1629
+ const callback = this.options.onNativeAuthUpdate;
1630
+ if (!callback) return false;
1631
+ try {
1632
+ await callback({
1633
+ params,
1634
+ url: this.playbackRequestUrl(this.options.playbackUrl)
1635
+ });
1636
+ return true;
1637
+ } catch (error) {
1638
+ this.options.logger.warn(
1639
+ error instanceof Error ? `Native auth update failed: ${error.message}` : "Native auth update failed"
1640
+ );
1641
+ return false;
1559
1642
  }
1560
1643
  }
1561
1644
  playbackRequestUrl(playbackUrl) {
@@ -1567,9 +1650,14 @@ var HlsEngine = class {
1567
1650
  keyProxyMaxFailures: this.options.keyProxyMaxFailures
1568
1651
  });
1569
1652
  }
1570
- resumeAfterAuthRenew() {
1653
+ /**
1654
+ * Auth params are already on the shared store, so the next request uses
1655
+ * the new token. Restart the loader only after a real auth failure.
1656
+ * A proactive refresh must not abort the buffered segments.
1657
+ */
1658
+ resumeAfterAuthRenew(restart = true) {
1571
1659
  this.networkRecoveryCount = 0;
1572
- this.hls?.startLoad();
1660
+ if (restart) this.hls?.startLoad();
1573
1661
  this.updateAuthParams();
1574
1662
  }
1575
1663
  setQuality(selection) {
@@ -1871,6 +1959,10 @@ function createVideoPlayer(options) {
1871
1959
  getKeyAccessToken: config.streaming.getKeyAccessToken ?? (() => authManager.getAccessToken()),
1872
1960
  keyProxyMaxFailures: config.streaming.keyProxyMaxFailures,
1873
1961
  hlsConfig: config.streaming.hls,
1962
+ useAppexHlsProfile: config.streaming.useAppexHlsProfile,
1963
+ isLive: isLiveStream,
1964
+ nativeSessionMode: config.streaming.nativeSessionMode,
1965
+ onNativeAuthUpdate: config.streaming.onNativeAuthUpdate,
1874
1966
  logger,
1875
1967
  callbacks: {
1876
1968
  onStateChange: (s) => {
@@ -1955,12 +2047,15 @@ function createVideoPlayer(options) {
1955
2047
  renewMaxRetries: options.playback.renewMaxRetries ?? 3,
1956
2048
  renewBackoffMs: options.playback.renewBackoffMs ?? 2e3,
1957
2049
  coalesceMs: options.playback.authRecoveryCoalesceMs ?? 1e3,
2050
+ refreshIntervalMs: options.playback.refreshIntervalMs ?? DEFAULT_PLAYBACK_REFRESH_INTERVAL_MS,
1958
2051
  logger,
1959
2052
  isDestroyed: () => destroyed,
1960
- onRenewing: () => setState("renewing"),
1961
- onRenewed: (nextExpiresAt) => {
1962
- engine?.resumeAfterAuthRenew();
1963
- if (!destroyed) {
2053
+ onRenewing: (reason) => {
2054
+ if (reason !== "proactive") setState("renewing");
2055
+ },
2056
+ onRenewed: (nextExpiresAt, reason) => {
2057
+ engine?.resumeAfterAuthRenew(reason !== "proactive");
2058
+ if (reason !== "proactive" && !destroyed) {
1964
2059
  const el2 = videoEl;
1965
2060
  if (el2 && !el2.paused && !el2.ended) {
1966
2061
  setState("playing");
@@ -2020,8 +2115,13 @@ function createVideoPlayer(options) {
2020
2115
  },
2021
2116
  seek(time) {
2022
2117
  const el = ensureVideoElement();
2023
- const duration = Number.isFinite(el.duration) ? el.duration : time;
2024
- el.currentTime = Math.min(Math.max(0, time), duration);
2118
+ const requested = Math.max(0, time);
2119
+ const duration = el.duration;
2120
+ if (Number.isFinite(duration) && duration > 0) {
2121
+ el.currentTime = Math.min(requested, Math.max(0, duration - 0.05));
2122
+ } else {
2123
+ el.currentTime = requested;
2124
+ }
2025
2125
  },
2026
2126
  goToLive() {
2027
2127
  const el = ensureVideoElement();
@@ -2196,7 +2296,10 @@ function createVideoPlayer(options) {
2196
2296
  mediaProxyUrlBuilder: partial?.streaming?.mediaProxyUrlBuilder ?? config.streaming.mediaProxyUrlBuilder,
2197
2297
  keyProxyUrlBuilder: partial?.streaming?.keyProxyUrlBuilder ?? config.streaming.keyProxyUrlBuilder,
2198
2298
  getKeyAccessToken: partial?.streaming?.getKeyAccessToken ?? config.streaming.getKeyAccessToken ?? (() => authManager.getAccessToken()),
2199
- keyProxyMaxFailures: partial?.streaming?.keyProxyMaxFailures ?? config.streaming.keyProxyMaxFailures
2299
+ keyProxyMaxFailures: partial?.streaming?.keyProxyMaxFailures ?? config.streaming.keyProxyMaxFailures,
2300
+ useAppexHlsProfile: partial?.streaming?.useAppexHlsProfile ?? config.streaming.useAppexHlsProfile,
2301
+ nativeSessionMode: partial?.streaming?.nativeSessionMode ?? config.streaming.nativeSessionMode,
2302
+ onNativeAuthUpdate: partial?.streaming?.onNativeAuthUpdate ?? config.streaming.onNativeAuthUpdate
2200
2303
  },
2201
2304
  logging: { ...config.logging, ...partial?.logging },
2202
2305
  debug: { ...config.debug, ...partial?.debug },
@@ -2217,11 +2320,477 @@ function createVideoPlayer(options) {
2217
2320
  };
2218
2321
  return api;
2219
2322
  }
2323
+
2324
+ // src/captions/restoreSubtitleSelection.ts
2325
+ var SDK_SUBTITLE_TRACK_SELECTOR = "track[data-sample-subtitle],track[data-appextech-subtitle]";
2326
+ function restoreSubtitleSelection(video, language) {
2327
+ const nodes = video.querySelectorAll(
2328
+ SDK_SUBTITLE_TRACK_SELECTOR
2329
+ );
2330
+ for (const node of Array.from(nodes)) {
2331
+ const selected = Boolean(language) && node.srclang === language;
2332
+ node.default = selected;
2333
+ if (node.track) node.track.mode = selected ? "showing" : "disabled";
2334
+ }
2335
+ }
2336
+
2337
+ // src/student/StudentLeaseClient.ts
2338
+ var STUDENT_HEARTBEAT_INTERVAL_MS = 15e3;
2339
+ var STUDENT_REQUEST_TIMEOUT_MS = 1e4;
2340
+ var STUDENT_NOT_READY_MAX_ATTEMPTS = 20;
2341
+ var STUDENT_NOT_READY_RETRY_DELAY_MS = 3e3;
2342
+ var STUDENT_NOT_READY_DEADLINE_MS = 6e4;
2343
+ var WATERMARK_MIN_DELAY_MS = 3e4;
2344
+ var WATERMARK_JITTER_MS = 60001;
2345
+ var WATERMARK_VISIBLE_MS = 5e3;
2346
+ var WATERMARK_MAX_LENGTH = 200;
2347
+ var TOKEN_MAX_LENGTH = 16384;
2348
+ var USERID_MAX_LENGTH = 200;
2349
+ var PLATFORM_LABELS = {
2350
+ android: "Android",
2351
+ ios: "iOS",
2352
+ web: "Web"
2353
+ };
2354
+ var StudentLeaseError = class extends Error {
2355
+ constructor(message, details = {}) {
2356
+ super(message);
2357
+ this.name = "StudentLeaseError";
2358
+ this.code = details.code;
2359
+ this.activePlatform = details.activePlatform;
2360
+ this.status = details.status;
2361
+ }
2362
+ };
2363
+ function mapStudentLeaseError(status, payload) {
2364
+ const error = payload && typeof payload === "object" ? payload.error : void 0;
2365
+ const code = typeof error?.code === "string" ? error.code : void 0;
2366
+ const activePlatform = typeof error?.active_platform === "string" ? error.active_platform : void 0;
2367
+ const label = activePlatform ? PLATFORM_LABELS[activePlatform] : void 0;
2368
+ let message = "Student playback authorization unavailable.";
2369
+ if (code === PLAYBACK_NOT_READY) {
2370
+ message = "Live video is preparing. Please retry shortly.";
2371
+ } else if (status === 409 && code === PLATFORM_IN_USE && label) {
2372
+ message = `You are already watching video on ${label}.`;
2373
+ }
2374
+ return new StudentLeaseError(message, { code, activePlatform, status });
2375
+ }
2376
+ var defaultSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
2377
+ var StudentLeaseClient = class {
2378
+ constructor(video, config, options = {}) {
2379
+ this.watermarkEl = null;
2380
+ this.active = null;
2381
+ this.version = 0;
2382
+ this.closed = false;
2383
+ this.inFlight = false;
2384
+ this.onEnded = () => {
2385
+ void this.stop();
2386
+ };
2387
+ this.onPageHide = () => {
2388
+ void this.stop();
2389
+ };
2390
+ const origin = new URL(config.baseUrl);
2391
+ if (origin.protocol !== "https:" || origin.username || origin.password || origin.search || origin.hash || origin.pathname !== "/") {
2392
+ throw new Error("Use an HTTPS base origin");
2393
+ }
2394
+ const platform = config.platform ?? "web";
2395
+ if (platform !== "web" || typeof config.userId !== "string" || !config.userId.trim() || config.userId.length > USERID_MAX_LENGTH) {
2396
+ throw new Error("userId and web platform are mandatory");
2397
+ }
2398
+ this.video = video;
2399
+ this.config = {
2400
+ baseUrl: origin.origin,
2401
+ userId: config.userId,
2402
+ platform,
2403
+ watermarkText: config.watermarkText,
2404
+ authorizationToken: assertToken(config.authorizationToken)
2405
+ };
2406
+ this.onError = options.onError ?? (() => {
2407
+ });
2408
+ this.fetchImpl = options.fetch ?? ((...args) => globalThis.fetch(...args));
2409
+ this.sleep = options.sleep ?? defaultSleep;
2410
+ this.now = options.now ?? Date.now;
2411
+ this.random = options.random ?? Math.random;
2412
+ this.container = options.watermarkContainer === void 0 ? video.parentElement ?? null : options.watermarkContainer;
2413
+ this.createWatermarkElement();
2414
+ video.addEventListener("ended", this.onEnded);
2415
+ if (typeof window !== "undefined") {
2416
+ window.addEventListener("pagehide", this.onPageHide);
2417
+ }
2418
+ }
2419
+ /** Replace the student bearer token (for example after the BFF renews it). */
2420
+ updateAuthorizationToken(value) {
2421
+ this.config.authorizationToken = assertToken(value);
2422
+ }
2423
+ /** True while a lease is held. */
2424
+ get isActive() {
2425
+ return this.active !== null;
2426
+ }
2427
+ /**
2428
+ * Acquire a lease. Retries `PLAYBACK_NOT_READY` up to 20 attempts, 3s apart,
2429
+ * inside a 60s deadline. Rejects with `StudentLeaseError` otherwise
2430
+ * (`PLATFORM_IN_USE` carries `activePlatform`).
2431
+ */
2432
+ async start(videoId, mediaType = "video") {
2433
+ if (this.closed) throw new Error("Player is closed");
2434
+ await this.stop();
2435
+ const version = this.version;
2436
+ const body = {
2437
+ userid: this.config.userId,
2438
+ platform: this.config.platform,
2439
+ video_id: videoId,
2440
+ media_type: mediaType
2441
+ };
2442
+ if (this.config.watermarkText != null) {
2443
+ body.watermark_text = this.config.watermarkText;
2444
+ }
2445
+ const deadline = this.now() + STUDENT_NOT_READY_DEADLINE_MS;
2446
+ let result;
2447
+ for (let attempt = 0; ; attempt += 1) {
2448
+ if (this.closed || version !== this.version) {
2449
+ throw new Error("Playback request cancelled");
2450
+ }
2451
+ try {
2452
+ result = await this.request(
2453
+ "/student/playback",
2454
+ this.config.authorizationToken,
2455
+ body
2456
+ );
2457
+ break;
2458
+ } catch (error) {
2459
+ const code = error?.code;
2460
+ if (code !== PLAYBACK_NOT_READY || attempt >= STUDENT_NOT_READY_MAX_ATTEMPTS - 1 || this.now() >= deadline) {
2461
+ throw error;
2462
+ }
2463
+ await this.sleep(STUDENT_NOT_READY_RETRY_DELAY_MS);
2464
+ }
2465
+ }
2466
+ const lease = result?.data?.student_session;
2467
+ if (!lease?.token) throw new Error("Invalid student playback response");
2468
+ if (this.closed || version !== this.version) {
2469
+ await this.request("/student/release", lease.token).catch(() => {
2470
+ });
2471
+ throw new Error("Playback request cancelled");
2472
+ }
2473
+ this.active = { token: lease.token, seq: 0 };
2474
+ this.heartbeatTimer = setInterval(() => {
2475
+ void this.heartbeat();
2476
+ }, STUDENT_HEARTBEAT_INTERVAL_MS);
2477
+ this.scheduleWatermark(
2478
+ typeof lease.watermark_text === "string" ? lease.watermark_text.slice(0, WATERMARK_MAX_LENGTH) : ""
2479
+ );
2480
+ return result.data;
2481
+ }
2482
+ /** Send one heartbeat. On failure the lease is released and `onError` runs. */
2483
+ async heartbeat() {
2484
+ const lease = this.active;
2485
+ if (!lease || this.inFlight) return;
2486
+ this.inFlight = true;
2487
+ try {
2488
+ await this.request("/student/heartbeat", lease.token, {
2489
+ seq: ++lease.seq,
2490
+ playing: true
2491
+ });
2492
+ } catch (error) {
2493
+ if (this.active === lease) {
2494
+ await this.stop();
2495
+ this.onError(toLeaseError(error));
2496
+ }
2497
+ } finally {
2498
+ this.inFlight = false;
2499
+ }
2500
+ }
2501
+ /**
2502
+ * Show the watermark at random positions every 30-90s for 5s while the video
2503
+ * plays. An empty string clears it. Requires an active lease.
2504
+ */
2505
+ scheduleWatermark(text) {
2506
+ clearTimeout(this.watermarkTimer);
2507
+ clearTimeout(this.hideTimer);
2508
+ this.hideWatermark();
2509
+ if (!text || !this.active) return;
2510
+ const nextDelay = () => WATERMARK_MIN_DELAY_MS + Math.floor(this.random() * WATERMARK_JITTER_MS);
2511
+ const tick = () => {
2512
+ if (!this.active) return;
2513
+ if (!this.video.paused && !this.video.ended) {
2514
+ this.showWatermark(text);
2515
+ this.hideTimer = setTimeout(
2516
+ () => this.hideWatermark(),
2517
+ WATERMARK_VISIBLE_MS
2518
+ );
2519
+ }
2520
+ this.watermarkTimer = setTimeout(tick, nextDelay());
2521
+ };
2522
+ this.watermarkTimer = setTimeout(tick, nextDelay());
2523
+ }
2524
+ /** Pause the video, stop timers, and release the lease (keepalive). */
2525
+ async stop() {
2526
+ this.version += 1;
2527
+ this.video.pause();
2528
+ const lease = this.active;
2529
+ this.active = null;
2530
+ clearInterval(this.heartbeatTimer);
2531
+ clearTimeout(this.watermarkTimer);
2532
+ clearTimeout(this.hideTimer);
2533
+ this.hideWatermark();
2534
+ if (lease) {
2535
+ await this.request("/student/release", lease.token, {}, true).catch(
2536
+ () => {
2537
+ }
2538
+ );
2539
+ }
2540
+ }
2541
+ /** Release the lease, remove the overlay, and detach listeners. */
2542
+ async close() {
2543
+ this.closed = true;
2544
+ await this.stop();
2545
+ this.watermarkEl?.remove();
2546
+ this.watermarkEl = null;
2547
+ this.video.removeEventListener("ended", this.onEnded);
2548
+ if (typeof window !== "undefined") {
2549
+ window.removeEventListener("pagehide", this.onPageHide);
2550
+ }
2551
+ }
2552
+ async request(path, token, body = {}, keepalive = false) {
2553
+ const controller = new AbortController();
2554
+ const timeout = setTimeout(
2555
+ () => controller.abort(),
2556
+ STUDENT_REQUEST_TIMEOUT_MS
2557
+ );
2558
+ try {
2559
+ const response = await this.fetchImpl(this.config.baseUrl + path, {
2560
+ method: "POST",
2561
+ headers: {
2562
+ Authorization: `Bearer ${token}`,
2563
+ "Content-Type": "application/json"
2564
+ },
2565
+ body: JSON.stringify(body),
2566
+ cache: "no-store",
2567
+ credentials: "omit",
2568
+ redirect: "error",
2569
+ signal: controller.signal,
2570
+ keepalive
2571
+ });
2572
+ const result = await response.json().catch(() => ({}));
2573
+ if (!response.ok) throw mapStudentLeaseError(response.status, result);
2574
+ return result;
2575
+ } finally {
2576
+ clearTimeout(timeout);
2577
+ }
2578
+ }
2579
+ createWatermarkElement() {
2580
+ if (!this.container || typeof document === "undefined") return;
2581
+ const el = document.createElement("div");
2582
+ Object.assign(el.style, {
2583
+ position: "absolute",
2584
+ display: "none",
2585
+ pointerEvents: "none",
2586
+ zIndex: "20",
2587
+ color: "white",
2588
+ background: "rgba(0,0,0,.4)",
2589
+ padding: "4px 8px",
2590
+ font: "14px sans-serif",
2591
+ maxWidth: "90%",
2592
+ overflowWrap: "anywhere"
2593
+ });
2594
+ if (getComputedStyle(this.container).position === "static") {
2595
+ this.container.style.position = "relative";
2596
+ }
2597
+ this.container.append(el);
2598
+ this.watermarkEl = el;
2599
+ }
2600
+ showWatermark(text) {
2601
+ const el = this.watermarkEl;
2602
+ const container = this.container;
2603
+ if (!el || !container) return;
2604
+ el.textContent = text;
2605
+ el.style.display = "block";
2606
+ el.style.left = `${Math.floor(
2607
+ this.random() * Math.max(1, container.clientWidth - el.offsetWidth)
2608
+ )}px`;
2609
+ el.style.top = `${Math.floor(
2610
+ this.random() * Math.max(1, container.clientHeight - el.offsetHeight)
2611
+ )}px`;
2612
+ }
2613
+ hideWatermark() {
2614
+ if (this.watermarkEl) this.watermarkEl.style.display = "none";
2615
+ }
2616
+ };
2617
+ function assertToken(value) {
2618
+ if (typeof value !== "string" || !value || value.length > TOKEN_MAX_LENGTH || /[\r\n]/.test(value)) {
2619
+ throw new Error("Student playback token is required");
2620
+ }
2621
+ return value;
2622
+ }
2623
+ function toLeaseError(error) {
2624
+ if (error instanceof StudentLeaseError) return error;
2625
+ return new StudentLeaseError(
2626
+ error instanceof Error ? error.message : "Student playback authorization unavailable."
2627
+ );
2628
+ }
2629
+
2630
+ // src/analytics/AnalyticsClient.ts
2631
+ var defaultSend = async (url, body, opts) => {
2632
+ const response = await fetch(url, {
2633
+ method: "POST",
2634
+ headers: { "Content-Type": "application/json" },
2635
+ body: JSON.stringify(body),
2636
+ keepalive: opts?.keepalive ?? false
2637
+ });
2638
+ const value = await response.json().catch(() => ({}));
2639
+ if (!response.ok) {
2640
+ throw new Error(
2641
+ value.error ?? "Analytics request failed"
2642
+ );
2643
+ }
2644
+ return value;
2645
+ };
2646
+ var AnalyticsClient = class {
2647
+ constructor(options) {
2648
+ this.options = options;
2649
+ this.session = null;
2650
+ this.watched = 0;
2651
+ this.sequence = 0;
2652
+ this.finished = false;
2653
+ this.destroyed = false;
2654
+ this.lastPosition = 0;
2655
+ this.progressedAt = Number.NEGATIVE_INFINITY;
2656
+ this.onPause = () => {
2657
+ void this.heartbeat(false);
2658
+ };
2659
+ this.onEnded = () => {
2660
+ void this.heartbeat(true);
2661
+ };
2662
+ this.onPageHide = () => {
2663
+ void this.heartbeat(true);
2664
+ };
2665
+ this.send = options.send ?? defaultSend;
2666
+ this.now = options.now ?? (() => typeof performance !== "undefined" ? performance.now() : Date.now());
2667
+ this.onError = options.onError ?? (() => {
2668
+ });
2669
+ this.lastTime = this.now();
2670
+ this.lastPosition = options.video.currentTime || 0;
2671
+ }
2672
+ /** Total seconds credited as watched so far. */
2673
+ get watchedSeconds() {
2674
+ return this.watched;
2675
+ }
2676
+ /** Session from `analytics/start`, or null before it resolves. */
2677
+ get currentSession() {
2678
+ return this.session;
2679
+ }
2680
+ /**
2681
+ * POST `{origin}/media/{videoKey}/analytics/start` and begin sampling.
2682
+ * Resolves to the session, or null on failure (reported via `onError`).
2683
+ */
2684
+ async start() {
2685
+ if (this.destroyed) return null;
2686
+ const { video, origin, videoKey, deviceId, platform } = this.options;
2687
+ const url = new URL(
2688
+ `/media/${encodeURIComponent(videoKey)}/analytics/start`,
2689
+ origin
2690
+ ).href;
2691
+ const token = typeof this.options.playbackToken === "function" ? this.options.playbackToken() : this.options.playbackToken;
2692
+ video.addEventListener("pause", this.onPause);
2693
+ video.addEventListener("ended", this.onEnded);
2694
+ if (typeof window !== "undefined") {
2695
+ window.addEventListener("pagehide", this.onPageHide);
2696
+ }
2697
+ this.lastTime = this.now();
2698
+ this.lastPosition = video.currentTime || 0;
2699
+ this.sampleTimer = setInterval(
2700
+ () => this.sample(),
2701
+ this.options.sampleIntervalMs ?? 1e3
2702
+ );
2703
+ this.heartbeatTimer = setInterval(
2704
+ () => void this.heartbeat(false),
2705
+ this.options.heartbeatIntervalMs ?? 15e3
2706
+ );
2707
+ try {
2708
+ const value = await this.send(url, {
2709
+ playback_token: token,
2710
+ device_id: deviceId,
2711
+ platform: platform ?? "web"
2712
+ });
2713
+ const session = unwrapSession(value);
2714
+ if (!session) throw new Error("Invalid analytics start response");
2715
+ if (this.destroyed) return null;
2716
+ this.session = session;
2717
+ return session;
2718
+ } catch (error) {
2719
+ this.onError(error);
2720
+ return null;
2721
+ }
2722
+ }
2723
+ /** Credit elapsed wall time when the video genuinely advanced. */
2724
+ sample() {
2725
+ const { video } = this.options;
2726
+ const now = this.now();
2727
+ const elapsed = Math.min(2, (now - this.lastTime) / 1e3);
2728
+ const advance = video.currentTime - this.lastPosition;
2729
+ const rate = Math.max(1, video.playbackRate || 1);
2730
+ if (!video.paused && !video.seeking && video.readyState >= 2 && advance > 0 && advance <= elapsed * rate + 1) {
2731
+ this.watched += Math.min(
2732
+ elapsed,
2733
+ advance / Math.max(0.1, video.playbackRate || 1)
2734
+ );
2735
+ this.progressedAt = now;
2736
+ }
2737
+ this.lastTime = now;
2738
+ this.lastPosition = video.currentTime;
2739
+ }
2740
+ /**
2741
+ * Send an event heartbeat. `end: true` marks the session finished, sends with
2742
+ * `keepalive`, and suppresses further heartbeats.
2743
+ */
2744
+ async heartbeat(end = false) {
2745
+ const session = this.session;
2746
+ if (!session || this.finished) return;
2747
+ this.sample();
2748
+ if (end) this.finished = true;
2749
+ const { video, origin } = this.options;
2750
+ const body = {
2751
+ token: session.token,
2752
+ seq: ++this.sequence,
2753
+ watched_seconds: this.watched,
2754
+ playing: !video.paused && !video.ended && !video.seeking && this.now() - this.progressedAt < (this.options.progressWindowMs ?? 5e3),
2755
+ ended: end
2756
+ };
2757
+ try {
2758
+ await this.send(new URL(session.event_url, origin).href, body, {
2759
+ keepalive: true
2760
+ });
2761
+ } catch (error) {
2762
+ this.onError(error);
2763
+ }
2764
+ }
2765
+ /** Send the final heartbeat (if started) and detach everything. */
2766
+ async destroy() {
2767
+ if (this.destroyed) return;
2768
+ await this.heartbeat(true);
2769
+ this.destroyed = true;
2770
+ clearInterval(this.sampleTimer);
2771
+ clearInterval(this.heartbeatTimer);
2772
+ const { video } = this.options;
2773
+ video.removeEventListener("pause", this.onPause);
2774
+ video.removeEventListener("ended", this.onEnded);
2775
+ if (typeof window !== "undefined") {
2776
+ window.removeEventListener("pagehide", this.onPageHide);
2777
+ }
2778
+ }
2779
+ };
2780
+ function unwrapSession(value) {
2781
+ const candidate = value && typeof value === "object" && "data" in value ? value.data : value;
2782
+ if (!candidate || typeof candidate !== "object") return null;
2783
+ const { token, event_url } = candidate;
2784
+ if (typeof token !== "string" || typeof event_url !== "string") return null;
2785
+ return candidate;
2786
+ }
2220
2787
  export {
2788
+ AnalyticsClient,
2221
2789
  AuthManager,
2222
2790
  AuthParamsStore,
2223
2791
  DEFAULT_CONTROLS,
2224
2792
  DEFAULT_LIVE_EDGE_TOLERANCE_SECONDS,
2793
+ DEFAULT_PLAYBACK_REFRESH_INTERVAL_MS,
2225
2794
  DEFAULT_PLAYER_BEHAVIOR,
2226
2795
  DEFAULT_PLAYER_CONFIG,
2227
2796
  DEFAULT_THEME,
@@ -2229,26 +2798,40 @@ export {
2229
2798
  EventEmitter,
2230
2799
  KEY_PROXY_MAX_FAILURES,
2231
2800
  PACKAGE_VERSION,
2801
+ PLATFORM_IN_USE,
2802
+ PLAYBACK_NOT_READY,
2232
2803
  PLAYBACK_RATES,
2233
2804
  PlaybackSourceManager,
2234
2805
  PlayerErrorCode,
2235
2806
  RefreshManager,
2807
+ SDK_SUBTITLE_TRACK_SELECTOR,
2236
2808
  SECRET_SCAN_MAX_DEPTH,
2809
+ STUDENT_HEARTBEAT_INTERVAL_MS,
2810
+ STUDENT_NOT_READY_DEADLINE_MS,
2811
+ STUDENT_NOT_READY_MAX_ATTEMPTS,
2812
+ STUDENT_NOT_READY_RETRY_DELAY_MS,
2813
+ STUDENT_REQUEST_TIMEOUT_MS,
2814
+ StudentLeaseClient,
2815
+ StudentLeaseError,
2816
+ appexHlsConfig,
2237
2817
  assertNoSecretsInConfig,
2238
2818
  createAuthParamsLoader,
2239
2819
  createPlayerError,
2240
2820
  createVideoPlayer,
2241
2821
  getLiveEdgeTime,
2822
+ hlsConfig,
2242
2823
  isAtLiveEdge,
2243
2824
  isEncryptionKeyUrl,
2244
2825
  isLivePlaylistUrl,
2245
2826
  isPlainObject,
2246
2827
  isSameOriginHttpUrl,
2828
+ mapStudentLeaseError,
2247
2829
  mergePlayerConfig,
2248
2830
  redactObject,
2249
2831
  redactSensitive,
2250
2832
  redactValue,
2251
2833
  resolveBuiltinHlsLoader,
2834
+ restoreSubtitleSelection,
2252
2835
  rewriteHlsRequestUrl,
2253
2836
  seekToLiveEdge,
2254
2837
  themeToCssVars