stormcloud-video-player 0.7.3 → 0.7.4

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.
@@ -347,185 +347,8 @@ __export(StormcloudVideoPlayer_exports, {
347
347
  }
348
348
  });
349
349
  module.exports = __toCommonJS(StormcloudVideoPlayer_exports);
350
- var import_hls2 = __toESM(require("hls.js"), 1);
350
+ var import_hls = __toESM(require("hls.js"), 1);
351
351
  // src/sdk/vastParser.ts
352
- function isHlsType(type) {
353
- return type === "application/x-mpegURL" || type.includes("m3u8");
354
- }
355
- function isMp4Type(type) {
356
- return type === "video/mp4" || type.includes("mp4");
357
- }
358
- function parseVastXml(xmlString) {
359
- var filter = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : "all", logPrefix = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : "[VastParser]";
360
- try {
361
- var _xmlDoc_querySelector, _xmlDoc_querySelector1, _xmlDoc_querySelector_textContent, _xmlDoc_querySelector2;
362
- var parser = new DOMParser();
363
- var xmlDoc = parser.parseFromString(xmlString, "text/xml");
364
- var parserError = xmlDoc.querySelector("parsererror");
365
- if (parserError) {
366
- console.error("".concat(logPrefix, " XML parsing error (malformed VAST XML):"), parserError.textContent);
367
- return null;
368
- }
369
- var adElement = xmlDoc.querySelector("Ad");
370
- if (!adElement) {
371
- console.warn("".concat(logPrefix, " No Ad element found in VAST XML"));
372
- return null;
373
- }
374
- var adId = adElement.getAttribute("id") || "unknown";
375
- var title = ((_xmlDoc_querySelector = xmlDoc.querySelector("AdTitle")) === null || _xmlDoc_querySelector === void 0 ? void 0 : _xmlDoc_querySelector.textContent) || "Ad";
376
- var isNoAdAvailable = adId === "empty" || title.toLowerCase().includes("no ad available") || title.toLowerCase() === "no ad available";
377
- var durationText = ((_xmlDoc_querySelector1 = xmlDoc.querySelector("Duration")) === null || _xmlDoc_querySelector1 === void 0 ? void 0 : _xmlDoc_querySelector1.textContent) || "00:00:30";
378
- var durationParts = durationText.split(":");
379
- var duration = parseInt(durationParts[0] || "0", 10) * 3600 + parseInt(durationParts[1] || "0", 10) * 60 + Math.round(parseFloat(durationParts[2] || "0"));
380
- var mediaFileElements = xmlDoc.querySelectorAll("MediaFile");
381
- var mediaFiles = [];
382
- console.log("".concat(logPrefix, " Found ").concat(mediaFileElements.length, " MediaFile element(s) in VAST XML"));
383
- mediaFileElements.forEach(function(mf, index) {
384
- var _mf_textContent;
385
- var type = mf.getAttribute("type") || "";
386
- var url = ((_mf_textContent = mf.textContent) === null || _mf_textContent === void 0 ? void 0 : _mf_textContent.trim()) || "";
387
- var width = mf.getAttribute("width") || "";
388
- var height = mf.getAttribute("height") || "";
389
- console.log("".concat(logPrefix, " MediaFile ").concat(index, ': type="').concat(type, '", url="').concat(url.substring(0, 80), '...", width="').concat(width, '", height="').concat(height, '"'));
390
- if (!url) {
391
- console.warn("".concat(logPrefix, " MediaFile ").concat(index, " has empty URL"));
392
- return;
393
- }
394
- var isHls = isHlsType(type);
395
- var isMp4 = isMp4Type(type);
396
- var accepted = false;
397
- if (filter === "hls-only") {
398
- accepted = isHls;
399
- } else if (filter === "mp4-first") {
400
- accepted = isMp4 || isHls;
401
- } else {
402
- accepted = true;
403
- }
404
- if (!accepted) {
405
- console.log("".concat(logPrefix, " MediaFile ").concat(index, ' ignored (type="').concat(type, '" not accepted by filter "').concat(filter, '")'));
406
- return;
407
- }
408
- var bitrateAttr = mf.getAttribute("bitrate");
409
- var bitrateValue = bitrateAttr ? parseInt(bitrateAttr, 10) : void 0;
410
- mediaFiles.push({
411
- url: url,
412
- type: type,
413
- width: parseInt(width || "1920", 10),
414
- height: parseInt(height || "1080", 10),
415
- bitrate: bitrateValue && bitrateValue > 0 ? bitrateValue : void 0
416
- });
417
- console.log("".concat(logPrefix, ' Added MediaFile: type="').concat(type, '" url="').concat(url.substring(0, 80), '..."'));
418
- });
419
- if (filter === "mp4-first" && mediaFiles.length > 1) {
420
- mediaFiles.sort(function(a, b) {
421
- var aIsMp4 = isMp4Type(a.type) ? 0 : 1;
422
- var bIsMp4 = isMp4Type(b.type) ? 0 : 1;
423
- return aIsMp4 - bIsMp4;
424
- });
425
- }
426
- if (mediaFiles.length === 0) {
427
- if (isNoAdAvailable) {
428
- console.warn("".concat(logPrefix, " No ads available (VAST response indicates no ads)"));
429
- } else {
430
- console.warn("".concat(logPrefix, " No compatible media files found in VAST XML"));
431
- }
432
- return null;
433
- }
434
- var trackingUrls = {
435
- impression: [],
436
- start: [],
437
- firstQuartile: [],
438
- midpoint: [],
439
- thirdQuartile: [],
440
- complete: [],
441
- mute: [],
442
- unmute: [],
443
- pause: [],
444
- resume: [],
445
- fullscreen: [],
446
- exitFullscreen: [],
447
- skip: [],
448
- error: []
449
- };
450
- xmlDoc.querySelectorAll("Impression").forEach(function(el) {
451
- var _el_textContent;
452
- var url = (_el_textContent = el.textContent) === null || _el_textContent === void 0 ? void 0 : _el_textContent.trim();
453
- if (url) trackingUrls.impression.push(url);
454
- });
455
- xmlDoc.querySelectorAll("Tracking").forEach(function(el) {
456
- var _el_textContent;
457
- var event = el.getAttribute("event");
458
- var url = (_el_textContent = el.textContent) === null || _el_textContent === void 0 ? void 0 : _el_textContent.trim();
459
- if (event && url) {
460
- var eventKey = event;
461
- if (trackingUrls[eventKey]) {
462
- trackingUrls[eventKey].push(url);
463
- }
464
- }
465
- });
466
- var clickThrough = (_xmlDoc_querySelector2 = xmlDoc.querySelector("ClickThrough")) === null || _xmlDoc_querySelector2 === void 0 ? void 0 : (_xmlDoc_querySelector_textContent = _xmlDoc_querySelector2.textContent) === null || _xmlDoc_querySelector_textContent === void 0 ? void 0 : _xmlDoc_querySelector_textContent.trim();
467
- return {
468
- id: adId,
469
- title: title,
470
- duration: duration,
471
- mediaFiles: mediaFiles,
472
- trackingUrls: trackingUrls,
473
- clickThrough: clickThrough
474
- };
475
- } catch (error) {
476
- console.error("".concat(logPrefix, " Error parsing VAST XML:"), error);
477
- return null;
478
- }
479
- }
480
- function fetchAndParseVastAd(vastTagUrl) {
481
- var filter = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : "all", logPrefix = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : "[VastParser]";
482
- return _async_to_generator(function() {
483
- var response, vastXml;
484
- return _ts_generator(this, function(_state) {
485
- switch(_state.label){
486
- case 0:
487
- return [
488
- 4,
489
- fetch(vastTagUrl, {
490
- mode: "cors",
491
- credentials: "include",
492
- headers: {
493
- Accept: "application/xml, text/xml, */*"
494
- },
495
- referrerPolicy: "no-referrer-when-downgrade"
496
- })
497
- ];
498
- case 1:
499
- response = _state.sent();
500
- if (!response.ok) {
501
- throw new Error("Failed to fetch VAST: ".concat(response.statusText));
502
- }
503
- return [
504
- 4,
505
- response.text()
506
- ];
507
- case 2:
508
- vastXml = _state.sent();
509
- console.log("".concat(logPrefix, " VAST XML received"));
510
- console.log("".concat(logPrefix, " VAST XML content (first 2000 chars):"), vastXml.substring(0, 2e3));
511
- return [
512
- 2,
513
- parseVastXml(vastXml, filter, logPrefix)
514
- ];
515
- }
516
- });
517
- })();
518
- }
519
- function createEmptyTrackingState() {
520
- return {
521
- impression: false,
522
- start: false,
523
- firstQuartile: false,
524
- midpoint: false,
525
- thirdQuartile: false,
526
- complete: false
527
- };
528
- }
529
352
  function firePixelWithRetry(url) {
530
353
  var retries = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 2, delayMs = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : 500, logPrefix = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : "[VastParser]";
531
354
  return _async_to_generator(function() {
@@ -648,16 +471,164 @@ function fireTrackingPixels(urls, sessionId) {
648
471
  }
649
472
  });
650
473
  }
651
- // src/sdk/vastManager.ts
652
- var VAST_TAG_URL = "https://pubads.g.doubleclick.net/gampad/ads?iu=/21821455290/Airy-Android&description_url=http%3A%2F%2Fairy.tv&tfcd=0&npa=0&sz=1x1%7C300x250%7C400x300%7C640x480&gdfp_req=1&unviewed_position_start=1&correlator=[placeholder]&vpos=preroll&output=vast&env=vp&vpmute=0&vpa=click";
653
- var DEFAULT_TIMEOUT_MS = 5e3;
654
- var MAX_RETRIES = 3;
655
- var RETRY_BACKOFF_MS = 1500;
656
- function createVastManager() {
657
- var options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
658
- var _options_debug;
659
- var initialized = false;
660
- var debug = (_options_debug = options.debug) !== null && _options_debug !== void 0 ? _options_debug : false;
474
+ // src/sdk/adstormPlayer.ts
475
+ var SUPPORTED_VIDEO_EXTENSIONS = [
476
+ ".mp4",
477
+ ".webm",
478
+ ".ogg",
479
+ ".m3u8",
480
+ ".ts"
481
+ ];
482
+ var UNSUPPORTED_VIDEO_EXTENSIONS = [
483
+ ".flv",
484
+ ".f4v",
485
+ ".swf",
486
+ ".wmv",
487
+ ".avi",
488
+ ".mov",
489
+ ".mkv"
490
+ ];
491
+ var REQUEST_TIMEOUT_MS = 5e3;
492
+ var REQUEST_MAX_RETRIES = 3;
493
+ var REQUEST_RETRY_BACKOFF_MS = 1500;
494
+ var AD_LAYER_Z_INDEX = "2147483646";
495
+ var COUNTDOWN_Z_INDEX = "2147483647";
496
+ var STALL_TIMEOUT_MS = 8e3;
497
+ function getFileExtension(url) {
498
+ try {
499
+ var pathname = new URL(url, "http://dummy").pathname;
500
+ var lastDot = pathname.lastIndexOf(".");
501
+ if (lastDot === -1) return "";
502
+ return pathname.slice(lastDot).toLowerCase();
503
+ } catch (unused) {
504
+ var lastDot1 = url.lastIndexOf(".");
505
+ if (lastDot1 === -1) return "";
506
+ var ext = url.slice(lastDot1).split(/[?#]/)[0];
507
+ return (ext || "").toLowerCase();
508
+ }
509
+ }
510
+ function isUnsupportedFormat(url) {
511
+ var ext = getFileExtension(url);
512
+ return UNSUPPORTED_VIDEO_EXTENSIONS.indexOf(ext) !== -1;
513
+ }
514
+ function replaceFlvExtension(url) {
515
+ var ext = getFileExtension(url);
516
+ if (ext === ".flv") {
517
+ return url.replace(/\.flv(\?|$)/i, ".mp4$1");
518
+ }
519
+ return url;
520
+ }
521
+ function isSupportedFormat(url, mimeType) {
522
+ if (isUnsupportedFormat(url)) {
523
+ return false;
524
+ }
525
+ var ext = getFileExtension(url);
526
+ if (SUPPORTED_VIDEO_EXTENSIONS.indexOf(ext) !== -1) {
527
+ return true;
528
+ }
529
+ if (ext === "" || ext === ".") {
530
+ return mimeType.includes("video/mp4") || mimeType.includes("video/webm") || mimeType.includes("m3u8") || mimeType.includes("application/x-mpegurl");
531
+ }
532
+ return false;
533
+ }
534
+ function createAdStormPlayer(contentVideo, options) {
535
+ var licenseKey = options.licenseKey, _options_debug = options.debug, debug = _options_debug === void 0 ? false : _options_debug;
536
+ var adPlaying = false;
537
+ var originalMutedState = false;
538
+ var originalVolume = Math.max(0, Math.min(1, contentVideo.volume || 1));
539
+ var listeners = /* @__PURE__ */ new Map();
540
+ var adVideoElement;
541
+ var adContainerEl;
542
+ var adCountdownEl;
543
+ var currentAd;
544
+ var destroyed = false;
545
+ var tornDown = false;
546
+ var continueLiveStreamDuringAds = false;
547
+ var sessionId;
548
+ var adStallTimerId;
549
+ var adCountdownTimerId;
550
+ var adHideTimerId;
551
+ var lastCountdownSecond = -1;
552
+ var adListenersBound = false;
553
+ var parentPositionOverridden = false;
554
+ var adHandlers = {
555
+ timeupdate: function timeupdate() {
556
+ if (!currentAd || !adVideoElement || destroyed || tornDown) return;
557
+ var progress = adVideoElement.currentTime / currentAd.duration;
558
+ if (progress >= 0.25 && !trackingFired.firstQuartile) {
559
+ trackingFired.firstQuartile = true;
560
+ fireTrackingPixels2(currentAd.trackingUrls.firstQuartile);
561
+ }
562
+ if (progress >= 0.5 && !trackingFired.midpoint) {
563
+ trackingFired.midpoint = true;
564
+ fireTrackingPixels2(currentAd.trackingUrls.midpoint);
565
+ }
566
+ if (progress >= 0.75 && !trackingFired.thirdQuartile) {
567
+ trackingFired.thirdQuartile = true;
568
+ fireTrackingPixels2(currentAd.trackingUrls.thirdQuartile);
569
+ }
570
+ updateAdCountdown();
571
+ },
572
+ playing: function playing() {
573
+ clearAdStallTimer();
574
+ if (!currentAd || trackingFired.start || destroyed || tornDown) return;
575
+ trackingFired.start = true;
576
+ fireTrackingPixels2(currentAd.trackingUrls.start);
577
+ startAdCountdown();
578
+ log("Ad started playing");
579
+ },
580
+ ended: function ended() {
581
+ if (!currentAd || trackingFired.complete || destroyed || tornDown) return;
582
+ trackingFired.complete = true;
583
+ fireTrackingPixels2(currentAd.trackingUrls.complete);
584
+ log("Ad completed");
585
+ handleAdComplete();
586
+ },
587
+ error: function error(e) {
588
+ if (destroyed || tornDown) return;
589
+ console.error("[AdStormPlayer] Ad video error:", e);
590
+ if (currentAd) fireTrackingPixels2(currentAd.trackingUrls.error);
591
+ handleAdError();
592
+ },
593
+ waiting: function waiting() {
594
+ clearAdStallTimer();
595
+ adStallTimerId = setTimeout(function() {
596
+ adStallTimerId = void 0;
597
+ if (!adPlaying || destroyed || tornDown) return;
598
+ console.warn("[AdStormPlayer] Ad playback stalled too long");
599
+ handleAdError();
600
+ }, STALL_TIMEOUT_MS);
601
+ },
602
+ volumechange: function volumechange() {
603
+ if (!currentAd || !adVideoElement || destroyed || tornDown) return;
604
+ if (adVideoElement.muted || adVideoElement.volume <= 0) {
605
+ fireTrackingPixels2(currentAd.trackingUrls.mute);
606
+ } else {
607
+ fireTrackingPixels2(currentAd.trackingUrls.unmute);
608
+ }
609
+ },
610
+ pause: function pause() {
611
+ if (!currentAd || !adVideoElement || destroyed || tornDown) return;
612
+ if (!adVideoElement.ended) {
613
+ fireTrackingPixels2(currentAd.trackingUrls.pause);
614
+ }
615
+ },
616
+ play: function play() {
617
+ if (!currentAd || !adVideoElement || destroyed || tornDown) return;
618
+ if (adVideoElement.currentTime > 0) {
619
+ fireTrackingPixels2(currentAd.trackingUrls.resume);
620
+ }
621
+ }
622
+ };
623
+ var trackingFired = {
624
+ impression: false,
625
+ start: false,
626
+ firstQuartile: false,
627
+ midpoint: false,
628
+ thirdQuartile: false,
629
+ complete: false
630
+ };
631
+ var preloadSlots = /* @__PURE__ */ new Map();
661
632
  function log() {
662
633
  for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
663
634
  args[_key] = arguments[_key];
@@ -665,58 +636,340 @@ function createVastManager() {
665
636
  if (debug) {
666
637
  var _console;
667
638
  (_console = console).log.apply(_console, [
668
- "[VastManager]"
639
+ "[AdStormPlayer]"
669
640
  ].concat(_to_consumable_array(args)));
670
641
  }
671
642
  }
672
- function warn() {
673
- for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
674
- args[_key] = arguments[_key];
643
+ function emit(event, payload) {
644
+ var set = listeners.get(event);
645
+ if (!set) return;
646
+ var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
647
+ try {
648
+ for(var _iterator = Array.from(set)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
649
+ var fn = _step.value;
650
+ try {
651
+ fn(payload);
652
+ } catch (error) {
653
+ console.warn("[AdStormPlayer] Error in event listener for ".concat(event, ":"), error);
654
+ }
655
+ }
656
+ } catch (err) {
657
+ _didIteratorError = true;
658
+ _iteratorError = err;
659
+ } finally{
660
+ try {
661
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
662
+ _iterator.return();
663
+ }
664
+ } finally{
665
+ if (_didIteratorError) {
666
+ throw _iteratorError;
667
+ }
668
+ }
675
669
  }
676
- var _console;
677
- (_console = console).warn.apply(_console, [
678
- "[VastManager]"
679
- ].concat(_to_consumable_array(args)));
680
670
  }
681
- function initialize() {
682
- return _async_to_generator(function() {
683
- return _ts_generator(this, function(_state) {
684
- if (initialized) return [
685
- 2
686
- ];
687
- initialized = true;
688
- log("Initialized, VAST tag URL:", VAST_TAG_URL.split("?")[0]);
689
- return [
690
- 2
691
- ];
671
+ function fireTrackingPixels2(urls) {
672
+ fireTrackingPixels(urls, sessionId, "[AdStormPlayer]");
673
+ }
674
+ function clearAdStallTimer() {
675
+ if (adStallTimerId) {
676
+ clearTimeout(adStallTimerId);
677
+ adStallTimerId = void 0;
678
+ }
679
+ }
680
+ function clearAdCountdownTimer() {
681
+ if (adCountdownTimerId) {
682
+ clearInterval(adCountdownTimerId);
683
+ adCountdownTimerId = void 0;
684
+ }
685
+ lastCountdownSecond = -1;
686
+ }
687
+ function updateAdCountdown() {
688
+ if (!adCountdownEl || !adVideoElement || !currentAd || !adPlaying) return;
689
+ var remainingSec = Math.max(0, Math.ceil((currentAd.duration || 0) - adVideoElement.currentTime));
690
+ if (remainingSec === lastCountdownSecond) return;
691
+ lastCountdownSecond = remainingSec;
692
+ adCountdownEl.textContent = "Ad ".concat(remainingSec, "s");
693
+ emit("ad_countdown", {
694
+ remainingSec: remainingSec,
695
+ durationSec: currentAd.duration,
696
+ currentTimeSec: adVideoElement.currentTime
697
+ });
698
+ }
699
+ function startAdCountdown() {
700
+ clearAdCountdownTimer();
701
+ updateAdCountdown();
702
+ adCountdownTimerId = setInterval(updateAdCountdown, 250);
703
+ }
704
+ function generateSessionId() {
705
+ return "adstorm-".concat(Date.now(), "-").concat(Math.random().toString(36).slice(2, 10));
706
+ }
707
+ function bindAdEventListeners() {
708
+ if (!adVideoElement || adListenersBound) return;
709
+ adVideoElement.addEventListener("timeupdate", adHandlers.timeupdate);
710
+ adVideoElement.addEventListener("playing", adHandlers.playing);
711
+ adVideoElement.addEventListener("ended", adHandlers.ended);
712
+ adVideoElement.addEventListener("error", adHandlers.error);
713
+ adVideoElement.addEventListener("waiting", adHandlers.waiting);
714
+ adVideoElement.addEventListener("volumechange", adHandlers.volumechange);
715
+ adVideoElement.addEventListener("pause", adHandlers.pause);
716
+ adVideoElement.addEventListener("play", adHandlers.play);
717
+ adListenersBound = true;
718
+ }
719
+ function unbindAdEventListeners() {
720
+ if (!adVideoElement || !adListenersBound) return;
721
+ adVideoElement.removeEventListener("timeupdate", adHandlers.timeupdate);
722
+ adVideoElement.removeEventListener("playing", adHandlers.playing);
723
+ adVideoElement.removeEventListener("ended", adHandlers.ended);
724
+ adVideoElement.removeEventListener("error", adHandlers.error);
725
+ adVideoElement.removeEventListener("waiting", adHandlers.waiting);
726
+ adVideoElement.removeEventListener("volumechange", adHandlers.volumechange);
727
+ adVideoElement.removeEventListener("pause", adHandlers.pause);
728
+ adVideoElement.removeEventListener("play", adHandlers.play);
729
+ adListenersBound = false;
730
+ }
731
+ function teardownCurrentPlayback() {
732
+ unbindAdEventListeners();
733
+ clearAdStallTimer();
734
+ clearAdCountdownTimer();
735
+ if (!adVideoElement) return;
736
+ adVideoElement.pause();
737
+ adVideoElement.removeAttribute("src");
738
+ adVideoElement.load();
739
+ }
740
+ function buildVastUrl(durationSeconds, metadata) {
741
+ var baseUrl = "https://adstorm.co/api-adstorm-dev/adstorm/vast/".concat(licenseKey, "/pod");
742
+ var defaultMetadata = {
743
+ video: {
744
+ codec: "h264",
745
+ width: contentVideo.videoWidth || 1280,
746
+ height: contentVideo.videoHeight || 720,
747
+ fps: 29.97,
748
+ bitrate: 5e3,
749
+ profile: "high",
750
+ pix_fmt: "yuv420p",
751
+ has_b_frames: 0
752
+ },
753
+ audio: {
754
+ codec: "aac",
755
+ sample_rate: 48e3,
756
+ bitrate: 128
757
+ }
758
+ };
759
+ var finalMetadata = metadata || defaultMetadata;
760
+ var metadataStr = encodeURIComponent(JSON.stringify(finalMetadata));
761
+ return "".concat(baseUrl, "?duration=").concat(Math.ceil(durationSeconds), "&metadata=").concat(metadataStr);
762
+ }
763
+ function parseVastXml(xmlString) {
764
+ var ads = [];
765
+ try {
766
+ var parser = new DOMParser();
767
+ var xmlDoc = parser.parseFromString(xmlString, "text/xml");
768
+ var parserError = xmlDoc.querySelector("parsererror");
769
+ if (parserError) {
770
+ console.error("[AdStormPlayer] XML parsing error:", parserError.textContent);
771
+ return [];
772
+ }
773
+ var adElements = xmlDoc.querySelectorAll("Ad");
774
+ adElements.forEach(function(adElement) {
775
+ var _adElement_querySelector, _adElement_querySelector1, _adElement_querySelector_textContent, _adElement_querySelector2;
776
+ var adId = adElement.getAttribute("id") || "unknown";
777
+ var title = ((_adElement_querySelector = adElement.querySelector("AdTitle")) === null || _adElement_querySelector === void 0 ? void 0 : _adElement_querySelector.textContent) || "Ad";
778
+ var durationText = ((_adElement_querySelector1 = adElement.querySelector("Duration")) === null || _adElement_querySelector1 === void 0 ? void 0 : _adElement_querySelector1.textContent) || "00:00:30";
779
+ var durationParts = durationText.split(":");
780
+ var duration = parseInt(durationParts[0] || "0", 10) * 3600 + parseInt(durationParts[1] || "0", 10) * 60 + parseFloat(durationParts[2] || "0");
781
+ var mediaFileElements = adElement.querySelectorAll("MediaFile");
782
+ var mediaFiles = [];
783
+ mediaFileElements.forEach(function(mf) {
784
+ var _mf_textContent;
785
+ var type = mf.getAttribute("type") || "";
786
+ var url = ((_mf_textContent = mf.textContent) === null || _mf_textContent === void 0 ? void 0 : _mf_textContent.trim()) || "";
787
+ var width = parseInt(mf.getAttribute("width") || "1920", 10);
788
+ var height = parseInt(mf.getAttribute("height") || "1080", 10);
789
+ var bitrate = mf.getAttribute("bitrate") ? parseInt(mf.getAttribute("bitrate"), 10) : void 0;
790
+ if (!url) {
791
+ log("Skipping empty MediaFile URL");
792
+ return;
793
+ }
794
+ var originalUrl = url;
795
+ url = replaceFlvExtension(url);
796
+ if (url !== originalUrl) {
797
+ log("Converted FLV to MP4: ".concat(originalUrl, " -> ").concat(url));
798
+ }
799
+ if (isUnsupportedFormat(url)) {
800
+ var ext = getFileExtension(url);
801
+ log("Skipping unsupported format: ".concat(url, " (extension: ").concat(ext, ", declared type: ").concat(type, ")"));
802
+ return;
803
+ }
804
+ if (isSupportedFormat(url, type)) {
805
+ mediaFiles.push({
806
+ url: url,
807
+ type: type,
808
+ width: width,
809
+ height: height,
810
+ bitrate: bitrate
811
+ });
812
+ log("Found media file: ".concat(url, " (").concat(type, ", ").concat(width, "x").concat(height, ")"));
813
+ } else {
814
+ log("Skipping incompatible media file: ".concat(url, " (type: ").concat(type, ")"));
815
+ }
816
+ });
817
+ if (mediaFiles.length === 0) {
818
+ log("No valid media files found in ad:", adId);
819
+ return;
820
+ }
821
+ var trackingUrls = {
822
+ impression: [],
823
+ start: [],
824
+ firstQuartile: [],
825
+ midpoint: [],
826
+ thirdQuartile: [],
827
+ complete: [],
828
+ mute: [],
829
+ unmute: [],
830
+ pause: [],
831
+ resume: [],
832
+ error: []
833
+ };
834
+ adElement.querySelectorAll("Impression").forEach(function(el) {
835
+ var _el_textContent;
836
+ var url = (_el_textContent = el.textContent) === null || _el_textContent === void 0 ? void 0 : _el_textContent.trim();
837
+ if (url) trackingUrls.impression.push(url);
838
+ });
839
+ adElement.querySelectorAll("Tracking").forEach(function(el) {
840
+ var _el_textContent;
841
+ var event = el.getAttribute("event");
842
+ var url = (_el_textContent = el.textContent) === null || _el_textContent === void 0 ? void 0 : _el_textContent.trim();
843
+ if (event && url) {
844
+ var eventKey = event;
845
+ if (trackingUrls[eventKey]) {
846
+ trackingUrls[eventKey].push(url);
847
+ }
848
+ }
849
+ });
850
+ var clickThrough = (_adElement_querySelector2 = adElement.querySelector("ClickThrough")) === null || _adElement_querySelector2 === void 0 ? void 0 : (_adElement_querySelector_textContent = _adElement_querySelector2.textContent) === null || _adElement_querySelector_textContent === void 0 ? void 0 : _adElement_querySelector_textContent.trim();
851
+ ads.push({
852
+ id: adId,
853
+ title: title,
854
+ duration: duration,
855
+ mediaFiles: mediaFiles,
856
+ trackingUrls: trackingUrls,
857
+ clickThrough: clickThrough
858
+ });
859
+ log("Parsed ad: ".concat(title, ", duration: ").concat(duration, "s, media files: ").concat(mediaFiles.length));
692
860
  });
693
- })();
861
+ } catch (error) {
862
+ console.error("[AdStormPlayer] Error parsing VAST XML:", error);
863
+ }
864
+ return ads;
865
+ }
866
+ function selectBestMediaFile(mediaFiles) {
867
+ if (mediaFiles.length === 0) return null;
868
+ if (mediaFiles.length === 1) return mediaFiles[0];
869
+ var mp4Files = mediaFiles.filter(function(mf) {
870
+ return mf.type.includes("video/mp4");
871
+ });
872
+ var candidates = mp4Files.length > 0 ? mp4Files : mediaFiles;
873
+ var targetWidth = contentVideo.videoWidth || 1280;
874
+ var targetHeight = contentVideo.videoHeight || 720;
875
+ candidates.sort(function(a, b) {
876
+ var diffA = Math.abs(a.width - targetWidth) + Math.abs(a.height - targetHeight);
877
+ var diffB = Math.abs(b.width - targetWidth) + Math.abs(b.height - targetHeight);
878
+ return diffA - diffB;
879
+ });
880
+ return candidates[0] || null;
694
881
  }
695
- function requestBids(_context) {
882
+ function createAdVideoElement() {
883
+ var video = document.createElement("video");
884
+ video.style.position = "absolute";
885
+ video.style.left = "0";
886
+ video.style.top = "0";
887
+ video.style.width = "100%";
888
+ video.style.height = "100%";
889
+ video.style.objectFit = "contain";
890
+ video.style.backgroundColor = "#000";
891
+ video.style.zIndex = "1";
892
+ video.playsInline = true;
893
+ video.preload = "auto";
894
+ video.muted = originalMutedState;
895
+ video.volume = originalMutedState ? 0 : originalVolume;
896
+ return video;
897
+ }
898
+ function setAdPlayingFlag(isPlaying) {
899
+ if (isPlaying) {
900
+ contentVideo.dataset.stormcloudAdPlaying = "true";
901
+ } else {
902
+ delete contentVideo.dataset.stormcloudAdPlaying;
903
+ }
904
+ }
905
+ function setupAdEventListeners() {
906
+ bindAdEventListeners();
907
+ }
908
+ function handleAdComplete() {
909
+ if (destroyed || tornDown) return;
910
+ log("Handling ad completion");
911
+ adPlaying = false;
912
+ setAdPlayingFlag(false);
913
+ clearAdStallTimer();
914
+ clearAdCountdownTimer();
915
+ if (adContainerEl) {
916
+ adContainerEl.style.opacity = "0";
917
+ adHideTimerId = setTimeout(function() {
918
+ if (adContainerEl) {
919
+ adContainerEl.style.display = "none";
920
+ adContainerEl.style.pointerEvents = "none";
921
+ }
922
+ }, 300);
923
+ }
924
+ contentVideo.style.visibility = "visible";
925
+ contentVideo.style.opacity = "1";
926
+ contentVideo.muted = originalMutedState;
927
+ contentVideo.volume = originalVolume;
928
+ currentAd = void 0;
929
+ emit("content_resume");
930
+ emit("all_ads_completed");
931
+ }
932
+ function handleAdError() {
933
+ if (destroyed || tornDown) return;
934
+ log("Handling ad error");
935
+ if (!adPlaying) return;
936
+ adPlaying = false;
937
+ setAdPlayingFlag(false);
938
+ clearAdStallTimer();
939
+ clearAdCountdownTimer();
940
+ contentVideo.muted = originalMutedState;
941
+ contentVideo.volume = originalVolume;
942
+ contentVideo.style.visibility = "visible";
943
+ contentVideo.style.opacity = "1";
944
+ if (adContainerEl) {
945
+ adContainerEl.style.display = "none";
946
+ adContainerEl.style.pointerEvents = "none";
947
+ }
948
+ currentAd = void 0;
949
+ emit("ad_error");
950
+ emit("content_resume");
951
+ }
952
+ function fetchVastOnce(durationSeconds) {
696
953
  return _async_to_generator(function() {
697
- var correlator, url, controller, timeoutId, _ref, _ref1, _vastAd_mediaFiles_, _vastAd_mediaFiles_1, fetchOptions, response, vastXml, vastAd, bid, error;
954
+ var vastUrl, controller, timeoutId, requestInit, response, xmlText;
698
955
  return _ts_generator(this, function(_state) {
699
956
  switch(_state.label){
700
957
  case 0:
701
- if (!initialized) {
702
- throw new Error("VastManager not initialized. Call initialize() first.");
703
- }
704
- correlator = Math.floor(Math.random() * 1e12).toString();
705
- url = VAST_TAG_URL.replace("[placeholder]", correlator);
706
- log("Fetching VAST tag, correlator:", correlator);
958
+ vastUrl = buildVastUrl(durationSeconds);
959
+ log("Fetching VAST from:", vastUrl);
707
960
  controller = typeof AbortController !== "undefined" ? new AbortController() : null;
708
961
  timeoutId = setTimeout(function() {
709
962
  return controller === null || controller === void 0 ? void 0 : controller.abort();
710
- }, DEFAULT_TIMEOUT_MS);
963
+ }, REQUEST_TIMEOUT_MS);
711
964
  _state.label = 1;
712
965
  case 1:
713
966
  _state.trys.push([
714
967
  1,
715
- 4,
716
968
  ,
969
+ 4,
717
970
  5
718
971
  ]);
719
- fetchOptions = {
972
+ requestInit = {
720
973
  method: "GET",
721
974
  mode: "cors",
722
975
  credentials: "omit",
@@ -725,62 +978,34 @@ function createVastManager() {
725
978
  },
726
979
  referrerPolicy: "no-referrer-when-downgrade"
727
980
  };
728
- if (controller) fetchOptions.signal = controller.signal;
981
+ if (controller) {
982
+ requestInit.signal = controller.signal;
983
+ }
729
984
  return [
730
985
  4,
731
- fetch(url, fetchOptions)
986
+ fetch(vastUrl, requestInit)
732
987
  ];
733
988
  case 2:
734
989
  response = _state.sent();
735
- clearTimeout(timeoutId);
736
990
  if (!response.ok) {
737
- throw new Error("VAST request returned HTTP ".concat(response.status));
991
+ throw new Error("Failed to fetch VAST: ".concat(response.status, " ").concat(response.statusText));
738
992
  }
739
993
  return [
740
994
  4,
741
995
  response.text()
742
996
  ];
743
997
  case 3:
744
- vastXml = _state.sent();
745
- log("VAST XML received, length:", vastXml.length);
746
- vastAd = parseVastXml(vastXml, "mp4-first", "[VastManager]");
747
- if (!vastAd) {
748
- log("VAST parsed but no usable ad found");
749
- return [
750
- 2,
751
- []
752
- ];
753
- }
754
- log("Ad parsed: id=".concat(vastAd.id, ", duration=").concat(vastAd.duration, "s, mediaFiles=").concat(vastAd.mediaFiles.length));
755
- bid = {
756
- bidder: "vast-direct",
757
- cpm: 0,
758
- vastXml: vastXml,
759
- width: (_ref = (_vastAd_mediaFiles_ = vastAd.mediaFiles[0]) === null || _vastAd_mediaFiles_ === void 0 ? void 0 : _vastAd_mediaFiles_.width) !== null && _ref !== void 0 ? _ref : 0,
760
- height: (_ref1 = (_vastAd_mediaFiles_1 = vastAd.mediaFiles[0]) === null || _vastAd_mediaFiles_1 === void 0 ? void 0 : _vastAd_mediaFiles_1.height) !== null && _ref1 !== void 0 ? _ref1 : 0,
761
- adId: vastAd.id,
762
- impId: correlator,
763
- creativeId: vastAd.id,
764
- currency: "USD",
765
- durationSec: vastAd.duration
766
- };
998
+ xmlText = _state.sent();
999
+ log("VAST response received, length:", xmlText.length);
767
1000
  return [
768
1001
  2,
769
- [
770
- bid
771
- ]
1002
+ parseVastXml(xmlText)
772
1003
  ];
773
1004
  case 4:
774
- error = _state.sent();
775
1005
  clearTimeout(timeoutId);
776
- if ((error === null || error === void 0 ? void 0 : error.name) === "AbortError") {
777
- warn("VAST request timed out after ".concat(DEFAULT_TIMEOUT_MS, "ms"));
778
- return [
779
- 2,
780
- []
781
- ];
782
- }
783
- throw error;
1006
+ return [
1007
+ 7
1008
+ ];
784
1009
  case 5:
785
1010
  return [
786
1011
  2
@@ -789,14 +1014,14 @@ function createVastManager() {
789
1014
  });
790
1015
  })();
791
1016
  }
792
- function requestBidsUntilResponse(context) {
1017
+ function fetchVast(durationSeconds) {
793
1018
  return _async_to_generator(function() {
794
1019
  var _loop, lastError, attempt, _ret;
795
1020
  return _ts_generator(this, function(_state) {
796
1021
  switch(_state.label){
797
1022
  case 0:
798
1023
  _loop = function(attempt) {
799
- var bids, err, delay;
1024
+ var ads, error, delay;
800
1025
  return _ts_generator(this, function(_state) {
801
1026
  switch(_state.label){
802
1027
  case 0:
@@ -808,39 +1033,39 @@ function createVastManager() {
808
1033
  ]);
809
1034
  return [
810
1035
  4,
811
- requestBids(context)
1036
+ fetchVastOnce(durationSeconds)
812
1037
  ];
813
1038
  case 1:
814
- bids = _state.sent();
815
- if (bids.length > 0) {
816
- log("requestBidsUntilResponse: got ".concat(bids.length, " ad(s) on attempt ").concat(attempt));
817
- return [
818
- 2,
819
- {
820
- v: bids
821
- }
822
- ];
823
- }
824
- log("requestBidsUntilResponse: no ads on attempt ".concat(attempt, "/").concat(MAX_RETRIES));
1039
+ ads = _state.sent();
1040
+ if (ads.length > 0) return [
1041
+ 2,
1042
+ {
1043
+ v: ads
1044
+ }
1045
+ ];
1046
+ log("No ad returned from VAST on attempt ".concat(attempt, "/").concat(REQUEST_MAX_RETRIES));
825
1047
  return [
826
1048
  3,
827
1049
  3
828
1050
  ];
829
1051
  case 2:
830
- err = _state.sent();
831
- lastError = err;
832
- warn("requestBidsUntilResponse: attempt ".concat(attempt, "/").concat(MAX_RETRIES, " failed:"), err);
1052
+ error = _state.sent();
1053
+ lastError = error;
1054
+ if ((error === null || error === void 0 ? void 0 : error.name) === "AbortError") {
1055
+ console.warn("[AdStormPlayer] VAST request timed out (".concat(REQUEST_TIMEOUT_MS, "ms), attempt ").concat(attempt, "/").concat(REQUEST_MAX_RETRIES));
1056
+ } else {
1057
+ console.warn("[AdStormPlayer] VAST request failed on attempt ".concat(attempt, "/").concat(REQUEST_MAX_RETRIES, ":"), error);
1058
+ }
833
1059
  return [
834
1060
  3,
835
1061
  3
836
1062
  ];
837
1063
  case 3:
838
- if (!(attempt < MAX_RETRIES)) return [
1064
+ if (!(attempt < REQUEST_MAX_RETRIES)) return [
839
1065
  3,
840
1066
  5
841
1067
  ];
842
- delay = RETRY_BACKOFF_MS * attempt;
843
- log("requestBidsUntilResponse: waiting ".concat(delay, "ms before retry"));
1068
+ delay = REQUEST_RETRY_BACKOFF_MS * attempt;
844
1069
  return [
845
1070
  4,
846
1071
  new Promise(function(resolve) {
@@ -857,13 +1082,10 @@ function createVastManager() {
857
1082
  }
858
1083
  });
859
1084
  };
860
- if (!initialized) {
861
- throw new Error("VastManager not initialized. Call initialize() first.");
862
- }
863
1085
  attempt = 1;
864
1086
  _state.label = 1;
865
1087
  case 1:
866
- if (!(attempt <= MAX_RETRIES)) return [
1088
+ if (!(attempt <= REQUEST_MAX_RETRIES)) return [
867
1089
  3,
868
1090
  4
869
1091
  ];
@@ -885,7 +1107,9 @@ function createVastManager() {
885
1107
  1
886
1108
  ];
887
1109
  case 4:
888
- if (_instanceof(lastError, Error)) throw lastError;
1110
+ if (_instanceof(lastError, Error)) {
1111
+ throw lastError;
1112
+ }
889
1113
  return [
890
1114
  2,
891
1115
  []
@@ -894,946 +1118,468 @@ function createVastManager() {
894
1118
  });
895
1119
  })();
896
1120
  }
897
- function destroy() {
898
- initialized = false;
899
- log("Destroyed");
900
- }
901
- return {
902
- initialize: initialize,
903
- requestBids: requestBids,
904
- requestBidsUntilResponse: requestBidsUntilResponse,
905
- destroy: destroy,
906
- get isInitialized () {
907
- return initialized;
908
- }
909
- };
910
- }
911
- // src/sdk/vastAdLayer.ts
912
- var import_hls = __toESM(require("hls.js"), 1);
913
- var LOG = "[VastAdLayer]";
914
- function resolveBidToVastAd(winner, logPrefix) {
915
- if (winner.vastXml) {
916
- var ad = parseVastXml(winner.vastXml, "mp4-first", logPrefix);
917
- return Promise.resolve(ad);
918
- }
919
- if (winner.vastUrl) {
920
- return fetchAndParseVastAd(winner.vastUrl, "mp4-first", logPrefix);
921
- }
922
- return Promise.resolve(null);
923
- }
924
- function createVastAdLayer(contentVideo, options) {
925
- var _ref, _ref1, _ref2, _ref3, _ref4;
926
- var adPlaying = false;
927
- var originalMutedState = false;
928
- var originalVolume = Math.max(0, Math.min(1, contentVideo.volume || 1));
929
- var listeners = /* @__PURE__ */ new Map();
930
- var mainHlsInstance = options === null || options === void 0 ? void 0 : options.mainHlsInstance;
931
- var continueLiveStreamDuringAds = (_ref = options === null || options === void 0 ? void 0 : options.continueLiveStreamDuringAds) !== null && _ref !== void 0 ? _ref : false;
932
- var smartTVMode = (_ref1 = options === null || options === void 0 ? void 0 : options.smartTVMode) !== null && _ref1 !== void 0 ? _ref1 : false;
933
- var singleElementMode = (_ref2 = options === null || options === void 0 ? void 0 : options.singleElementMode) !== null && _ref2 !== void 0 ? _ref2 : false;
934
- var forceMP4Ads = (_ref3 = options === null || options === void 0 ? void 0 : options.forceMP4Ads) !== null && _ref3 !== void 0 ? _ref3 : smartTVMode || singleElementMode;
935
- var debug = (_ref4 = options === null || options === void 0 ? void 0 : options.debug) !== null && _ref4 !== void 0 ? _ref4 : false;
936
- var adVideoElement;
937
- var adHls;
938
- var adContainerEl;
939
- var currentAd;
940
- var sessionId;
941
- var destroyed = false;
942
- var tornDown = false;
943
- var trackingFired = createEmptyTrackingState();
944
- var adStallTimerId;
945
- var currentAdEventHandlers;
946
- var preloadSlots = /* @__PURE__ */ new Map();
947
- function emit(event, payload) {
948
- var set = listeners.get(event);
949
- if (!set) return;
950
- var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
951
- try {
952
- for(var _iterator = Array.from(set)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
953
- var fn = _step.value;
954
- try {
955
- fn(payload);
956
- } catch (error) {
957
- console.warn("".concat(LOG, " Error in event listener for ").concat(event, ":"), error);
958
- }
959
- }
960
- } catch (err) {
961
- _didIteratorError = true;
962
- _iteratorError = err;
963
- } finally{
964
- try {
965
- if (!_iteratorNormalCompletion && _iterator.return != null) {
966
- _iterator.return();
967
- }
968
- } finally{
969
- if (_didIteratorError) {
970
- throw _iteratorError;
971
- }
972
- }
973
- }
974
- }
975
- function generateSessionId() {
976
- return "session-".concat(Date.now(), "-").concat(Math.random().toString(36).substr(2, 9));
977
- }
978
- function fireTrackingPixels2(urls) {
979
- fireTrackingPixels(urls, sessionId, LOG);
980
- }
981
- function getMainStreamQuality() {
982
- if (!(mainHlsInstance === null || mainHlsInstance === void 0 ? void 0 : mainHlsInstance.levels)) return null;
983
- var currentLevel = mainHlsInstance.currentLevel;
984
- if (currentLevel === -1 || !mainHlsInstance.levels[currentLevel]) {
985
- var autoLevel = mainHlsInstance.loadLevel;
986
- if (autoLevel !== -1 && mainHlsInstance.levels[autoLevel]) {
987
- var level2 = mainHlsInstance.levels[autoLevel];
988
- return {
989
- width: level2.width || 1920,
990
- height: level2.height || 1080,
991
- bitrate: level2.bitrate || 5e6
992
- };
993
- }
994
- return null;
995
- }
996
- var level = mainHlsInstance.levels[currentLevel];
997
- return {
998
- width: level.width || 1920,
999
- height: level.height || 1080,
1000
- bitrate: level.bitrate || 5e6
1001
- };
1002
- }
1003
- function selectBestMediaFile(mediaFiles) {
1004
- var _ref;
1005
- var _scoredFiles_;
1006
- if (mediaFiles.length === 0) throw new Error("No media files available");
1007
- var candidates = mediaFiles;
1008
- if (forceMP4Ads) {
1009
- var mp4Only = candidates.filter(function(f) {
1010
- return !isHlsMediaFile(f);
1011
- });
1012
- if (mp4Only.length > 0) {
1013
- candidates = mp4Only;
1014
- if (debug) console.log("".concat(LOG, " forceMP4Ads: filtered to ").concat(mp4Only.length, " MP4-only file(s)"));
1015
- } else if (debug) {
1016
- console.warn("".concat(LOG, " forceMP4Ads: no MP4 files available, falling back to all media files"));
1017
- }
1018
- } else {
1019
- var mp4Only1 = candidates.filter(function(f) {
1020
- return !isHlsMediaFile(f);
1021
- });
1022
- if (mp4Only1.length > 0) {
1023
- candidates = mp4Only1;
1024
- if (debug) console.log("".concat(LOG, " Preferring ").concat(mp4Only1.length, " MP4 file(s) over HLS (mp4-first)"));
1025
- }
1121
+ function getDurationSecondsFromContext(requestContext) {
1122
+ var _ctx_remainingBreakSec;
1123
+ if (!requestContext || (typeof requestContext === "undefined" ? "undefined" : _type_of(requestContext)) !== "object") {
1124
+ return 30;
1026
1125
  }
1027
- var firstFile = candidates[0];
1028
- if (candidates.length === 1) return firstFile;
1029
- var mainQuality = getMainStreamQuality();
1030
- if (!mainQuality) {
1031
- if (debug) console.log("".concat(LOG, " No main stream quality info, using first media file"));
1032
- return firstFile;
1126
+ var ctx = requestContext;
1127
+ var value = (_ctx_remainingBreakSec = ctx.remainingBreakSec) !== null && _ctx_remainingBreakSec !== void 0 ? _ctx_remainingBreakSec : ctx.breakDurationSec;
1128
+ if (typeof value !== "number" || Number.isNaN(value)) {
1129
+ return 30;
1033
1130
  }
1034
- var scoredFiles = candidates.map(function(file) {
1035
- var widthDiff = Math.abs(file.width - mainQuality.width);
1036
- var heightDiff = Math.abs(file.height - mainQuality.height);
1037
- var resolutionDiff = widthDiff + heightDiff;
1038
- var fileBitrate = (file.bitrate || 5e3) * 1e3;
1039
- var bitrateDiff = Math.abs(fileBitrate - mainQuality.bitrate);
1040
- var score = resolutionDiff * 2 + bitrateDiff / 1e3;
1041
- return {
1042
- file: file,
1043
- score: score
1044
- };
1045
- });
1046
- scoredFiles.sort(function(a, b) {
1047
- return a.score - b.score;
1048
- });
1049
- return (_ref = (_scoredFiles_ = scoredFiles[0]) === null || _scoredFiles_ === void 0 ? void 0 : _scoredFiles_.file) !== null && _ref !== void 0 ? _ref : firstFile;
1050
- }
1051
- function isHlsMediaFile(file) {
1052
- return file.type === "application/x-mpegURL" || file.type.includes("m3u8");
1053
- }
1054
- function createAdVideoElement() {
1055
- var video = document.createElement("video");
1056
- video.style.position = "absolute";
1057
- video.style.left = "0";
1058
- video.style.top = "0";
1059
- video.style.width = "100%";
1060
- video.style.height = "100%";
1061
- video.style.objectFit = "contain";
1062
- video.style.backgroundColor = "#000";
1063
- video.playsInline = true;
1064
- video.muted = false;
1065
- video.volume = 1;
1066
- return video;
1067
- }
1068
- function clearAdStallTimer() {
1069
- if (adStallTimerId != null) {
1070
- clearTimeout(adStallTimerId);
1071
- adStallTimerId = void 0;
1072
- }
1073
- }
1074
- function removeAdEventListeners() {
1075
- clearAdStallTimer();
1076
- if (!currentAdEventHandlers || !adVideoElement) return;
1077
- var el = adVideoElement;
1078
- el.removeEventListener("timeupdate", currentAdEventHandlers.timeupdate);
1079
- el.removeEventListener("playing", currentAdEventHandlers.playing);
1080
- el.removeEventListener("ended", currentAdEventHandlers.ended);
1081
- el.removeEventListener("error", currentAdEventHandlers.error);
1082
- el.removeEventListener("volumechange", currentAdEventHandlers.volumechange);
1083
- el.removeEventListener("pause", currentAdEventHandlers.pause);
1084
- el.removeEventListener("play", currentAdEventHandlers.play);
1085
- el.removeEventListener("waiting", currentAdEventHandlers.waiting);
1086
- currentAdEventHandlers = void 0;
1087
- }
1088
- function setupAdEventListeners() {
1089
- if (!adVideoElement) return;
1090
- removeAdEventListeners();
1091
- var handlers = {
1092
- timeupdate: function timeupdate() {
1093
- var ad = currentAd;
1094
- if (!ad || !adVideoElement) return;
1095
- var progress = adVideoElement.currentTime / ad.duration;
1096
- if (progress >= 0.25 && !trackingFired.firstQuartile) {
1097
- trackingFired.firstQuartile = true;
1098
- fireTrackingPixels2(ad.trackingUrls.firstQuartile);
1099
- }
1100
- if (progress >= 0.5 && !trackingFired.midpoint) {
1101
- trackingFired.midpoint = true;
1102
- fireTrackingPixels2(ad.trackingUrls.midpoint);
1103
- }
1104
- if (progress >= 0.75 && !trackingFired.thirdQuartile) {
1105
- trackingFired.thirdQuartile = true;
1106
- fireTrackingPixels2(ad.trackingUrls.thirdQuartile);
1107
- }
1108
- },
1109
- playing: function playing() {
1110
- clearAdStallTimer();
1111
- var ad = currentAd;
1112
- if (!ad || trackingFired.start) return;
1113
- trackingFired.start = true;
1114
- fireTrackingPixels2(ad.trackingUrls.start);
1115
- if (debug) console.log("".concat(LOG, " Ad started playing"));
1116
- },
1117
- ended: function ended() {
1118
- if (tornDown || !currentAd || trackingFired.complete) return;
1119
- trackingFired.complete = true;
1120
- fireTrackingPixels2(currentAd.trackingUrls.complete);
1121
- if (debug) console.log("".concat(LOG, " Ad completed"));
1122
- handleAdComplete();
1123
- },
1124
- error: function error(e) {
1125
- if (tornDown) return;
1126
- console.error("".concat(LOG, " Ad video error:"), e);
1127
- if (currentAd) fireTrackingPixels2(currentAd.trackingUrls.error);
1128
- handleAdError();
1129
- },
1130
- volumechange: function volumechange() {
1131
- if (!currentAd || !adVideoElement) return;
1132
- if (adVideoElement.muted) {
1133
- fireTrackingPixels2(currentAd.trackingUrls.mute);
1134
- } else {
1135
- fireTrackingPixels2(currentAd.trackingUrls.unmute);
1136
- }
1137
- },
1138
- pause: function pause() {
1139
- if (currentAd && adVideoElement && !adVideoElement.ended) {
1140
- fireTrackingPixels2(currentAd.trackingUrls.pause);
1141
- }
1142
- },
1143
- play: function play() {
1144
- if (currentAd && adVideoElement && adVideoElement.currentTime > 0) {
1145
- fireTrackingPixels2(currentAd.trackingUrls.resume);
1146
- }
1147
- },
1148
- waiting: function waiting() {
1149
- clearAdStallTimer();
1150
- adStallTimerId = setTimeout(function() {
1151
- adStallTimerId = void 0;
1152
- if (adPlaying) {
1153
- if (debug) console.warn("".concat(LOG, " Ad video stalled for too long, treating as error"));
1154
- handleAdError();
1155
- }
1156
- }, 8e3);
1157
- }
1158
- };
1159
- adVideoElement.addEventListener("timeupdate", handlers.timeupdate);
1160
- adVideoElement.addEventListener("playing", handlers.playing);
1161
- adVideoElement.addEventListener("ended", handlers.ended);
1162
- adVideoElement.addEventListener("error", handlers.error);
1163
- adVideoElement.addEventListener("volumechange", handlers.volumechange);
1164
- adVideoElement.addEventListener("pause", handlers.pause);
1165
- adVideoElement.addEventListener("play", handlers.play);
1166
- adVideoElement.addEventListener("waiting", handlers.waiting);
1167
- currentAdEventHandlers = handlers;
1168
- }
1169
- function setAdPlayingFlag(isPlaying) {
1170
- if (isPlaying) {
1171
- contentVideo.dataset.stormcloudAdPlaying = "true";
1172
- } else {
1173
- delete contentVideo.dataset.stormcloudAdPlaying;
1174
- }
1175
- }
1176
- function handleAdComplete() {
1177
- if (tornDown) return;
1178
- clearAdStallTimer();
1179
- if (debug) console.log("".concat(LOG, " Handling ad completion"));
1180
- adPlaying = false;
1181
- setAdPlayingFlag(false);
1182
- if (adContainerEl) {
1183
- adContainerEl.style.display = "none";
1184
- adContainerEl.style.pointerEvents = "none";
1185
- }
1186
- emit("ad_impression");
1187
- emit("content_resume");
1131
+ return Math.max(1, Math.ceil(value));
1188
1132
  }
1189
- function handleAdError() {
1190
- if (tornDown) return;
1191
- if (!adPlaying) return;
1192
- clearAdStallTimer();
1193
- if (debug) console.log("".concat(LOG, " Handling ad error"));
1194
- adPlaying = false;
1195
- setAdPlayingFlag(false);
1196
- if (adContainerEl) {
1197
- adContainerEl.style.display = "none";
1198
- adContainerEl.style.pointerEvents = "none";
1199
- }
1200
- emit("ad_error");
1201
- }
1202
- function teardownCurrentPlayback() {
1203
- removeAdEventListeners();
1204
- if (adHls) {
1205
- adHls.destroy();
1206
- adHls = void 0;
1207
- }
1208
- if (adVideoElement) {
1209
- if (singleElementMode && adVideoElement === contentVideo) {
1210
- contentVideo.pause();
1211
- } else {
1212
- adVideoElement.pause();
1213
- adVideoElement.removeAttribute("src");
1214
- adVideoElement.load();
1215
- }
1216
- }
1217
- }
1218
- function startNativePlayback(mediaFile) {
1219
- if (!adVideoElement) return;
1220
- if (debug) console.log("".concat(LOG, " Starting native MP4 playback: ").concat(mediaFile.url));
1221
- adVideoElement.src = mediaFile.url;
1222
- adVideoElement.load();
1223
- adVideoElement.play().catch(function(error) {
1224
- console.error("".concat(LOG, " Error starting native ad playback:"), error);
1225
- handleAdError();
1226
- });
1227
- }
1228
- function startHlsPlayback(mediaFile) {
1229
- if (!adVideoElement) return;
1230
- if (debug) console.log("".concat(LOG, " Starting HLS playback: ").concat(mediaFile.url));
1231
- if (import_hls.default.isSupported()) {
1232
- if (adHls) {
1233
- adHls.destroy();
1234
- adHls = void 0;
1235
- }
1236
- adHls = new import_hls.default({
1237
- enableWorker: true,
1238
- lowLatencyMode: false
1239
- });
1240
- adHls.loadSource(mediaFile.url);
1241
- adHls.attachMedia(adVideoElement);
1242
- adHls.on(import_hls.default.Events.MANIFEST_PARSED, function() {
1243
- if (!adPlaying) return;
1244
- adVideoElement.play().catch(function(error) {
1245
- console.error("".concat(LOG, " Error starting HLS ad playback:"), error);
1246
- handleAdError();
1247
- });
1248
- });
1249
- var nonFatalNetworkErrors = 0;
1250
- adHls.on(import_hls.default.Events.ERROR, function(_event, data) {
1251
- if (data.fatal) {
1252
- handleAdError();
1253
- } else if (data.type === import_hls.default.ErrorTypes.NETWORK_ERROR) {
1254
- nonFatalNetworkErrors++;
1255
- if (nonFatalNetworkErrors >= 3) {
1256
- if (debug) console.warn("".concat(LOG, " Too many non-fatal HLS network errors (").concat(nonFatalNetworkErrors, "), treating as fatal"));
1257
- handleAdError();
1258
- }
1259
- }
1260
- });
1261
- } else if (adVideoElement.canPlayType("application/vnd.apple.mpegurl")) {
1262
- adVideoElement.src = mediaFile.url;
1263
- adVideoElement.play().catch(function(error) {
1264
- console.error("".concat(LOG, " Error starting native HLS ad playback:"), error);
1265
- handleAdError();
1266
- });
1267
- } else {
1268
- console.error("".concat(LOG, " HLS not supported on this platform"));
1269
- handleAdError();
1270
- }
1271
- }
1272
- function startPlayback(mediaFile) {
1273
- if (!adVideoElement) return;
1274
- if (singleElementMode && isHlsMediaFile(mediaFile)) {
1275
- var mp4Fallback = currentAd === null || currentAd === void 0 ? void 0 : currentAd.mediaFiles.find(function(f) {
1276
- return !isHlsMediaFile(f);
1277
- });
1278
- if (mp4Fallback) {
1279
- if (debug) console.log("".concat(LOG, " singleElementMode: HLS ad blocked, using MP4 fallback"));
1280
- startNativePlayback(mp4Fallback);
1281
- return;
1282
- }
1283
- }
1284
- if (isHlsMediaFile(mediaFile)) {
1285
- startHlsPlayback(mediaFile);
1286
- } else {
1287
- startNativePlayback(mediaFile);
1288
- }
1289
- }
1290
- function playAd(bids) {
1133
+ function requestAdFromApi(requestContext) {
1291
1134
  return _async_to_generator(function() {
1292
- var winner, ad, contentVolume, adVolume2, mediaFile2, _contentVideo_parentElement, container, adVolume, mediaFile;
1135
+ var durationSeconds, ads;
1293
1136
  return _ts_generator(this, function(_state) {
1294
1137
  switch(_state.label){
1295
1138
  case 0:
1296
- if (destroyed) {
1297
- return [
1298
- 2,
1299
- Promise.reject(new Error("Layer has been destroyed"))
1300
- ];
1301
- }
1302
- if (bids.length === 0) {
1303
- return [
1304
- 2,
1305
- Promise.reject(new Error("No bids provided"))
1306
- ];
1307
- }
1308
- winner = bids[0];
1309
- if (debug) {
1310
- console.log("".concat(LOG, " Winning bid: ").concat(winner.bidder, " $").concat(winner.cpm.toFixed(2), " ").concat(winner.currency));
1311
- }
1139
+ durationSeconds = getDurationSecondsFromContext(requestContext);
1312
1140
  return [
1313
1141
  4,
1314
- resolveBidToVastAd(winner, LOG)
1142
+ fetchVast(durationSeconds)
1315
1143
  ];
1316
1144
  case 1:
1317
- ad = _state.sent();
1318
- if (!ad) {
1319
- if (debug) console.warn("".concat(LOG, " Winning bid has no VAST URL or XML"));
1320
- emit("ad_error");
1321
- return [
1322
- 2,
1323
- Promise.reject(new Error("No VAST from bid"))
1324
- ];
1325
- }
1326
- if (debug) {
1327
- console.log("".concat(LOG, " Ad parsed: ").concat(ad.title, ", duration: ").concat(ad.duration, "s, mediaFiles: ").concat(ad.mediaFiles.length));
1328
- }
1329
- sessionId = generateSessionId();
1330
- currentAd = ad;
1331
- trackingFired = _object_spread({}, createEmptyTrackingState());
1332
- fireTrackingPixels2(ad.trackingUrls.impression);
1333
- trackingFired.impression = true;
1334
- contentVolume = contentVideo.volume;
1335
- originalVolume = Math.max(0, Math.min(1, contentVolume || originalVolume));
1336
- if (!singleElementMode) return [
1337
- 3,
1338
- 3
1339
- ];
1340
- mainHlsInstance === null || mainHlsInstance === void 0 ? void 0 : mainHlsInstance.detachMedia();
1341
- teardownCurrentPlayback();
1342
- adVideoElement = contentVideo;
1343
- adHls = void 0;
1344
- adPlaying = true;
1345
- setAdPlayingFlag(true);
1346
- contentVideo.removeAttribute("src");
1347
- contentVideo.load();
1348
- if (!continueLiveStreamDuringAds) {
1349
- contentVideo.pause();
1350
- }
1351
- contentVideo.muted = true;
1352
- contentVideo.volume = 0;
1145
+ ads = _state.sent();
1353
1146
  return [
1354
- 4,
1355
- new Promise(function(resolve) {
1356
- return setTimeout(resolve, 200);
1357
- })
1358
- ];
1359
- case 2:
1360
- _state.sent();
1361
- if (destroyed || tornDown) return [
1362
- 2
1363
- ];
1364
- contentVideo.style.visibility = "visible";
1365
- contentVideo.style.opacity = "1";
1366
- emit("content_pause");
1367
- setupAdEventListeners();
1368
- adVolume2 = originalMutedState ? 1 : originalVolume;
1369
- adVideoElement.volume = Math.max(0, Math.min(1, adVolume2));
1370
- adVideoElement.muted = false;
1371
- mediaFile2 = selectBestMediaFile(ad.mediaFiles);
1372
- if (debug) console.log("".concat(LOG, " Loading ad from: ").concat(mediaFile2.url));
1373
- startPlayback(mediaFile2);
1374
- return [
1375
- 2
1376
- ];
1377
- case 3:
1378
- if (!adContainerEl) {
1379
- ;
1380
- container = document.createElement("div");
1381
- container.style.position = "absolute";
1382
- container.style.left = "0";
1383
- container.style.top = "0";
1384
- container.style.right = "0";
1385
- container.style.bottom = "0";
1386
- container.style.display = "none";
1387
- container.style.alignItems = "center";
1388
- container.style.justifyContent = "center";
1389
- container.style.pointerEvents = "none";
1390
- container.style.zIndex = "10";
1391
- container.style.backgroundColor = "#000";
1392
- (_contentVideo_parentElement = contentVideo.parentElement) === null || _contentVideo_parentElement === void 0 ? void 0 : _contentVideo_parentElement.appendChild(container);
1393
- adContainerEl = container;
1394
- }
1395
- if (!adVideoElement) {
1396
- adVideoElement = createAdVideoElement();
1397
- adContainerEl.appendChild(adVideoElement);
1398
- setupAdEventListeners();
1399
- } else {
1400
- teardownCurrentPlayback();
1401
- }
1402
- if (!continueLiveStreamDuringAds) {
1403
- contentVideo.pause();
1404
- }
1405
- contentVideo.muted = true;
1406
- contentVideo.volume = 0;
1407
- adPlaying = true;
1408
- setAdPlayingFlag(true);
1409
- adVolume = originalMutedState ? 1 : originalVolume;
1410
- adVideoElement.volume = Math.max(0, Math.min(1, adVolume));
1411
- adVideoElement.muted = false;
1412
- if (adContainerEl) {
1413
- adContainerEl.style.display = "flex";
1414
- adContainerEl.style.pointerEvents = "auto";
1415
- }
1416
- emit("content_pause");
1417
- mediaFile = selectBestMediaFile(ad.mediaFiles);
1418
- if (debug) console.log("".concat(LOG, " Loading ad from: ").concat(mediaFile.url));
1419
- startPlayback(mediaFile);
1420
- return [
1421
- 2
1147
+ 2,
1148
+ ads[0] || null
1422
1149
  ];
1423
1150
  }
1424
1151
  });
1425
1152
  })();
1426
1153
  }
1427
- function ensureAdContainer() {
1428
- if (!adContainerEl) {
1429
- var _contentVideo_parentElement;
1430
- var container = document.createElement("div");
1431
- container.style.position = "absolute";
1432
- container.style.left = "0";
1433
- container.style.top = "0";
1434
- container.style.right = "0";
1435
- container.style.bottom = "0";
1436
- container.style.display = "none";
1437
- container.style.alignItems = "center";
1438
- container.style.justifyContent = "center";
1439
- container.style.pointerEvents = "none";
1440
- container.style.zIndex = "10";
1441
- container.style.backgroundColor = "#000";
1442
- (_contentVideo_parentElement = contentVideo.parentElement) === null || _contentVideo_parentElement === void 0 ? void 0 : _contentVideo_parentElement.appendChild(container);
1443
- adContainerEl = container;
1444
- }
1445
- return adContainerEl;
1154
+ function assignCurrentAd(ad) {
1155
+ currentAd = ad;
1156
+ sessionId = generateSessionId();
1157
+ trackingFired = {
1158
+ impression: false,
1159
+ start: false,
1160
+ firstQuartile: false,
1161
+ midpoint: false,
1162
+ thirdQuartile: false,
1163
+ complete: false
1164
+ };
1165
+ fireTrackingPixels2(currentAd.trackingUrls.impression);
1166
+ trackingFired.impression = true;
1167
+ emit("ad_impression");
1446
1168
  }
1447
- function preloadAd(bids, token) {
1448
- return _async_to_generator(function() {
1449
- var winner, ad, mediaFile, slot, videoEl, container, hls, slot1, slot2;
1450
- return _ts_generator(this, function(_state) {
1451
- switch(_state.label){
1452
- case 0:
1453
- if (destroyed) return [
1454
- 2
1455
- ];
1456
- winner = bids[0];
1457
- if (!winner) return [
1458
- 2
1459
- ];
1460
- if (debug) console.log("".concat(LOG, " [preload] Resolving VAST for token=").concat(token));
1461
- return [
1462
- 4,
1463
- resolveBidToVastAd(winner, LOG)
1464
- ];
1465
- case 1:
1466
- ad = _state.sent();
1467
- if (!ad || destroyed) return [
1468
- 2
1469
- ];
1470
- mediaFile = selectBestMediaFile(ad.mediaFiles);
1471
- if (!mediaFile) return [
1472
- 2
1473
- ];
1474
- if (smartTVMode || singleElementMode) {
1475
- slot = {
1476
- bids: bids,
1477
- ad: ad,
1478
- mediaFile: mediaFile,
1479
- videoEl: null,
1480
- ready: true
1481
- };
1482
- preloadSlots.set(token, slot);
1483
- if (debug) console.log("".concat(LOG, " [preload] Metadata-only preload (smartTV/singleElement), token=").concat(token, ", url=").concat(mediaFile.url));
1169
+ return {
1170
+ initialize: function initialize() {
1171
+ log("Initializing");
1172
+ if (!adContainerEl) {
1173
+ var _contentVideo_parentElement;
1174
+ var parent = contentVideo.parentElement;
1175
+ if (parent) {
1176
+ var computed = window.getComputedStyle(parent).position;
1177
+ if (computed === "static") {
1178
+ parent.style.position = "relative";
1179
+ parentPositionOverridden = true;
1180
+ }
1181
+ }
1182
+ var container = document.createElement("div");
1183
+ container.style.position = "absolute";
1184
+ container.style.left = "0";
1185
+ container.style.top = "0";
1186
+ container.style.right = "0";
1187
+ container.style.bottom = "0";
1188
+ container.style.display = "none";
1189
+ container.style.alignItems = "center";
1190
+ container.style.justifyContent = "center";
1191
+ container.style.pointerEvents = "none";
1192
+ container.style.zIndex = AD_LAYER_Z_INDEX;
1193
+ container.style.backgroundColor = "#000";
1194
+ container.style.transition = "opacity 0.3s ease-in-out";
1195
+ container.style.opacity = "0";
1196
+ container.style.isolation = "isolate";
1197
+ var countdown = document.createElement("div");
1198
+ countdown.style.position = "absolute";
1199
+ countdown.style.right = "12px";
1200
+ countdown.style.top = "12px";
1201
+ countdown.style.padding = "4px 8px";
1202
+ countdown.style.borderRadius = "4px";
1203
+ countdown.style.background = "rgba(0,0,0,0.75)";
1204
+ countdown.style.color = "#fff";
1205
+ countdown.style.fontFamily = "sans-serif";
1206
+ countdown.style.fontSize = "12px";
1207
+ countdown.style.lineHeight = "1.2";
1208
+ countdown.style.pointerEvents = "none";
1209
+ countdown.style.zIndex = COUNTDOWN_Z_INDEX;
1210
+ countdown.textContent = "Ad";
1211
+ container.appendChild(countdown);
1212
+ (_contentVideo_parentElement = contentVideo.parentElement) === null || _contentVideo_parentElement === void 0 ? void 0 : _contentVideo_parentElement.appendChild(container);
1213
+ adContainerEl = container;
1214
+ adCountdownEl = countdown;
1215
+ }
1216
+ },
1217
+ requestAds: function requestAds(duration) {
1218
+ return _async_to_generator(function() {
1219
+ var durationSeconds, parsed, ads, error;
1220
+ return _ts_generator(this, function(_state) {
1221
+ switch(_state.label){
1222
+ case 0:
1223
+ log("Requesting ads for duration:", duration);
1224
+ if (adPlaying) {
1225
+ return [
1226
+ 2,
1227
+ Promise.reject(new Error("Ad already playing"))
1228
+ ];
1229
+ }
1230
+ if (destroyed) {
1231
+ return [
1232
+ 2,
1233
+ Promise.reject(new Error("Player has been destroyed"))
1234
+ ];
1235
+ }
1236
+ _state.label = 1;
1237
+ case 1:
1238
+ _state.trys.push([
1239
+ 1,
1240
+ 3,
1241
+ ,
1242
+ 4
1243
+ ]);
1244
+ tornDown = false;
1245
+ durationSeconds = 30;
1246
+ parsed = parseInt(duration || "", 10);
1247
+ if (!isNaN(parsed) && parsed > 0) {
1248
+ durationSeconds = parsed;
1249
+ }
1484
1250
  return [
1485
- 2
1251
+ 4,
1252
+ fetchVast(durationSeconds)
1486
1253
  ];
1487
- }
1488
- videoEl = createAdVideoElement();
1489
- videoEl.style.visibility = "hidden";
1490
- videoEl.style.pointerEvents = "none";
1491
- videoEl.preload = "auto";
1492
- container = ensureAdContainer();
1493
- container.appendChild(videoEl);
1494
- if (isHlsMediaFile(mediaFile) && import_hls.default.isSupported()) {
1495
- hls = new import_hls.default({
1496
- enableWorker: true,
1497
- lowLatencyMode: false
1498
- });
1499
- hls.loadSource(mediaFile.url);
1500
- hls.attachMedia(videoEl);
1501
- slot1 = {
1502
- bids: bids,
1503
- ad: ad,
1504
- mediaFile: mediaFile,
1505
- videoEl: videoEl,
1506
- hlsInstance: hls,
1507
- ready: false
1508
- };
1509
- preloadSlots.set(token, slot1);
1510
- hls.on(import_hls.default.Events.MANIFEST_PARSED, function() {
1511
- var s = preloadSlots.get(token);
1512
- if (s) s.ready = true;
1513
- if (debug) console.log("".concat(LOG, " [preload] HLS manifest parsed, token=").concat(token));
1514
- });
1515
- hls.on(import_hls.default.Events.ERROR, function(_evt, data) {
1516
- if (!preloadSlots.has(token)) return;
1517
- if (data.fatal) {
1518
- if (debug) console.warn("".concat(LOG, " [preload] HLS error for token=").concat(token));
1519
- preloadSlots.delete(token);
1520
- hls.destroy();
1521
- videoEl.remove();
1522
- }
1523
- });
1524
- } else {
1525
- videoEl.src = mediaFile.url;
1526
- videoEl.load();
1527
- slot2 = {
1528
- bids: bids,
1529
- ad: ad,
1530
- mediaFile: mediaFile,
1531
- videoEl: videoEl,
1532
- ready: false
1533
- };
1534
- preloadSlots.set(token, slot2);
1535
- videoEl.addEventListener("canplay", function() {
1536
- var s = preloadSlots.get(token);
1537
- if (s) s.ready = true;
1538
- if (debug) console.log("".concat(LOG, " [preload] canplay fired, token=").concat(token));
1539
- }, {
1540
- once: true
1541
- });
1542
- }
1543
- if (debug) console.log("".concat(LOG, " [preload] Started buffering token=").concat(token, ", url=").concat(mediaFile.url));
1544
- return [
1545
- 2
1546
- ];
1547
- }
1548
- });
1549
- })();
1550
- }
1551
- function playPreloaded(token) {
1552
- return _async_to_generator(function() {
1553
- var slot, contentVolume, adVolume2, videoEl, container2, adVolume21, nonFatalNetworkErrors, adVolume, container;
1554
- return _ts_generator(this, function(_state) {
1555
- switch(_state.label){
1556
- case 0:
1557
- if (destroyed) return [
1558
- 2,
1559
- Promise.reject(new Error("Layer has been destroyed"))
1560
- ];
1561
- slot = preloadSlots.get(token);
1562
- if (!slot) {
1563
- if (debug) console.warn("".concat(LOG, " [preload] No slot found for token=").concat(token, ", nothing to play"));
1254
+ case 2:
1255
+ ads = _state.sent();
1256
+ if (ads.length === 0) {
1257
+ log("No ads available from VAST response");
1258
+ emit("ad_error");
1259
+ return [
1260
+ 2,
1261
+ Promise.resolve()
1262
+ ];
1263
+ }
1264
+ assignCurrentAd(ads[0]);
1265
+ log("Ad loaded: ".concat(currentAd.title, ", duration: ").concat(currentAd.duration, "s"));
1266
+ return [
1267
+ 2,
1268
+ Promise.resolve()
1269
+ ];
1270
+ case 3:
1271
+ error = _state.sent();
1272
+ console.error("[AdStormPlayer] Error requesting ads:", error);
1273
+ emit("ad_error");
1274
+ return [
1275
+ 2,
1276
+ Promise.reject(error)
1277
+ ];
1278
+ case 4:
1564
1279
  return [
1565
1280
  2
1566
1281
  ];
1567
- }
1568
- preloadSlots.delete(token);
1569
- if (debug) console.log("".concat(LOG, " [preload] Playing preloaded ad, token=").concat(token, ", ready=").concat(slot.ready));
1570
- contentVolume = contentVideo.volume;
1571
- originalVolume = Math.max(0, Math.min(1, contentVolume || originalVolume));
1572
- sessionId = generateSessionId();
1573
- currentAd = slot.ad;
1574
- trackingFired = _object_spread({}, createEmptyTrackingState());
1575
- fireTrackingPixels2(slot.ad.trackingUrls.impression);
1576
- trackingFired.impression = true;
1577
- if (!singleElementMode) return [
1578
- 3,
1579
- 2
1580
- ];
1581
- mainHlsInstance === null || mainHlsInstance === void 0 ? void 0 : mainHlsInstance.detachMedia();
1582
- teardownCurrentPlayback();
1583
- adVideoElement = contentVideo;
1584
- adHls = void 0;
1585
- adPlaying = true;
1586
- setAdPlayingFlag(true);
1587
- contentVideo.removeAttribute("src");
1588
- contentVideo.load();
1589
- contentVideo.muted = true;
1590
- contentVideo.volume = 0;
1591
- return [
1592
- 4,
1593
- new Promise(function(resolve) {
1594
- return setTimeout(resolve, 200);
1595
- })
1596
- ];
1597
- case 1:
1598
- _state.sent();
1599
- if (destroyed || tornDown) return [
1600
- 2
1601
- ];
1602
- contentVideo.style.visibility = "visible";
1603
- contentVideo.style.opacity = "1";
1604
- emit("content_pause");
1605
- setupAdEventListeners();
1606
- adVolume2 = originalMutedState ? 1 : originalVolume;
1607
- contentVideo.volume = Math.max(0, Math.min(1, adVolume2));
1608
- contentVideo.muted = false;
1609
- if (debug) console.log("".concat(LOG, " [preload] singleElementMode: attaching ad to contentVideo, url=").concat(slot.mediaFile.url));
1610
- startPlayback(slot.mediaFile);
1611
- return [
1612
- 2
1613
- ];
1614
- case 2:
1615
- if (smartTVMode && !slot.videoEl) {
1616
- teardownCurrentPlayback();
1617
- if (adVideoElement) {
1618
- adVideoElement.remove();
1619
- adVideoElement = void 0;
1282
+ }
1283
+ });
1284
+ })();
1285
+ },
1286
+ play: function play() {
1287
+ return _async_to_generator(function() {
1288
+ var mediaFile, error;
1289
+ return _ts_generator(this, function(_state) {
1290
+ switch(_state.label){
1291
+ case 0:
1292
+ if (!currentAd) {
1293
+ return [
1294
+ 2,
1295
+ Promise.reject(new Error("No ad loaded"))
1296
+ ];
1297
+ }
1298
+ if (destroyed) {
1299
+ return [
1300
+ 2,
1301
+ Promise.reject(new Error("Player has been destroyed"))
1302
+ ];
1303
+ }
1304
+ log("Starting ad playback");
1305
+ _state.label = 1;
1306
+ case 1:
1307
+ _state.trys.push([
1308
+ 1,
1309
+ 3,
1310
+ ,
1311
+ 4
1312
+ ]);
1313
+ tornDown = false;
1314
+ if (adHideTimerId) {
1315
+ clearTimeout(adHideTimerId);
1316
+ adHideTimerId = void 0;
1317
+ }
1318
+ if (!adVideoElement) {
1319
+ adVideoElement = createAdVideoElement();
1320
+ adContainerEl === null || adContainerEl === void 0 ? void 0 : adContainerEl.appendChild(adVideoElement);
1321
+ } else {
1322
+ teardownCurrentPlayback();
1620
1323
  }
1621
- videoEl = createAdVideoElement();
1622
- videoEl.style.visibility = "visible";
1623
- videoEl.style.pointerEvents = "none";
1624
- container2 = ensureAdContainer();
1625
- container2.appendChild(videoEl);
1626
- adVideoElement = videoEl;
1627
1324
  setupAdEventListeners();
1325
+ trackingFired = {
1326
+ impression: trackingFired.impression,
1327
+ start: false,
1328
+ firstQuartile: false,
1329
+ midpoint: false,
1330
+ thirdQuartile: false,
1331
+ complete: false
1332
+ };
1333
+ contentVideo.style.transition = "opacity 0.3s ease-in-out";
1334
+ contentVideo.style.opacity = "0";
1335
+ setTimeout(function() {
1336
+ contentVideo.style.visibility = "hidden";
1337
+ }, 300);
1338
+ contentVideo.muted = true;
1339
+ contentVideo.volume = 0;
1628
1340
  if (!continueLiveStreamDuringAds) {
1629
1341
  contentVideo.pause();
1630
1342
  }
1631
- contentVideo.muted = true;
1632
- contentVideo.volume = 0;
1633
1343
  adPlaying = true;
1634
1344
  setAdPlayingFlag(true);
1635
- adVolume21 = originalMutedState ? 1 : originalVolume;
1636
- adVideoElement.volume = Math.max(0, Math.min(1, adVolume21));
1637
- adVideoElement.muted = false;
1638
- container2.style.display = "flex";
1639
- container2.style.pointerEvents = "auto";
1345
+ if (adVideoElement) {
1346
+ adVideoElement.volume = originalMutedState ? 0 : originalVolume;
1347
+ adVideoElement.muted = originalMutedState;
1348
+ }
1349
+ if (adContainerEl) {
1350
+ adContainerEl.style.display = "flex";
1351
+ adContainerEl.style.pointerEvents = "auto";
1352
+ adContainerEl.offsetHeight;
1353
+ adContainerEl.style.opacity = "1";
1354
+ }
1640
1355
  emit("content_pause");
1641
- if (debug) console.log("".concat(LOG, " [preload] smartTVMode deferred: creating video element and loading, url=").concat(slot.mediaFile.url));
1642
- startPlayback(slot.mediaFile);
1356
+ mediaFile = selectBestMediaFile(currentAd.mediaFiles);
1357
+ if (!mediaFile) {
1358
+ throw new Error("No media file available");
1359
+ }
1360
+ log("Playing media file:", mediaFile.url);
1361
+ adVideoElement.src = mediaFile.url;
1362
+ adVideoElement.load();
1643
1363
  return [
1644
- 2
1364
+ 4,
1365
+ adVideoElement.play()
1645
1366
  ];
1646
- }
1647
- teardownCurrentPlayback();
1648
- if (adVideoElement && adVideoElement !== slot.videoEl) {
1649
- adVideoElement.remove();
1650
- }
1651
- slot.videoEl.style.visibility = "visible";
1652
- slot.videoEl.style.pointerEvents = "none";
1653
- adVideoElement = slot.videoEl;
1654
- adHls = slot.hlsInstance;
1655
- if (adHls) {
1656
- nonFatalNetworkErrors = 0;
1657
- adHls.on(import_hls.default.Events.ERROR, function(_event, data) {
1658
- if (!adPlaying) return;
1659
- if (data.fatal) {
1660
- handleAdError();
1661
- } else if (data.type === import_hls.default.ErrorTypes.NETWORK_ERROR) {
1662
- nonFatalNetworkErrors++;
1663
- if (nonFatalNetworkErrors >= 3) {
1664
- if (debug) console.warn("".concat(LOG, " [preload] Too many non-fatal HLS network errors during playback, treating as fatal"));
1665
- handleAdError();
1666
- }
1667
- }
1668
- });
1669
- }
1670
- setupAdEventListeners();
1671
- if (!continueLiveStreamDuringAds) {
1672
- contentVideo.pause();
1673
- }
1674
- contentVideo.muted = true;
1675
- contentVideo.volume = 0;
1676
- adPlaying = true;
1677
- setAdPlayingFlag(true);
1678
- adVolume = originalMutedState ? 1 : originalVolume;
1679
- adVideoElement.volume = Math.max(0, Math.min(1, adVolume));
1680
- adVideoElement.muted = false;
1681
- container = ensureAdContainer();
1682
- container.style.display = "flex";
1683
- container.style.pointerEvents = "auto";
1684
- emit("content_pause");
1685
- adVideoElement.play().catch(function(error) {
1686
- console.error("".concat(LOG, " [preload] Error playing preloaded ad:"), error);
1367
+ case 2:
1368
+ _state.sent();
1369
+ return [
1370
+ 2,
1371
+ Promise.resolve()
1372
+ ];
1373
+ case 3:
1374
+ error = _state.sent();
1375
+ console.error("[AdStormPlayer] Error playing ad:", error);
1687
1376
  handleAdError();
1688
- });
1689
- return [
1690
- 2
1691
- ];
1692
- }
1693
- });
1694
- })();
1695
- }
1696
- function cancelPreload(token) {
1697
- var slot = preloadSlots.get(token);
1698
- if (!slot) return;
1699
- preloadSlots.delete(token);
1700
- if (slot.hlsInstance) {
1701
- slot.hlsInstance.destroy();
1702
- }
1703
- if (slot.videoEl) {
1704
- slot.videoEl.pause();
1705
- slot.videoEl.removeAttribute("src");
1706
- slot.videoEl.load();
1707
- slot.videoEl.remove();
1708
- }
1709
- if (debug) console.log("".concat(LOG, " [preload] Cancelled and cleaned up token=").concat(token));
1710
- }
1711
- return {
1712
- initialize: function initialize() {
1713
- if (debug) console.log("".concat(LOG, " Initializing"));
1714
- },
1715
- updateOptions: function updateOptions(opts) {
1716
- if (opts.continueLiveStreamDuringAds !== void 0) {
1717
- continueLiveStreamDuringAds = opts.continueLiveStreamDuringAds;
1718
- }
1719
- if (opts.mainHlsInstance !== void 0) {
1720
- var _opts_mainHlsInstance;
1721
- mainHlsInstance = (_opts_mainHlsInstance = opts.mainHlsInstance) !== null && _opts_mainHlsInstance !== void 0 ? _opts_mainHlsInstance : void 0;
1722
- }
1723
- },
1724
- playAd: playAd,
1725
- preloadAd: preloadAd,
1726
- playPreloaded: playPreloaded,
1727
- hasPreloaded: function hasPreloaded(token) {
1728
- return preloadSlots.has(token);
1729
- },
1730
- cancelPreload: cancelPreload,
1731
- pause: function pause() {
1732
- if (!adPlaying || !adVideoElement) return;
1733
- try {
1734
- if (!adVideoElement.paused) adVideoElement.pause();
1735
- } catch (error) {
1736
- if (debug) console.warn("".concat(LOG, " Error pausing ad:"), error);
1737
- }
1738
- },
1739
- resume: function resume() {
1740
- if (!adPlaying || !adVideoElement) return;
1741
- try {
1742
- if (adVideoElement.paused) adVideoElement.play().catch(function() {});
1743
- } catch (error) {
1744
- if (debug) console.warn("".concat(LOG, " Error resuming ad:"), error);
1745
- }
1377
+ return [
1378
+ 2,
1379
+ Promise.reject(error)
1380
+ ];
1381
+ case 4:
1382
+ return [
1383
+ 2
1384
+ ];
1385
+ }
1386
+ });
1387
+ })();
1746
1388
  },
1747
1389
  stop: function stop() {
1748
1390
  return _async_to_generator(function() {
1749
1391
  return _ts_generator(this, function(_state) {
1392
+ log("Stopping ad");
1750
1393
  tornDown = true;
1751
- if (debug) console.log("".concat(LOG, " Stopping ad"));
1752
1394
  adPlaying = false;
1753
1395
  setAdPlayingFlag(false);
1754
- contentVideo.muted = originalMutedState;
1755
- contentVideo.volume = originalMutedState ? 0 : originalVolume;
1396
+ clearAdStallTimer();
1397
+ clearAdCountdownTimer();
1398
+ if (adContainerEl) {
1399
+ adContainerEl.style.opacity = "0";
1400
+ adHideTimerId = setTimeout(function() {
1401
+ if (adContainerEl) {
1402
+ adContainerEl.style.display = "none";
1403
+ adContainerEl.style.pointerEvents = "none";
1404
+ }
1405
+ }, 300);
1406
+ }
1407
+ teardownCurrentPlayback();
1756
1408
  contentVideo.style.visibility = "visible";
1757
1409
  contentVideo.style.opacity = "1";
1758
- if (singleElementMode) {
1759
- teardownCurrentPlayback();
1760
- contentVideo.removeAttribute("src");
1761
- contentVideo.load();
1762
- adVideoElement = void 0;
1763
- } else {
1764
- if (adContainerEl) {
1765
- adContainerEl.style.display = "none";
1766
- adContainerEl.style.pointerEvents = "none";
1767
- }
1768
- if (continueLiveStreamDuringAds) {
1769
- contentVideo.play().catch(function() {});
1770
- }
1771
- teardownCurrentPlayback();
1772
- if (adVideoElement) {
1773
- adVideoElement.pause();
1774
- adVideoElement.removeAttribute("src");
1775
- adVideoElement.load();
1776
- }
1777
- }
1410
+ contentVideo.muted = originalMutedState;
1411
+ contentVideo.volume = originalVolume;
1778
1412
  currentAd = void 0;
1779
1413
  tornDown = false;
1780
1414
  return [
1781
- 2
1415
+ 2,
1416
+ Promise.resolve()
1782
1417
  ];
1783
1418
  });
1784
1419
  })();
1785
1420
  },
1421
+ pause: function pause() {
1422
+ if (!adPlaying || !adVideoElement) return;
1423
+ try {
1424
+ if (!adVideoElement.paused) adVideoElement.pause();
1425
+ } catch (error) {
1426
+ console.warn("[AdStormPlayer] Error pausing ad:", error);
1427
+ }
1428
+ },
1429
+ resume: function resume() {
1430
+ if (!adPlaying || !adVideoElement) return;
1431
+ try {
1432
+ if (adVideoElement.paused) adVideoElement.play().catch(function() {});
1433
+ } catch (error) {
1434
+ console.warn("[AdStormPlayer] Error resuming ad:", error);
1435
+ }
1436
+ },
1786
1437
  destroy: function destroy() {
1787
- tornDown = true;
1788
- if (debug) console.log("".concat(LOG, " Destroying"));
1438
+ log("Destroying");
1789
1439
  destroyed = true;
1440
+ tornDown = true;
1790
1441
  adPlaying = false;
1791
1442
  setAdPlayingFlag(false);
1443
+ clearAdStallTimer();
1444
+ clearAdCountdownTimer();
1445
+ if (adHideTimerId) {
1446
+ clearTimeout(adHideTimerId);
1447
+ adHideTimerId = void 0;
1448
+ }
1792
1449
  contentVideo.muted = originalMutedState;
1793
1450
  contentVideo.volume = originalVolume;
1794
- var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
1795
- try {
1796
- for(var _iterator = Array.from(preloadSlots.entries())[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
1797
- var _step_value = _sliced_to_array(_step.value, 1), token = _step_value[0];
1798
- cancelPreload(token);
1799
- }
1800
- } catch (err) {
1801
- _didIteratorError = true;
1802
- _iteratorError = err;
1803
- } finally{
1804
- try {
1805
- if (!_iteratorNormalCompletion && _iterator.return != null) {
1806
- _iterator.return();
1807
- }
1808
- } finally{
1809
- if (_didIteratorError) {
1810
- throw _iteratorError;
1811
- }
1812
- }
1813
- }
1451
+ contentVideo.style.visibility = "visible";
1452
+ contentVideo.style.opacity = "1";
1814
1453
  teardownCurrentPlayback();
1815
- if (adVideoElement) {
1816
- if (singleElementMode && adVideoElement === contentVideo) {
1817
- contentVideo.removeAttribute("src");
1818
- contentVideo.load();
1819
- } else {
1820
- adVideoElement.pause();
1821
- adVideoElement.removeAttribute("src");
1822
- adVideoElement.remove();
1823
- }
1824
- adVideoElement = void 0;
1825
- }
1454
+ adVideoElement === null || adVideoElement === void 0 ? void 0 : adVideoElement.remove();
1455
+ adVideoElement = void 0;
1826
1456
  if (adContainerEl === null || adContainerEl === void 0 ? void 0 : adContainerEl.parentElement) {
1827
1457
  adContainerEl.parentElement.removeChild(adContainerEl);
1828
1458
  }
1829
1459
  adContainerEl = void 0;
1460
+ adCountdownEl = void 0;
1830
1461
  currentAd = void 0;
1462
+ sessionId = void 0;
1463
+ preloadSlots.clear();
1831
1464
  listeners.clear();
1465
+ if (parentPositionOverridden && contentVideo.parentElement) {
1466
+ contentVideo.parentElement.style.position = "";
1467
+ parentPositionOverridden = false;
1468
+ }
1469
+ },
1470
+ updateOptions: function updateOptions(opts) {
1471
+ if (opts.continueLiveStreamDuringAds !== void 0) {
1472
+ continueLiveStreamDuringAds = opts.continueLiveStreamDuringAds;
1473
+ }
1474
+ },
1475
+ playAd: function playAd(requestContext) {
1476
+ return _async_to_generator(function() {
1477
+ var ad;
1478
+ return _ts_generator(this, function(_state) {
1479
+ switch(_state.label){
1480
+ case 0:
1481
+ if (destroyed) return [
1482
+ 2,
1483
+ Promise.reject(new Error("Player has been destroyed"))
1484
+ ];
1485
+ if (!!currentAd) return [
1486
+ 3,
1487
+ 2
1488
+ ];
1489
+ return [
1490
+ 4,
1491
+ requestAdFromApi(requestContext)
1492
+ ];
1493
+ case 1:
1494
+ ad = _state.sent();
1495
+ if (!ad) {
1496
+ emit("ad_error", {
1497
+ message: "No valid ad from AdStorm API"
1498
+ });
1499
+ return [
1500
+ 2,
1501
+ Promise.reject(new Error("No valid ad from AdStorm API"))
1502
+ ];
1503
+ }
1504
+ assignCurrentAd(ad);
1505
+ _state.label = 2;
1506
+ case 2:
1507
+ return [
1508
+ 2,
1509
+ this.play()
1510
+ ];
1511
+ }
1512
+ });
1513
+ }).call(this);
1514
+ },
1515
+ preloadAd: function preloadAd(arg1, arg2) {
1516
+ return _async_to_generator(function() {
1517
+ var token, requestContext, ad;
1518
+ return _ts_generator(this, function(_state) {
1519
+ switch(_state.label){
1520
+ case 0:
1521
+ if (destroyed) return [
1522
+ 2
1523
+ ];
1524
+ token = typeof arg1 === "string" ? arg1 : typeof arg2 === "string" ? arg2 : void 0;
1525
+ if (!token) return [
1526
+ 2
1527
+ ];
1528
+ requestContext = typeof arg1 === "string" ? arg2 : arg1;
1529
+ return [
1530
+ 4,
1531
+ requestAdFromApi(requestContext)
1532
+ ];
1533
+ case 1:
1534
+ ad = _state.sent();
1535
+ if (!ad) return [
1536
+ 2
1537
+ ];
1538
+ preloadSlots.set(token, {
1539
+ ad: ad
1540
+ });
1541
+ return [
1542
+ 2
1543
+ ];
1544
+ }
1545
+ });
1546
+ })();
1547
+ },
1548
+ playPreloaded: function playPreloaded(token) {
1549
+ return _async_to_generator(function() {
1550
+ var slot;
1551
+ return _ts_generator(this, function(_state) {
1552
+ if (destroyed) return [
1553
+ 2,
1554
+ Promise.reject(new Error("Player has been destroyed"))
1555
+ ];
1556
+ slot = preloadSlots.get(token);
1557
+ if (!slot) {
1558
+ return [
1559
+ 2,
1560
+ Promise.reject(new Error("No preloaded ad for token ".concat(token)))
1561
+ ];
1562
+ }
1563
+ preloadSlots.delete(token);
1564
+ assignCurrentAd(slot.ad);
1565
+ return [
1566
+ 2,
1567
+ this.play()
1568
+ ];
1569
+ });
1570
+ }).call(this);
1571
+ },
1572
+ hasPreloaded: function hasPreloaded(token) {
1573
+ return preloadSlots.has(token);
1574
+ },
1575
+ cancelPreload: function cancelPreload(token) {
1576
+ preloadSlots.delete(token);
1832
1577
  },
1833
1578
  isAdPlaying: function isAdPlaying() {
1834
1579
  return adPlaying;
1835
1580
  },
1836
1581
  resize: function resize(width, height) {
1582
+ log("Resizing to ".concat(width, "x").concat(height));
1837
1583
  if (adContainerEl) {
1838
1584
  adContainerEl.style.width = "".concat(width, "px");
1839
1585
  adContainerEl.style.height = "".concat(height, "px");
@@ -1853,6 +1599,7 @@ function createVastAdLayer(contentVideo, options) {
1853
1599
  },
1854
1600
  updateOriginalMutedState: function updateOriginalMutedState(muted, volume) {
1855
1601
  var nextVolume = typeof volume === "number" && !Number.isNaN(volume) ? Math.max(0, Math.min(1, volume)) : originalVolume;
1602
+ log("updateOriginalMutedState: muted=".concat(muted, ", volume=").concat(nextVolume));
1856
1603
  originalMutedState = muted;
1857
1604
  originalVolume = nextVolume;
1858
1605
  },
@@ -1865,6 +1612,7 @@ function createVastAdLayer(contentVideo, options) {
1865
1612
  setAdVolume: function setAdVolume(volume) {
1866
1613
  if (adVideoElement && adPlaying) {
1867
1614
  adVideoElement.volume = Math.max(0, Math.min(1, volume));
1615
+ adVideoElement.muted = volume === 0;
1868
1616
  }
1869
1617
  },
1870
1618
  getAdVolume: function getAdVolume() {
@@ -1874,11 +1622,16 @@ function createVastAdLayer(contentVideo, options) {
1874
1622
  return 1;
1875
1623
  },
1876
1624
  showPlaceholder: function showPlaceholder() {
1877
- if (singleElementMode) return;
1878
- contentVideo.style.opacity = "0";
1879
- contentVideo.style.visibility = "hidden";
1880
1625
  if (!adContainerEl) {
1881
1626
  var _contentVideo_parentElement;
1627
+ var parent = contentVideo.parentElement;
1628
+ if (parent) {
1629
+ var computed = window.getComputedStyle(parent).position;
1630
+ if (computed === "static") {
1631
+ parent.style.position = "relative";
1632
+ parentPositionOverridden = true;
1633
+ }
1634
+ }
1882
1635
  var container = document.createElement("div");
1883
1636
  container.style.position = "absolute";
1884
1637
  container.style.left = "0";
@@ -1889,24 +1642,43 @@ function createVastAdLayer(contentVideo, options) {
1889
1642
  container.style.alignItems = "center";
1890
1643
  container.style.justifyContent = "center";
1891
1644
  container.style.pointerEvents = "none";
1892
- container.style.zIndex = "10";
1645
+ container.style.zIndex = AD_LAYER_Z_INDEX;
1893
1646
  container.style.backgroundColor = "#000";
1647
+ container.style.isolation = "isolate";
1648
+ var countdown = document.createElement("div");
1649
+ countdown.style.position = "absolute";
1650
+ countdown.style.right = "12px";
1651
+ countdown.style.top = "12px";
1652
+ countdown.style.padding = "4px 8px";
1653
+ countdown.style.borderRadius = "4px";
1654
+ countdown.style.background = "rgba(0,0,0,0.75)";
1655
+ countdown.style.color = "#fff";
1656
+ countdown.style.fontFamily = "sans-serif";
1657
+ countdown.style.fontSize = "12px";
1658
+ countdown.style.lineHeight = "1.2";
1659
+ countdown.style.pointerEvents = "none";
1660
+ countdown.style.zIndex = COUNTDOWN_Z_INDEX;
1661
+ countdown.textContent = "Ad";
1662
+ container.appendChild(countdown);
1894
1663
  (_contentVideo_parentElement = contentVideo.parentElement) === null || _contentVideo_parentElement === void 0 ? void 0 : _contentVideo_parentElement.appendChild(container);
1895
1664
  adContainerEl = container;
1665
+ adCountdownEl = countdown;
1896
1666
  }
1897
1667
  if (adContainerEl) {
1898
1668
  adContainerEl.style.display = "flex";
1669
+ adContainerEl.style.opacity = "1";
1899
1670
  adContainerEl.style.pointerEvents = "auto";
1900
1671
  }
1901
1672
  },
1902
1673
  hidePlaceholder: function hidePlaceholder() {
1903
1674
  if (adContainerEl) {
1904
- adContainerEl.style.display = "none";
1905
- adContainerEl.style.pointerEvents = "none";
1906
- }
1907
- if (!adPlaying) {
1908
- contentVideo.style.visibility = "visible";
1909
- contentVideo.style.opacity = "1";
1675
+ adContainerEl.style.opacity = "0";
1676
+ setTimeout(function() {
1677
+ if (adContainerEl) {
1678
+ adContainerEl.style.display = "none";
1679
+ adContainerEl.style.pointerEvents = "none";
1680
+ }
1681
+ }, 300);
1910
1682
  }
1911
1683
  }
1912
1684
  };
@@ -3009,6 +2781,9 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
3009
2781
  this.backoffBaseMs = 1e3;
3010
2782
  this.maxBackoffMs = 15e3;
3011
2783
  this.MIN_AD_REMAINING_MS = 15e3;
2784
+ this.adRequestTimeoutMs = 5e3;
2785
+ this.adRequestMaxRetries = 3;
2786
+ this.adRequestRetryBackoffMs = 1500;
3012
2787
  this.preloadedTokens = [];
3013
2788
  initializePolyfills();
3014
2789
  var browserOverrides = getBrowserConfigOverrides();
@@ -3016,24 +2791,22 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
3016
2791
  this.video = config.videoElement;
3017
2792
  this.adTransitionGapMs = (_this_config_adTransitionGapMs = this.config.adTransitionGapMs) !== null && _this_config_adTransitionGapMs !== void 0 ? _this_config_adTransitionGapMs : 100;
3018
2793
  logBrowserInfo(config.debugAdTiming);
3019
- this.vastManager = createVastManager(config.debugAdTiming !== void 0 ? {
3020
- debug: !!config.debugAdTiming
3021
- } : {});
3022
2794
  var browserForAdLayer = detectBrowser();
3023
2795
  var isSinglePipeline = browserForAdLayer.isSmartTV || !!this.config.singlePipelineMode;
3024
- this.adLayer = createVastAdLayer(this.video, {
3025
- continueLiveStreamDuringAds: false,
3026
- smartTVMode: isSinglePipeline,
3027
- singleElementMode: isSinglePipeline,
3028
- forceMP4Ads: isSinglePipeline,
2796
+ this.adLayer = createAdStormPlayer(this.video, {
2797
+ licenseKey: this.config.licenseKey || "",
3029
2798
  debug: !!config.debugAdTiming
3030
2799
  });
2800
+ this.adLayer.updateOptions({
2801
+ continueLiveStreamDuringAds: !isSinglePipeline && this.shouldContinueLiveStreamDuringAds()
2802
+ });
3031
2803
  }
3032
2804
  _create_class(StormcloudVideoPlayer, [
3033
2805
  {
3034
2806
  key: "adRequest",
3035
2807
  value: function adRequest(context) {
3036
2808
  return _async_to_generator(function() {
2809
+ var _ref, _ref1, durationSeconds;
3037
2810
  return _ts_generator(this, function(_state) {
3038
2811
  switch(_state.label){
3039
2812
  case 0:
@@ -3041,15 +2814,28 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
3041
2814
  2,
3042
2815
  []
3043
2816
  ];
2817
+ durationSeconds = Math.max(1, Math.ceil((_ref = (_ref1 = context === null || context === void 0 ? void 0 : context.remainingBreakSec) !== null && _ref1 !== void 0 ? _ref1 : context === null || context === void 0 ? void 0 : context.breakDurationSec) !== null && _ref !== void 0 ? _ref : 30));
3044
2818
  return [
3045
2819
  4,
3046
- this.vastManager.initialize()
2820
+ this.adLayer.requestAds(String(durationSeconds))
3047
2821
  ];
3048
2822
  case 1:
3049
2823
  _state.sent();
3050
2824
  return [
3051
2825
  2,
3052
- this.vastManager.requestBidsUntilResponse(context)
2826
+ [
2827
+ {
2828
+ bidder: "adstorm-direct",
2829
+ cpm: 0,
2830
+ width: 0,
2831
+ height: 0,
2832
+ adId: "adstorm",
2833
+ impId: "",
2834
+ creativeId: "adstorm",
2835
+ currency: "USD",
2836
+ durationSec: durationSeconds
2837
+ }
2838
+ ]
3053
2839
  ];
3054
2840
  }
3055
2841
  });
@@ -3106,7 +2892,7 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
3106
2892
  2
3107
2893
  ];
3108
2894
  case 3:
3109
- this.hls = new import_hls2.default(_object_spread_props(_object_spread({
2895
+ this.hls = new import_hls.default(_object_spread_props(_object_spread({
3110
2896
  enableWorker: true,
3111
2897
  backBufferLength: 30,
3112
2898
  liveDurationInfinity: true,
@@ -3124,11 +2910,11 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
3124
2910
  nudgeMaxRetry: 3,
3125
2911
  startPosition: -1
3126
2912
  }));
3127
- this.hls.on(import_hls2.default.Events.MEDIA_ATTACHED, function() {
2913
+ this.hls.on(import_hls.default.Events.MEDIA_ATTACHED, function() {
3128
2914
  var _this_hls;
3129
2915
  (_this_hls = _this.hls) === null || _this_hls === void 0 ? void 0 : _this_hls.loadSource(_this.config.src);
3130
2916
  });
3131
- this.hls.on(import_hls2.default.Events.MANIFEST_PARSED, function(_, data) {
2917
+ this.hls.on(import_hls.default.Events.MANIFEST_PARSED, function(_, data) {
3132
2918
  return _async_to_generator(function() {
3133
2919
  var _this_config_minSegmentsBeforePlay, _ref, _this_hls_levels, _this_hls, adBehavior, _this_hls1, minSegments, _this_video_play;
3134
2920
  return _ts_generator(this, function(_state) {
@@ -3190,7 +2976,7 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
3190
2976
  });
3191
2977
  }).call(_this);
3192
2978
  });
3193
- this.hls.on(import_hls2.default.Events.LEVEL_LOADED, function(_evt, data) {
2979
+ this.hls.on(import_hls.default.Events.LEVEL_LOADED, function(_evt, data) {
3194
2980
  if (_this.inAdBreak || _this.pendingAdBreak) {
3195
2981
  return;
3196
2982
  }
@@ -3263,7 +3049,7 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
3263
3049
  }
3264
3050
  }
3265
3051
  });
3266
- this.hls.on(import_hls2.default.Events.FRAG_BUFFERED, function(_evt, data) {
3052
+ this.hls.on(import_hls.default.Events.FRAG_BUFFERED, function(_evt, data) {
3267
3053
  return _async_to_generator(function() {
3268
3054
  var _this, _this_config_minSegmentsBeforePlay, minSegments, _this_video_play;
3269
3055
  return _ts_generator(this, function(_state) {
@@ -3323,7 +3109,7 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
3323
3109
  });
3324
3110
  }).call(_this);
3325
3111
  });
3326
- this.hls.on(import_hls2.default.Events.FRAG_PARSING_METADATA, function(_evt, data) {
3112
+ this.hls.on(import_hls.default.Events.FRAG_PARSING_METADATA, function(_evt, data) {
3327
3113
  var id3Tags = ((data === null || data === void 0 ? void 0 : data.samples) || []).map(function(s) {
3328
3114
  return {
3329
3115
  key: "ID3",
@@ -3335,7 +3121,7 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
3335
3121
  return _this.onId3Tag(tag);
3336
3122
  });
3337
3123
  });
3338
- this.hls.on(import_hls2.default.Events.FRAG_CHANGED, function(_evt, data) {
3124
+ this.hls.on(import_hls.default.Events.FRAG_CHANGED, function(_evt, data) {
3339
3125
  var frag = data === null || data === void 0 ? void 0 : data.frag;
3340
3126
  var tagList = frag === null || frag === void 0 ? void 0 : frag.tagList;
3341
3127
  if (!Array.isArray(tagList)) return;
@@ -3444,14 +3230,14 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
3444
3230
  }
3445
3231
  }
3446
3232
  });
3447
- this.hls.on(import_hls2.default.Events.ERROR, function(_evt, data) {
3233
+ this.hls.on(import_hls.default.Events.ERROR, function(_evt, data) {
3448
3234
  if (data === null || data === void 0 ? void 0 : data.fatal) {
3449
3235
  switch(data.type){
3450
- case import_hls2.default.ErrorTypes.NETWORK_ERROR:
3236
+ case import_hls.default.ErrorTypes.NETWORK_ERROR:
3451
3237
  var _this_hls;
3452
3238
  (_this_hls = _this.hls) === null || _this_hls === void 0 ? void 0 : _this_hls.startLoad();
3453
3239
  break;
3454
- case import_hls2.default.ErrorTypes.MEDIA_ERROR:
3240
+ case import_hls.default.ErrorTypes.MEDIA_ERROR:
3455
3241
  var _this_hls1;
3456
3242
  (_this_hls1 = _this.hls) === null || _this_hls1 === void 0 ? void 0 : _this_hls1.recoverMediaError();
3457
3243
  break;
@@ -3543,7 +3329,11 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
3543
3329
  }
3544
3330
  });
3545
3331
  this.adLayer.on("content_resume", function() {
3332
+ var _ref, _ref1;
3333
+ var _this_savedMutedStateBeforeScte, _this_savedMutedStateBeforeScte1;
3546
3334
  var remaining = _this.getRemainingAdMs();
3335
+ var breakMuted = (_ref = (_this_savedMutedStateBeforeScte = _this.savedMutedStateBeforeScte) === null || _this_savedMutedStateBeforeScte === void 0 ? void 0 : _this_savedMutedStateBeforeScte.muted) !== null && _ref !== void 0 ? _ref : _this.adLayer.getOriginalMutedState();
3336
+ var breakVolume = (_ref1 = (_this_savedMutedStateBeforeScte1 = _this.savedMutedStateBeforeScte) === null || _this_savedMutedStateBeforeScte1 === void 0 ? void 0 : _this_savedMutedStateBeforeScte1.volume) !== null && _ref1 !== void 0 ? _ref1 : _this.adLayer.getOriginalVolume();
3547
3337
  if (_this.config.debugAdTiming) {
3548
3338
  console.log("[StormcloudVideoPlayer] content_resume received, inAdBreak=%s, remaining=%s, preloadedTokens=%d, pendingNext=%s", _this.inAdBreak, remaining, _this.preloadedTokens.length, !!_this.pendingNextAdBids);
3549
3339
  }
@@ -3558,7 +3348,7 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
3558
3348
  return;
3559
3349
  }
3560
3350
  _this.consecutiveFailures = 0;
3561
- if (!_this.video.muted) {
3351
+ if (!_this.config.disableFiller && !_this.video.muted) {
3562
3352
  _this.video.muted = true;
3563
3353
  _this.video.volume = 0;
3564
3354
  }
@@ -3625,6 +3415,18 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
3625
3415
  if (!_this.config.disableFiller) {
3626
3416
  _this.showPlaceholderLayer();
3627
3417
  _this.adLayer.showPlaceholder();
3418
+ } else {
3419
+ _this.adLayer.hidePlaceholder();
3420
+ if (_this.video.muted !== breakMuted) {
3421
+ _this.video.muted = breakMuted;
3422
+ }
3423
+ if (Math.abs(_this.video.volume - breakVolume) > 0.01) {
3424
+ _this.video.volume = breakVolume;
3425
+ }
3426
+ if (_this.video.paused) {
3427
+ var _this_video_play;
3428
+ (_this_video_play = _this.video.play()) === null || _this_video_play === void 0 ? void 0 : _this_video_play.catch(function() {});
3429
+ }
3628
3430
  }
3629
3431
  _this.stopContinuousFetching();
3630
3432
  return;
@@ -4352,6 +4154,16 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
4352
4154
  return this.totalAdsInBreak;
4353
4155
  }
4354
4156
  },
4157
+ {
4158
+ key: "getRemainingAdSeconds",
4159
+ value: function getRemainingAdSeconds() {
4160
+ var remainingMs = this.getRemainingAdMs();
4161
+ if (!Number.isFinite(remainingMs) || remainingMs <= 0 || remainingMs === Number.MAX_SAFE_INTEGER) {
4162
+ return 0;
4163
+ }
4164
+ return Math.ceil(remainingMs / 1e3);
4165
+ }
4166
+ },
4355
4167
  {
4356
4168
  key: "isAdPlaying",
4357
4169
  value: function isAdPlaying() {
@@ -5581,7 +5393,7 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
5581
5393
  });
5582
5394
  };
5583
5395
  var onManifestParsedRestore = function onManifestParsedRestore1() {
5584
- hlsRef.off(import_hls2.default.Events.MANIFEST_PARSED, onManifestParsedRestore);
5396
+ hlsRef.off(import_hls.default.Events.MANIFEST_PARSED, onManifestParsedRestore);
5585
5397
  if (!_this.inAdBreak && !_this.adLayer.isAdPlaying()) {
5586
5398
  if (videoRef.muted !== savedMuted) videoRef.muted = savedMuted;
5587
5399
  if (Math.abs(videoRef.volume - savedVolume) > 0.01) videoRef.volume = savedVolume;
@@ -5594,7 +5406,7 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
5594
5406
  }
5595
5407
  }
5596
5408
  };
5597
- hlsRef.on(import_hls2.default.Events.MANIFEST_PARSED, onManifestParsedRestore);
5409
+ hlsRef.on(import_hls.default.Events.MANIFEST_PARSED, onManifestParsedRestore);
5598
5410
  var pipelineDelayMs = 300;
5599
5411
  if (debugEnabled) {
5600
5412
  console.log("[StormcloudVideoPlayer] Smart TV: waiting ".concat(pipelineDelayMs, "ms for hardware pipeline release before re-attach"));