@codenkay/video-nsgplayer-core 5.2.0 → 5.4.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.cjs CHANGED
@@ -30,6 +30,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
30
30
  // src/index.ts
31
31
  var index_exports = {};
32
32
  __export(index_exports, {
33
+ AnalyticsClient: () => AnalyticsClient,
33
34
  AuthManager: () => AuthManager,
34
35
  AuthParamsStore: () => AuthParamsStore,
35
36
  DEFAULT_CONTROLS: () => DEFAULT_CONTROLS,
@@ -42,26 +43,40 @@ __export(index_exports, {
42
43
  EventEmitter: () => EventEmitter,
43
44
  KEY_PROXY_MAX_FAILURES: () => KEY_PROXY_MAX_FAILURES,
44
45
  PACKAGE_VERSION: () => PACKAGE_VERSION,
46
+ PLATFORM_IN_USE: () => PLATFORM_IN_USE,
47
+ PLAYBACK_NOT_READY: () => PLAYBACK_NOT_READY,
45
48
  PLAYBACK_RATES: () => PLAYBACK_RATES,
46
49
  PlaybackSourceManager: () => PlaybackSourceManager,
47
50
  PlayerErrorCode: () => PlayerErrorCode,
48
51
  RefreshManager: () => RefreshManager,
52
+ SDK_SUBTITLE_TRACK_SELECTOR: () => SDK_SUBTITLE_TRACK_SELECTOR,
49
53
  SECRET_SCAN_MAX_DEPTH: () => SECRET_SCAN_MAX_DEPTH,
54
+ STUDENT_HEARTBEAT_INTERVAL_MS: () => STUDENT_HEARTBEAT_INTERVAL_MS,
55
+ STUDENT_NOT_READY_DEADLINE_MS: () => STUDENT_NOT_READY_DEADLINE_MS,
56
+ STUDENT_NOT_READY_MAX_ATTEMPTS: () => STUDENT_NOT_READY_MAX_ATTEMPTS,
57
+ STUDENT_NOT_READY_RETRY_DELAY_MS: () => STUDENT_NOT_READY_RETRY_DELAY_MS,
58
+ STUDENT_REQUEST_TIMEOUT_MS: () => STUDENT_REQUEST_TIMEOUT_MS,
59
+ StudentLeaseClient: () => StudentLeaseClient,
60
+ StudentLeaseError: () => StudentLeaseError,
61
+ appexHlsConfig: () => appexHlsConfig,
50
62
  assertNoSecretsInConfig: () => assertNoSecretsInConfig,
51
63
  createAuthParamsLoader: () => createAuthParamsLoader,
52
64
  createPlayerError: () => createPlayerError,
53
65
  createVideoPlayer: () => createVideoPlayer,
54
66
  getLiveEdgeTime: () => getLiveEdgeTime,
67
+ hlsConfig: () => hlsConfig,
55
68
  isAtLiveEdge: () => isAtLiveEdge,
56
69
  isEncryptionKeyUrl: () => isEncryptionKeyUrl,
57
70
  isLivePlaylistUrl: () => isLivePlaylistUrl,
58
71
  isPlainObject: () => isPlainObject,
59
72
  isSameOriginHttpUrl: () => isSameOriginHttpUrl,
73
+ mapStudentLeaseError: () => mapStudentLeaseError,
60
74
  mergePlayerConfig: () => mergePlayerConfig,
61
75
  redactObject: () => redactObject,
62
76
  redactSensitive: () => redactSensitive,
63
77
  redactValue: () => redactValue,
64
78
  resolveBuiltinHlsLoader: () => resolveBuiltinHlsLoader,
79
+ restoreSubtitleSelection: () => restoreSubtitleSelection,
65
80
  rewriteHlsRequestUrl: () => rewriteHlsRequestUrl,
66
81
  seekToLiveEdge: () => seekToLiveEdge,
67
82
  themeToCssVars: () => themeToCssVars
@@ -82,9 +97,13 @@ var PlayerErrorCode = /* @__PURE__ */ ((PlayerErrorCode2) => {
82
97
  PlayerErrorCode2["PLAYBACK_ERROR"] = "PLAYBACK_ERROR";
83
98
  PlayerErrorCode2["UNSUPPORTED_BROWSER"] = "UNSUPPORTED_BROWSER";
84
99
  PlayerErrorCode2["AUTOPLAY_BLOCKED"] = "AUTOPLAY_BLOCKED";
100
+ PlayerErrorCode2["PLATFORM_IN_USE"] = "PLATFORM_IN_USE";
101
+ PlayerErrorCode2["PLAYBACK_NOT_READY"] = "PLAYBACK_NOT_READY";
85
102
  PlayerErrorCode2["UNKNOWN"] = "UNKNOWN";
86
103
  return PlayerErrorCode2;
87
104
  })(PlayerErrorCode || {});
105
+ var PLATFORM_IN_USE = "PLATFORM_IN_USE";
106
+ var PLAYBACK_NOT_READY = "PLAYBACK_NOT_READY";
88
107
  function createPlayerError(code, message, options) {
89
108
  return {
90
109
  code,
@@ -217,7 +236,7 @@ var AuthManager = class {
217
236
  // src/config/defaults.ts
218
237
  var PLAYBACK_RATES = [0.5, 0.75, 1, 1.25, 1.5, 2];
219
238
  var DEFAULT_PLAYBACK_REFRESH_INTERVAL_MS = 45e3;
220
- var PACKAGE_VERSION = "5.2.0";
239
+ var PACKAGE_VERSION = "5.4.0";
221
240
  var DEFAULT_PLAYER_BEHAVIOR = {
222
241
  autoplay: true,
223
242
  startMuted: true,
@@ -319,7 +338,8 @@ var SKIP_DEEP_SCAN_KEYS = /* @__PURE__ */ new Set([
319
338
  "refreshsource",
320
339
  "keyproxyurlbuilder",
321
340
  "mediaproxyurlbuilder",
322
- "getkeyaccesstoken"
341
+ "getkeyaccesstoken",
342
+ "onnativeauthupdate"
323
343
  ]);
324
344
  var SECRET_SCAN_MAX_DEPTH = 32;
325
345
  function isPlainObject(value) {
@@ -406,7 +426,10 @@ function mergePlayerConfig(partial) {
406
426
  mediaProxyUrlBuilder: partial?.streaming?.mediaProxyUrlBuilder,
407
427
  keyProxyUrlBuilder: partial?.streaming?.keyProxyUrlBuilder,
408
428
  getKeyAccessToken: partial?.streaming?.getKeyAccessToken,
409
- keyProxyMaxFailures: partial?.streaming?.keyProxyMaxFailures
429
+ keyProxyMaxFailures: partial?.streaming?.keyProxyMaxFailures,
430
+ useAppexHlsProfile: partial?.streaming?.useAppexHlsProfile,
431
+ nativeSessionMode: partial?.streaming?.nativeSessionMode,
432
+ onNativeAuthUpdate: partial?.streaming?.onNativeAuthUpdate
410
433
  },
411
434
  logging: { ...DEFAULT_PLAYER_CONFIG.logging, ...partial?.logging },
412
435
  debug: { ...DEFAULT_PLAYER_CONFIG.debug, ...partial?.debug },
@@ -881,6 +904,26 @@ function isSameOriginHttpUrl(value, baseOrigin) {
881
904
  }
882
905
  }
883
906
 
907
+ // src/config/hlsProfiles.ts
908
+ function hlsConfig(isLive = false) {
909
+ return {
910
+ maxBufferLength: isLive ? 24 : 60,
911
+ maxMaxBufferLength: isLive ? 40 : 120,
912
+ maxBufferSize: 32 * 1024 * 1024,
913
+ backBufferLength: 30,
914
+ startLevel: 0,
915
+ abrEwmaDefaultEstimate: 5e5,
916
+ abrBandWidthFactor: 0.7,
917
+ abrBandWidthUpFactor: 0.55,
918
+ maxStarvationDelay: 2,
919
+ lowLatencyMode: false,
920
+ liveSyncDurationCount: 4,
921
+ liveMaxLatencyDurationCount: 8,
922
+ maxLiveSyncPlaybackRate: 1.1
923
+ };
924
+ }
925
+ var appexHlsConfig = hlsConfig;
926
+
884
927
  // src/streaming/authParamsLoader.ts
885
928
  var ENC_KEY_PATH_RE = /enc\.key$/i;
886
929
  var BUILTIN_LOADER_NAMES = /* @__PURE__ */ new Set(["XhrLoader", "FetchLoader"]);
@@ -1430,7 +1473,7 @@ var HlsEngine = class {
1430
1473
  const {
1431
1474
  videoEl,
1432
1475
  authParams,
1433
- hlsConfig,
1476
+ hlsConfig: hlsConfig2,
1434
1477
  callbacks,
1435
1478
  videoId,
1436
1479
  keyProxyUrlBuilder,
@@ -1443,8 +1486,8 @@ var HlsEngine = class {
1443
1486
  getKeyAccessToken,
1444
1487
  keyProxyMaxFailures: this.options.keyProxyMaxFailures
1445
1488
  });
1446
- const enableWorker = hlsConfig.enableWorker && !isGeckoBrowser();
1447
- if (hlsConfig.enableWorker && !enableWorker) {
1489
+ const enableWorker = hlsConfig2.enableWorker && !isGeckoBrowser();
1490
+ if (hlsConfig2.enableWorker && !enableWorker) {
1448
1491
  this.options.logger.warn(
1449
1492
  "Disabling hls.js worker on Firefox to avoid MSE bufferAppendError"
1450
1493
  );
@@ -1453,17 +1496,19 @@ var HlsEngine = class {
1453
1496
  this.hls = new Hls({
1454
1497
  enableWorker,
1455
1498
  // LL mode on short encrypted VOD drives aggressive ABR thrash → MSE errors.
1456
- lowLatencyMode: hlsConfig.lowLatencyMode,
1457
- backBufferLength: hlsConfig.backBufferLength,
1458
- maxBufferLength: hlsConfig.maxBufferLength,
1459
- maxMaxBufferLength: hlsConfig.maxMaxBufferLength,
1460
- maxBufferSize: hlsConfig.maxBufferSize,
1499
+ lowLatencyMode: hlsConfig2.lowLatencyMode,
1500
+ backBufferLength: hlsConfig2.backBufferLength,
1501
+ maxBufferLength: hlsConfig2.maxBufferLength,
1502
+ maxMaxBufferLength: hlsConfig2.maxMaxBufferLength,
1503
+ maxBufferSize: hlsConfig2.maxBufferSize,
1461
1504
  startPosition: typeof startPosition === "number" && startPosition > 0 ? startPosition : -1,
1462
1505
  // A first-fragment bandwidth probe on short encrypted VODs truncates
1463
1506
  // the body and immediately hops levels. ABR itself stays on hls.js
1464
1507
  // defaults so a long VOD is not held on the lowest rung.
1465
1508
  testBandwidth: false,
1466
1509
  startLevel: -1,
1510
+ // Opt-in Appextech profile (buffers, ABR, live sync). Wins for its keys.
1511
+ ...this.options.useAppexHlsProfile ? appexHlsConfig(Boolean(this.options.isLive)) : {},
1467
1512
  loader
1468
1513
  });
1469
1514
  this.hls.attachMedia(videoEl);
@@ -1502,7 +1547,7 @@ var HlsEngine = class {
1502
1547
  }
1503
1548
  handleHlsError(Hls, data) {
1504
1549
  if (this.destroyed) return;
1505
- const { callbacks, hlsConfig } = this.options;
1550
+ const { callbacks, hlsConfig: hlsConfig2 } = this.options;
1506
1551
  const status = data.response?.code;
1507
1552
  const authFailure = isAuthHttpStatus(status);
1508
1553
  if (data.details === Hls.ErrorDetails.KEY_LOAD_ERROR) {
@@ -1534,7 +1579,7 @@ var HlsEngine = class {
1534
1579
  }
1535
1580
  if (data.type === Hls.ErrorTypes.NETWORK_ERROR) {
1536
1581
  this.networkRecoveryCount += 1;
1537
- if (this.networkRecoveryCount <= hlsConfig.fatalRecoveryLimit) {
1582
+ if (this.networkRecoveryCount <= hlsConfig2.fatalRecoveryLimit) {
1538
1583
  if (authFailure) {
1539
1584
  callbacks.onAuthRecoveryNeeded?.("fatal_network");
1540
1585
  }
@@ -1544,7 +1589,7 @@ var HlsEngine = class {
1544
1589
  }
1545
1590
  if (data.type === Hls.ErrorTypes.MEDIA_ERROR) {
1546
1591
  this.mediaRecoveryCount += 1;
1547
- if (this.mediaRecoveryCount > hlsConfig.fatalRecoveryLimit) {
1592
+ if (this.mediaRecoveryCount > hlsConfig2.fatalRecoveryLimit) {
1548
1593
  callbacks.onFatalError?.(data.details || "Fatal HLS error");
1549
1594
  return;
1550
1595
  }
@@ -1642,12 +1687,43 @@ var HlsEngine = class {
1642
1687
  });
1643
1688
  }
1644
1689
  updateAuthParams() {
1645
- if (this.supportMode === "native" && this.options.videoEl) {
1646
- const time = this.options.videoEl.currentTime;
1647
- const wasPaused = this.options.videoEl.paused;
1648
- this.options.videoEl.src = this.playbackRequestUrl(this.options.playbackUrl);
1649
- this.options.videoEl.currentTime = time;
1650
- if (!wasPaused) void this.options.videoEl.play();
1690
+ if (this.supportMode !== "native" || !this.options.videoEl) return;
1691
+ if (this.options.nativeSessionMode) {
1692
+ void this.updateNativeAuthParams(this.options.authParams.toRecord());
1693
+ return;
1694
+ }
1695
+ const time = this.options.videoEl.currentTime;
1696
+ const wasPaused = this.options.videoEl.paused;
1697
+ this.options.videoEl.src = this.playbackRequestUrl(this.options.playbackUrl);
1698
+ this.options.videoEl.currentTime = time;
1699
+ if (!wasPaused) void this.options.videoEl.play();
1700
+ }
1701
+ /**
1702
+ * Native HLS: apply new auth parameters without replacing `video.src`.
1703
+ *
1704
+ * With `nativeSessionMode`, `onNativeAuthUpdate` receives the params and the
1705
+ * current request URL so the BFF session/cookie can be renewed; the element
1706
+ * keeps playing. Without it this method is a no-op unless a callback exists,
1707
+ * because rewriting `video.src` would restart the stream (use
1708
+ * `updateAuthParams()` for that reload path).
1709
+ *
1710
+ * Returns true when a callback handled the update.
1711
+ */
1712
+ async updateNativeAuthParams(params) {
1713
+ if (this.destroyed || this.supportMode !== "native") return false;
1714
+ const callback = this.options.onNativeAuthUpdate;
1715
+ if (!callback) return false;
1716
+ try {
1717
+ await callback({
1718
+ params,
1719
+ url: this.playbackRequestUrl(this.options.playbackUrl)
1720
+ });
1721
+ return true;
1722
+ } catch (error) {
1723
+ this.options.logger.warn(
1724
+ error instanceof Error ? `Native auth update failed: ${error.message}` : "Native auth update failed"
1725
+ );
1726
+ return false;
1651
1727
  }
1652
1728
  }
1653
1729
  playbackRequestUrl(playbackUrl) {
@@ -1968,6 +2044,10 @@ function createVideoPlayer(options) {
1968
2044
  getKeyAccessToken: config.streaming.getKeyAccessToken ?? (() => authManager.getAccessToken()),
1969
2045
  keyProxyMaxFailures: config.streaming.keyProxyMaxFailures,
1970
2046
  hlsConfig: config.streaming.hls,
2047
+ useAppexHlsProfile: config.streaming.useAppexHlsProfile,
2048
+ isLive: isLiveStream,
2049
+ nativeSessionMode: config.streaming.nativeSessionMode,
2050
+ onNativeAuthUpdate: config.streaming.onNativeAuthUpdate,
1971
2051
  logger,
1972
2052
  callbacks: {
1973
2053
  onStateChange: (s) => {
@@ -2301,7 +2381,10 @@ function createVideoPlayer(options) {
2301
2381
  mediaProxyUrlBuilder: partial?.streaming?.mediaProxyUrlBuilder ?? config.streaming.mediaProxyUrlBuilder,
2302
2382
  keyProxyUrlBuilder: partial?.streaming?.keyProxyUrlBuilder ?? config.streaming.keyProxyUrlBuilder,
2303
2383
  getKeyAccessToken: partial?.streaming?.getKeyAccessToken ?? config.streaming.getKeyAccessToken ?? (() => authManager.getAccessToken()),
2304
- keyProxyMaxFailures: partial?.streaming?.keyProxyMaxFailures ?? config.streaming.keyProxyMaxFailures
2384
+ keyProxyMaxFailures: partial?.streaming?.keyProxyMaxFailures ?? config.streaming.keyProxyMaxFailures,
2385
+ useAppexHlsProfile: partial?.streaming?.useAppexHlsProfile ?? config.streaming.useAppexHlsProfile,
2386
+ nativeSessionMode: partial?.streaming?.nativeSessionMode ?? config.streaming.nativeSessionMode,
2387
+ onNativeAuthUpdate: partial?.streaming?.onNativeAuthUpdate ?? config.streaming.onNativeAuthUpdate
2305
2388
  },
2306
2389
  logging: { ...config.logging, ...partial?.logging },
2307
2390
  debug: { ...config.debug, ...partial?.debug },
@@ -2322,8 +2405,473 @@ function createVideoPlayer(options) {
2322
2405
  };
2323
2406
  return api;
2324
2407
  }
2408
+
2409
+ // src/captions/restoreSubtitleSelection.ts
2410
+ var SDK_SUBTITLE_TRACK_SELECTOR = "track[data-sample-subtitle],track[data-appextech-subtitle]";
2411
+ function restoreSubtitleSelection(video, language) {
2412
+ const nodes = video.querySelectorAll(
2413
+ SDK_SUBTITLE_TRACK_SELECTOR
2414
+ );
2415
+ for (const node of Array.from(nodes)) {
2416
+ const selected = Boolean(language) && node.srclang === language;
2417
+ node.default = selected;
2418
+ if (node.track) node.track.mode = selected ? "showing" : "disabled";
2419
+ }
2420
+ }
2421
+
2422
+ // src/student/StudentLeaseClient.ts
2423
+ var STUDENT_HEARTBEAT_INTERVAL_MS = 15e3;
2424
+ var STUDENT_REQUEST_TIMEOUT_MS = 1e4;
2425
+ var STUDENT_NOT_READY_MAX_ATTEMPTS = 20;
2426
+ var STUDENT_NOT_READY_RETRY_DELAY_MS = 3e3;
2427
+ var STUDENT_NOT_READY_DEADLINE_MS = 6e4;
2428
+ var WATERMARK_MIN_DELAY_MS = 3e4;
2429
+ var WATERMARK_JITTER_MS = 60001;
2430
+ var WATERMARK_VISIBLE_MS = 5e3;
2431
+ var WATERMARK_MAX_LENGTH = 200;
2432
+ var TOKEN_MAX_LENGTH = 16384;
2433
+ var USERID_MAX_LENGTH = 200;
2434
+ var PLATFORM_LABELS = {
2435
+ android: "Android",
2436
+ ios: "iOS",
2437
+ web: "Web"
2438
+ };
2439
+ var StudentLeaseError = class extends Error {
2440
+ constructor(message, details = {}) {
2441
+ super(message);
2442
+ this.name = "StudentLeaseError";
2443
+ this.code = details.code;
2444
+ this.activePlatform = details.activePlatform;
2445
+ this.status = details.status;
2446
+ }
2447
+ };
2448
+ function mapStudentLeaseError(status, payload) {
2449
+ const error = payload && typeof payload === "object" ? payload.error : void 0;
2450
+ const code = typeof error?.code === "string" ? error.code : void 0;
2451
+ const activePlatform = typeof error?.active_platform === "string" ? error.active_platform : void 0;
2452
+ const label = activePlatform ? PLATFORM_LABELS[activePlatform] : void 0;
2453
+ let message = "Student playback authorization unavailable.";
2454
+ if (code === PLAYBACK_NOT_READY) {
2455
+ message = "Live video is preparing. Please retry shortly.";
2456
+ } else if (status === 409 && code === PLATFORM_IN_USE && label) {
2457
+ message = `You are already watching video on ${label}.`;
2458
+ }
2459
+ return new StudentLeaseError(message, { code, activePlatform, status });
2460
+ }
2461
+ var defaultSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
2462
+ var StudentLeaseClient = class {
2463
+ constructor(video, config, options = {}) {
2464
+ this.watermarkEl = null;
2465
+ this.active = null;
2466
+ this.version = 0;
2467
+ this.closed = false;
2468
+ this.inFlight = false;
2469
+ this.onEnded = () => {
2470
+ void this.stop();
2471
+ };
2472
+ this.onPageHide = () => {
2473
+ void this.stop();
2474
+ };
2475
+ const origin = new URL(config.baseUrl);
2476
+ if (origin.protocol !== "https:" || origin.username || origin.password || origin.search || origin.hash || origin.pathname !== "/") {
2477
+ throw new Error("Use an HTTPS base origin");
2478
+ }
2479
+ const platform = config.platform ?? "web";
2480
+ if (platform !== "web" || typeof config.userId !== "string" || !config.userId.trim() || config.userId.length > USERID_MAX_LENGTH) {
2481
+ throw new Error("userId and web platform are mandatory");
2482
+ }
2483
+ this.video = video;
2484
+ this.config = {
2485
+ baseUrl: origin.origin,
2486
+ userId: config.userId,
2487
+ platform,
2488
+ watermarkText: config.watermarkText,
2489
+ authorizationToken: assertToken(config.authorizationToken)
2490
+ };
2491
+ this.onError = options.onError ?? (() => {
2492
+ });
2493
+ this.fetchImpl = options.fetch ?? ((...args) => globalThis.fetch(...args));
2494
+ this.sleep = options.sleep ?? defaultSleep;
2495
+ this.now = options.now ?? Date.now;
2496
+ this.random = options.random ?? Math.random;
2497
+ this.container = options.watermarkContainer === void 0 ? video.parentElement ?? null : options.watermarkContainer;
2498
+ this.createWatermarkElement();
2499
+ video.addEventListener("ended", this.onEnded);
2500
+ if (typeof window !== "undefined") {
2501
+ window.addEventListener("pagehide", this.onPageHide);
2502
+ }
2503
+ }
2504
+ /** Replace the student bearer token (for example after the BFF renews it). */
2505
+ updateAuthorizationToken(value) {
2506
+ this.config.authorizationToken = assertToken(value);
2507
+ }
2508
+ /** True while a lease is held. */
2509
+ get isActive() {
2510
+ return this.active !== null;
2511
+ }
2512
+ /**
2513
+ * Acquire a lease. Retries `PLAYBACK_NOT_READY` up to 20 attempts, 3s apart,
2514
+ * inside a 60s deadline. Rejects with `StudentLeaseError` otherwise
2515
+ * (`PLATFORM_IN_USE` carries `activePlatform`).
2516
+ */
2517
+ async start(videoId, mediaType = "video") {
2518
+ if (this.closed) throw new Error("Player is closed");
2519
+ await this.stop();
2520
+ const version = this.version;
2521
+ const body = {
2522
+ userid: this.config.userId,
2523
+ platform: this.config.platform,
2524
+ video_id: videoId,
2525
+ media_type: mediaType
2526
+ };
2527
+ if (this.config.watermarkText != null) {
2528
+ body.watermark_text = this.config.watermarkText;
2529
+ }
2530
+ const deadline = this.now() + STUDENT_NOT_READY_DEADLINE_MS;
2531
+ let result;
2532
+ for (let attempt = 0; ; attempt += 1) {
2533
+ if (this.closed || version !== this.version) {
2534
+ throw new Error("Playback request cancelled");
2535
+ }
2536
+ try {
2537
+ result = await this.request(
2538
+ "/student/playback",
2539
+ this.config.authorizationToken,
2540
+ body
2541
+ );
2542
+ break;
2543
+ } catch (error) {
2544
+ const code = error?.code;
2545
+ if (code !== PLAYBACK_NOT_READY || attempt >= STUDENT_NOT_READY_MAX_ATTEMPTS - 1 || this.now() >= deadline) {
2546
+ throw error;
2547
+ }
2548
+ await this.sleep(STUDENT_NOT_READY_RETRY_DELAY_MS);
2549
+ }
2550
+ }
2551
+ const lease = result?.data?.student_session;
2552
+ if (!lease?.token) throw new Error("Invalid student playback response");
2553
+ if (this.closed || version !== this.version) {
2554
+ await this.request("/student/release", lease.token).catch(() => {
2555
+ });
2556
+ throw new Error("Playback request cancelled");
2557
+ }
2558
+ this.active = { token: lease.token, seq: 0 };
2559
+ this.heartbeatTimer = setInterval(() => {
2560
+ void this.heartbeat();
2561
+ }, STUDENT_HEARTBEAT_INTERVAL_MS);
2562
+ this.scheduleWatermark(
2563
+ typeof lease.watermark_text === "string" ? lease.watermark_text.slice(0, WATERMARK_MAX_LENGTH) : ""
2564
+ );
2565
+ return result.data;
2566
+ }
2567
+ /** Send one heartbeat. On failure the lease is released and `onError` runs. */
2568
+ async heartbeat() {
2569
+ const lease = this.active;
2570
+ if (!lease || this.inFlight) return;
2571
+ this.inFlight = true;
2572
+ try {
2573
+ await this.request("/student/heartbeat", lease.token, {
2574
+ seq: ++lease.seq,
2575
+ playing: true
2576
+ });
2577
+ } catch (error) {
2578
+ if (this.active === lease) {
2579
+ await this.stop();
2580
+ this.onError(toLeaseError(error));
2581
+ }
2582
+ } finally {
2583
+ this.inFlight = false;
2584
+ }
2585
+ }
2586
+ /**
2587
+ * Show the watermark at random positions every 30-90s for 5s while the video
2588
+ * plays. An empty string clears it. Requires an active lease.
2589
+ */
2590
+ scheduleWatermark(text) {
2591
+ clearTimeout(this.watermarkTimer);
2592
+ clearTimeout(this.hideTimer);
2593
+ this.hideWatermark();
2594
+ if (!text || !this.active) return;
2595
+ const nextDelay = () => WATERMARK_MIN_DELAY_MS + Math.floor(this.random() * WATERMARK_JITTER_MS);
2596
+ const tick = () => {
2597
+ if (!this.active) return;
2598
+ if (!this.video.paused && !this.video.ended) {
2599
+ this.showWatermark(text);
2600
+ this.hideTimer = setTimeout(
2601
+ () => this.hideWatermark(),
2602
+ WATERMARK_VISIBLE_MS
2603
+ );
2604
+ }
2605
+ this.watermarkTimer = setTimeout(tick, nextDelay());
2606
+ };
2607
+ this.watermarkTimer = setTimeout(tick, nextDelay());
2608
+ }
2609
+ /** Pause the video, stop timers, and release the lease (keepalive). */
2610
+ async stop() {
2611
+ this.version += 1;
2612
+ this.video.pause();
2613
+ const lease = this.active;
2614
+ this.active = null;
2615
+ clearInterval(this.heartbeatTimer);
2616
+ clearTimeout(this.watermarkTimer);
2617
+ clearTimeout(this.hideTimer);
2618
+ this.hideWatermark();
2619
+ if (lease) {
2620
+ await this.request("/student/release", lease.token, {}, true).catch(
2621
+ () => {
2622
+ }
2623
+ );
2624
+ }
2625
+ }
2626
+ /** Release the lease, remove the overlay, and detach listeners. */
2627
+ async close() {
2628
+ this.closed = true;
2629
+ await this.stop();
2630
+ this.watermarkEl?.remove();
2631
+ this.watermarkEl = null;
2632
+ this.video.removeEventListener("ended", this.onEnded);
2633
+ if (typeof window !== "undefined") {
2634
+ window.removeEventListener("pagehide", this.onPageHide);
2635
+ }
2636
+ }
2637
+ async request(path, token, body = {}, keepalive = false) {
2638
+ const controller = new AbortController();
2639
+ const timeout = setTimeout(
2640
+ () => controller.abort(),
2641
+ STUDENT_REQUEST_TIMEOUT_MS
2642
+ );
2643
+ try {
2644
+ const response = await this.fetchImpl(this.config.baseUrl + path, {
2645
+ method: "POST",
2646
+ headers: {
2647
+ Authorization: `Bearer ${token}`,
2648
+ "Content-Type": "application/json"
2649
+ },
2650
+ body: JSON.stringify(body),
2651
+ cache: "no-store",
2652
+ credentials: "omit",
2653
+ redirect: "error",
2654
+ signal: controller.signal,
2655
+ keepalive
2656
+ });
2657
+ const result = await response.json().catch(() => ({}));
2658
+ if (!response.ok) throw mapStudentLeaseError(response.status, result);
2659
+ return result;
2660
+ } finally {
2661
+ clearTimeout(timeout);
2662
+ }
2663
+ }
2664
+ createWatermarkElement() {
2665
+ if (!this.container || typeof document === "undefined") return;
2666
+ const el = document.createElement("div");
2667
+ Object.assign(el.style, {
2668
+ position: "absolute",
2669
+ display: "none",
2670
+ pointerEvents: "none",
2671
+ zIndex: "20",
2672
+ color: "white",
2673
+ background: "rgba(0,0,0,.4)",
2674
+ padding: "4px 8px",
2675
+ font: "14px sans-serif",
2676
+ maxWidth: "90%",
2677
+ overflowWrap: "anywhere"
2678
+ });
2679
+ if (getComputedStyle(this.container).position === "static") {
2680
+ this.container.style.position = "relative";
2681
+ }
2682
+ this.container.append(el);
2683
+ this.watermarkEl = el;
2684
+ }
2685
+ showWatermark(text) {
2686
+ const el = this.watermarkEl;
2687
+ const container = this.container;
2688
+ if (!el || !container) return;
2689
+ el.textContent = text;
2690
+ el.style.display = "block";
2691
+ el.style.left = `${Math.floor(
2692
+ this.random() * Math.max(1, container.clientWidth - el.offsetWidth)
2693
+ )}px`;
2694
+ el.style.top = `${Math.floor(
2695
+ this.random() * Math.max(1, container.clientHeight - el.offsetHeight)
2696
+ )}px`;
2697
+ }
2698
+ hideWatermark() {
2699
+ if (this.watermarkEl) this.watermarkEl.style.display = "none";
2700
+ }
2701
+ };
2702
+ function assertToken(value) {
2703
+ if (typeof value !== "string" || !value || value.length > TOKEN_MAX_LENGTH || /[\r\n]/.test(value)) {
2704
+ throw new Error("Student playback token is required");
2705
+ }
2706
+ return value;
2707
+ }
2708
+ function toLeaseError(error) {
2709
+ if (error instanceof StudentLeaseError) return error;
2710
+ return new StudentLeaseError(
2711
+ error instanceof Error ? error.message : "Student playback authorization unavailable."
2712
+ );
2713
+ }
2714
+
2715
+ // src/analytics/AnalyticsClient.ts
2716
+ var defaultSend = async (url, body, opts) => {
2717
+ const response = await fetch(url, {
2718
+ method: "POST",
2719
+ headers: { "Content-Type": "application/json" },
2720
+ body: JSON.stringify(body),
2721
+ keepalive: opts?.keepalive ?? false
2722
+ });
2723
+ const value = await response.json().catch(() => ({}));
2724
+ if (!response.ok) {
2725
+ throw new Error(
2726
+ value.error ?? "Analytics request failed"
2727
+ );
2728
+ }
2729
+ return value;
2730
+ };
2731
+ var AnalyticsClient = class {
2732
+ constructor(options) {
2733
+ this.options = options;
2734
+ this.session = null;
2735
+ this.watched = 0;
2736
+ this.sequence = 0;
2737
+ this.finished = false;
2738
+ this.destroyed = false;
2739
+ this.lastPosition = 0;
2740
+ this.progressedAt = Number.NEGATIVE_INFINITY;
2741
+ this.onPause = () => {
2742
+ void this.heartbeat(false);
2743
+ };
2744
+ this.onEnded = () => {
2745
+ void this.heartbeat(true);
2746
+ };
2747
+ this.onPageHide = () => {
2748
+ void this.heartbeat(true);
2749
+ };
2750
+ this.send = options.send ?? defaultSend;
2751
+ this.now = options.now ?? (() => typeof performance !== "undefined" ? performance.now() : Date.now());
2752
+ this.onError = options.onError ?? (() => {
2753
+ });
2754
+ this.lastTime = this.now();
2755
+ this.lastPosition = options.video.currentTime || 0;
2756
+ }
2757
+ /** Total seconds credited as watched so far. */
2758
+ get watchedSeconds() {
2759
+ return this.watched;
2760
+ }
2761
+ /** Session from `analytics/start`, or null before it resolves. */
2762
+ get currentSession() {
2763
+ return this.session;
2764
+ }
2765
+ /**
2766
+ * POST `{origin}/media/{videoKey}/analytics/start` and begin sampling.
2767
+ * Resolves to the session, or null on failure (reported via `onError`).
2768
+ */
2769
+ async start() {
2770
+ if (this.destroyed) return null;
2771
+ const { video, origin, videoKey, deviceId, platform } = this.options;
2772
+ const url = new URL(
2773
+ `/media/${encodeURIComponent(videoKey)}/analytics/start`,
2774
+ origin
2775
+ ).href;
2776
+ const token = typeof this.options.playbackToken === "function" ? this.options.playbackToken() : this.options.playbackToken;
2777
+ video.addEventListener("pause", this.onPause);
2778
+ video.addEventListener("ended", this.onEnded);
2779
+ if (typeof window !== "undefined") {
2780
+ window.addEventListener("pagehide", this.onPageHide);
2781
+ }
2782
+ this.lastTime = this.now();
2783
+ this.lastPosition = video.currentTime || 0;
2784
+ this.sampleTimer = setInterval(
2785
+ () => this.sample(),
2786
+ this.options.sampleIntervalMs ?? 1e3
2787
+ );
2788
+ this.heartbeatTimer = setInterval(
2789
+ () => void this.heartbeat(false),
2790
+ this.options.heartbeatIntervalMs ?? 15e3
2791
+ );
2792
+ try {
2793
+ const value = await this.send(url, {
2794
+ playback_token: token,
2795
+ device_id: deviceId,
2796
+ platform: platform ?? "web"
2797
+ });
2798
+ const session = unwrapSession(value);
2799
+ if (!session) throw new Error("Invalid analytics start response");
2800
+ if (this.destroyed) return null;
2801
+ this.session = session;
2802
+ return session;
2803
+ } catch (error) {
2804
+ this.onError(error);
2805
+ return null;
2806
+ }
2807
+ }
2808
+ /** Credit elapsed wall time when the video genuinely advanced. */
2809
+ sample() {
2810
+ const { video } = this.options;
2811
+ const now = this.now();
2812
+ const elapsed = Math.min(2, (now - this.lastTime) / 1e3);
2813
+ const advance = video.currentTime - this.lastPosition;
2814
+ const rate = Math.max(1, video.playbackRate || 1);
2815
+ if (!video.paused && !video.seeking && video.readyState >= 2 && advance > 0 && advance <= elapsed * rate + 1) {
2816
+ this.watched += Math.min(
2817
+ elapsed,
2818
+ advance / Math.max(0.1, video.playbackRate || 1)
2819
+ );
2820
+ this.progressedAt = now;
2821
+ }
2822
+ this.lastTime = now;
2823
+ this.lastPosition = video.currentTime;
2824
+ }
2825
+ /**
2826
+ * Send an event heartbeat. `end: true` marks the session finished, sends with
2827
+ * `keepalive`, and suppresses further heartbeats.
2828
+ */
2829
+ async heartbeat(end = false) {
2830
+ const session = this.session;
2831
+ if (!session || this.finished) return;
2832
+ this.sample();
2833
+ if (end) this.finished = true;
2834
+ const { video, origin } = this.options;
2835
+ const body = {
2836
+ token: session.token,
2837
+ seq: ++this.sequence,
2838
+ watched_seconds: this.watched,
2839
+ playing: !video.paused && !video.ended && !video.seeking && this.now() - this.progressedAt < (this.options.progressWindowMs ?? 5e3),
2840
+ ended: end
2841
+ };
2842
+ try {
2843
+ await this.send(new URL(session.event_url, origin).href, body, {
2844
+ keepalive: true
2845
+ });
2846
+ } catch (error) {
2847
+ this.onError(error);
2848
+ }
2849
+ }
2850
+ /** Send the final heartbeat (if started) and detach everything. */
2851
+ async destroy() {
2852
+ if (this.destroyed) return;
2853
+ await this.heartbeat(true);
2854
+ this.destroyed = true;
2855
+ clearInterval(this.sampleTimer);
2856
+ clearInterval(this.heartbeatTimer);
2857
+ const { video } = this.options;
2858
+ video.removeEventListener("pause", this.onPause);
2859
+ video.removeEventListener("ended", this.onEnded);
2860
+ if (typeof window !== "undefined") {
2861
+ window.removeEventListener("pagehide", this.onPageHide);
2862
+ }
2863
+ }
2864
+ };
2865
+ function unwrapSession(value) {
2866
+ const candidate = value && typeof value === "object" && "data" in value ? value.data : value;
2867
+ if (!candidate || typeof candidate !== "object") return null;
2868
+ const { token, event_url } = candidate;
2869
+ if (typeof token !== "string" || typeof event_url !== "string") return null;
2870
+ return candidate;
2871
+ }
2325
2872
  // Annotate the CommonJS export names for ESM import in node:
2326
2873
  0 && (module.exports = {
2874
+ AnalyticsClient,
2327
2875
  AuthManager,
2328
2876
  AuthParamsStore,
2329
2877
  DEFAULT_CONTROLS,
@@ -2336,26 +2884,40 @@ function createVideoPlayer(options) {
2336
2884
  EventEmitter,
2337
2885
  KEY_PROXY_MAX_FAILURES,
2338
2886
  PACKAGE_VERSION,
2887
+ PLATFORM_IN_USE,
2888
+ PLAYBACK_NOT_READY,
2339
2889
  PLAYBACK_RATES,
2340
2890
  PlaybackSourceManager,
2341
2891
  PlayerErrorCode,
2342
2892
  RefreshManager,
2893
+ SDK_SUBTITLE_TRACK_SELECTOR,
2343
2894
  SECRET_SCAN_MAX_DEPTH,
2895
+ STUDENT_HEARTBEAT_INTERVAL_MS,
2896
+ STUDENT_NOT_READY_DEADLINE_MS,
2897
+ STUDENT_NOT_READY_MAX_ATTEMPTS,
2898
+ STUDENT_NOT_READY_RETRY_DELAY_MS,
2899
+ STUDENT_REQUEST_TIMEOUT_MS,
2900
+ StudentLeaseClient,
2901
+ StudentLeaseError,
2902
+ appexHlsConfig,
2344
2903
  assertNoSecretsInConfig,
2345
2904
  createAuthParamsLoader,
2346
2905
  createPlayerError,
2347
2906
  createVideoPlayer,
2348
2907
  getLiveEdgeTime,
2908
+ hlsConfig,
2349
2909
  isAtLiveEdge,
2350
2910
  isEncryptionKeyUrl,
2351
2911
  isLivePlaylistUrl,
2352
2912
  isPlainObject,
2353
2913
  isSameOriginHttpUrl,
2914
+ mapStudentLeaseError,
2354
2915
  mergePlayerConfig,
2355
2916
  redactObject,
2356
2917
  redactSensitive,
2357
2918
  redactValue,
2358
2919
  resolveBuiltinHlsLoader,
2920
+ restoreSubtitleSelection,
2359
2921
  rewriteHlsRequestUrl,
2360
2922
  seekToLiveEdge,
2361
2923
  themeToCssVars