stormcloud-video-player 0.8.64 → 0.8.66

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.
@@ -7,6 +7,9 @@ function _array_like_to_array(arr, len) {
7
7
  function _array_with_holes(arr) {
8
8
  if (Array.isArray(arr)) return arr;
9
9
  }
10
+ function _array_without_holes(arr) {
11
+ if (Array.isArray(arr)) return _array_like_to_array(arr);
12
+ }
10
13
  function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
11
14
  try {
12
15
  var info = gen[key](arg);
@@ -44,6 +47,11 @@ function _define_property(obj, key, value) {
44
47
  } else obj[key] = value;
45
48
  return obj;
46
49
  }
50
+ function _iterable_to_array(iter) {
51
+ if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) {
52
+ return Array.from(iter);
53
+ }
54
+ }
47
55
  function _iterable_to_array_limit(arr, i) {
48
56
  var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
49
57
  if (_i == null) return;
@@ -71,6 +79,9 @@ function _iterable_to_array_limit(arr, i) {
71
79
  function _non_iterable_rest() {
72
80
  throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
73
81
  }
82
+ function _non_iterable_spread() {
83
+ throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
84
+ }
74
85
  function _object_spread(target) {
75
86
  for(var i = 1; i < arguments.length; i++){
76
87
  var source = arguments[i] != null ? arguments[i] : {};
@@ -86,9 +97,35 @@ function _object_spread(target) {
86
97
  }
87
98
  return target;
88
99
  }
100
+ function ownKeys(object, enumerableOnly) {
101
+ var keys = Object.keys(object);
102
+ if (Object.getOwnPropertySymbols) {
103
+ var symbols = Object.getOwnPropertySymbols(object);
104
+ if (enumerableOnly) {
105
+ symbols = symbols.filter(function(sym) {
106
+ return Object.getOwnPropertyDescriptor(object, sym).enumerable;
107
+ });
108
+ }
109
+ keys.push.apply(keys, symbols);
110
+ }
111
+ return keys;
112
+ }
113
+ function _object_spread_props(target, source) {
114
+ source = source != null ? source : {};
115
+ if (Object.getOwnPropertyDescriptors) Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
116
+ else {
117
+ ownKeys(Object(source)).forEach(function(key) {
118
+ Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
119
+ });
120
+ }
121
+ return target;
122
+ }
89
123
  function _sliced_to_array(arr, i) {
90
124
  return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
91
125
  }
126
+ function _to_consumable_array(arr) {
127
+ return _array_without_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_spread();
128
+ }
92
129
  function _ts_generator(thisArg, body) {
93
130
  var f, y, t, _ = {
94
131
  label: 0,
@@ -614,7 +651,7 @@ function toVastMediaErrorCode(error) {
614
651
  }
615
652
  }
616
653
  function createHlsAdPlayer(contentVideo, options) {
617
- var _contentVideo_AD_VIDEO_PROP, _contentVideo_AD_CONTAINER_PROP;
654
+ var _contentVideo_AD_VIDEO_PROP, _contentVideo_AD_CONTAINER_PROP, _ref;
618
655
  var adPlaying = false;
619
656
  var originalMutedState = false;
620
657
  var originalVolume = Math.max(0, Math.min(1, contentVideo.volume || 1));
@@ -646,6 +683,18 @@ function createHlsAdPlayer(contentVideo, options) {
646
683
  var sawDecodedVideoFrame = false;
647
684
  var videoFrameCallbackHandle;
648
685
  var pendingPlayPromise;
686
+ var currentVastTagUrl;
687
+ var funnelContext = {};
688
+ var mediaProbe;
689
+ var lastPodAdElementCount = 0;
690
+ var mediaCandidates = [];
691
+ var mediaCandidateIndex = 0;
692
+ var mediaStartTimerId;
693
+ var MEDIA_START_TIMEOUT_MS = (_ref = options === null || options === void 0 ? void 0 : options.mediaStartTimeoutMs) !== null && _ref !== void 0 ? _ref : 8e3;
694
+ var VAST_ERROR_MEDIA_TIMEOUT = 402;
695
+ var pendingVastRequests = /* @__PURE__ */ new Set();
696
+ var pendingRequestAbortReason;
697
+ var forcedMuteByAutoplay = false;
649
698
  function createTrackingState() {
650
699
  return {
651
700
  impression: false,
@@ -696,6 +745,78 @@ function createHlsAdPlayer(contentVideo, options) {
696
745
  }
697
746
  }
698
747
  }
748
+ var SENSITIVE_URL_PARAMS = /* @__PURE__ */ new Set([
749
+ "ppid",
750
+ "rdid",
751
+ "idtype",
752
+ "is_lat",
753
+ "ifa",
754
+ "idfa",
755
+ "aaid",
756
+ "uid",
757
+ "user_id",
758
+ "userid",
759
+ "device_id",
760
+ "deviceid",
761
+ "ip",
762
+ "ua",
763
+ "gdpr_consent",
764
+ "us_privacy",
765
+ "gpp",
766
+ "addtl_consent",
767
+ "cust_params",
768
+ "email"
769
+ ]);
770
+ function redactUrl(url) {
771
+ if (!url) return url;
772
+ try {
773
+ var parsed = new URL(url);
774
+ var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
775
+ try {
776
+ for(var _iterator = Array.from(parsed.searchParams.keys())[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
777
+ var key = _step.value;
778
+ if (SENSITIVE_URL_PARAMS.has(key.toLowerCase())) {
779
+ parsed.searchParams.set(key, "REDACTED");
780
+ }
781
+ }
782
+ } catch (err) {
783
+ _didIteratorError = true;
784
+ _iteratorError = err;
785
+ } finally{
786
+ try {
787
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
788
+ _iterator.return();
789
+ }
790
+ } finally{
791
+ if (_didIteratorError) {
792
+ throw _iteratorError;
793
+ }
794
+ }
795
+ }
796
+ return parsed.toString();
797
+ } catch (unused) {
798
+ return url.split("?")[0];
799
+ }
800
+ }
801
+ function logFunnel(stage) {
802
+ var extra = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
803
+ var payload = _object_spread({
804
+ stage: stage,
805
+ breakId: funnelContext.breakId,
806
+ requestId: funnelContext.requestId,
807
+ controllerId: funnelContext.controllerId,
808
+ visibilityState: typeof document !== "undefined" ? document.visibilityState : void 0,
809
+ adId: currentAd === null || currentAd === void 0 ? void 0 : currentAd.id,
810
+ podIndex: podIndex,
811
+ podSize: podAds.length,
812
+ vastUrl: redactUrl(currentVastTagUrl),
813
+ mediaUrl: currentAdMediaFile === null || currentAdMediaFile === void 0 ? void 0 : currentAdMediaFile.url,
814
+ mediaType: currentAdMediaFile === null || currentAdMediaFile === void 0 ? void 0 : currentAdMediaFile.type,
815
+ muted: adVideoElement ? adVideoElement.muted : void 0
816
+ }, extra);
817
+ console.log("[HlsAdPlayer][FUNNEL] ".concat(stage), payload);
818
+ emit("ad_funnel", payload);
819
+ }
699
820
  function buildTrackingMacroContext() {
700
821
  var options2 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
701
822
  var _options2_ad;
@@ -735,20 +856,53 @@ function createHlsAdPlayer(contentVideo, options) {
735
856
  urls.forEach(function(url) {
736
857
  try {
737
858
  var trackingUrl = substituteVastTrackingMacros(url, macroContext);
859
+ var trackingHost;
860
+ try {
861
+ trackingHost = new URL(trackingUrl).host;
862
+ } catch (unused) {
863
+ logFunnel("tracking_url_invalid", {
864
+ trackingUrl: redactUrl(trackingUrl)
865
+ });
866
+ return;
867
+ }
868
+ var unexpanded = trackingUrl.match(/\[[A-Z_]+\]/g);
869
+ if (unexpanded) {
870
+ logFunnel("tracking_url_unexpanded_macro", {
871
+ trackingHost: trackingHost,
872
+ macros: Array.from(new Set(unexpanded))
873
+ });
874
+ }
738
875
  var img = new Image(1, 1);
739
876
  inFlightBeacons.add(img);
740
877
  var timeoutId;
741
- var release = function release() {
878
+ var release = function release(outcome) {
742
879
  if (timeoutId !== void 0) clearTimeout(timeoutId);
743
880
  img.onload = null;
744
881
  img.onerror = null;
745
882
  inFlightBeacons.delete(img);
883
+ console.log("[HlsAdPlayer] Tracking pixel settled (".concat(outcome, "): ").concat(trackingUrl));
884
+ if (outcome !== "load") {
885
+ logFunnel("tracking_request_settled", {
886
+ reason: outcome,
887
+ trackingHost: trackingHost
888
+ });
889
+ }
890
+ };
891
+ img.onload = function() {
892
+ return release("load");
893
+ };
894
+ img.onerror = function() {
895
+ return release("error");
746
896
  };
747
- img.onload = release;
748
- img.onerror = release;
749
- timeoutId = setTimeout(release, BEACON_TIMEOUT_MS);
897
+ timeoutId = setTimeout(function() {
898
+ return release("timeout");
899
+ }, BEACON_TIMEOUT_MS);
750
900
  img.src = trackingUrl;
751
901
  console.log("[HlsAdPlayer] Fired tracking pixel: ".concat(trackingUrl));
902
+ logFunnel("tracking_request_created", {
903
+ trackingHost: trackingHost,
904
+ errorCode: options2 === null || options2 === void 0 ? void 0 : options2.errorCode
905
+ });
752
906
  } catch (error) {
753
907
  console.warn("[HlsAdPlayer] Error firing tracking pixel:", error);
754
908
  }
@@ -778,54 +932,79 @@ function createHlsAdPlayer(contentVideo, options) {
778
932
  bitrate: level.bitrate || 5e6
779
933
  };
780
934
  }
781
- function selectBestMediaFile(mediaFiles) {
782
- if (mediaFiles.length === 0) {
783
- throw new Error("No media files available");
784
- }
785
- var firstFile = mediaFiles[0];
786
- if (!firstFile) {
787
- throw new Error("No media files available");
788
- }
789
- if (mediaFiles.length === 1) {
790
- return firstFile;
791
- }
935
+ function getMediaTargetQuality() {
792
936
  var mainQuality = getMainStreamQuality();
793
- if (!mainQuality) {
794
- console.log("[HlsAdPlayer] No main stream quality info, using first media file");
795
- return firstFile;
796
- }
797
- console.log("[HlsAdPlayer] Main stream quality:", mainQuality);
798
- var scoredFiles = mediaFiles.map(function(file) {
799
- var widthDiff = Math.abs(file.width - mainQuality.width);
800
- var heightDiff = Math.abs(file.height - mainQuality.height);
801
- var resolutionDiff = widthDiff + heightDiff;
802
- var fileBitrate = (file.bitrate || 5e3) * 1e3;
803
- var bitrateDiff = Math.abs(fileBitrate - mainQuality.bitrate);
804
- var score = resolutionDiff * 2 + bitrateDiff / 1e3;
805
- return {
937
+ var dpr = typeof window !== "undefined" && window.devicePixelRatio > 0 ? window.devicePixelRatio : 1;
938
+ var containerWidth = ((adContainerEl === null || adContainerEl === void 0 ? void 0 : adContainerEl.clientWidth) || contentVideo.clientWidth) * dpr;
939
+ var containerHeight = ((adContainerEl === null || adContainerEl === void 0 ? void 0 : adContainerEl.clientHeight) || contentVideo.clientHeight) * dpr;
940
+ if (!mainQuality && !(containerWidth > 0 && containerHeight > 0)) {
941
+ return null;
942
+ }
943
+ var base = mainQuality !== null && mainQuality !== void 0 ? mainQuality : {
944
+ width: containerWidth,
945
+ height: containerHeight,
946
+ bitrate: 5e6
947
+ };
948
+ var width = containerWidth > 0 ? Math.min(base.width, containerWidth) : base.width;
949
+ var height = containerHeight > 0 ? Math.min(base.height, containerHeight) : base.height;
950
+ return {
951
+ width: width,
952
+ height: height,
953
+ bitrate: base.bitrate
954
+ };
955
+ }
956
+ function rankMediaCandidates(mediaFiles) {
957
+ var probe = adVideoElement !== null && adVideoElement !== void 0 ? adVideoElement : document.createElement("video");
958
+ var pageIsHttps = typeof location !== "undefined" && location.protocol === "https:";
959
+ var target = getMediaTargetQuality();
960
+ var accepted = [];
961
+ mediaFiles.forEach(function(file, index) {
962
+ var isHls = isHlsMediaFile(file);
963
+ var mimeForProbe = isHls ? "application/vnd.apple.mpegurl" : file.type || "video/mp4";
964
+ var canPlay = probe.canPlayType(mimeForProbe);
965
+ var playable = isHls ? import_hls.default.isSupported() || canPlay !== "" : canPlay !== "";
966
+ var insecure = pageIsHttps && /^http:/i.test(file.url);
967
+ var details = {
968
+ index: index,
969
+ candidateUrl: file.url,
970
+ candidateType: file.type,
971
+ width: file.width,
972
+ height: file.height,
973
+ bitrate: file.bitrate,
974
+ canPlayType: canPlay,
975
+ hlsJs: isHls ? import_hls.default.isSupported() : void 0
976
+ };
977
+ if (!playable) {
978
+ logFunnel("media_candidate", _object_spread_props(_object_spread({}, details), {
979
+ reason: "rejected",
980
+ why: "cannot_play_type"
981
+ }));
982
+ return;
983
+ }
984
+ var score = 0;
985
+ if (target) {
986
+ var resolutionDiff = Math.abs(file.width - target.width) + Math.abs(file.height - target.height);
987
+ var bitrateDiff = Math.abs((file.bitrate || 5e3) * 1e3 - target.bitrate);
988
+ score = resolutionDiff * 2 + bitrateDiff / 1e3;
989
+ }
990
+ accepted.push({
806
991
  file: file,
807
992
  score: score,
808
- resolutionDiff: resolutionDiff,
809
- bitrateDiff: bitrateDiff
810
- };
993
+ insecure: insecure
994
+ });
995
+ logFunnel("media_candidate", _object_spread_props(_object_spread({}, details), {
996
+ reason: "accepted",
997
+ why: insecure ? "insecure_http_deprioritized" : "playable",
998
+ score: score
999
+ }));
811
1000
  });
812
- scoredFiles.sort(function(a, b) {
1001
+ accepted.sort(function(a, b) {
1002
+ if (a.insecure !== b.insecure) return a.insecure ? 1 : -1;
813
1003
  return a.score - b.score;
814
1004
  });
815
- var bestMatch = scoredFiles[0];
816
- if (!bestMatch) {
817
- console.log("[HlsAdPlayer] No best match found, using first media file");
818
- return firstFile;
819
- }
820
- console.log("[HlsAdPlayer] Selected media file:", {
821
- url: bestMatch.file.url,
822
- resolution: "".concat(bestMatch.file.width, "x").concat(bestMatch.file.height),
823
- bitrate: bestMatch.file.bitrate,
824
- score: bestMatch.score,
825
- resolutionDiff: bestMatch.resolutionDiff,
826
- bitrateDiff: bestMatch.bitrateDiff
1005
+ return accepted.map(function(entry) {
1006
+ return entry.file;
827
1007
  });
828
- return bestMatch.file;
829
1008
  }
830
1009
  function isHlsMediaFile(mediaFile) {
831
1010
  var type = mediaFile.type.toLowerCase();
@@ -842,59 +1021,181 @@ function createHlsAdPlayer(contentVideo, options) {
842
1021
  var url = (mediaFile.url.toLowerCase().split("?")[0] || "").trim();
843
1022
  return type.startsWith("audio/") || url.endsWith(".mp3") || url.endsWith(".aac") || url.endsWith(".m4a") || url.endsWith(".ogg") || url.endsWith(".oga") || url.endsWith(".opus") || url.endsWith(".wav") || url.endsWith(".weba");
844
1023
  }
845
- function collectVideoMediaFiles(linear, verbose) {
1024
+ function getMediaProbe() {
1025
+ if (adVideoElement) return adVideoElement;
1026
+ if (!mediaProbe && typeof document !== "undefined") {
1027
+ mediaProbe = document.createElement("video");
1028
+ }
1029
+ return mediaProbe;
1030
+ }
1031
+ function evaluateMediaFile(mf) {
1032
+ var _mf_textContent;
1033
+ var type = mf.getAttribute("type") || "";
1034
+ var url = ((_mf_textContent = mf.textContent) === null || _mf_textContent === void 0 ? void 0 : _mf_textContent.trim()) || "";
1035
+ var delivery = mf.getAttribute("delivery") || void 0;
1036
+ var codec = mf.getAttribute("codec") || void 0;
1037
+ if (!url) {
1038
+ return {
1039
+ category: "missing_media",
1040
+ whyRejected: "empty_url",
1041
+ canPlayType: ""
1042
+ };
1043
+ }
1044
+ var apiFramework = (mf.getAttribute("apiFramework") || "").toUpperCase();
1045
+ if (apiFramework === "VPAID") {
1046
+ return {
1047
+ category: "vpaid",
1048
+ whyRejected: "vpaid_not_supported",
1049
+ canPlayType: ""
1050
+ };
1051
+ }
1052
+ try {
1053
+ var protocol = new URL(url).protocol;
1054
+ if (protocol !== "https:" && protocol !== "http:") {
1055
+ return {
1056
+ category: "invalid_url",
1057
+ whyRejected: "protocol_".concat(protocol),
1058
+ canPlayType: ""
1059
+ };
1060
+ }
1061
+ } catch (unused) {
1062
+ return {
1063
+ category: "invalid_url",
1064
+ whyRejected: "unparseable_url",
1065
+ canPlayType: ""
1066
+ };
1067
+ }
1068
+ var bitrateAttr = mf.getAttribute("bitrate");
1069
+ var bitrateValue = bitrateAttr ? parseInt(bitrateAttr, 10) : void 0;
1070
+ var file = {
1071
+ url: url,
1072
+ type: type,
1073
+ width: parseInt(mf.getAttribute("width") || "1920", 10),
1074
+ height: parseInt(mf.getAttribute("height") || "1080", 10),
1075
+ bitrate: bitrateValue && bitrateValue > 0 ? bitrateValue : void 0,
1076
+ delivery: delivery,
1077
+ codec: codec
1078
+ };
1079
+ if (isAudioMediaFile(file)) {
1080
+ return {
1081
+ category: "audio_only",
1082
+ whyRejected: type.toLowerCase().startsWith("audio/") ? "audio_mime" : "audio_extension",
1083
+ canPlayType: ""
1084
+ };
1085
+ }
1086
+ var isHls = isHlsMediaFile(file);
1087
+ var hasExplicitDimensions = mf.getAttribute("width") != null && mf.getAttribute("height") != null;
1088
+ if (!isHls && hasExplicitDimensions && (file.width <= 1 || file.height <= 1)) {
1089
+ return {
1090
+ category: "audio_only",
1091
+ whyRejected: "zero_dimensions",
1092
+ canPlayType: ""
1093
+ };
1094
+ }
1095
+ var probe = getMediaProbe();
1096
+ if (isHls) {
1097
+ var _ref;
1098
+ var nativeHls = (_ref = probe === null || probe === void 0 ? void 0 : probe.canPlayType("application/vnd.apple.mpegurl")) !== null && _ref !== void 0 ? _ref : "";
1099
+ if (import_hls.default.isSupported()) {
1100
+ return {
1101
+ file: file,
1102
+ whyAccepted: "hls_js",
1103
+ canPlayType: nativeHls
1104
+ };
1105
+ }
1106
+ if (nativeHls !== "") {
1107
+ return {
1108
+ file: file,
1109
+ whyAccepted: "native_hls",
1110
+ canPlayType: nativeHls
1111
+ };
1112
+ }
1113
+ return {
1114
+ category: "unsupported_hls",
1115
+ whyRejected: "no_hls_support",
1116
+ canPlayType: nativeHls
1117
+ };
1118
+ }
1119
+ if (!isProgressiveMediaFile(file)) {
1120
+ return {
1121
+ category: "unsupported_mime",
1122
+ whyRejected: "not_a_video_mime",
1123
+ canPlayType: ""
1124
+ };
1125
+ }
1126
+ if (!probe) {
1127
+ return {
1128
+ file: file,
1129
+ whyAccepted: "no_probe_available",
1130
+ canPlayType: ""
1131
+ };
1132
+ }
1133
+ var baseType = type || "video/mp4";
1134
+ var canPlay = probe.canPlayType(baseType);
1135
+ if (canPlay === "") {
1136
+ return {
1137
+ category: "unsupported_mime",
1138
+ whyRejected: "canPlayType_empty",
1139
+ canPlayType: canPlay
1140
+ };
1141
+ }
1142
+ if (codec) {
1143
+ var withCodec = probe.canPlayType("".concat(baseType, '; codecs="').concat(codec, '"'));
1144
+ if (withCodec === "") {
1145
+ return {
1146
+ category: "unsupported_codec",
1147
+ whyRejected: "codec_canPlayType_empty",
1148
+ canPlayType: withCodec
1149
+ };
1150
+ }
1151
+ return {
1152
+ file: file,
1153
+ whyAccepted: "canPlayType_".concat(withCodec),
1154
+ canPlayType: withCodec
1155
+ };
1156
+ }
1157
+ return {
1158
+ file: file,
1159
+ whyAccepted: "canPlayType_".concat(canPlay),
1160
+ canPlayType: canPlay
1161
+ };
1162
+ }
1163
+ function collectVideoMediaFiles(linear, verbose, stats) {
846
1164
  var mediaFileElements = linear.querySelectorAll(":scope > MediaFiles > MediaFile");
847
1165
  var mediaFiles = [];
1166
+ if (stats) stats.total += mediaFileElements.length;
848
1167
  if (verbose) {
849
1168
  console.log("[HlsAdPlayer] Found ".concat(mediaFileElements.length, " MediaFile element(s) in VAST XML"));
850
1169
  }
851
1170
  mediaFileElements.forEach(function(mf, index) {
852
1171
  var _mf_textContent;
853
- var type = mf.getAttribute("type") || "";
1172
+ var result = evaluateMediaFile(mf);
854
1173
  var url = ((_mf_textContent = mf.textContent) === null || _mf_textContent === void 0 ? void 0 : _mf_textContent.trim()) || "";
855
- var width = mf.getAttribute("width") || "";
856
- var height = mf.getAttribute("height") || "";
857
- if (verbose) {
858
- console.log("[HlsAdPlayer] MediaFile ".concat(index, ': type="').concat(type, '", url="').concat(url, '", width="').concat(width, '", height="').concat(height, '"'));
859
- }
860
- if (!url) {
861
- if (verbose) {
862
- console.warn("[HlsAdPlayer] MediaFile ".concat(index, " has empty URL"));
863
- }
864
- return;
865
- }
866
- var apiFramework = (mf.getAttribute("apiFramework") || "").toUpperCase();
867
- if (apiFramework === "VPAID") {
868
- if (verbose) {
869
- console.log("[HlsAdPlayer] MediaFile ".concat(index, " ignored (VPAID creatives are not supported)"));
870
- }
871
- return;
872
- }
873
- var bitrateAttr = mf.getAttribute("bitrate");
874
- var bitrateValue = bitrateAttr ? parseInt(bitrateAttr, 10) : void 0;
875
- var mediaFile = {
876
- url: url,
877
- type: type,
878
- width: parseInt(width || "1920", 10),
879
- height: parseInt(height || "1080", 10),
880
- bitrate: bitrateValue && bitrateValue > 0 ? bitrateValue : void 0
881
- };
882
- if (isAudioMediaFile(mediaFile)) {
883
- console.warn("[HlsAdPlayer] MediaFile ".concat(index, ' skipped (audio-only, type="').concat(type, '") — audio ads are not played to avoid a black screen'));
1174
+ var accepted = "file" in result;
1175
+ logFunnel("mediafile_evaluated", {
1176
+ reason: accepted ? "accepted" : result.category,
1177
+ index: index,
1178
+ type: mf.getAttribute("type") || "",
1179
+ delivery: mf.getAttribute("delivery") || void 0,
1180
+ codec: mf.getAttribute("codec") || void 0,
1181
+ apiFramework: mf.getAttribute("apiFramework") || void 0,
1182
+ width: mf.getAttribute("width"),
1183
+ height: mf.getAttribute("height"),
1184
+ fileUrl: redactUrl(url),
1185
+ canPlayType: result.canPlayType,
1186
+ whyAccepted: accepted ? result.whyAccepted : void 0,
1187
+ whyRejected: accepted ? void 0 : result.whyRejected
1188
+ });
1189
+ if ("file" in result) {
1190
+ mediaFiles.push(result.file);
884
1191
  return;
885
1192
  }
886
- var hasExplicitDimensions = mf.getAttribute("width") != null && mf.getAttribute("height") != null;
887
- if (!isHlsMediaFile(mediaFile) && hasExplicitDimensions && (mediaFile.width <= 1 || mediaFile.height <= 1)) {
888
- console.warn("[HlsAdPlayer] MediaFile ".concat(index, " skipped (degenerate dimensions ").concat(mediaFile.width, "x").concat(mediaFile.height, ', type="').concat(type, '") — likely an audio-only placeholder rendition'));
889
- return;
1193
+ if (stats) {
1194
+ var _stats_categories_result_category;
1195
+ stats.categories[result.category] = ((_stats_categories_result_category = stats.categories[result.category]) !== null && _stats_categories_result_category !== void 0 ? _stats_categories_result_category : 0) + 1;
890
1196
  }
891
- if (isHlsMediaFile(mediaFile) || isProgressiveMediaFile(mediaFile)) {
892
- mediaFiles.push(mediaFile);
893
- if (verbose) {
894
- console.log("[HlsAdPlayer] Added ".concat(isHlsMediaFile(mediaFile) ? "HLS" : "progressive", " MediaFile: ").concat(url));
895
- }
896
- } else if (verbose) {
897
- console.log("[HlsAdPlayer] MediaFile ".concat(index, ' ignored (type="').concat(type, '" is not supported)'));
1197
+ if (result.category === "audio_only") {
1198
+ console.warn("[HlsAdPlayer] MediaFile ".concat(index, " skipped (audio-only: ").concat(result.whyRejected, ', type="').concat(mf.getAttribute("type") || "", '") — audio-only ads are not played on video inventory'));
898
1199
  }
899
1200
  });
900
1201
  return mediaFiles;
@@ -1018,26 +1319,58 @@ function createHlsAdPlayer(contentVideo, options) {
1018
1319
  }
1019
1320
  function parseVastXml(xmlString) {
1020
1321
  try {
1021
- var _adElements_find;
1022
1322
  var xmlDoc = parseXml(xmlString);
1023
1323
  if (!xmlDoc) return {
1024
1324
  type: "empty"
1025
1325
  };
1026
1326
  var root = xmlDoc.documentElement;
1027
1327
  var adElements = Array.from(root.querySelectorAll(":scope > Ad"));
1028
- var adElement = (_adElements_find = adElements.find(function(el) {
1029
- return getAdSequence(el) === void 0;
1030
- })) !== null && _adElements_find !== void 0 ? _adElements_find : adElements[0];
1031
- if (!adElement) {
1328
+ if (adElements.length === 0) {
1032
1329
  var _root_getAttribute;
1033
1330
  console.warn("[HlsAdPlayer] No Ad element found in VAST ".concat((_root_getAttribute = root.getAttribute("version")) !== null && _root_getAttribute !== void 0 ? _root_getAttribute : "", " response"));
1034
1331
  return emptyVastResult(root);
1035
1332
  }
1036
- var parsed = parseAdElement(adElement, true);
1037
- if (parsed.type === "wrapper") {
1038
- console.log("[HlsAdPlayer] VAST wrapper detected, following VASTAdTagURI: ".concat(parsed.vastAdTagUri));
1333
+ var ordered = _to_consumable_array(adElements.filter(function(el) {
1334
+ return getAdSequence(el) === void 0;
1335
+ })).concat(_to_consumable_array(adElements.filter(function(el) {
1336
+ return getAdSequence(el) !== void 0;
1337
+ })));
1338
+ var firstEmpty;
1339
+ var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
1340
+ try {
1341
+ for(var _iterator = ordered.entries()[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
1342
+ var _step_value = _sliced_to_array(_step.value, 2), index = _step_value[0], adElement = _step_value[1];
1343
+ var parsed = parseAdElement(adElement, true);
1344
+ if (parsed.type === "empty") {
1345
+ firstEmpty !== null && firstEmpty !== void 0 ? firstEmpty : firstEmpty = parsed;
1346
+ continue;
1347
+ }
1348
+ if (index > 0) {
1349
+ logFunnel("vast_ad_fallback", {
1350
+ usedAdIndex: index,
1351
+ adCount: ordered.length
1352
+ });
1353
+ }
1354
+ if (parsed.type === "wrapper") {
1355
+ console.log("[HlsAdPlayer] VAST wrapper detected, following VASTAdTagURI: ".concat(parsed.vastAdTagUri));
1356
+ }
1357
+ return parsed;
1358
+ }
1359
+ } catch (err) {
1360
+ _didIteratorError = true;
1361
+ _iteratorError = err;
1362
+ } finally{
1363
+ try {
1364
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
1365
+ _iterator.return();
1366
+ }
1367
+ } finally{
1368
+ if (_didIteratorError) {
1369
+ throw _iteratorError;
1370
+ }
1371
+ }
1039
1372
  }
1040
- return parsed;
1373
+ return firstEmpty !== null && firstEmpty !== void 0 ? firstEmpty : emptyVastResult(root);
1041
1374
  } catch (error) {
1042
1375
  console.error("[HlsAdPlayer] Error parsing VAST XML:", error);
1043
1376
  return {
@@ -1083,6 +1416,10 @@ function createHlsAdPlayer(contentVideo, options) {
1083
1416
  pushUrls(errorUrls, inLine.querySelectorAll(":scope > Error"));
1084
1417
  if (adElement.getAttribute("conditionalAd") === "true") {
1085
1418
  console.warn("[HlsAdPlayer] Skipping conditional <Ad> (VPAID-only)");
1419
+ logFunnel("vast_no_supported_media", {
1420
+ reason: "vpaid",
1421
+ conditionalAd: true
1422
+ });
1086
1423
  return {
1087
1424
  type: "empty",
1088
1425
  errorUrls: errorUrls,
@@ -1091,11 +1428,15 @@ function createHlsAdPlayer(contentVideo, options) {
1091
1428
  }
1092
1429
  var linear;
1093
1430
  var mediaFiles = [];
1431
+ var rejectStats = {
1432
+ total: 0,
1433
+ categories: {}
1434
+ };
1094
1435
  var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
1095
1436
  try {
1096
1437
  for(var _iterator = Array.from(inLine.querySelectorAll(":scope > Creatives > Creative > Linear"))[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
1097
1438
  var candidate = _step.value;
1098
- var files = collectVideoMediaFiles(candidate, verbose);
1439
+ var files = collectVideoMediaFiles(candidate, verbose, rejectStats);
1099
1440
  if (files.length > 0) {
1100
1441
  linear = candidate;
1101
1442
  mediaFiles = files;
@@ -1118,6 +1459,39 @@ function createHlsAdPlayer(contentVideo, options) {
1118
1459
  }
1119
1460
  if (!linear) {
1120
1461
  console.warn("[HlsAdPlayer] No supported linear media files in <Ad>");
1462
+ var reason = "missing_media";
1463
+ var top = 0;
1464
+ var _iteratorNormalCompletion1 = true, _didIteratorError1 = false, _iteratorError1 = undefined;
1465
+ try {
1466
+ for(var _iterator1 = Object.keys(rejectStats.categories)[Symbol.iterator](), _step1; !(_iteratorNormalCompletion1 = (_step1 = _iterator1.next()).done); _iteratorNormalCompletion1 = true){
1467
+ var category = _step1.value;
1468
+ var _rejectStats_categories_category;
1469
+ var count = (_rejectStats_categories_category = rejectStats.categories[category]) !== null && _rejectStats_categories_category !== void 0 ? _rejectStats_categories_category : 0;
1470
+ if (count > top) {
1471
+ top = count;
1472
+ reason = category;
1473
+ }
1474
+ }
1475
+ } catch (err) {
1476
+ _didIteratorError1 = true;
1477
+ _iteratorError1 = err;
1478
+ } finally{
1479
+ try {
1480
+ if (!_iteratorNormalCompletion1 && _iterator1.return != null) {
1481
+ _iterator1.return();
1482
+ }
1483
+ } finally{
1484
+ if (_didIteratorError1) {
1485
+ throw _iteratorError1;
1486
+ }
1487
+ }
1488
+ }
1489
+ if (rejectStats.total > 0 && top === 0) reason = "other";
1490
+ logFunnel("vast_no_supported_media", {
1491
+ reason: reason,
1492
+ mediaFileCount: rejectStats.total,
1493
+ rejectedByCategory: rejectStats.categories
1494
+ });
1121
1495
  return {
1122
1496
  type: "empty",
1123
1497
  errorUrls: errorUrls,
@@ -1147,27 +1521,65 @@ function createHlsAdPlayer(contentVideo, options) {
1147
1521
  }
1148
1522
  }
1149
1523
  function fetchVastXml(vastTagUrl) {
1150
- var credentials = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : "include";
1524
+ var credentials = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : "include", kind = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : "gam";
1151
1525
  return _async_to_generator(function() {
1152
- var controller, timeoutId, requestVast, response, error, error1;
1526
+ var controller, timeoutId, startedAt, attempt, requestVast, response, error, error1;
1153
1527
  return _ts_generator(this, function(_state) {
1154
1528
  switch(_state.label){
1155
1529
  case 0:
1530
+ if (destroyed) {
1531
+ throw new Error("VAST request skipped: ad player destroyed");
1532
+ }
1156
1533
  controller = typeof AbortController !== "undefined" ? new AbortController() : void 0;
1534
+ if (controller) pendingVastRequests.add(controller);
1157
1535
  timeoutId = controller ? setTimeout(function() {
1158
1536
  return controller.abort();
1159
1537
  }, VAST_REQUEST_TIMEOUT_MS) : void 0;
1538
+ startedAt = Date.now();
1539
+ attempt = 0;
1160
1540
  requestVast = function requestVast(creds) {
1161
- return fetch(vastTagUrl, _object_spread({
1162
- mode: "cors",
1163
- credentials: creds,
1164
- headers: {
1165
- "Accept": "application/xml, text/xml, */*"
1166
- },
1167
- referrerPolicy: "no-referrer-when-downgrade"
1168
- }, controller ? {
1169
- signal: controller.signal
1170
- } : {}));
1541
+ return _async_to_generator(function() {
1542
+ var response;
1543
+ return _ts_generator(this, function(_state) {
1544
+ switch(_state.label){
1545
+ case 0:
1546
+ attempt++;
1547
+ if (kind === "gam") {
1548
+ logFunnel("gam_http_request_sent", {
1549
+ attempt: attempt,
1550
+ credentials: creds
1551
+ });
1552
+ }
1553
+ return [
1554
+ 4,
1555
+ fetch(vastTagUrl, _object_spread({
1556
+ mode: "cors",
1557
+ credentials: creds,
1558
+ headers: {
1559
+ "Accept": "application/xml, text/xml, */*"
1560
+ },
1561
+ referrerPolicy: "no-referrer-when-downgrade"
1562
+ }, controller ? {
1563
+ signal: controller.signal
1564
+ } : {}))
1565
+ ];
1566
+ case 1:
1567
+ response = _state.sent();
1568
+ if (kind === "gam") {
1569
+ logFunnel("gam_response_received", {
1570
+ attempt: attempt,
1571
+ httpStatus: response.status,
1572
+ ok: response.ok,
1573
+ elapsedMs: Date.now() - startedAt
1574
+ });
1575
+ }
1576
+ return [
1577
+ 2,
1578
+ response
1579
+ ];
1580
+ }
1581
+ });
1582
+ })();
1171
1583
  };
1172
1584
  _state.label = 1;
1173
1585
  case 1:
@@ -1202,6 +1614,9 @@ function createHlsAdPlayer(contentVideo, options) {
1202
1614
  6
1203
1615
  ];
1204
1616
  console.warn('[HlsAdPlayer] VAST fetch failed with credentials="'.concat(credentials, '", retrying without credentials:'), error);
1617
+ logFunnel("vast_credentials_retry", {
1618
+ errorMessage: error === null || error === void 0 ? void 0 : error.message
1619
+ });
1205
1620
  return [
1206
1621
  4,
1207
1622
  requestVast("omit")
@@ -1221,7 +1636,7 @@ function createHlsAdPlayer(contentVideo, options) {
1221
1636
  ];
1222
1637
  case 8:
1223
1638
  if (!response.ok) {
1224
- throw new Error("Failed to fetch VAST: ".concat(response.statusText));
1639
+ throw new Error("Failed to fetch VAST: HTTP ".concat(response.status, " ").concat(response.statusText));
1225
1640
  }
1226
1641
  return [
1227
1642
  4,
@@ -1235,11 +1650,15 @@ function createHlsAdPlayer(contentVideo, options) {
1235
1650
  case 10:
1236
1651
  error1 = _state.sent();
1237
1652
  if (controller === null || controller === void 0 ? void 0 : controller.signal.aborted) {
1653
+ if (pendingRequestAbortReason) {
1654
+ throw new Error("".concat(pendingRequestAbortReason, ": ").concat(vastTagUrl));
1655
+ }
1238
1656
  throw new Error("VAST request timeout after ".concat(VAST_REQUEST_TIMEOUT_MS, "ms: ").concat(vastTagUrl));
1239
1657
  }
1240
1658
  throw error1;
1241
1659
  case 11:
1242
1660
  if (timeoutId !== void 0) clearTimeout(timeoutId);
1661
+ if (controller) pendingVastRequests.delete(controller);
1243
1662
  return [
1244
1663
  7
1245
1664
  ];
@@ -1253,7 +1672,7 @@ function createHlsAdPlayer(contentVideo, options) {
1253
1672
  }
1254
1673
  function fetchAndParseVastAd(_0) {
1255
1674
  return _async_to_generator(function(vastTagUrl) {
1256
- var depth, accumulatedTracking, rules, vastXml, error, parsed, _parsed_errorUrls, _parsed_errorCode;
1675
+ var depth, accumulatedTracking, rules, vastXml, fetchStartedAt, error, parsed, _parsed_errorUrls, _parsed_errorCode;
1257
1676
  var _arguments = arguments;
1258
1677
  return _ts_generator(this, function(_state) {
1259
1678
  switch(_state.label){
@@ -1261,6 +1680,11 @@ function createHlsAdPlayer(contentVideo, options) {
1261
1680
  depth = _arguments.length > 1 && _arguments[1] !== void 0 ? _arguments[1] : 0, accumulatedTracking = _arguments.length > 2 && _arguments[2] !== void 0 ? _arguments[2] : createEmptyTrackingUrls(), rules = _arguments.length > 3 && _arguments[3] !== void 0 ? _arguments[3] : {
1262
1681
  followAdditionalWrappers: true
1263
1682
  };
1683
+ if (destroyed) return [
1684
+ 2,
1685
+ null
1686
+ ];
1687
+ fetchStartedAt = Date.now();
1264
1688
  _state.label = 1;
1265
1689
  case 1:
1266
1690
  _state.trys.push([
@@ -1271,7 +1695,7 @@ function createHlsAdPlayer(contentVideo, options) {
1271
1695
  ]);
1272
1696
  return [
1273
1697
  4,
1274
- fetchVastXml(vastTagUrl, depth === 0 ? "include" : "omit")
1698
+ fetchVastXml(vastTagUrl, depth === 0 ? "include" : "omit", depth === 0 ? "gam" : "wrapper")
1275
1699
  ];
1276
1700
  case 2:
1277
1701
  vastXml = _state.sent();
@@ -1283,14 +1707,35 @@ function createHlsAdPlayer(contentVideo, options) {
1283
1707
  error = _state.sent();
1284
1708
  if (depth === 0) throw error;
1285
1709
  console.warn("[HlsAdPlayer] Wrapped VAST request failed:", error);
1286
- fireTrackingPixels(accumulatedTracking.error, {
1287
- errorCode: VAST_ERROR_WRAPPER_TIMEOUT
1710
+ logFunnel("wrapper_fetch", {
1711
+ reason: "failure",
1712
+ depth: depth,
1713
+ wrapperUrl: redactUrl(vastTagUrl),
1714
+ elapsedMs: Date.now() - fetchStartedAt,
1715
+ errorMessage: error === null || error === void 0 ? void 0 : error.message
1288
1716
  });
1717
+ if (!destroyed) {
1718
+ fireTrackingPixels(accumulatedTracking.error, {
1719
+ errorCode: VAST_ERROR_WRAPPER_TIMEOUT
1720
+ });
1721
+ }
1289
1722
  return [
1290
1723
  2,
1291
1724
  null
1292
1725
  ];
1293
1726
  case 4:
1727
+ if (destroyed) return [
1728
+ 2,
1729
+ null
1730
+ ];
1731
+ if (depth > 0) {
1732
+ logFunnel("wrapper_fetch", {
1733
+ reason: "success",
1734
+ depth: depth,
1735
+ wrapperUrl: redactUrl(vastTagUrl),
1736
+ elapsedMs: Date.now() - fetchStartedAt
1737
+ });
1738
+ }
1294
1739
  console.log("[HlsAdPlayer] VAST XML received");
1295
1740
  console.log("[HlsAdPlayer] VAST XML content (first 2000 chars):", vastXml.substring(0, 2e3));
1296
1741
  parsed = parseVastXml(vastXml);
@@ -1322,6 +1767,9 @@ function createHlsAdPlayer(contentVideo, options) {
1322
1767
  ];
1323
1768
  }
1324
1769
  mergeTrackingUrls(parsed.ad.trackingUrls, accumulatedTracking);
1770
+ logFunnel("inline_resolved", {
1771
+ depth: depth
1772
+ });
1325
1773
  return [
1326
1774
  2,
1327
1775
  parsed.ad
@@ -1332,20 +1780,29 @@ function createHlsAdPlayer(contentVideo, options) {
1332
1780
  }
1333
1781
  function fetchAndParsePod(vastTagUrl) {
1334
1782
  return _async_to_generator(function() {
1335
- var _root_getAttribute, vastXml, trimmedXml, xmlDoc, root, adElements, _root_getAttribute1, _empty_errorUrls, empty, _empty_errorCode, resolveAd, podElements, buffet, resolveAll, ads, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, ad, err, _iteratorNormalCompletion1, _didIteratorError1, _iteratorError1, _iterator1, _step1, ad1, err;
1783
+ var _root_getAttribute, _root_getAttribute1, vastXml, trimmedXml, xmlDoc, root, adElements, _root_getAttribute2, _empty_errorUrls, empty, _empty_errorCode, resolveAd, podElements, buffet, resolveAll, ads, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, ad, err, _iteratorNormalCompletion1, _didIteratorError1, _iteratorError1, _iterator1, _step1, ad1, err;
1336
1784
  return _ts_generator(this, function(_state) {
1337
1785
  switch(_state.label){
1338
1786
  case 0:
1787
+ lastPodAdElementCount = 0;
1339
1788
  return [
1340
1789
  4,
1341
1790
  fetchVastXml(vastTagUrl)
1342
1791
  ];
1343
1792
  case 1:
1344
1793
  vastXml = _state.sent();
1794
+ if (destroyed) return [
1795
+ 2,
1796
+ []
1797
+ ];
1345
1798
  console.log("[HlsAdPlayer] Pod VAST XML received (length=".concat(vastXml.length, ")"));
1346
1799
  trimmedXml = vastXml.trim();
1347
1800
  if (trimmedXml.length === 0) {
1348
1801
  console.warn("[HlsAdPlayer] Pod VAST response body is empty (no fill)");
1802
+ logFunnel("vast_parsed", {
1803
+ adElementCount: 0,
1804
+ reason: "empty_body"
1805
+ });
1349
1806
  return [
1350
1807
  2,
1351
1808
  []
@@ -1354,6 +1811,10 @@ function createHlsAdPlayer(contentVideo, options) {
1354
1811
  xmlDoc = parseXml(vastXml);
1355
1812
  if (!xmlDoc) {
1356
1813
  console.error("[HlsAdPlayer] Pod VAST XML content (first 2000 chars):", vastXml.substring(0, 2e3));
1814
+ logFunnel("vast_parsed", {
1815
+ adElementCount: 0,
1816
+ reason: "xml_parse_error"
1817
+ });
1357
1818
  return [
1358
1819
  2,
1359
1820
  []
@@ -1361,10 +1822,21 @@ function createHlsAdPlayer(contentVideo, options) {
1361
1822
  }
1362
1823
  root = xmlDoc.documentElement;
1363
1824
  adElements = Array.from(root.querySelectorAll(":scope > Ad"));
1825
+ logFunnel("vast_parsed", {
1826
+ reason: adElements.length > 0 ? "has_ads" : "no_ads",
1827
+ vastVersion: (_root_getAttribute = root.getAttribute("version")) !== null && _root_getAttribute !== void 0 ? _root_getAttribute : void 0,
1828
+ adElementCount: adElements.length,
1829
+ inlineCount: adElements.filter(function(el) {
1830
+ return el.querySelector(":scope > InLine");
1831
+ }).length,
1832
+ wrapperCount: adElements.filter(function(el) {
1833
+ return el.querySelector(":scope > Wrapper");
1834
+ }).length
1835
+ });
1364
1836
  if (adElements.length === 0) {
1365
1837
  ;
1366
1838
  ;
1367
- console.warn("[HlsAdPlayer] No <Ad> elements in VAST ".concat((_root_getAttribute1 = root.getAttribute("version")) !== null && _root_getAttribute1 !== void 0 ? _root_getAttribute1 : "", " pod response (no fill)"));
1839
+ console.warn("[HlsAdPlayer] No <Ad> elements in VAST ".concat((_root_getAttribute2 = root.getAttribute("version")) !== null && _root_getAttribute2 !== void 0 ? _root_getAttribute2 : "", " pod response (no fill)"));
1368
1840
  empty = emptyVastResult(root);
1369
1841
  if (empty.type === "empty" && ((_empty_errorUrls = empty.errorUrls) === null || _empty_errorUrls === void 0 ? void 0 : _empty_errorUrls.length)) {
1370
1842
  ;
@@ -1382,10 +1854,15 @@ function createHlsAdPlayer(contentVideo, options) {
1382
1854
  var _parsed_errorUrls, parsed, _parsed_errorCode;
1383
1855
  return _ts_generator(this, function(_state) {
1384
1856
  parsed = parseAdElement(adElement);
1385
- if (parsed.type === "inline") return [
1386
- 2,
1387
- parsed.ad
1388
- ];
1857
+ if (parsed.type === "inline") {
1858
+ logFunnel("inline_resolved", {
1859
+ depth: 0
1860
+ });
1861
+ return [
1862
+ 2,
1863
+ parsed.ad
1864
+ ];
1865
+ }
1389
1866
  if (parsed.type === "wrapper") {
1390
1867
  return [
1391
1868
  2,
@@ -1563,7 +2040,8 @@ function createHlsAdPlayer(contentVideo, options) {
1563
2040
  7
1564
2041
  ];
1565
2042
  case 21:
1566
- console.log("[HlsAdPlayer] Parsed ".concat(ads.length, " ad(s) from VAST ").concat((_root_getAttribute = root.getAttribute("version")) !== null && _root_getAttribute !== void 0 ? _root_getAttribute : "", " pod response"));
2043
+ console.log("[HlsAdPlayer] Parsed ".concat(ads.length, " ad(s) from VAST ").concat((_root_getAttribute1 = root.getAttribute("version")) !== null && _root_getAttribute1 !== void 0 ? _root_getAttribute1 : "", " pod response"));
2044
+ lastPodAdElementCount = adElements.length;
1567
2045
  return [
1568
2046
  2,
1569
2047
  ads
@@ -1629,14 +2107,17 @@ function createHlsAdPlayer(contentVideo, options) {
1629
2107
  var progress = currentTime / currentAd.duration;
1630
2108
  if (progress >= 0.25 && !trackingFired.firstQuartile) {
1631
2109
  trackingFired.firstQuartile = true;
2110
+ logFunnel("first_quartile");
1632
2111
  fireTrackingPixels(currentAd.trackingUrls.firstQuartile);
1633
2112
  }
1634
2113
  if (progress >= 0.5 && !trackingFired.midpoint) {
1635
2114
  trackingFired.midpoint = true;
2115
+ logFunnel("midpoint");
1636
2116
  fireTrackingPixels(currentAd.trackingUrls.midpoint);
1637
2117
  }
1638
2118
  if (progress >= 0.75 && !trackingFired.thirdQuartile) {
1639
2119
  trackingFired.thirdQuartile = true;
2120
+ logFunnel("third_quartile");
1640
2121
  fireTrackingPixels(currentAd.trackingUrls.thirdQuartile);
1641
2122
  }
1642
2123
  };
@@ -1659,6 +2140,16 @@ function createHlsAdPlayer(contentVideo, options) {
1659
2140
  if (!trackingFired.impression) {
1660
2141
  trackingFired.impression = true;
1661
2142
  resolvedAds.add(currentAd);
2143
+ logFunnel("playing", {
2144
+ mutedByAutoplay: forcedMuteByAutoplay,
2145
+ candidateIndex: mediaCandidateIndex
2146
+ });
2147
+ logFunnel("impression_fired", {
2148
+ pixelCount: currentAd.trackingUrls.impression.length
2149
+ });
2150
+ if (currentAd.trackingUrls.impression.length === 0) {
2151
+ console.warn("[HlsAdPlayer] Ad started but VAST contained no <Impression> URLs - GAM will not count it");
2152
+ }
1662
2153
  fireTrackingPixels(currentAd.trackingUrls.impression);
1663
2154
  fireTrackingPixels(currentAd.trackingUrls.creativeView);
1664
2155
  fireTrackingPixels(currentAd.trackingUrls.verificationNotExecuted, {
@@ -1681,6 +2172,7 @@ function createHlsAdPlayer(contentVideo, options) {
1681
2172
  sampleViewability();
1682
2173
  settleViewability();
1683
2174
  trackingFired.complete = true;
2175
+ logFunnel("complete");
1684
2176
  fireTrackingPixels(currentAd.trackingUrls.complete);
1685
2177
  console.log("[HlsAdPlayer] Ad completed");
1686
2178
  if (podIndex < podAds.length - 1 && advanceToNextPodAd()) {
@@ -1689,16 +2181,41 @@ function createHlsAdPlayer(contentVideo, options) {
1689
2181
  handleAdComplete();
1690
2182
  };
1691
2183
  var onError = function onError(e) {
2184
+ var _adVideoElement_error, _adVideoElement_error1;
1692
2185
  if (!adPlaying) return;
1693
2186
  console.error("[HlsAdPlayer] Ad video error:", e);
1694
- reportCurrentAdError(toVastMediaErrorCode(adVideoElement === null || adVideoElement === void 0 ? void 0 : adVideoElement.error));
1695
- if (podIndex < podAds.length - 1 && advanceToNextPodAd()) {
1696
- return;
1697
- }
1698
- handleAdError();
2187
+ var vastErrorCode = toVastMediaErrorCode(adVideoElement === null || adVideoElement === void 0 ? void 0 : adVideoElement.error);
2188
+ logFunnel("media_error", {
2189
+ mediaErrorCode: adVideoElement === null || adVideoElement === void 0 ? void 0 : (_adVideoElement_error = adVideoElement.error) === null || _adVideoElement_error === void 0 ? void 0 : _adVideoElement_error.code,
2190
+ errorMessage: adVideoElement === null || adVideoElement === void 0 ? void 0 : (_adVideoElement_error1 = adVideoElement.error) === null || _adVideoElement_error1 === void 0 ? void 0 : _adVideoElement_error1.message,
2191
+ networkState: adVideoElement === null || adVideoElement === void 0 ? void 0 : adVideoElement.networkState,
2192
+ readyState: adVideoElement === null || adVideoElement === void 0 ? void 0 : adVideoElement.readyState,
2193
+ currentSrc: adVideoElement === null || adVideoElement === void 0 ? void 0 : adVideoElement.currentSrc,
2194
+ vastErrorCode: vastErrorCode
2195
+ });
2196
+ recoverFromAdFailure(vastErrorCode);
2197
+ };
2198
+ var onMediaDiagnostic = function onMediaDiagnostic(event) {
2199
+ if (!adPlaying || !adVideoElement || trackingFired.impression) return;
2200
+ if (!adVideoElement.currentSrc) return;
2201
+ logFunnel("media_event", {
2202
+ reason: event.type,
2203
+ readyState: adVideoElement.readyState,
2204
+ networkState: adVideoElement.networkState,
2205
+ currentSrc: adVideoElement.currentSrc
2206
+ });
1699
2207
  };
1700
2208
  var onVolumeChange = function onVolumeChange() {
1701
2209
  if (!currentAd || !adVideoElement) return;
2210
+ if (forcedMuteByAutoplay && !adVideoElement.muted) {
2211
+ var userActivation = navigator.userActivation;
2212
+ if (userActivation && !userActivation.isActive) {
2213
+ logFunnel("unexpected_unmute", {
2214
+ paused: adVideoElement.paused
2215
+ });
2216
+ }
2217
+ forcedMuteByAutoplay = false;
2218
+ }
1702
2219
  var muted = adVideoElement.muted || adVideoElement.volume === 0;
1703
2220
  if (!trackingFired.start) {
1704
2221
  trackingFired.lastMuted = muted;
@@ -1758,6 +2275,22 @@ function createHlsAdPlayer(contentVideo, options) {
1758
2275
  {
1759
2276
  type: "play",
1760
2277
  handler: onPlay
2278
+ },
2279
+ {
2280
+ type: "stalled",
2281
+ handler: onMediaDiagnostic
2282
+ },
2283
+ {
2284
+ type: "suspend",
2285
+ handler: onMediaDiagnostic
2286
+ },
2287
+ {
2288
+ type: "abort",
2289
+ handler: onMediaDiagnostic
2290
+ },
2291
+ {
2292
+ type: "emptied",
2293
+ handler: onMediaDiagnostic
1761
2294
  }
1762
2295
  ];
1763
2296
  var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
@@ -2047,16 +2580,51 @@ function createHlsAdPlayer(contentVideo, options) {
2047
2580
  function settlePendingPlay() {
2048
2581
  pendingPlayPromise = void 0;
2049
2582
  }
2583
+ function toVastPlayErrorCode(error) {
2584
+ return (error === null || error === void 0 ? void 0 : error.name) === "NotSupportedError" ? VAST_ERROR_NO_SUPPORTED_MEDIA : VAST_ERROR_MEDIA_DISPLAY;
2585
+ }
2586
+ function failAdPlayback(context, error) {
2587
+ var vastErrorCode = toVastPlayErrorCode(error);
2588
+ console.error("[HlsAdPlayer] Error starting ".concat(context, ":"), error);
2589
+ logFunnel("play_failed", {
2590
+ errorName: error === null || error === void 0 ? void 0 : error.name,
2591
+ errorMessage: error === null || error === void 0 ? void 0 : error.message,
2592
+ vastErrorCode: vastErrorCode
2593
+ });
2594
+ recoverFromAdFailure(vastErrorCode);
2595
+ }
2050
2596
  function startAdPlayback(context) {
2597
+ var isMutedRetry = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : false;
2051
2598
  if (!adVideoElement) return;
2599
+ var computed = typeof getComputedStyle === "function" && adContainerEl ? getComputedStyle(adContainerEl) : void 0;
2600
+ logFunnel(isMutedRetry ? "muted_retry" : "play_called", {
2601
+ context: context,
2602
+ isConnected: adVideoElement.isConnected,
2603
+ clientWidth: adVideoElement.clientWidth,
2604
+ clientHeight: adVideoElement.clientHeight,
2605
+ containerDisplay: computed === null || computed === void 0 ? void 0 : computed.display,
2606
+ containerVisibility: computed === null || computed === void 0 ? void 0 : computed.visibility
2607
+ });
2052
2608
  var playPromise = adVideoElement.play();
2053
2609
  pendingPlayPromise = playPromise;
2054
2610
  playPromise.catch(function(error) {
2055
2611
  if (pendingPlayPromise !== playPromise) {
2056
2612
  return;
2057
2613
  }
2058
- console.error("[HlsAdPlayer] Error starting ".concat(context, ":"), error);
2059
- handleAdError();
2614
+ logFunnel("play_rejected", {
2615
+ context: context,
2616
+ errorName: error === null || error === void 0 ? void 0 : error.name,
2617
+ errorMessage: error === null || error === void 0 ? void 0 : error.message
2618
+ });
2619
+ if (!isMutedRetry && (error === null || error === void 0 ? void 0 : error.name) === "NotAllowedError" && adVideoElement && !adVideoElement.muted) {
2620
+ console.warn("[HlsAdPlayer] Unmuted ".concat(context, " blocked by autoplay policy - retrying muted"));
2621
+ originalMutedState = true;
2622
+ forcedMuteByAutoplay = true;
2623
+ adVideoElement.muted = true;
2624
+ startAdPlayback(context, true);
2625
+ return;
2626
+ }
2627
+ failAdPlayback(context, error);
2060
2628
  }).finally(function() {
2061
2629
  if (pendingPlayPromise === playPromise) {
2062
2630
  pendingPlayPromise = void 0;
@@ -2095,17 +2663,109 @@ function createHlsAdPlayer(contentVideo, options) {
2095
2663
  adVideoElement.volume = Math.max(0, Math.min(1, originalVolume));
2096
2664
  adVideoElement.muted = originalMutedState;
2097
2665
  }
2666
+ function clearMediaStartTimer() {
2667
+ if (mediaStartTimerId !== void 0) {
2668
+ clearTimeout(mediaStartTimerId);
2669
+ mediaStartTimerId = void 0;
2670
+ }
2671
+ }
2672
+ function startMediaStartTimer() {
2673
+ clearMediaStartTimer();
2674
+ if (!(MEDIA_START_TIMEOUT_MS > 0)) return;
2675
+ var startedAt = Date.now();
2676
+ mediaStartTimerId = setTimeout(function() {
2677
+ mediaStartTimerId = void 0;
2678
+ if (!adPlaying || trackingFired.impression) return;
2679
+ console.warn("[HlsAdPlayer] Ad media did not start playing within ".concat(MEDIA_START_TIMEOUT_MS, "ms"));
2680
+ logFunnel("play_resolved_but_never_started", {
2681
+ timeoutMs: MEDIA_START_TIMEOUT_MS,
2682
+ elapsedMs: Date.now() - startedAt,
2683
+ readyState: adVideoElement === null || adVideoElement === void 0 ? void 0 : adVideoElement.readyState,
2684
+ networkState: adVideoElement === null || adVideoElement === void 0 ? void 0 : adVideoElement.networkState,
2685
+ currentSrc: adVideoElement === null || adVideoElement === void 0 ? void 0 : adVideoElement.currentSrc,
2686
+ paused: adVideoElement === null || adVideoElement === void 0 ? void 0 : adVideoElement.paused,
2687
+ vastErrorCode: VAST_ERROR_MEDIA_TIMEOUT
2688
+ });
2689
+ recoverFromAdFailure(VAST_ERROR_MEDIA_TIMEOUT);
2690
+ }, MEDIA_START_TIMEOUT_MS);
2691
+ }
2692
+ function resetVideoElementForNextSource() {
2693
+ clearStallWatchdog();
2694
+ if (requiresMediaPipelineResetAfterAds()) {
2695
+ recreateAdVideoElement();
2696
+ setupAdEventListeners();
2697
+ } else {
2698
+ prepareVideoElementForNewSource();
2699
+ }
2700
+ }
2701
+ function tryNextMediaCandidate() {
2702
+ if (!currentAd || trackingFired.impression) return false;
2703
+ if (mediaCandidateIndex >= mediaCandidates.length - 1) return false;
2704
+ var failedUrl = currentAdMediaFile === null || currentAdMediaFile === void 0 ? void 0 : currentAdMediaFile.url;
2705
+ mediaCandidateIndex++;
2706
+ var next = mediaCandidates[mediaCandidateIndex];
2707
+ if (!next) return false;
2708
+ logFunnel("media_fallback", {
2709
+ failedUrl: failedUrl,
2710
+ nextUrl: next.url,
2711
+ nextType: next.type,
2712
+ candidateIndex: mediaCandidateIndex,
2713
+ candidateCount: mediaCandidates.length
2714
+ });
2715
+ resetVideoElementForNextSource();
2716
+ try {
2717
+ loadMediaCandidate(next);
2718
+ return true;
2719
+ } catch (error) {
2720
+ console.error("[HlsAdPlayer] Failed to load fallback media file:", error);
2721
+ return tryNextMediaCandidate();
2722
+ }
2723
+ }
2724
+ function recoverFromAdFailure(vastErrorCode) {
2725
+ clearMediaStartTimer();
2726
+ if (tryNextMediaCandidate()) return;
2727
+ reportCurrentAdError(vastErrorCode);
2728
+ if (podIndex < podAds.length - 1 && advanceToNextPodAd()) return;
2729
+ handleAdError();
2730
+ }
2098
2731
  function loadCurrentAdMedia() {
2099
2732
  if (!adVideoElement || !currentAd) {
2100
2733
  throw new Error("No ad video element or ad to load");
2101
2734
  }
2102
- var mediaFile = selectBestMediaFile(currentAd.mediaFiles);
2735
+ mediaCandidates = rankMediaCandidates(currentAd.mediaFiles);
2736
+ mediaCandidateIndex = 0;
2737
+ var mediaFile = mediaCandidates[0];
2103
2738
  if (!mediaFile) {
2104
- throw new Error("No media file available for ad");
2739
+ logFunnel("media_unsupported", {
2740
+ vastErrorCode: VAST_ERROR_NO_SUPPORTED_MEDIA,
2741
+ candidates: currentAd.mediaFiles.length
2742
+ });
2743
+ reportCurrentAdError(VAST_ERROR_NO_SUPPORTED_MEDIA);
2744
+ throw new Error("No media file this browser can play");
2745
+ }
2746
+ try {
2747
+ loadMediaCandidate(mediaFile);
2748
+ } catch (error) {
2749
+ if (tryNextMediaCandidate()) return;
2750
+ reportCurrentAdError(VAST_ERROR_NO_SUPPORTED_MEDIA);
2751
+ throw error;
2752
+ }
2753
+ }
2754
+ function loadMediaCandidate(mediaFile) {
2755
+ if (!adVideoElement || !currentAd) {
2756
+ throw new Error("No ad video element or ad to load");
2105
2757
  }
2106
2758
  currentAdMediaFile = mediaFile;
2107
2759
  var isHlsAd = isHlsMediaFile(mediaFile);
2760
+ logFunnel("media_selected", {
2761
+ width: mediaFile.width,
2762
+ height: mediaFile.height,
2763
+ bitrate: mediaFile.bitrate,
2764
+ candidateIndex: mediaCandidateIndex,
2765
+ candidates: mediaCandidates.length
2766
+ });
2108
2767
  console.log("[HlsAdPlayer] Loading ".concat(isHlsAd ? "HLS" : "progressive", " ad (pod ").concat(podIndex + 1, "/").concat(podAds.length || 1, ") from: ").concat(mediaFile.url));
2768
+ startMediaStartTimer();
2109
2769
  if (isHlsAd && import_hls.default.isSupported()) {
2110
2770
  if (adHls) {
2111
2771
  adHls.destroy();
@@ -2114,6 +2774,9 @@ function createHlsAdPlayer(contentVideo, options) {
2114
2774
  enableWorker: true,
2115
2775
  lowLatencyMode: false
2116
2776
  });
2777
+ logFunnel("media_load", {
2778
+ pipeline: "hls.js"
2779
+ });
2117
2780
  adHls.loadSource(mediaFile.url);
2118
2781
  adHls.attachMedia(adVideoElement);
2119
2782
  adHls.on(import_hls.default.Events.MANIFEST_PARSED, function() {
@@ -2123,10 +2786,24 @@ function createHlsAdPlayer(contentVideo, options) {
2123
2786
  adHls.on(import_hls.default.Events.ERROR, function(_event, data) {
2124
2787
  console.error("[HlsAdPlayer] HLS error:", data);
2125
2788
  if (data.fatal) {
2126
- handleAdError();
2789
+ var _data_response, _data_response1, _data_frag;
2790
+ var vastErrorCode = data.type === import_hls.default.ErrorTypes.NETWORK_ERROR ? 401 : VAST_ERROR_MEDIA_DISPLAY;
2791
+ logFunnel("hls_fatal", {
2792
+ reason: data.details,
2793
+ errorName: data.type,
2794
+ errorMessage: data.details,
2795
+ responseCode: (_data_response = data.response) === null || _data_response === void 0 ? void 0 : _data_response.code,
2796
+ responseText: (_data_response1 = data.response) === null || _data_response1 === void 0 ? void 0 : _data_response1.text,
2797
+ fragUrl: (_data_frag = data.frag) === null || _data_frag === void 0 ? void 0 : _data_frag.url,
2798
+ vastErrorCode: vastErrorCode
2799
+ });
2800
+ recoverFromAdFailure(vastErrorCode);
2127
2801
  }
2128
2802
  });
2129
2803
  } else if (isHlsAd && adVideoElement.canPlayType("application/vnd.apple.mpegurl")) {
2804
+ logFunnel("media_load", {
2805
+ pipeline: "native-hls"
2806
+ });
2130
2807
  adVideoElement.src = mediaFile.url;
2131
2808
  startAdPlayback("native HLS ad playback");
2132
2809
  } else if (!isHlsAd && isProgressiveMediaFile(mediaFile)) {
@@ -2134,45 +2811,47 @@ function createHlsAdPlayer(contentVideo, options) {
2134
2811
  adHls.destroy();
2135
2812
  adHls = void 0;
2136
2813
  }
2814
+ logFunnel("media_load", {
2815
+ pipeline: "progressive"
2816
+ });
2137
2817
  adVideoElement.src = mediaFile.url;
2138
2818
  adVideoElement.load();
2139
2819
  startAdPlayback("progressive ad playback");
2140
2820
  } else {
2821
+ clearMediaStartTimer();
2822
+ logFunnel("media_unsupported", {
2823
+ vastErrorCode: VAST_ERROR_NO_SUPPORTED_MEDIA
2824
+ });
2141
2825
  throw new Error("Unsupported ad media file type: ".concat(mediaFile.type));
2142
2826
  }
2143
2827
  }
2144
2828
  function advanceToNextPodAd() {
2145
- if (podIndex >= podAds.length - 1) {
2146
- return false;
2147
- }
2148
- settleViewability();
2149
- podIndex++;
2150
- currentAd = podAds[podIndex];
2151
- currentAdMediaFile = void 0;
2152
- resetAdTracking();
2153
- if (currentAd) {
2154
- console.log("[HlsAdPlayer] Advancing to next pod ad (".concat(podIndex + 1, "/").concat(podAds.length, "): ").concat(currentAd.title, ", duration: ").concat(currentAd.duration, "s"));
2155
- }
2156
- clearStallWatchdog();
2157
- if (requiresMediaPipelineResetAfterAds()) {
2158
- recreateAdVideoElement();
2159
- setupAdEventListeners();
2160
- } else {
2161
- prepareVideoElementForNewSource();
2162
- }
2163
- try {
2164
- loadCurrentAdMedia();
2165
- emit("pod_ad_started", {
2166
- index: podIndex,
2167
- total: podAds.length
2168
- });
2169
- return true;
2170
- } catch (error) {
2171
- console.error("[HlsAdPlayer] Failed to load next pod ad:", error);
2172
- return false;
2829
+ clearMediaStartTimer();
2830
+ while(podIndex < podAds.length - 1){
2831
+ settleViewability();
2832
+ podIndex++;
2833
+ currentAd = podAds[podIndex];
2834
+ currentAdMediaFile = void 0;
2835
+ resetAdTracking();
2836
+ if (currentAd) {
2837
+ console.log("[HlsAdPlayer] Advancing to next pod ad (".concat(podIndex + 1, "/").concat(podAds.length, "): ").concat(currentAd.title, ", duration: ").concat(currentAd.duration, "s"));
2838
+ }
2839
+ resetVideoElementForNextSource();
2840
+ try {
2841
+ loadCurrentAdMedia();
2842
+ emit("pod_ad_started", {
2843
+ index: podIndex,
2844
+ total: podAds.length
2845
+ });
2846
+ return true;
2847
+ } catch (error) {
2848
+ console.error("[HlsAdPlayer] Failed to load next pod ad:", error);
2849
+ }
2173
2850
  }
2851
+ return false;
2174
2852
  }
2175
2853
  function clearStallWatchdog() {
2854
+ clearMediaStartTimer();
2176
2855
  if (stallWatchdogId != null) {
2177
2856
  clearInterval(stallWatchdogId);
2178
2857
  stallWatchdogId = void 0;
@@ -2188,11 +2867,10 @@ function createHlsAdPlayer(contentVideo, options) {
2188
2867
  function handleAdStall() {
2189
2868
  console.warn("[HlsAdPlayer] Ad playback stalled (no progress) - recovering to avoid a blank frame");
2190
2869
  clearStallWatchdog();
2191
- reportCurrentAdError(VAST_ERROR_MEDIA_DISPLAY);
2192
- if (podIndex < podAds.length - 1 && advanceToNextPodAd()) {
2193
- return;
2194
- }
2195
- handleAdError();
2870
+ logFunnel("stall", {
2871
+ vastErrorCode: VAST_ERROR_MEDIA_DISPLAY
2872
+ });
2873
+ recoverFromAdFailure(VAST_ERROR_MEDIA_DISPLAY);
2196
2874
  }
2197
2875
  function getDecodedVideoFrameCount(video) {
2198
2876
  try {
@@ -2254,11 +2932,10 @@ function createHlsAdPlayer(contentVideo, options) {
2254
2932
  function handleVideoDecodeFailure() {
2255
2933
  console.warn("[HlsAdPlayer] Ad audio is advancing but no video frames decoded (black screen) - skipping this creative");
2256
2934
  clearStallWatchdog();
2257
- reportCurrentAdError(VAST_ERROR_MEDIA_DISPLAY);
2258
- if (podIndex < podAds.length - 1 && advanceToNextPodAd()) {
2259
- return;
2260
- }
2261
- handleAdError();
2935
+ logFunnel("decode_failure", {
2936
+ vastErrorCode: VAST_ERROR_MEDIA_DISPLAY
2937
+ });
2938
+ recoverFromAdFailure(VAST_ERROR_MEDIA_DISPLAY);
2262
2939
  }
2263
2940
  function startStallWatchdog() {
2264
2941
  clearStallWatchdog();
@@ -2382,6 +3059,15 @@ function createHlsAdPlayer(contentVideo, options) {
2382
3059
  Promise.reject(new Error("Ad already playing"))
2383
3060
  ];
2384
3061
  }
3062
+ if (destroyed) {
3063
+ return [
3064
+ 2,
3065
+ Promise.reject(new Error("Ad player destroyed"))
3066
+ ];
3067
+ }
3068
+ currentVastTagUrl = vastTagUrl;
3069
+ pendingRequestAbortReason = void 0;
3070
+ logFunnel("request_sent");
2385
3071
  _state.label = 1;
2386
3072
  case 1:
2387
3073
  _state.trys.push([
@@ -2416,8 +3102,29 @@ function createHlsAdPlayer(contentVideo, options) {
2416
3102
  ads = _state.sent();
2417
3103
  _state.label = 4;
2418
3104
  case 4:
3105
+ if (destroyed) {
3106
+ return [
3107
+ 2,
3108
+ Promise.reject(new Error("Ad player destroyed"))
3109
+ ];
3110
+ }
3111
+ if (!ads.length && pendingRequestAbortReason) {
3112
+ throw new Error(pendingRequestAbortReason);
3113
+ }
3114
+ if (!ads.length && lastPodAdElementCount > 0) {
3115
+ console.warn("[HlsAdPlayer] VAST response had ads but none were playable");
3116
+ logFunnel("vast_fill_rejected", {
3117
+ adElementCount: lastPodAdElementCount
3118
+ });
3119
+ emit("ad_error");
3120
+ return [
3121
+ 2,
3122
+ Promise.reject(new Error("VAST fill rejected: no playable ad in response"))
3123
+ ];
3124
+ }
2419
3125
  if (!ads.length) {
2420
3126
  console.warn("[HlsAdPlayer] No ads available from VAST response");
3127
+ logFunnel("no_fill");
2421
3128
  emit("ad_error");
2422
3129
  return [
2423
3130
  2,
@@ -2428,6 +3135,23 @@ function createHlsAdPlayer(contentVideo, options) {
2428
3135
  podIndex = 0;
2429
3136
  currentAd = ads[0];
2430
3137
  currentAdMediaFile = void 0;
3138
+ logFunnel("vast_received", {
3139
+ adCount: ads.length,
3140
+ durations: ads.map(function(ad) {
3141
+ return ad.duration;
3142
+ }),
3143
+ impressionUrls: ads.map(function(ad) {
3144
+ return ad.trackingUrls.impression.length;
3145
+ })
3146
+ });
3147
+ ads.forEach(function(ad, index) {
3148
+ if (ad.trackingUrls.impression.length === 0) {
3149
+ logFunnel("vast_missing_impression", {
3150
+ adIndex: index,
3151
+ missingAdId: ad.id
3152
+ });
3153
+ }
3154
+ });
2431
3155
  console.log("[HlsAdPlayer] Pod parsed: ".concat(ads.length, ' ad(s), first="').concat(currentAd === null || currentAd === void 0 ? void 0 : currentAd.title, '", duration=').concat(currentAd === null || currentAd === void 0 ? void 0 : currentAd.duration, "s"));
2432
3156
  return [
2433
3157
  2,
@@ -2436,6 +3160,9 @@ function createHlsAdPlayer(contentVideo, options) {
2436
3160
  case 5:
2437
3161
  error = _state.sent();
2438
3162
  console.error("[HlsAdPlayer] Error requesting ads:", error);
3163
+ logFunnel("request_failed", {
3164
+ errorMessage: error === null || error === void 0 ? void 0 : error.message
3165
+ });
2439
3166
  emit("ad_error");
2440
3167
  return [
2441
3168
  2,
@@ -2491,13 +3218,22 @@ function createHlsAdPlayer(contentVideo, options) {
2491
3218
  adContainerEl.style.pointerEvents = "auto";
2492
3219
  }
2493
3220
  emit("content_pause");
2494
- loadCurrentAdMedia();
3221
+ try {
3222
+ loadCurrentAdMedia();
3223
+ } catch (loadError) {
3224
+ if (!(podIndex < podAds.length - 1 && advanceToNextPodAd())) {
3225
+ throw loadError;
3226
+ }
3227
+ }
2495
3228
  return [
2496
3229
  2,
2497
3230
  Promise.resolve()
2498
3231
  ];
2499
3232
  } catch (error) {
2500
3233
  console.error("[HlsAdPlayer] Error playing ad:", error);
3234
+ logFunnel("play_failed", {
3235
+ errorMessage: error === null || error === void 0 ? void 0 : error.message
3236
+ });
2501
3237
  handleAdError();
2502
3238
  return [
2503
3239
  2,
@@ -2539,6 +3275,9 @@ function createHlsAdPlayer(contentVideo, options) {
2539
3275
  var previousMutedState;
2540
3276
  return _ts_generator(this, function(_state) {
2541
3277
  console.log("[HlsAdPlayer] Stopping ad");
3278
+ if (adPlaying && currentAd && !trackingFired.impression) {
3279
+ logFunnel("stopped_before_start");
3280
+ }
2542
3281
  settleViewability();
2543
3282
  fireNotUsedForUnplayedAds();
2544
3283
  clearStallWatchdog();
@@ -2571,15 +3310,18 @@ function createHlsAdPlayer(contentVideo, options) {
2571
3310
  },
2572
3311
  destroy: function destroy() {
2573
3312
  console.log("[HlsAdPlayer] Destroying");
3313
+ if (adPlaying && currentAd && !trackingFired.impression) {
3314
+ logFunnel("stopped_before_start");
3315
+ }
2574
3316
  settleViewability();
2575
3317
  fireNotUsedForUnplayedAds();
2576
3318
  destroyed = true;
2577
- clearStallWatchdog();
3319
+ pendingRequestAbortReason = "Ad player destroyed";
2578
3320
  var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
2579
3321
  try {
2580
- for(var _iterator = pendingTimeouts[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
2581
- var timeoutId = _step.value;
2582
- clearTimeout(timeoutId);
3322
+ for(var _iterator = Array.from(pendingVastRequests)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
3323
+ var controller = _step.value;
3324
+ controller.abort();
2583
3325
  }
2584
3326
  } catch (err) {
2585
3327
  _didIteratorError = true;
@@ -2595,6 +3337,28 @@ function createHlsAdPlayer(contentVideo, options) {
2595
3337
  }
2596
3338
  }
2597
3339
  }
3340
+ pendingVastRequests.clear();
3341
+ clearStallWatchdog();
3342
+ var _iteratorNormalCompletion1 = true, _didIteratorError1 = false, _iteratorError1 = undefined;
3343
+ try {
3344
+ for(var _iterator1 = pendingTimeouts[Symbol.iterator](), _step1; !(_iteratorNormalCompletion1 = (_step1 = _iterator1.next()).done); _iteratorNormalCompletion1 = true){
3345
+ var timeoutId = _step1.value;
3346
+ clearTimeout(timeoutId);
3347
+ }
3348
+ } catch (err) {
3349
+ _didIteratorError1 = true;
3350
+ _iteratorError1 = err;
3351
+ } finally{
3352
+ try {
3353
+ if (!_iteratorNormalCompletion1 && _iterator1.return != null) {
3354
+ _iterator1.return();
3355
+ }
3356
+ } finally{
3357
+ if (_didIteratorError1) {
3358
+ throw _iteratorError1;
3359
+ }
3360
+ }
3361
+ }
2598
3362
  pendingTimeouts = [];
2599
3363
  adPlaying = false;
2600
3364
  setAdPlayingFlag(false);
@@ -2614,6 +3378,35 @@ function createHlsAdPlayer(contentVideo, options) {
2614
3378
  isAdPlaying: function isAdPlaying() {
2615
3379
  return adPlaying;
2616
3380
  },
3381
+ setFunnelContext: function setFunnelContext(context) {
3382
+ funnelContext = _object_spread({}, context);
3383
+ },
3384
+ abortPendingRequest: function abortPendingRequest() {
3385
+ var reason = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : "VAST request aborted (timeout)";
3386
+ if (pendingVastRequests.size === 0) return;
3387
+ pendingRequestAbortReason = reason;
3388
+ var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
3389
+ try {
3390
+ for(var _iterator = Array.from(pendingVastRequests)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
3391
+ var controller = _step.value;
3392
+ controller.abort();
3393
+ }
3394
+ } catch (err) {
3395
+ _didIteratorError = true;
3396
+ _iteratorError = err;
3397
+ } finally{
3398
+ try {
3399
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
3400
+ _iterator.return();
3401
+ }
3402
+ } finally{
3403
+ if (_didIteratorError) {
3404
+ throw _iteratorError;
3405
+ }
3406
+ }
3407
+ }
3408
+ pendingVastRequests.clear();
3409
+ },
2617
3410
  resize: function resize(width, height) {
2618
3411
  console.log("[HlsAdPlayer] Resizing to ".concat(width, "x").concat(height));
2619
3412
  if (adContainerEl) {
@@ -2649,6 +3442,13 @@ function createHlsAdPlayer(contentVideo, options) {
2649
3442
  if (adVideoElement && adPlaying) {
2650
3443
  var clamped = Math.max(0, Math.min(1, volume));
2651
3444
  adVideoElement.volume = clamped;
3445
+ var userActivation = navigator.userActivation;
3446
+ if (clamped > 0 && forcedMuteByAutoplay && userActivation && !userActivation.isActive) {
3447
+ logFunnel("unmute_blocked_without_gesture", {
3448
+ requestedVolume: clamped
3449
+ });
3450
+ return;
3451
+ }
2652
3452
  adVideoElement.muted = clamped === 0;
2653
3453
  }
2654
3454
  },