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.
@@ -143,6 +143,42 @@ function _object_spread_props(target, source) {
143
143
  }
144
144
  return target;
145
145
  }
146
+ function _object_without_properties(source, excluded) {
147
+ if (source == null) return {};
148
+ var target = {}, sourceKeys, key, i;
149
+ if (typeof Reflect !== "undefined" && Reflect.ownKeys) {
150
+ sourceKeys = Reflect.ownKeys(Object(source));
151
+ for(i = 0; i < sourceKeys.length; i++){
152
+ key = sourceKeys[i];
153
+ if (excluded.indexOf(key) >= 0) continue;
154
+ if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
155
+ target[key] = source[key];
156
+ }
157
+ return target;
158
+ }
159
+ target = _object_without_properties_loose(source, excluded);
160
+ if (Object.getOwnPropertySymbols) {
161
+ sourceKeys = Object.getOwnPropertySymbols(source);
162
+ for(i = 0; i < sourceKeys.length; i++){
163
+ key = sourceKeys[i];
164
+ if (excluded.indexOf(key) >= 0) continue;
165
+ if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
166
+ target[key] = source[key];
167
+ }
168
+ }
169
+ return target;
170
+ }
171
+ function _object_without_properties_loose(source, excluded) {
172
+ if (source == null) return {};
173
+ var target = {}, sourceKeys = Object.getOwnPropertyNames(source), key, i;
174
+ for(i = 0; i < sourceKeys.length; i++){
175
+ key = sourceKeys[i];
176
+ if (excluded.indexOf(key) >= 0) continue;
177
+ if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
178
+ target[key] = source[key];
179
+ }
180
+ return target;
181
+ }
146
182
  function _sliced_to_array(arr, i) {
147
183
  return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
148
184
  }
@@ -248,26 +284,6 @@ function _ts_generator(thisArg, body) {
248
284
  };
249
285
  }
250
286
  }
251
- function _ts_values(o) {
252
- var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
253
- if (m) {
254
- return m.call(o);
255
- }
256
- if (o && typeof o.length === "number") {
257
- return {
258
- next: function() {
259
- if (o && i >= o.length) {
260
- o = void 0;
261
- }
262
- return {
263
- value: o && o[i++],
264
- done: !o
265
- };
266
- }
267
- };
268
- }
269
- throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
270
- }
271
287
  function _type_of(obj) {
272
288
  "@swc/helpers - typeof";
273
289
  return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
@@ -724,7 +740,7 @@ function toVastMediaErrorCode(error) {
724
740
  }
725
741
  }
726
742
  function createHlsAdPlayer(contentVideo, options) {
727
- var _contentVideo_AD_VIDEO_PROP, _contentVideo_AD_CONTAINER_PROP;
743
+ var _contentVideo_AD_VIDEO_PROP, _contentVideo_AD_CONTAINER_PROP, _ref;
728
744
  var adPlaying = false;
729
745
  var originalMutedState = false;
730
746
  var originalVolume = Math.max(0, Math.min(1, contentVideo.volume || 1));
@@ -756,6 +772,18 @@ function createHlsAdPlayer(contentVideo, options) {
756
772
  var sawDecodedVideoFrame = false;
757
773
  var videoFrameCallbackHandle;
758
774
  var pendingPlayPromise;
775
+ var currentVastTagUrl;
776
+ var funnelContext = {};
777
+ var mediaProbe;
778
+ var lastPodAdElementCount = 0;
779
+ var mediaCandidates = [];
780
+ var mediaCandidateIndex = 0;
781
+ var mediaStartTimerId;
782
+ var MEDIA_START_TIMEOUT_MS = (_ref = options === null || options === void 0 ? void 0 : options.mediaStartTimeoutMs) !== null && _ref !== void 0 ? _ref : 8e3;
783
+ var VAST_ERROR_MEDIA_TIMEOUT = 402;
784
+ var pendingVastRequests = /* @__PURE__ */ new Set();
785
+ var pendingRequestAbortReason;
786
+ var forcedMuteByAutoplay = false;
759
787
  function createTrackingState() {
760
788
  return {
761
789
  impression: false,
@@ -806,6 +834,78 @@ function createHlsAdPlayer(contentVideo, options) {
806
834
  }
807
835
  }
808
836
  }
837
+ var SENSITIVE_URL_PARAMS = /* @__PURE__ */ new Set([
838
+ "ppid",
839
+ "rdid",
840
+ "idtype",
841
+ "is_lat",
842
+ "ifa",
843
+ "idfa",
844
+ "aaid",
845
+ "uid",
846
+ "user_id",
847
+ "userid",
848
+ "device_id",
849
+ "deviceid",
850
+ "ip",
851
+ "ua",
852
+ "gdpr_consent",
853
+ "us_privacy",
854
+ "gpp",
855
+ "addtl_consent",
856
+ "cust_params",
857
+ "email"
858
+ ]);
859
+ function redactUrl(url) {
860
+ if (!url) return url;
861
+ try {
862
+ var parsed = new URL(url);
863
+ var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
864
+ try {
865
+ for(var _iterator = Array.from(parsed.searchParams.keys())[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
866
+ var key = _step.value;
867
+ if (SENSITIVE_URL_PARAMS.has(key.toLowerCase())) {
868
+ parsed.searchParams.set(key, "REDACTED");
869
+ }
870
+ }
871
+ } catch (err) {
872
+ _didIteratorError = true;
873
+ _iteratorError = err;
874
+ } finally{
875
+ try {
876
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
877
+ _iterator.return();
878
+ }
879
+ } finally{
880
+ if (_didIteratorError) {
881
+ throw _iteratorError;
882
+ }
883
+ }
884
+ }
885
+ return parsed.toString();
886
+ } catch (unused) {
887
+ return url.split("?")[0];
888
+ }
889
+ }
890
+ function logFunnel(stage) {
891
+ var extra = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
892
+ var payload = _object_spread({
893
+ stage: stage,
894
+ breakId: funnelContext.breakId,
895
+ requestId: funnelContext.requestId,
896
+ controllerId: funnelContext.controllerId,
897
+ visibilityState: typeof document !== "undefined" ? document.visibilityState : void 0,
898
+ adId: currentAd === null || currentAd === void 0 ? void 0 : currentAd.id,
899
+ podIndex: podIndex,
900
+ podSize: podAds.length,
901
+ vastUrl: redactUrl(currentVastTagUrl),
902
+ mediaUrl: currentAdMediaFile === null || currentAdMediaFile === void 0 ? void 0 : currentAdMediaFile.url,
903
+ mediaType: currentAdMediaFile === null || currentAdMediaFile === void 0 ? void 0 : currentAdMediaFile.type,
904
+ muted: adVideoElement ? adVideoElement.muted : void 0
905
+ }, extra);
906
+ console.log("[HlsAdPlayer][FUNNEL] ".concat(stage), payload);
907
+ emit("ad_funnel", payload);
908
+ }
809
909
  function buildTrackingMacroContext() {
810
910
  var options2 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
811
911
  var _options2_ad;
@@ -845,20 +945,53 @@ function createHlsAdPlayer(contentVideo, options) {
845
945
  urls.forEach(function(url) {
846
946
  try {
847
947
  var trackingUrl = substituteVastTrackingMacros(url, macroContext);
948
+ var trackingHost;
949
+ try {
950
+ trackingHost = new URL(trackingUrl).host;
951
+ } catch (unused) {
952
+ logFunnel("tracking_url_invalid", {
953
+ trackingUrl: redactUrl(trackingUrl)
954
+ });
955
+ return;
956
+ }
957
+ var unexpanded = trackingUrl.match(/\[[A-Z_]+\]/g);
958
+ if (unexpanded) {
959
+ logFunnel("tracking_url_unexpanded_macro", {
960
+ trackingHost: trackingHost,
961
+ macros: Array.from(new Set(unexpanded))
962
+ });
963
+ }
848
964
  var img = new Image(1, 1);
849
965
  inFlightBeacons.add(img);
850
966
  var timeoutId;
851
- var release = function release() {
967
+ var release = function release(outcome) {
852
968
  if (timeoutId !== void 0) clearTimeout(timeoutId);
853
969
  img.onload = null;
854
970
  img.onerror = null;
855
971
  inFlightBeacons.delete(img);
972
+ console.log("[HlsAdPlayer] Tracking pixel settled (".concat(outcome, "): ").concat(trackingUrl));
973
+ if (outcome !== "load") {
974
+ logFunnel("tracking_request_settled", {
975
+ reason: outcome,
976
+ trackingHost: trackingHost
977
+ });
978
+ }
979
+ };
980
+ img.onload = function() {
981
+ return release("load");
982
+ };
983
+ img.onerror = function() {
984
+ return release("error");
856
985
  };
857
- img.onload = release;
858
- img.onerror = release;
859
- timeoutId = setTimeout(release, BEACON_TIMEOUT_MS);
986
+ timeoutId = setTimeout(function() {
987
+ return release("timeout");
988
+ }, BEACON_TIMEOUT_MS);
860
989
  img.src = trackingUrl;
861
990
  console.log("[HlsAdPlayer] Fired tracking pixel: ".concat(trackingUrl));
991
+ logFunnel("tracking_request_created", {
992
+ trackingHost: trackingHost,
993
+ errorCode: options2 === null || options2 === void 0 ? void 0 : options2.errorCode
994
+ });
862
995
  } catch (error) {
863
996
  console.warn("[HlsAdPlayer] Error firing tracking pixel:", error);
864
997
  }
@@ -888,54 +1021,79 @@ function createHlsAdPlayer(contentVideo, options) {
888
1021
  bitrate: level.bitrate || 5e6
889
1022
  };
890
1023
  }
891
- function selectBestMediaFile(mediaFiles) {
892
- if (mediaFiles.length === 0) {
893
- throw new Error("No media files available");
894
- }
895
- var firstFile = mediaFiles[0];
896
- if (!firstFile) {
897
- throw new Error("No media files available");
898
- }
899
- if (mediaFiles.length === 1) {
900
- return firstFile;
901
- }
1024
+ function getMediaTargetQuality() {
902
1025
  var mainQuality = getMainStreamQuality();
903
- if (!mainQuality) {
904
- console.log("[HlsAdPlayer] No main stream quality info, using first media file");
905
- return firstFile;
906
- }
907
- console.log("[HlsAdPlayer] Main stream quality:", mainQuality);
908
- var scoredFiles = mediaFiles.map(function(file) {
909
- var widthDiff = Math.abs(file.width - mainQuality.width);
910
- var heightDiff = Math.abs(file.height - mainQuality.height);
911
- var resolutionDiff = widthDiff + heightDiff;
912
- var fileBitrate = (file.bitrate || 5e3) * 1e3;
913
- var bitrateDiff = Math.abs(fileBitrate - mainQuality.bitrate);
914
- var score = resolutionDiff * 2 + bitrateDiff / 1e3;
915
- return {
1026
+ var dpr = typeof window !== "undefined" && window.devicePixelRatio > 0 ? window.devicePixelRatio : 1;
1027
+ var containerWidth = ((adContainerEl === null || adContainerEl === void 0 ? void 0 : adContainerEl.clientWidth) || contentVideo.clientWidth) * dpr;
1028
+ var containerHeight = ((adContainerEl === null || adContainerEl === void 0 ? void 0 : adContainerEl.clientHeight) || contentVideo.clientHeight) * dpr;
1029
+ if (!mainQuality && !(containerWidth > 0 && containerHeight > 0)) {
1030
+ return null;
1031
+ }
1032
+ var base = mainQuality !== null && mainQuality !== void 0 ? mainQuality : {
1033
+ width: containerWidth,
1034
+ height: containerHeight,
1035
+ bitrate: 5e6
1036
+ };
1037
+ var width = containerWidth > 0 ? Math.min(base.width, containerWidth) : base.width;
1038
+ var height = containerHeight > 0 ? Math.min(base.height, containerHeight) : base.height;
1039
+ return {
1040
+ width: width,
1041
+ height: height,
1042
+ bitrate: base.bitrate
1043
+ };
1044
+ }
1045
+ function rankMediaCandidates(mediaFiles) {
1046
+ var probe = adVideoElement !== null && adVideoElement !== void 0 ? adVideoElement : document.createElement("video");
1047
+ var pageIsHttps = typeof location !== "undefined" && location.protocol === "https:";
1048
+ var target = getMediaTargetQuality();
1049
+ var accepted = [];
1050
+ mediaFiles.forEach(function(file, index) {
1051
+ var isHls = isHlsMediaFile(file);
1052
+ var mimeForProbe = isHls ? "application/vnd.apple.mpegurl" : file.type || "video/mp4";
1053
+ var canPlay = probe.canPlayType(mimeForProbe);
1054
+ var playable = isHls ? import_hls.default.isSupported() || canPlay !== "" : canPlay !== "";
1055
+ var insecure = pageIsHttps && /^http:/i.test(file.url);
1056
+ var details = {
1057
+ index: index,
1058
+ candidateUrl: file.url,
1059
+ candidateType: file.type,
1060
+ width: file.width,
1061
+ height: file.height,
1062
+ bitrate: file.bitrate,
1063
+ canPlayType: canPlay,
1064
+ hlsJs: isHls ? import_hls.default.isSupported() : void 0
1065
+ };
1066
+ if (!playable) {
1067
+ logFunnel("media_candidate", _object_spread_props(_object_spread({}, details), {
1068
+ reason: "rejected",
1069
+ why: "cannot_play_type"
1070
+ }));
1071
+ return;
1072
+ }
1073
+ var score = 0;
1074
+ if (target) {
1075
+ var resolutionDiff = Math.abs(file.width - target.width) + Math.abs(file.height - target.height);
1076
+ var bitrateDiff = Math.abs((file.bitrate || 5e3) * 1e3 - target.bitrate);
1077
+ score = resolutionDiff * 2 + bitrateDiff / 1e3;
1078
+ }
1079
+ accepted.push({
916
1080
  file: file,
917
1081
  score: score,
918
- resolutionDiff: resolutionDiff,
919
- bitrateDiff: bitrateDiff
920
- };
1082
+ insecure: insecure
1083
+ });
1084
+ logFunnel("media_candidate", _object_spread_props(_object_spread({}, details), {
1085
+ reason: "accepted",
1086
+ why: insecure ? "insecure_http_deprioritized" : "playable",
1087
+ score: score
1088
+ }));
921
1089
  });
922
- scoredFiles.sort(function(a, b) {
1090
+ accepted.sort(function(a, b) {
1091
+ if (a.insecure !== b.insecure) return a.insecure ? 1 : -1;
923
1092
  return a.score - b.score;
924
1093
  });
925
- var bestMatch = scoredFiles[0];
926
- if (!bestMatch) {
927
- console.log("[HlsAdPlayer] No best match found, using first media file");
928
- return firstFile;
929
- }
930
- console.log("[HlsAdPlayer] Selected media file:", {
931
- url: bestMatch.file.url,
932
- resolution: "".concat(bestMatch.file.width, "x").concat(bestMatch.file.height),
933
- bitrate: bestMatch.file.bitrate,
934
- score: bestMatch.score,
935
- resolutionDiff: bestMatch.resolutionDiff,
936
- bitrateDiff: bestMatch.bitrateDiff
1094
+ return accepted.map(function(entry) {
1095
+ return entry.file;
937
1096
  });
938
- return bestMatch.file;
939
1097
  }
940
1098
  function isHlsMediaFile(mediaFile) {
941
1099
  var type = mediaFile.type.toLowerCase();
@@ -952,59 +1110,181 @@ function createHlsAdPlayer(contentVideo, options) {
952
1110
  var url = (mediaFile.url.toLowerCase().split("?")[0] || "").trim();
953
1111
  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");
954
1112
  }
955
- function collectVideoMediaFiles(linear, verbose) {
1113
+ function getMediaProbe() {
1114
+ if (adVideoElement) return adVideoElement;
1115
+ if (!mediaProbe && typeof document !== "undefined") {
1116
+ mediaProbe = document.createElement("video");
1117
+ }
1118
+ return mediaProbe;
1119
+ }
1120
+ function evaluateMediaFile(mf) {
1121
+ var _mf_textContent;
1122
+ var type = mf.getAttribute("type") || "";
1123
+ var url = ((_mf_textContent = mf.textContent) === null || _mf_textContent === void 0 ? void 0 : _mf_textContent.trim()) || "";
1124
+ var delivery = mf.getAttribute("delivery") || void 0;
1125
+ var codec = mf.getAttribute("codec") || void 0;
1126
+ if (!url) {
1127
+ return {
1128
+ category: "missing_media",
1129
+ whyRejected: "empty_url",
1130
+ canPlayType: ""
1131
+ };
1132
+ }
1133
+ var apiFramework = (mf.getAttribute("apiFramework") || "").toUpperCase();
1134
+ if (apiFramework === "VPAID") {
1135
+ return {
1136
+ category: "vpaid",
1137
+ whyRejected: "vpaid_not_supported",
1138
+ canPlayType: ""
1139
+ };
1140
+ }
1141
+ try {
1142
+ var protocol = new URL(url).protocol;
1143
+ if (protocol !== "https:" && protocol !== "http:") {
1144
+ return {
1145
+ category: "invalid_url",
1146
+ whyRejected: "protocol_".concat(protocol),
1147
+ canPlayType: ""
1148
+ };
1149
+ }
1150
+ } catch (unused) {
1151
+ return {
1152
+ category: "invalid_url",
1153
+ whyRejected: "unparseable_url",
1154
+ canPlayType: ""
1155
+ };
1156
+ }
1157
+ var bitrateAttr = mf.getAttribute("bitrate");
1158
+ var bitrateValue = bitrateAttr ? parseInt(bitrateAttr, 10) : void 0;
1159
+ var file = {
1160
+ url: url,
1161
+ type: type,
1162
+ width: parseInt(mf.getAttribute("width") || "1920", 10),
1163
+ height: parseInt(mf.getAttribute("height") || "1080", 10),
1164
+ bitrate: bitrateValue && bitrateValue > 0 ? bitrateValue : void 0,
1165
+ delivery: delivery,
1166
+ codec: codec
1167
+ };
1168
+ if (isAudioMediaFile(file)) {
1169
+ return {
1170
+ category: "audio_only",
1171
+ whyRejected: type.toLowerCase().startsWith("audio/") ? "audio_mime" : "audio_extension",
1172
+ canPlayType: ""
1173
+ };
1174
+ }
1175
+ var isHls = isHlsMediaFile(file);
1176
+ var hasExplicitDimensions = mf.getAttribute("width") != null && mf.getAttribute("height") != null;
1177
+ if (!isHls && hasExplicitDimensions && (file.width <= 1 || file.height <= 1)) {
1178
+ return {
1179
+ category: "audio_only",
1180
+ whyRejected: "zero_dimensions",
1181
+ canPlayType: ""
1182
+ };
1183
+ }
1184
+ var probe = getMediaProbe();
1185
+ if (isHls) {
1186
+ var _ref;
1187
+ var nativeHls = (_ref = probe === null || probe === void 0 ? void 0 : probe.canPlayType("application/vnd.apple.mpegurl")) !== null && _ref !== void 0 ? _ref : "";
1188
+ if (import_hls.default.isSupported()) {
1189
+ return {
1190
+ file: file,
1191
+ whyAccepted: "hls_js",
1192
+ canPlayType: nativeHls
1193
+ };
1194
+ }
1195
+ if (nativeHls !== "") {
1196
+ return {
1197
+ file: file,
1198
+ whyAccepted: "native_hls",
1199
+ canPlayType: nativeHls
1200
+ };
1201
+ }
1202
+ return {
1203
+ category: "unsupported_hls",
1204
+ whyRejected: "no_hls_support",
1205
+ canPlayType: nativeHls
1206
+ };
1207
+ }
1208
+ if (!isProgressiveMediaFile(file)) {
1209
+ return {
1210
+ category: "unsupported_mime",
1211
+ whyRejected: "not_a_video_mime",
1212
+ canPlayType: ""
1213
+ };
1214
+ }
1215
+ if (!probe) {
1216
+ return {
1217
+ file: file,
1218
+ whyAccepted: "no_probe_available",
1219
+ canPlayType: ""
1220
+ };
1221
+ }
1222
+ var baseType = type || "video/mp4";
1223
+ var canPlay = probe.canPlayType(baseType);
1224
+ if (canPlay === "") {
1225
+ return {
1226
+ category: "unsupported_mime",
1227
+ whyRejected: "canPlayType_empty",
1228
+ canPlayType: canPlay
1229
+ };
1230
+ }
1231
+ if (codec) {
1232
+ var withCodec = probe.canPlayType("".concat(baseType, '; codecs="').concat(codec, '"'));
1233
+ if (withCodec === "") {
1234
+ return {
1235
+ category: "unsupported_codec",
1236
+ whyRejected: "codec_canPlayType_empty",
1237
+ canPlayType: withCodec
1238
+ };
1239
+ }
1240
+ return {
1241
+ file: file,
1242
+ whyAccepted: "canPlayType_".concat(withCodec),
1243
+ canPlayType: withCodec
1244
+ };
1245
+ }
1246
+ return {
1247
+ file: file,
1248
+ whyAccepted: "canPlayType_".concat(canPlay),
1249
+ canPlayType: canPlay
1250
+ };
1251
+ }
1252
+ function collectVideoMediaFiles(linear, verbose, stats) {
956
1253
  var mediaFileElements = linear.querySelectorAll(":scope > MediaFiles > MediaFile");
957
1254
  var mediaFiles = [];
1255
+ if (stats) stats.total += mediaFileElements.length;
958
1256
  if (verbose) {
959
1257
  console.log("[HlsAdPlayer] Found ".concat(mediaFileElements.length, " MediaFile element(s) in VAST XML"));
960
1258
  }
961
1259
  mediaFileElements.forEach(function(mf, index) {
962
1260
  var _mf_textContent;
963
- var type = mf.getAttribute("type") || "";
1261
+ var result = evaluateMediaFile(mf);
964
1262
  var url = ((_mf_textContent = mf.textContent) === null || _mf_textContent === void 0 ? void 0 : _mf_textContent.trim()) || "";
965
- var width = mf.getAttribute("width") || "";
966
- var height = mf.getAttribute("height") || "";
967
- if (verbose) {
968
- console.log("[HlsAdPlayer] MediaFile ".concat(index, ': type="').concat(type, '", url="').concat(url, '", width="').concat(width, '", height="').concat(height, '"'));
969
- }
970
- if (!url) {
971
- if (verbose) {
972
- console.warn("[HlsAdPlayer] MediaFile ".concat(index, " has empty URL"));
973
- }
974
- return;
975
- }
976
- var apiFramework = (mf.getAttribute("apiFramework") || "").toUpperCase();
977
- if (apiFramework === "VPAID") {
978
- if (verbose) {
979
- console.log("[HlsAdPlayer] MediaFile ".concat(index, " ignored (VPAID creatives are not supported)"));
980
- }
981
- return;
982
- }
983
- var bitrateAttr = mf.getAttribute("bitrate");
984
- var bitrateValue = bitrateAttr ? parseInt(bitrateAttr, 10) : void 0;
985
- var mediaFile = {
986
- url: url,
987
- type: type,
988
- width: parseInt(width || "1920", 10),
989
- height: parseInt(height || "1080", 10),
990
- bitrate: bitrateValue && bitrateValue > 0 ? bitrateValue : void 0
991
- };
992
- if (isAudioMediaFile(mediaFile)) {
993
- console.warn("[HlsAdPlayer] MediaFile ".concat(index, ' skipped (audio-only, type="').concat(type, '") — audio ads are not played to avoid a black screen'));
1263
+ var accepted = "file" in result;
1264
+ logFunnel("mediafile_evaluated", {
1265
+ reason: accepted ? "accepted" : result.category,
1266
+ index: index,
1267
+ type: mf.getAttribute("type") || "",
1268
+ delivery: mf.getAttribute("delivery") || void 0,
1269
+ codec: mf.getAttribute("codec") || void 0,
1270
+ apiFramework: mf.getAttribute("apiFramework") || void 0,
1271
+ width: mf.getAttribute("width"),
1272
+ height: mf.getAttribute("height"),
1273
+ fileUrl: redactUrl(url),
1274
+ canPlayType: result.canPlayType,
1275
+ whyAccepted: accepted ? result.whyAccepted : void 0,
1276
+ whyRejected: accepted ? void 0 : result.whyRejected
1277
+ });
1278
+ if ("file" in result) {
1279
+ mediaFiles.push(result.file);
994
1280
  return;
995
1281
  }
996
- var hasExplicitDimensions = mf.getAttribute("width") != null && mf.getAttribute("height") != null;
997
- if (!isHlsMediaFile(mediaFile) && hasExplicitDimensions && (mediaFile.width <= 1 || mediaFile.height <= 1)) {
998
- 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'));
999
- return;
1282
+ if (stats) {
1283
+ var _stats_categories_result_category;
1284
+ 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;
1000
1285
  }
1001
- if (isHlsMediaFile(mediaFile) || isProgressiveMediaFile(mediaFile)) {
1002
- mediaFiles.push(mediaFile);
1003
- if (verbose) {
1004
- console.log("[HlsAdPlayer] Added ".concat(isHlsMediaFile(mediaFile) ? "HLS" : "progressive", " MediaFile: ").concat(url));
1005
- }
1006
- } else if (verbose) {
1007
- console.log("[HlsAdPlayer] MediaFile ".concat(index, ' ignored (type="').concat(type, '" is not supported)'));
1286
+ if (result.category === "audio_only") {
1287
+ 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'));
1008
1288
  }
1009
1289
  });
1010
1290
  return mediaFiles;
@@ -1128,26 +1408,58 @@ function createHlsAdPlayer(contentVideo, options) {
1128
1408
  }
1129
1409
  function parseVastXml(xmlString) {
1130
1410
  try {
1131
- var _adElements_find;
1132
1411
  var xmlDoc = parseXml(xmlString);
1133
1412
  if (!xmlDoc) return {
1134
1413
  type: "empty"
1135
1414
  };
1136
1415
  var root = xmlDoc.documentElement;
1137
1416
  var adElements = Array.from(root.querySelectorAll(":scope > Ad"));
1138
- var adElement = (_adElements_find = adElements.find(function(el) {
1139
- return getAdSequence(el) === void 0;
1140
- })) !== null && _adElements_find !== void 0 ? _adElements_find : adElements[0];
1141
- if (!adElement) {
1417
+ if (adElements.length === 0) {
1142
1418
  var _root_getAttribute;
1143
1419
  console.warn("[HlsAdPlayer] No Ad element found in VAST ".concat((_root_getAttribute = root.getAttribute("version")) !== null && _root_getAttribute !== void 0 ? _root_getAttribute : "", " response"));
1144
1420
  return emptyVastResult(root);
1145
1421
  }
1146
- var parsed = parseAdElement(adElement, true);
1147
- if (parsed.type === "wrapper") {
1148
- console.log("[HlsAdPlayer] VAST wrapper detected, following VASTAdTagURI: ".concat(parsed.vastAdTagUri));
1422
+ var ordered = _to_consumable_array(adElements.filter(function(el) {
1423
+ return getAdSequence(el) === void 0;
1424
+ })).concat(_to_consumable_array(adElements.filter(function(el) {
1425
+ return getAdSequence(el) !== void 0;
1426
+ })));
1427
+ var firstEmpty;
1428
+ var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
1429
+ try {
1430
+ for(var _iterator = ordered.entries()[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
1431
+ var _step_value = _sliced_to_array(_step.value, 2), index = _step_value[0], adElement = _step_value[1];
1432
+ var parsed = parseAdElement(adElement, true);
1433
+ if (parsed.type === "empty") {
1434
+ firstEmpty !== null && firstEmpty !== void 0 ? firstEmpty : firstEmpty = parsed;
1435
+ continue;
1436
+ }
1437
+ if (index > 0) {
1438
+ logFunnel("vast_ad_fallback", {
1439
+ usedAdIndex: index,
1440
+ adCount: ordered.length
1441
+ });
1442
+ }
1443
+ if (parsed.type === "wrapper") {
1444
+ console.log("[HlsAdPlayer] VAST wrapper detected, following VASTAdTagURI: ".concat(parsed.vastAdTagUri));
1445
+ }
1446
+ return parsed;
1447
+ }
1448
+ } catch (err) {
1449
+ _didIteratorError = true;
1450
+ _iteratorError = err;
1451
+ } finally{
1452
+ try {
1453
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
1454
+ _iterator.return();
1455
+ }
1456
+ } finally{
1457
+ if (_didIteratorError) {
1458
+ throw _iteratorError;
1459
+ }
1460
+ }
1149
1461
  }
1150
- return parsed;
1462
+ return firstEmpty !== null && firstEmpty !== void 0 ? firstEmpty : emptyVastResult(root);
1151
1463
  } catch (error) {
1152
1464
  console.error("[HlsAdPlayer] Error parsing VAST XML:", error);
1153
1465
  return {
@@ -1193,6 +1505,10 @@ function createHlsAdPlayer(contentVideo, options) {
1193
1505
  pushUrls(errorUrls, inLine.querySelectorAll(":scope > Error"));
1194
1506
  if (adElement.getAttribute("conditionalAd") === "true") {
1195
1507
  console.warn("[HlsAdPlayer] Skipping conditional <Ad> (VPAID-only)");
1508
+ logFunnel("vast_no_supported_media", {
1509
+ reason: "vpaid",
1510
+ conditionalAd: true
1511
+ });
1196
1512
  return {
1197
1513
  type: "empty",
1198
1514
  errorUrls: errorUrls,
@@ -1201,11 +1517,15 @@ function createHlsAdPlayer(contentVideo, options) {
1201
1517
  }
1202
1518
  var linear;
1203
1519
  var mediaFiles = [];
1520
+ var rejectStats = {
1521
+ total: 0,
1522
+ categories: {}
1523
+ };
1204
1524
  var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
1205
1525
  try {
1206
1526
  for(var _iterator = Array.from(inLine.querySelectorAll(":scope > Creatives > Creative > Linear"))[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
1207
1527
  var candidate = _step.value;
1208
- var files = collectVideoMediaFiles(candidate, verbose);
1528
+ var files = collectVideoMediaFiles(candidate, verbose, rejectStats);
1209
1529
  if (files.length > 0) {
1210
1530
  linear = candidate;
1211
1531
  mediaFiles = files;
@@ -1228,6 +1548,39 @@ function createHlsAdPlayer(contentVideo, options) {
1228
1548
  }
1229
1549
  if (!linear) {
1230
1550
  console.warn("[HlsAdPlayer] No supported linear media files in <Ad>");
1551
+ var reason = "missing_media";
1552
+ var top = 0;
1553
+ var _iteratorNormalCompletion1 = true, _didIteratorError1 = false, _iteratorError1 = undefined;
1554
+ try {
1555
+ for(var _iterator1 = Object.keys(rejectStats.categories)[Symbol.iterator](), _step1; !(_iteratorNormalCompletion1 = (_step1 = _iterator1.next()).done); _iteratorNormalCompletion1 = true){
1556
+ var category = _step1.value;
1557
+ var _rejectStats_categories_category;
1558
+ var count = (_rejectStats_categories_category = rejectStats.categories[category]) !== null && _rejectStats_categories_category !== void 0 ? _rejectStats_categories_category : 0;
1559
+ if (count > top) {
1560
+ top = count;
1561
+ reason = category;
1562
+ }
1563
+ }
1564
+ } catch (err) {
1565
+ _didIteratorError1 = true;
1566
+ _iteratorError1 = err;
1567
+ } finally{
1568
+ try {
1569
+ if (!_iteratorNormalCompletion1 && _iterator1.return != null) {
1570
+ _iterator1.return();
1571
+ }
1572
+ } finally{
1573
+ if (_didIteratorError1) {
1574
+ throw _iteratorError1;
1575
+ }
1576
+ }
1577
+ }
1578
+ if (rejectStats.total > 0 && top === 0) reason = "other";
1579
+ logFunnel("vast_no_supported_media", {
1580
+ reason: reason,
1581
+ mediaFileCount: rejectStats.total,
1582
+ rejectedByCategory: rejectStats.categories
1583
+ });
1231
1584
  return {
1232
1585
  type: "empty",
1233
1586
  errorUrls: errorUrls,
@@ -1257,27 +1610,65 @@ function createHlsAdPlayer(contentVideo, options) {
1257
1610
  }
1258
1611
  }
1259
1612
  function fetchVastXml(vastTagUrl) {
1260
- var credentials = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : "include";
1613
+ var credentials = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : "include", kind = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : "gam";
1261
1614
  return _async_to_generator(function() {
1262
- var controller, timeoutId, requestVast, response, error, error1;
1615
+ var controller, timeoutId, startedAt, attempt, requestVast, response, error, error1;
1263
1616
  return _ts_generator(this, function(_state) {
1264
1617
  switch(_state.label){
1265
1618
  case 0:
1619
+ if (destroyed) {
1620
+ throw new Error("VAST request skipped: ad player destroyed");
1621
+ }
1266
1622
  controller = typeof AbortController !== "undefined" ? new AbortController() : void 0;
1623
+ if (controller) pendingVastRequests.add(controller);
1267
1624
  timeoutId = controller ? setTimeout(function() {
1268
1625
  return controller.abort();
1269
1626
  }, VAST_REQUEST_TIMEOUT_MS) : void 0;
1627
+ startedAt = Date.now();
1628
+ attempt = 0;
1270
1629
  requestVast = function requestVast(creds) {
1271
- return fetch(vastTagUrl, _object_spread({
1272
- mode: "cors",
1273
- credentials: creds,
1274
- headers: {
1275
- "Accept": "application/xml, text/xml, */*"
1276
- },
1277
- referrerPolicy: "no-referrer-when-downgrade"
1278
- }, controller ? {
1279
- signal: controller.signal
1280
- } : {}));
1630
+ return _async_to_generator(function() {
1631
+ var response;
1632
+ return _ts_generator(this, function(_state) {
1633
+ switch(_state.label){
1634
+ case 0:
1635
+ attempt++;
1636
+ if (kind === "gam") {
1637
+ logFunnel("gam_http_request_sent", {
1638
+ attempt: attempt,
1639
+ credentials: creds
1640
+ });
1641
+ }
1642
+ return [
1643
+ 4,
1644
+ fetch(vastTagUrl, _object_spread({
1645
+ mode: "cors",
1646
+ credentials: creds,
1647
+ headers: {
1648
+ "Accept": "application/xml, text/xml, */*"
1649
+ },
1650
+ referrerPolicy: "no-referrer-when-downgrade"
1651
+ }, controller ? {
1652
+ signal: controller.signal
1653
+ } : {}))
1654
+ ];
1655
+ case 1:
1656
+ response = _state.sent();
1657
+ if (kind === "gam") {
1658
+ logFunnel("gam_response_received", {
1659
+ attempt: attempt,
1660
+ httpStatus: response.status,
1661
+ ok: response.ok,
1662
+ elapsedMs: Date.now() - startedAt
1663
+ });
1664
+ }
1665
+ return [
1666
+ 2,
1667
+ response
1668
+ ];
1669
+ }
1670
+ });
1671
+ })();
1281
1672
  };
1282
1673
  _state.label = 1;
1283
1674
  case 1:
@@ -1312,6 +1703,9 @@ function createHlsAdPlayer(contentVideo, options) {
1312
1703
  6
1313
1704
  ];
1314
1705
  console.warn('[HlsAdPlayer] VAST fetch failed with credentials="'.concat(credentials, '", retrying without credentials:'), error);
1706
+ logFunnel("vast_credentials_retry", {
1707
+ errorMessage: error === null || error === void 0 ? void 0 : error.message
1708
+ });
1315
1709
  return [
1316
1710
  4,
1317
1711
  requestVast("omit")
@@ -1331,7 +1725,7 @@ function createHlsAdPlayer(contentVideo, options) {
1331
1725
  ];
1332
1726
  case 8:
1333
1727
  if (!response.ok) {
1334
- throw new Error("Failed to fetch VAST: ".concat(response.statusText));
1728
+ throw new Error("Failed to fetch VAST: HTTP ".concat(response.status, " ").concat(response.statusText));
1335
1729
  }
1336
1730
  return [
1337
1731
  4,
@@ -1345,11 +1739,15 @@ function createHlsAdPlayer(contentVideo, options) {
1345
1739
  case 10:
1346
1740
  error1 = _state.sent();
1347
1741
  if (controller === null || controller === void 0 ? void 0 : controller.signal.aborted) {
1742
+ if (pendingRequestAbortReason) {
1743
+ throw new Error("".concat(pendingRequestAbortReason, ": ").concat(vastTagUrl));
1744
+ }
1348
1745
  throw new Error("VAST request timeout after ".concat(VAST_REQUEST_TIMEOUT_MS, "ms: ").concat(vastTagUrl));
1349
1746
  }
1350
1747
  throw error1;
1351
1748
  case 11:
1352
1749
  if (timeoutId !== void 0) clearTimeout(timeoutId);
1750
+ if (controller) pendingVastRequests.delete(controller);
1353
1751
  return [
1354
1752
  7
1355
1753
  ];
@@ -1363,7 +1761,7 @@ function createHlsAdPlayer(contentVideo, options) {
1363
1761
  }
1364
1762
  function fetchAndParseVastAd(_0) {
1365
1763
  return _async_to_generator(function(vastTagUrl) {
1366
- var depth, accumulatedTracking, rules, vastXml, error, parsed, _parsed_errorUrls, _parsed_errorCode;
1764
+ var depth, accumulatedTracking, rules, vastXml, fetchStartedAt, error, parsed, _parsed_errorUrls, _parsed_errorCode;
1367
1765
  var _arguments = arguments;
1368
1766
  return _ts_generator(this, function(_state) {
1369
1767
  switch(_state.label){
@@ -1371,6 +1769,11 @@ function createHlsAdPlayer(contentVideo, options) {
1371
1769
  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] : {
1372
1770
  followAdditionalWrappers: true
1373
1771
  };
1772
+ if (destroyed) return [
1773
+ 2,
1774
+ null
1775
+ ];
1776
+ fetchStartedAt = Date.now();
1374
1777
  _state.label = 1;
1375
1778
  case 1:
1376
1779
  _state.trys.push([
@@ -1381,7 +1784,7 @@ function createHlsAdPlayer(contentVideo, options) {
1381
1784
  ]);
1382
1785
  return [
1383
1786
  4,
1384
- fetchVastXml(vastTagUrl, depth === 0 ? "include" : "omit")
1787
+ fetchVastXml(vastTagUrl, depth === 0 ? "include" : "omit", depth === 0 ? "gam" : "wrapper")
1385
1788
  ];
1386
1789
  case 2:
1387
1790
  vastXml = _state.sent();
@@ -1393,14 +1796,35 @@ function createHlsAdPlayer(contentVideo, options) {
1393
1796
  error = _state.sent();
1394
1797
  if (depth === 0) throw error;
1395
1798
  console.warn("[HlsAdPlayer] Wrapped VAST request failed:", error);
1396
- fireTrackingPixels(accumulatedTracking.error, {
1397
- errorCode: VAST_ERROR_WRAPPER_TIMEOUT
1799
+ logFunnel("wrapper_fetch", {
1800
+ reason: "failure",
1801
+ depth: depth,
1802
+ wrapperUrl: redactUrl(vastTagUrl),
1803
+ elapsedMs: Date.now() - fetchStartedAt,
1804
+ errorMessage: error === null || error === void 0 ? void 0 : error.message
1398
1805
  });
1806
+ if (!destroyed) {
1807
+ fireTrackingPixels(accumulatedTracking.error, {
1808
+ errorCode: VAST_ERROR_WRAPPER_TIMEOUT
1809
+ });
1810
+ }
1399
1811
  return [
1400
1812
  2,
1401
1813
  null
1402
1814
  ];
1403
1815
  case 4:
1816
+ if (destroyed) return [
1817
+ 2,
1818
+ null
1819
+ ];
1820
+ if (depth > 0) {
1821
+ logFunnel("wrapper_fetch", {
1822
+ reason: "success",
1823
+ depth: depth,
1824
+ wrapperUrl: redactUrl(vastTagUrl),
1825
+ elapsedMs: Date.now() - fetchStartedAt
1826
+ });
1827
+ }
1404
1828
  console.log("[HlsAdPlayer] VAST XML received");
1405
1829
  console.log("[HlsAdPlayer] VAST XML content (first 2000 chars):", vastXml.substring(0, 2e3));
1406
1830
  parsed = parseVastXml(vastXml);
@@ -1432,6 +1856,9 @@ function createHlsAdPlayer(contentVideo, options) {
1432
1856
  ];
1433
1857
  }
1434
1858
  mergeTrackingUrls(parsed.ad.trackingUrls, accumulatedTracking);
1859
+ logFunnel("inline_resolved", {
1860
+ depth: depth
1861
+ });
1435
1862
  return [
1436
1863
  2,
1437
1864
  parsed.ad
@@ -1442,20 +1869,29 @@ function createHlsAdPlayer(contentVideo, options) {
1442
1869
  }
1443
1870
  function fetchAndParsePod(vastTagUrl) {
1444
1871
  return _async_to_generator(function() {
1445
- 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;
1872
+ 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;
1446
1873
  return _ts_generator(this, function(_state) {
1447
1874
  switch(_state.label){
1448
1875
  case 0:
1876
+ lastPodAdElementCount = 0;
1449
1877
  return [
1450
1878
  4,
1451
1879
  fetchVastXml(vastTagUrl)
1452
1880
  ];
1453
1881
  case 1:
1454
1882
  vastXml = _state.sent();
1883
+ if (destroyed) return [
1884
+ 2,
1885
+ []
1886
+ ];
1455
1887
  console.log("[HlsAdPlayer] Pod VAST XML received (length=".concat(vastXml.length, ")"));
1456
1888
  trimmedXml = vastXml.trim();
1457
1889
  if (trimmedXml.length === 0) {
1458
1890
  console.warn("[HlsAdPlayer] Pod VAST response body is empty (no fill)");
1891
+ logFunnel("vast_parsed", {
1892
+ adElementCount: 0,
1893
+ reason: "empty_body"
1894
+ });
1459
1895
  return [
1460
1896
  2,
1461
1897
  []
@@ -1464,6 +1900,10 @@ function createHlsAdPlayer(contentVideo, options) {
1464
1900
  xmlDoc = parseXml(vastXml);
1465
1901
  if (!xmlDoc) {
1466
1902
  console.error("[HlsAdPlayer] Pod VAST XML content (first 2000 chars):", vastXml.substring(0, 2e3));
1903
+ logFunnel("vast_parsed", {
1904
+ adElementCount: 0,
1905
+ reason: "xml_parse_error"
1906
+ });
1467
1907
  return [
1468
1908
  2,
1469
1909
  []
@@ -1471,10 +1911,21 @@ function createHlsAdPlayer(contentVideo, options) {
1471
1911
  }
1472
1912
  root = xmlDoc.documentElement;
1473
1913
  adElements = Array.from(root.querySelectorAll(":scope > Ad"));
1914
+ logFunnel("vast_parsed", {
1915
+ reason: adElements.length > 0 ? "has_ads" : "no_ads",
1916
+ vastVersion: (_root_getAttribute = root.getAttribute("version")) !== null && _root_getAttribute !== void 0 ? _root_getAttribute : void 0,
1917
+ adElementCount: adElements.length,
1918
+ inlineCount: adElements.filter(function(el) {
1919
+ return el.querySelector(":scope > InLine");
1920
+ }).length,
1921
+ wrapperCount: adElements.filter(function(el) {
1922
+ return el.querySelector(":scope > Wrapper");
1923
+ }).length
1924
+ });
1474
1925
  if (adElements.length === 0) {
1475
1926
  ;
1476
1927
  ;
1477
- 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)"));
1928
+ 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)"));
1478
1929
  empty = emptyVastResult(root);
1479
1930
  if (empty.type === "empty" && ((_empty_errorUrls = empty.errorUrls) === null || _empty_errorUrls === void 0 ? void 0 : _empty_errorUrls.length)) {
1480
1931
  ;
@@ -1492,10 +1943,15 @@ function createHlsAdPlayer(contentVideo, options) {
1492
1943
  var _parsed_errorUrls, parsed, _parsed_errorCode;
1493
1944
  return _ts_generator(this, function(_state) {
1494
1945
  parsed = parseAdElement(adElement);
1495
- if (parsed.type === "inline") return [
1496
- 2,
1497
- parsed.ad
1498
- ];
1946
+ if (parsed.type === "inline") {
1947
+ logFunnel("inline_resolved", {
1948
+ depth: 0
1949
+ });
1950
+ return [
1951
+ 2,
1952
+ parsed.ad
1953
+ ];
1954
+ }
1499
1955
  if (parsed.type === "wrapper") {
1500
1956
  return [
1501
1957
  2,
@@ -1673,7 +2129,8 @@ function createHlsAdPlayer(contentVideo, options) {
1673
2129
  7
1674
2130
  ];
1675
2131
  case 21:
1676
- 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"));
2132
+ 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"));
2133
+ lastPodAdElementCount = adElements.length;
1677
2134
  return [
1678
2135
  2,
1679
2136
  ads
@@ -1739,14 +2196,17 @@ function createHlsAdPlayer(contentVideo, options) {
1739
2196
  var progress = currentTime / currentAd.duration;
1740
2197
  if (progress >= 0.25 && !trackingFired.firstQuartile) {
1741
2198
  trackingFired.firstQuartile = true;
2199
+ logFunnel("first_quartile");
1742
2200
  fireTrackingPixels(currentAd.trackingUrls.firstQuartile);
1743
2201
  }
1744
2202
  if (progress >= 0.5 && !trackingFired.midpoint) {
1745
2203
  trackingFired.midpoint = true;
2204
+ logFunnel("midpoint");
1746
2205
  fireTrackingPixels(currentAd.trackingUrls.midpoint);
1747
2206
  }
1748
2207
  if (progress >= 0.75 && !trackingFired.thirdQuartile) {
1749
2208
  trackingFired.thirdQuartile = true;
2209
+ logFunnel("third_quartile");
1750
2210
  fireTrackingPixels(currentAd.trackingUrls.thirdQuartile);
1751
2211
  }
1752
2212
  };
@@ -1769,6 +2229,16 @@ function createHlsAdPlayer(contentVideo, options) {
1769
2229
  if (!trackingFired.impression) {
1770
2230
  trackingFired.impression = true;
1771
2231
  resolvedAds.add(currentAd);
2232
+ logFunnel("playing", {
2233
+ mutedByAutoplay: forcedMuteByAutoplay,
2234
+ candidateIndex: mediaCandidateIndex
2235
+ });
2236
+ logFunnel("impression_fired", {
2237
+ pixelCount: currentAd.trackingUrls.impression.length
2238
+ });
2239
+ if (currentAd.trackingUrls.impression.length === 0) {
2240
+ console.warn("[HlsAdPlayer] Ad started but VAST contained no <Impression> URLs - GAM will not count it");
2241
+ }
1772
2242
  fireTrackingPixels(currentAd.trackingUrls.impression);
1773
2243
  fireTrackingPixels(currentAd.trackingUrls.creativeView);
1774
2244
  fireTrackingPixels(currentAd.trackingUrls.verificationNotExecuted, {
@@ -1791,6 +2261,7 @@ function createHlsAdPlayer(contentVideo, options) {
1791
2261
  sampleViewability();
1792
2262
  settleViewability();
1793
2263
  trackingFired.complete = true;
2264
+ logFunnel("complete");
1794
2265
  fireTrackingPixels(currentAd.trackingUrls.complete);
1795
2266
  console.log("[HlsAdPlayer] Ad completed");
1796
2267
  if (podIndex < podAds.length - 1 && advanceToNextPodAd()) {
@@ -1799,16 +2270,41 @@ function createHlsAdPlayer(contentVideo, options) {
1799
2270
  handleAdComplete();
1800
2271
  };
1801
2272
  var onError = function onError(e) {
2273
+ var _adVideoElement_error, _adVideoElement_error1;
1802
2274
  if (!adPlaying) return;
1803
2275
  console.error("[HlsAdPlayer] Ad video error:", e);
1804
- reportCurrentAdError(toVastMediaErrorCode(adVideoElement === null || adVideoElement === void 0 ? void 0 : adVideoElement.error));
1805
- if (podIndex < podAds.length - 1 && advanceToNextPodAd()) {
1806
- return;
1807
- }
1808
- handleAdError();
2276
+ var vastErrorCode = toVastMediaErrorCode(adVideoElement === null || adVideoElement === void 0 ? void 0 : adVideoElement.error);
2277
+ logFunnel("media_error", {
2278
+ mediaErrorCode: adVideoElement === null || adVideoElement === void 0 ? void 0 : (_adVideoElement_error = adVideoElement.error) === null || _adVideoElement_error === void 0 ? void 0 : _adVideoElement_error.code,
2279
+ errorMessage: adVideoElement === null || adVideoElement === void 0 ? void 0 : (_adVideoElement_error1 = adVideoElement.error) === null || _adVideoElement_error1 === void 0 ? void 0 : _adVideoElement_error1.message,
2280
+ networkState: adVideoElement === null || adVideoElement === void 0 ? void 0 : adVideoElement.networkState,
2281
+ readyState: adVideoElement === null || adVideoElement === void 0 ? void 0 : adVideoElement.readyState,
2282
+ currentSrc: adVideoElement === null || adVideoElement === void 0 ? void 0 : adVideoElement.currentSrc,
2283
+ vastErrorCode: vastErrorCode
2284
+ });
2285
+ recoverFromAdFailure(vastErrorCode);
2286
+ };
2287
+ var onMediaDiagnostic = function onMediaDiagnostic(event) {
2288
+ if (!adPlaying || !adVideoElement || trackingFired.impression) return;
2289
+ if (!adVideoElement.currentSrc) return;
2290
+ logFunnel("media_event", {
2291
+ reason: event.type,
2292
+ readyState: adVideoElement.readyState,
2293
+ networkState: adVideoElement.networkState,
2294
+ currentSrc: adVideoElement.currentSrc
2295
+ });
1809
2296
  };
1810
2297
  var onVolumeChange = function onVolumeChange() {
1811
2298
  if (!currentAd || !adVideoElement) return;
2299
+ if (forcedMuteByAutoplay && !adVideoElement.muted) {
2300
+ var userActivation = navigator.userActivation;
2301
+ if (userActivation && !userActivation.isActive) {
2302
+ logFunnel("unexpected_unmute", {
2303
+ paused: adVideoElement.paused
2304
+ });
2305
+ }
2306
+ forcedMuteByAutoplay = false;
2307
+ }
1812
2308
  var muted = adVideoElement.muted || adVideoElement.volume === 0;
1813
2309
  if (!trackingFired.start) {
1814
2310
  trackingFired.lastMuted = muted;
@@ -1868,6 +2364,22 @@ function createHlsAdPlayer(contentVideo, options) {
1868
2364
  {
1869
2365
  type: "play",
1870
2366
  handler: onPlay
2367
+ },
2368
+ {
2369
+ type: "stalled",
2370
+ handler: onMediaDiagnostic
2371
+ },
2372
+ {
2373
+ type: "suspend",
2374
+ handler: onMediaDiagnostic
2375
+ },
2376
+ {
2377
+ type: "abort",
2378
+ handler: onMediaDiagnostic
2379
+ },
2380
+ {
2381
+ type: "emptied",
2382
+ handler: onMediaDiagnostic
1871
2383
  }
1872
2384
  ];
1873
2385
  var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
@@ -2157,16 +2669,51 @@ function createHlsAdPlayer(contentVideo, options) {
2157
2669
  function settlePendingPlay() {
2158
2670
  pendingPlayPromise = void 0;
2159
2671
  }
2672
+ function toVastPlayErrorCode(error) {
2673
+ return (error === null || error === void 0 ? void 0 : error.name) === "NotSupportedError" ? VAST_ERROR_NO_SUPPORTED_MEDIA : VAST_ERROR_MEDIA_DISPLAY;
2674
+ }
2675
+ function failAdPlayback(context, error) {
2676
+ var vastErrorCode = toVastPlayErrorCode(error);
2677
+ console.error("[HlsAdPlayer] Error starting ".concat(context, ":"), error);
2678
+ logFunnel("play_failed", {
2679
+ errorName: error === null || error === void 0 ? void 0 : error.name,
2680
+ errorMessage: error === null || error === void 0 ? void 0 : error.message,
2681
+ vastErrorCode: vastErrorCode
2682
+ });
2683
+ recoverFromAdFailure(vastErrorCode);
2684
+ }
2160
2685
  function startAdPlayback(context) {
2686
+ var isMutedRetry = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : false;
2161
2687
  if (!adVideoElement) return;
2688
+ var computed = typeof getComputedStyle === "function" && adContainerEl ? getComputedStyle(adContainerEl) : void 0;
2689
+ logFunnel(isMutedRetry ? "muted_retry" : "play_called", {
2690
+ context: context,
2691
+ isConnected: adVideoElement.isConnected,
2692
+ clientWidth: adVideoElement.clientWidth,
2693
+ clientHeight: adVideoElement.clientHeight,
2694
+ containerDisplay: computed === null || computed === void 0 ? void 0 : computed.display,
2695
+ containerVisibility: computed === null || computed === void 0 ? void 0 : computed.visibility
2696
+ });
2162
2697
  var playPromise = adVideoElement.play();
2163
2698
  pendingPlayPromise = playPromise;
2164
2699
  playPromise.catch(function(error) {
2165
2700
  if (pendingPlayPromise !== playPromise) {
2166
2701
  return;
2167
2702
  }
2168
- console.error("[HlsAdPlayer] Error starting ".concat(context, ":"), error);
2169
- handleAdError();
2703
+ logFunnel("play_rejected", {
2704
+ context: context,
2705
+ errorName: error === null || error === void 0 ? void 0 : error.name,
2706
+ errorMessage: error === null || error === void 0 ? void 0 : error.message
2707
+ });
2708
+ if (!isMutedRetry && (error === null || error === void 0 ? void 0 : error.name) === "NotAllowedError" && adVideoElement && !adVideoElement.muted) {
2709
+ console.warn("[HlsAdPlayer] Unmuted ".concat(context, " blocked by autoplay policy - retrying muted"));
2710
+ originalMutedState = true;
2711
+ forcedMuteByAutoplay = true;
2712
+ adVideoElement.muted = true;
2713
+ startAdPlayback(context, true);
2714
+ return;
2715
+ }
2716
+ failAdPlayback(context, error);
2170
2717
  }).finally(function() {
2171
2718
  if (pendingPlayPromise === playPromise) {
2172
2719
  pendingPlayPromise = void 0;
@@ -2205,17 +2752,109 @@ function createHlsAdPlayer(contentVideo, options) {
2205
2752
  adVideoElement.volume = Math.max(0, Math.min(1, originalVolume));
2206
2753
  adVideoElement.muted = originalMutedState;
2207
2754
  }
2755
+ function clearMediaStartTimer() {
2756
+ if (mediaStartTimerId !== void 0) {
2757
+ clearTimeout(mediaStartTimerId);
2758
+ mediaStartTimerId = void 0;
2759
+ }
2760
+ }
2761
+ function startMediaStartTimer() {
2762
+ clearMediaStartTimer();
2763
+ if (!(MEDIA_START_TIMEOUT_MS > 0)) return;
2764
+ var startedAt = Date.now();
2765
+ mediaStartTimerId = setTimeout(function() {
2766
+ mediaStartTimerId = void 0;
2767
+ if (!adPlaying || trackingFired.impression) return;
2768
+ console.warn("[HlsAdPlayer] Ad media did not start playing within ".concat(MEDIA_START_TIMEOUT_MS, "ms"));
2769
+ logFunnel("play_resolved_but_never_started", {
2770
+ timeoutMs: MEDIA_START_TIMEOUT_MS,
2771
+ elapsedMs: Date.now() - startedAt,
2772
+ readyState: adVideoElement === null || adVideoElement === void 0 ? void 0 : adVideoElement.readyState,
2773
+ networkState: adVideoElement === null || adVideoElement === void 0 ? void 0 : adVideoElement.networkState,
2774
+ currentSrc: adVideoElement === null || adVideoElement === void 0 ? void 0 : adVideoElement.currentSrc,
2775
+ paused: adVideoElement === null || adVideoElement === void 0 ? void 0 : adVideoElement.paused,
2776
+ vastErrorCode: VAST_ERROR_MEDIA_TIMEOUT
2777
+ });
2778
+ recoverFromAdFailure(VAST_ERROR_MEDIA_TIMEOUT);
2779
+ }, MEDIA_START_TIMEOUT_MS);
2780
+ }
2781
+ function resetVideoElementForNextSource() {
2782
+ clearStallWatchdog();
2783
+ if (requiresMediaPipelineResetAfterAds()) {
2784
+ recreateAdVideoElement();
2785
+ setupAdEventListeners();
2786
+ } else {
2787
+ prepareVideoElementForNewSource();
2788
+ }
2789
+ }
2790
+ function tryNextMediaCandidate() {
2791
+ if (!currentAd || trackingFired.impression) return false;
2792
+ if (mediaCandidateIndex >= mediaCandidates.length - 1) return false;
2793
+ var failedUrl = currentAdMediaFile === null || currentAdMediaFile === void 0 ? void 0 : currentAdMediaFile.url;
2794
+ mediaCandidateIndex++;
2795
+ var next = mediaCandidates[mediaCandidateIndex];
2796
+ if (!next) return false;
2797
+ logFunnel("media_fallback", {
2798
+ failedUrl: failedUrl,
2799
+ nextUrl: next.url,
2800
+ nextType: next.type,
2801
+ candidateIndex: mediaCandidateIndex,
2802
+ candidateCount: mediaCandidates.length
2803
+ });
2804
+ resetVideoElementForNextSource();
2805
+ try {
2806
+ loadMediaCandidate(next);
2807
+ return true;
2808
+ } catch (error) {
2809
+ console.error("[HlsAdPlayer] Failed to load fallback media file:", error);
2810
+ return tryNextMediaCandidate();
2811
+ }
2812
+ }
2813
+ function recoverFromAdFailure(vastErrorCode) {
2814
+ clearMediaStartTimer();
2815
+ if (tryNextMediaCandidate()) return;
2816
+ reportCurrentAdError(vastErrorCode);
2817
+ if (podIndex < podAds.length - 1 && advanceToNextPodAd()) return;
2818
+ handleAdError();
2819
+ }
2208
2820
  function loadCurrentAdMedia() {
2209
2821
  if (!adVideoElement || !currentAd) {
2210
2822
  throw new Error("No ad video element or ad to load");
2211
2823
  }
2212
- var mediaFile = selectBestMediaFile(currentAd.mediaFiles);
2824
+ mediaCandidates = rankMediaCandidates(currentAd.mediaFiles);
2825
+ mediaCandidateIndex = 0;
2826
+ var mediaFile = mediaCandidates[0];
2213
2827
  if (!mediaFile) {
2214
- throw new Error("No media file available for ad");
2828
+ logFunnel("media_unsupported", {
2829
+ vastErrorCode: VAST_ERROR_NO_SUPPORTED_MEDIA,
2830
+ candidates: currentAd.mediaFiles.length
2831
+ });
2832
+ reportCurrentAdError(VAST_ERROR_NO_SUPPORTED_MEDIA);
2833
+ throw new Error("No media file this browser can play");
2834
+ }
2835
+ try {
2836
+ loadMediaCandidate(mediaFile);
2837
+ } catch (error) {
2838
+ if (tryNextMediaCandidate()) return;
2839
+ reportCurrentAdError(VAST_ERROR_NO_SUPPORTED_MEDIA);
2840
+ throw error;
2841
+ }
2842
+ }
2843
+ function loadMediaCandidate(mediaFile) {
2844
+ if (!adVideoElement || !currentAd) {
2845
+ throw new Error("No ad video element or ad to load");
2215
2846
  }
2216
2847
  currentAdMediaFile = mediaFile;
2217
2848
  var isHlsAd = isHlsMediaFile(mediaFile);
2849
+ logFunnel("media_selected", {
2850
+ width: mediaFile.width,
2851
+ height: mediaFile.height,
2852
+ bitrate: mediaFile.bitrate,
2853
+ candidateIndex: mediaCandidateIndex,
2854
+ candidates: mediaCandidates.length
2855
+ });
2218
2856
  console.log("[HlsAdPlayer] Loading ".concat(isHlsAd ? "HLS" : "progressive", " ad (pod ").concat(podIndex + 1, "/").concat(podAds.length || 1, ") from: ").concat(mediaFile.url));
2857
+ startMediaStartTimer();
2219
2858
  if (isHlsAd && import_hls.default.isSupported()) {
2220
2859
  if (adHls) {
2221
2860
  adHls.destroy();
@@ -2224,6 +2863,9 @@ function createHlsAdPlayer(contentVideo, options) {
2224
2863
  enableWorker: true,
2225
2864
  lowLatencyMode: false
2226
2865
  });
2866
+ logFunnel("media_load", {
2867
+ pipeline: "hls.js"
2868
+ });
2227
2869
  adHls.loadSource(mediaFile.url);
2228
2870
  adHls.attachMedia(adVideoElement);
2229
2871
  adHls.on(import_hls.default.Events.MANIFEST_PARSED, function() {
@@ -2233,10 +2875,24 @@ function createHlsAdPlayer(contentVideo, options) {
2233
2875
  adHls.on(import_hls.default.Events.ERROR, function(_event, data) {
2234
2876
  console.error("[HlsAdPlayer] HLS error:", data);
2235
2877
  if (data.fatal) {
2236
- handleAdError();
2878
+ var _data_response, _data_response1, _data_frag;
2879
+ var vastErrorCode = data.type === import_hls.default.ErrorTypes.NETWORK_ERROR ? 401 : VAST_ERROR_MEDIA_DISPLAY;
2880
+ logFunnel("hls_fatal", {
2881
+ reason: data.details,
2882
+ errorName: data.type,
2883
+ errorMessage: data.details,
2884
+ responseCode: (_data_response = data.response) === null || _data_response === void 0 ? void 0 : _data_response.code,
2885
+ responseText: (_data_response1 = data.response) === null || _data_response1 === void 0 ? void 0 : _data_response1.text,
2886
+ fragUrl: (_data_frag = data.frag) === null || _data_frag === void 0 ? void 0 : _data_frag.url,
2887
+ vastErrorCode: vastErrorCode
2888
+ });
2889
+ recoverFromAdFailure(vastErrorCode);
2237
2890
  }
2238
2891
  });
2239
2892
  } else if (isHlsAd && adVideoElement.canPlayType("application/vnd.apple.mpegurl")) {
2893
+ logFunnel("media_load", {
2894
+ pipeline: "native-hls"
2895
+ });
2240
2896
  adVideoElement.src = mediaFile.url;
2241
2897
  startAdPlayback("native HLS ad playback");
2242
2898
  } else if (!isHlsAd && isProgressiveMediaFile(mediaFile)) {
@@ -2244,45 +2900,47 @@ function createHlsAdPlayer(contentVideo, options) {
2244
2900
  adHls.destroy();
2245
2901
  adHls = void 0;
2246
2902
  }
2903
+ logFunnel("media_load", {
2904
+ pipeline: "progressive"
2905
+ });
2247
2906
  adVideoElement.src = mediaFile.url;
2248
2907
  adVideoElement.load();
2249
2908
  startAdPlayback("progressive ad playback");
2250
2909
  } else {
2910
+ clearMediaStartTimer();
2911
+ logFunnel("media_unsupported", {
2912
+ vastErrorCode: VAST_ERROR_NO_SUPPORTED_MEDIA
2913
+ });
2251
2914
  throw new Error("Unsupported ad media file type: ".concat(mediaFile.type));
2252
2915
  }
2253
2916
  }
2254
2917
  function advanceToNextPodAd() {
2255
- if (podIndex >= podAds.length - 1) {
2256
- return false;
2257
- }
2258
- settleViewability();
2259
- podIndex++;
2260
- currentAd = podAds[podIndex];
2261
- currentAdMediaFile = void 0;
2262
- resetAdTracking();
2263
- if (currentAd) {
2264
- console.log("[HlsAdPlayer] Advancing to next pod ad (".concat(podIndex + 1, "/").concat(podAds.length, "): ").concat(currentAd.title, ", duration: ").concat(currentAd.duration, "s"));
2265
- }
2266
- clearStallWatchdog();
2267
- if (requiresMediaPipelineResetAfterAds()) {
2268
- recreateAdVideoElement();
2269
- setupAdEventListeners();
2270
- } else {
2271
- prepareVideoElementForNewSource();
2272
- }
2273
- try {
2274
- loadCurrentAdMedia();
2275
- emit("pod_ad_started", {
2276
- index: podIndex,
2277
- total: podAds.length
2278
- });
2279
- return true;
2280
- } catch (error) {
2281
- console.error("[HlsAdPlayer] Failed to load next pod ad:", error);
2282
- return false;
2918
+ clearMediaStartTimer();
2919
+ while(podIndex < podAds.length - 1){
2920
+ settleViewability();
2921
+ podIndex++;
2922
+ currentAd = podAds[podIndex];
2923
+ currentAdMediaFile = void 0;
2924
+ resetAdTracking();
2925
+ if (currentAd) {
2926
+ console.log("[HlsAdPlayer] Advancing to next pod ad (".concat(podIndex + 1, "/").concat(podAds.length, "): ").concat(currentAd.title, ", duration: ").concat(currentAd.duration, "s"));
2927
+ }
2928
+ resetVideoElementForNextSource();
2929
+ try {
2930
+ loadCurrentAdMedia();
2931
+ emit("pod_ad_started", {
2932
+ index: podIndex,
2933
+ total: podAds.length
2934
+ });
2935
+ return true;
2936
+ } catch (error) {
2937
+ console.error("[HlsAdPlayer] Failed to load next pod ad:", error);
2938
+ }
2283
2939
  }
2940
+ return false;
2284
2941
  }
2285
2942
  function clearStallWatchdog() {
2943
+ clearMediaStartTimer();
2286
2944
  if (stallWatchdogId != null) {
2287
2945
  clearInterval(stallWatchdogId);
2288
2946
  stallWatchdogId = void 0;
@@ -2298,11 +2956,10 @@ function createHlsAdPlayer(contentVideo, options) {
2298
2956
  function handleAdStall() {
2299
2957
  console.warn("[HlsAdPlayer] Ad playback stalled (no progress) - recovering to avoid a blank frame");
2300
2958
  clearStallWatchdog();
2301
- reportCurrentAdError(VAST_ERROR_MEDIA_DISPLAY);
2302
- if (podIndex < podAds.length - 1 && advanceToNextPodAd()) {
2303
- return;
2304
- }
2305
- handleAdError();
2959
+ logFunnel("stall", {
2960
+ vastErrorCode: VAST_ERROR_MEDIA_DISPLAY
2961
+ });
2962
+ recoverFromAdFailure(VAST_ERROR_MEDIA_DISPLAY);
2306
2963
  }
2307
2964
  function getDecodedVideoFrameCount(video) {
2308
2965
  try {
@@ -2364,11 +3021,10 @@ function createHlsAdPlayer(contentVideo, options) {
2364
3021
  function handleVideoDecodeFailure() {
2365
3022
  console.warn("[HlsAdPlayer] Ad audio is advancing but no video frames decoded (black screen) - skipping this creative");
2366
3023
  clearStallWatchdog();
2367
- reportCurrentAdError(VAST_ERROR_MEDIA_DISPLAY);
2368
- if (podIndex < podAds.length - 1 && advanceToNextPodAd()) {
2369
- return;
2370
- }
2371
- handleAdError();
3024
+ logFunnel("decode_failure", {
3025
+ vastErrorCode: VAST_ERROR_MEDIA_DISPLAY
3026
+ });
3027
+ recoverFromAdFailure(VAST_ERROR_MEDIA_DISPLAY);
2372
3028
  }
2373
3029
  function startStallWatchdog() {
2374
3030
  clearStallWatchdog();
@@ -2492,6 +3148,15 @@ function createHlsAdPlayer(contentVideo, options) {
2492
3148
  Promise.reject(new Error("Ad already playing"))
2493
3149
  ];
2494
3150
  }
3151
+ if (destroyed) {
3152
+ return [
3153
+ 2,
3154
+ Promise.reject(new Error("Ad player destroyed"))
3155
+ ];
3156
+ }
3157
+ currentVastTagUrl = vastTagUrl;
3158
+ pendingRequestAbortReason = void 0;
3159
+ logFunnel("request_sent");
2495
3160
  _state.label = 1;
2496
3161
  case 1:
2497
3162
  _state.trys.push([
@@ -2526,8 +3191,29 @@ function createHlsAdPlayer(contentVideo, options) {
2526
3191
  ads = _state.sent();
2527
3192
  _state.label = 4;
2528
3193
  case 4:
3194
+ if (destroyed) {
3195
+ return [
3196
+ 2,
3197
+ Promise.reject(new Error("Ad player destroyed"))
3198
+ ];
3199
+ }
3200
+ if (!ads.length && pendingRequestAbortReason) {
3201
+ throw new Error(pendingRequestAbortReason);
3202
+ }
3203
+ if (!ads.length && lastPodAdElementCount > 0) {
3204
+ console.warn("[HlsAdPlayer] VAST response had ads but none were playable");
3205
+ logFunnel("vast_fill_rejected", {
3206
+ adElementCount: lastPodAdElementCount
3207
+ });
3208
+ emit("ad_error");
3209
+ return [
3210
+ 2,
3211
+ Promise.reject(new Error("VAST fill rejected: no playable ad in response"))
3212
+ ];
3213
+ }
2529
3214
  if (!ads.length) {
2530
3215
  console.warn("[HlsAdPlayer] No ads available from VAST response");
3216
+ logFunnel("no_fill");
2531
3217
  emit("ad_error");
2532
3218
  return [
2533
3219
  2,
@@ -2538,6 +3224,23 @@ function createHlsAdPlayer(contentVideo, options) {
2538
3224
  podIndex = 0;
2539
3225
  currentAd = ads[0];
2540
3226
  currentAdMediaFile = void 0;
3227
+ logFunnel("vast_received", {
3228
+ adCount: ads.length,
3229
+ durations: ads.map(function(ad) {
3230
+ return ad.duration;
3231
+ }),
3232
+ impressionUrls: ads.map(function(ad) {
3233
+ return ad.trackingUrls.impression.length;
3234
+ })
3235
+ });
3236
+ ads.forEach(function(ad, index) {
3237
+ if (ad.trackingUrls.impression.length === 0) {
3238
+ logFunnel("vast_missing_impression", {
3239
+ adIndex: index,
3240
+ missingAdId: ad.id
3241
+ });
3242
+ }
3243
+ });
2541
3244
  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"));
2542
3245
  return [
2543
3246
  2,
@@ -2546,6 +3249,9 @@ function createHlsAdPlayer(contentVideo, options) {
2546
3249
  case 5:
2547
3250
  error = _state.sent();
2548
3251
  console.error("[HlsAdPlayer] Error requesting ads:", error);
3252
+ logFunnel("request_failed", {
3253
+ errorMessage: error === null || error === void 0 ? void 0 : error.message
3254
+ });
2549
3255
  emit("ad_error");
2550
3256
  return [
2551
3257
  2,
@@ -2601,13 +3307,22 @@ function createHlsAdPlayer(contentVideo, options) {
2601
3307
  adContainerEl.style.pointerEvents = "auto";
2602
3308
  }
2603
3309
  emit("content_pause");
2604
- loadCurrentAdMedia();
3310
+ try {
3311
+ loadCurrentAdMedia();
3312
+ } catch (loadError) {
3313
+ if (!(podIndex < podAds.length - 1 && advanceToNextPodAd())) {
3314
+ throw loadError;
3315
+ }
3316
+ }
2605
3317
  return [
2606
3318
  2,
2607
3319
  Promise.resolve()
2608
3320
  ];
2609
3321
  } catch (error) {
2610
3322
  console.error("[HlsAdPlayer] Error playing ad:", error);
3323
+ logFunnel("play_failed", {
3324
+ errorMessage: error === null || error === void 0 ? void 0 : error.message
3325
+ });
2611
3326
  handleAdError();
2612
3327
  return [
2613
3328
  2,
@@ -2649,6 +3364,9 @@ function createHlsAdPlayer(contentVideo, options) {
2649
3364
  var previousMutedState;
2650
3365
  return _ts_generator(this, function(_state) {
2651
3366
  console.log("[HlsAdPlayer] Stopping ad");
3367
+ if (adPlaying && currentAd && !trackingFired.impression) {
3368
+ logFunnel("stopped_before_start");
3369
+ }
2652
3370
  settleViewability();
2653
3371
  fireNotUsedForUnplayedAds();
2654
3372
  clearStallWatchdog();
@@ -2681,15 +3399,18 @@ function createHlsAdPlayer(contentVideo, options) {
2681
3399
  },
2682
3400
  destroy: function destroy() {
2683
3401
  console.log("[HlsAdPlayer] Destroying");
3402
+ if (adPlaying && currentAd && !trackingFired.impression) {
3403
+ logFunnel("stopped_before_start");
3404
+ }
2684
3405
  settleViewability();
2685
3406
  fireNotUsedForUnplayedAds();
2686
3407
  destroyed = true;
2687
- clearStallWatchdog();
3408
+ pendingRequestAbortReason = "Ad player destroyed";
2688
3409
  var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
2689
3410
  try {
2690
- for(var _iterator = pendingTimeouts[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
2691
- var timeoutId = _step.value;
2692
- clearTimeout(timeoutId);
3411
+ for(var _iterator = Array.from(pendingVastRequests)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
3412
+ var controller = _step.value;
3413
+ controller.abort();
2693
3414
  }
2694
3415
  } catch (err) {
2695
3416
  _didIteratorError = true;
@@ -2705,6 +3426,28 @@ function createHlsAdPlayer(contentVideo, options) {
2705
3426
  }
2706
3427
  }
2707
3428
  }
3429
+ pendingVastRequests.clear();
3430
+ clearStallWatchdog();
3431
+ var _iteratorNormalCompletion1 = true, _didIteratorError1 = false, _iteratorError1 = undefined;
3432
+ try {
3433
+ for(var _iterator1 = pendingTimeouts[Symbol.iterator](), _step1; !(_iteratorNormalCompletion1 = (_step1 = _iterator1.next()).done); _iteratorNormalCompletion1 = true){
3434
+ var timeoutId = _step1.value;
3435
+ clearTimeout(timeoutId);
3436
+ }
3437
+ } catch (err) {
3438
+ _didIteratorError1 = true;
3439
+ _iteratorError1 = err;
3440
+ } finally{
3441
+ try {
3442
+ if (!_iteratorNormalCompletion1 && _iterator1.return != null) {
3443
+ _iterator1.return();
3444
+ }
3445
+ } finally{
3446
+ if (_didIteratorError1) {
3447
+ throw _iteratorError1;
3448
+ }
3449
+ }
3450
+ }
2708
3451
  pendingTimeouts = [];
2709
3452
  adPlaying = false;
2710
3453
  setAdPlayingFlag(false);
@@ -2724,6 +3467,35 @@ function createHlsAdPlayer(contentVideo, options) {
2724
3467
  isAdPlaying: function isAdPlaying() {
2725
3468
  return adPlaying;
2726
3469
  },
3470
+ setFunnelContext: function setFunnelContext(context) {
3471
+ funnelContext = _object_spread({}, context);
3472
+ },
3473
+ abortPendingRequest: function abortPendingRequest() {
3474
+ var reason = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : "VAST request aborted (timeout)";
3475
+ if (pendingVastRequests.size === 0) return;
3476
+ pendingRequestAbortReason = reason;
3477
+ var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
3478
+ try {
3479
+ for(var _iterator = Array.from(pendingVastRequests)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
3480
+ var controller = _step.value;
3481
+ controller.abort();
3482
+ }
3483
+ } catch (err) {
3484
+ _didIteratorError = true;
3485
+ _iteratorError = err;
3486
+ } finally{
3487
+ try {
3488
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
3489
+ _iterator.return();
3490
+ }
3491
+ } finally{
3492
+ if (_didIteratorError) {
3493
+ throw _iteratorError;
3494
+ }
3495
+ }
3496
+ }
3497
+ pendingVastRequests.clear();
3498
+ },
2727
3499
  resize: function resize(width, height) {
2728
3500
  console.log("[HlsAdPlayer] Resizing to ".concat(width, "x").concat(height));
2729
3501
  if (adContainerEl) {
@@ -2759,6 +3531,13 @@ function createHlsAdPlayer(contentVideo, options) {
2759
3531
  if (adVideoElement && adPlaying) {
2760
3532
  var clamped = Math.max(0, Math.min(1, volume));
2761
3533
  adVideoElement.volume = clamped;
3534
+ var userActivation = navigator.userActivation;
3535
+ if (clamped > 0 && forcedMuteByAutoplay && userActivation && !userActivation.isActive) {
3536
+ logFunnel("unmute_blocked_without_gesture", {
3537
+ requestedVolume: clamped
3538
+ });
3539
+ return;
3540
+ }
2762
3541
  adVideoElement.muted = clamped === 0;
2763
3542
  }
2764
3543
  },
@@ -4865,6 +5644,21 @@ function normalizeVastTagUrl(raw) {
4865
5644
  return raw;
4866
5645
  }
4867
5646
  }
5647
+ var GAM_AD_HOSTS = /* @__PURE__ */ new Set([
5648
+ "pubads.g.doubleclick.net",
5649
+ "securepubads.g.doubleclick.net"
5650
+ ]);
5651
+ function ensureVideoAdType(rawUrl) {
5652
+ try {
5653
+ var url = new URL(rawUrl);
5654
+ if (!GAM_AD_HOSTS.has(url.hostname)) return rawUrl;
5655
+ if (url.searchParams.has("ad_type")) return rawUrl;
5656
+ url.searchParams.set("ad_type", "video");
5657
+ return url.toString();
5658
+ } catch (unused) {
5659
+ return rawUrl;
5660
+ }
5661
+ }
4868
5662
  function applyVastMacros(baseUrl, ctx) {
4869
5663
  var expandedUrl = expandInlineMacroPlaceholders(baseUrl, ctx);
4870
5664
  var url;
@@ -6575,7 +7369,7 @@ var AdConfigManager = /*#__PURE__*/ function() {
6575
7369
  } : {}), {
6576
7370
  consent: this.consentSignals
6577
7371
  }));
6578
- var finalUrl = palNonce.injectNonce(urlWithMacros);
7372
+ var finalUrl = palNonce.injectNonce(ensureVideoAdType(urlWithMacros));
6579
7373
  console.log("[StormcloudVideoPlayer] Resolved optimized-pod request URL (pod=".concat(this.podCounter, ", pmad=").concat(podParams.maxAds, ", pmnd=").concat(podParams.minDurationMs, ", pmxd=").concat((_podParams_maxDurationMs = podParams.maxDurationMs) !== null && _podParams_maxDurationMs !== void 0 ? _podParams_maxDurationMs : "?", "):"), finalUrl);
6580
7374
  return finalUrl;
6581
7375
  }
@@ -6822,7 +7616,7 @@ var AdTimingService = /*#__PURE__*/ function() {
6822
7616
  {
6823
7617
  key: "adFitsRemainingBudget",
6824
7618
  value: function adFitsRemainingBudget(durationMs) {
6825
- if (durationMs <= 0) {
7619
+ if (durationMs <= 0 || this.expectedAdBreakDurationMs == null) {
6826
7620
  return true;
6827
7621
  }
6828
7622
  return durationMs <= this.getDurationBudgetRemainingMs();
@@ -6881,6 +7675,11 @@ var AdTimingService = /*#__PURE__*/ function() {
6881
7675
  value: function markAdStarted() {
6882
7676
  this.currentAdIndex++;
6883
7677
  this.totalAdsInBreak = this.currentAdIndex;
7678
+ }
7679
+ },
7680
+ {
7681
+ key: "noteAdRequestSent",
7682
+ value: function noteAdRequestSent() {
6884
7683
  this.totalAdRequestsInBreak++;
6885
7684
  this.lastAdRequestTime = Date.now();
6886
7685
  }
@@ -6932,6 +7731,9 @@ var AdTimingService = /*#__PURE__*/ function() {
6932
7731
  if (message.includes("timeout")) {
6933
7732
  return true;
6934
7733
  }
7734
+ if (message.includes("ad player destroyed") || message.includes("aborted")) {
7735
+ return true;
7736
+ }
6935
7737
  if (message.includes("rate limit") || message.includes("too many requests")) {
6936
7738
  return true;
6937
7739
  }
@@ -8056,6 +8858,18 @@ function resizePlayer(video, adPlayer, debug) {
8056
8858
  }
8057
8859
  }
8058
8860
  // src/player/AdBreakOrchestrator.ts
8861
+ var REQUEST_FAILURE_STAGES = /* @__PURE__ */ new Set([
8862
+ "no_fill",
8863
+ "vast_fill_rejected",
8864
+ "request_failed",
8865
+ "media_unsupported",
8866
+ "play_failed",
8867
+ "play_resolved_but_never_started",
8868
+ "hls_fatal",
8869
+ "media_error",
8870
+ "stall",
8871
+ "decode_failure"
8872
+ ]);
8059
8873
  var AdBreakOrchestrator = /*#__PURE__*/ function() {
8060
8874
  function AdBreakOrchestrator(host, timing, adConfig, cueManager, placeholder) {
8061
8875
  _class_call_check(this, AdBreakOrchestrator);
@@ -8063,11 +8877,17 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8063
8877
  this.showAds = false;
8064
8878
  this.isShowingPlaceholder = false;
8065
8879
  this.adDetectSentForCurrentBreak = false;
8066
- this.continuousFetchingActive = false;
8067
- this.continuousFetchLoopRunning = false;
8068
- this.adRequestQueue = [];
8880
+ this.slotState = "IDLE";
8881
+ this.unusableResponsesInBreak = 0;
8882
+ this.controllerGeneration = 0;
8883
+ this.requestDiagnostics = /* @__PURE__ */ new Map();
8884
+ this.breakFunnel = {};
8885
+ this.controllerCallInFlight = false;
8886
+ this.playbackStartedForCurrentRequest = false;
8887
+ this.opportunityEpoch = -1;
8069
8888
  this.adPodQueue = [];
8070
- this.maxPlaceholderDurationMs = 5e3;
8889
+ this.defaultMinRemainingMsToRequestAd = 1e4;
8890
+ this.defaultMaxNoFillsPerBreak = 2;
8071
8891
  this.pendingAdBreak = null;
8072
8892
  this.host = host;
8073
8893
  this.timing = timing;
@@ -8103,7 +8923,23 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8103
8923
  key: "attachImaEventListeners",
8104
8924
  value: function attachImaEventListeners() {
8105
8925
  var _this = this;
8106
- var adPlayer = this.host.getAdPlayer();
8926
+ var controller = this.host.getAdPlayer();
8927
+ var generation = this.controllerGeneration;
8928
+ var adPlayer = {
8929
+ on: function on(event, handler) {
8930
+ controller.on(event, function(payload) {
8931
+ if (generation !== _this.controllerGeneration) {
8932
+ _this.logOrchestratorFunnel("stale_callback_ignored", {
8933
+ event: event,
8934
+ staleControllerId: generation,
8935
+ currentControllerId: _this.controllerGeneration
8936
+ });
8937
+ return;
8938
+ }
8939
+ handler(payload);
8940
+ });
8941
+ }
8942
+ };
8107
8943
  adPlayer.on("pod_ad_started", function(payload) {
8108
8944
  _this.timing.notePodAdStarted();
8109
8945
  if (_this.debug) {
@@ -8117,7 +8953,35 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8117
8953
  adPlayer.on("ad_interaction", function(event) {
8118
8954
  if (event) _this.host.onAdInteraction(event);
8119
8955
  });
8956
+ adPlayer.on("ad_funnel", function(payload) {
8957
+ if (!(payload === null || payload === void 0 ? void 0 : payload.stage)) return;
8958
+ var stage = payload.stage;
8959
+ _this.countFunnelStage(stage);
8960
+ if (payload.reason) {
8961
+ _this.countFunnelStage("".concat(stage, ":").concat(payload.reason));
8962
+ }
8963
+ if (stage === "impression_fired" && payload.pixelCount != null) {
8964
+ _this.countFunnelStage("impression_urls", payload.pixelCount);
8965
+ }
8966
+ if (payload.visibilityState === "hidden") {
8967
+ _this.countFunnelStage("while_hidden");
8968
+ }
8969
+ if (stage === "gam_http_request_sent") {
8970
+ if (payload.attempt === 1) {
8971
+ _this.timing.noteAdRequestSent();
8972
+ } else {
8973
+ _this.countFunnelStage("gam_http_request_retry");
8974
+ }
8975
+ }
8976
+ _this.recordRequestDiagnostic(payload);
8977
+ });
8120
8978
  adPlayer.on("ad_impression", function() {
8979
+ _this.timing.consecutiveFailures = 0;
8980
+ _this.setSlotState("PLAYING", "impression");
8981
+ if (!_this.playbackStartedForCurrentRequest) {
8982
+ _this.playbackStartedForCurrentRequest = true;
8983
+ _this.timing.markAdStarted();
8984
+ }
8121
8985
  sendAdImpressionTracking(_this.host.config.licenseKey, _object_spread_props(_object_spread({
8122
8986
  source: "hls",
8123
8987
  adIndex: _this.timing.currentAdIndex
@@ -8132,16 +8996,11 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8132
8996
  var remaining = _this.timing.getRemainingAdMs();
8133
8997
  _this.timing.consecutiveFailures = 0;
8134
8998
  if (_this.debug) {
8135
- console.log("[StormcloudVideoPlayer] all_ads_completed event received - remaining=".concat(remaining, "ms, queued ads=").concat(_this.adRequestQueue.length), _this.adRequestQueue.length > 0 ? {
8136
- queuedUrls: _to_consumable_array(_this.adRequestQueue)
8137
- } : {});
8999
+ console.log("[StormcloudVideoPlayer] all_ads_completed event received - remaining=".concat(remaining, "ms"));
8138
9000
  }
8139
9001
  if (_this.inAdBreak) {
8140
- if (_this.timing.hasTimeToStartAnotherAd()) {
8141
- _this.tryNextAvailableAdWithRateLimit();
8142
- } else {
8143
- _this.handleAdPodComplete();
8144
- }
9002
+ _this.setSlotState("NEEDS_NEXT_AD", "all_ads_completed");
9003
+ _this.requestNextAd("all_ads_completed");
8145
9004
  }
8146
9005
  });
8147
9006
  adPlayer.on("ad_error", function(errorPayload) {
@@ -8161,7 +9020,10 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8161
9020
  }
8162
9021
  }
8163
9022
  console.error("[AD-ERROR]", errorMessage, errorPayload || "");
8164
- _this.handleAdFailure();
9023
+ if (_this.controllerCallInFlight) {
9024
+ return;
9025
+ }
9026
+ _this.handleAdFailure("ad_error");
8165
9027
  });
8166
9028
  adPlayer.on("content_pause", function() {
8167
9029
  _this.timing.clearAdFailsafeTimer();
@@ -8200,26 +9062,32 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8200
9062
  }
8201
9063
  _this.timing.consecutiveFailures = 0;
8202
9064
  _this.timing.recordPlayedAdDuration(_this.host.getAdPlayer());
8203
- var remaining = _this.timing.getRemainingAdMs();
8204
9065
  if (_this.debug) {
8205
- console.log("[CONTINUOUS-FETCH] content_resume event: remaining=".concat(remaining, "ms, queued ads=").concat(_this.adRequestQueue.length), _this.adRequestQueue.length > 0 ? {
8206
- queuedUrls: _to_consumable_array(_this.adRequestQueue)
8207
- } : {});
8208
- }
8209
- if (_this.timing.hasTimeToStartAnotherAd()) {
8210
- _this.tryNextAvailableAdWithRateLimit();
8211
- } else {
8212
- _this.handleAdPodComplete();
9066
+ console.log("[AdBreak] content_resume: remaining=".concat(_this.timing.getRemainingAdMs(), "ms"));
8213
9067
  }
9068
+ _this.setSlotState("NEEDS_NEXT_AD", "ad_complete");
9069
+ _this.requestNextAd("ad_complete");
8214
9070
  });
8215
9071
  }
8216
9072
  },
8217
9073
  {
8218
9074
  key: "recreateAdController",
8219
- value: function recreateAdController() {
8220
- if (this.debug) {
8221
- console.log("[StormcloudVideoPlayer] Recreating AdController for new ad");
9075
+ value: function recreateAdController(reason) {
9076
+ if (reason === "new_request" && (this.slotState === "REQUESTING" || this.slotState === "READY")) {
9077
+ console.warn("[AD-CONTROLLER] destroy during active request", {
9078
+ controllerId: this.controllerGeneration,
9079
+ requestId: this.currentRequestId,
9080
+ state: this.slotState,
9081
+ reason: reason
9082
+ });
8222
9083
  }
9084
+ console.log("[AD-CONTROLLER] destroy", {
9085
+ controllerId: this.controllerGeneration,
9086
+ requestId: this.currentRequestId,
9087
+ state: this.slotState,
9088
+ reason: reason
9089
+ });
9090
+ this.countFunnelStage("controller_destroy:".concat(reason));
8223
9091
  var shouldShowPlaceholder = this.inAdBreak && this.showAds;
8224
9092
  var adPlayer = this.host.getAdPlayer();
8225
9093
  if (shouldShowPlaceholder && adPlayer) {
@@ -8232,6 +9100,7 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8232
9100
  }
8233
9101
  var preservedMutedState = adPlayer.getOriginalMutedState();
8234
9102
  var preservedVolumeState = adPlayer.getOriginalVolume();
9103
+ this.playbackStartedForCurrentRequest = false;
8235
9104
  if (adPlayer) {
8236
9105
  try {
8237
9106
  adPlayer.destroy();
@@ -8245,9 +9114,16 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8245
9114
  var continueLiveStreamDuringAds = this.host.shouldContinueLiveStreamDuringAds();
8246
9115
  var newAdPlayer = this.host.createAdPlayer(continueLiveStreamDuringAds);
8247
9116
  this.host.setAdPlayer(newAdPlayer);
9117
+ this.controllerGeneration++;
8248
9118
  newAdPlayer.initialize();
8249
9119
  newAdPlayer.updateOriginalMutedState(preservedMutedState, preservedVolumeState);
8250
9120
  this.attachImaEventListeners();
9121
+ if (this.debug) {
9122
+ console.log("[AD-CONTROLLER] create", {
9123
+ controllerId: this.controllerGeneration,
9124
+ reason: reason
9125
+ });
9126
+ }
8251
9127
  if (shouldShowPlaceholder) {
8252
9128
  this.placeholder.show();
8253
9129
  newAdPlayer.showPlaceholder();
@@ -8268,32 +9144,57 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8268
9144
  }
8269
9145
  },
8270
9146
  {
8271
- key: "handleAdStart",
8272
- value: // ───────────────────────────────────────────────────────────────
9147
+ // ───────────────────────────────────────────────────────────────
8273
9148
  // Ad break start
8274
9149
  // ───────────────────────────────────────────────────────────────
8275
- function handleAdStart(_marker) {
9150
+ key: "isBreakActive",
9151
+ value: function isBreakActive() {
9152
+ return this.slotState !== "IDLE";
9153
+ }
9154
+ },
9155
+ {
9156
+ key: "getSlotState",
9157
+ value: function getSlotState() {
9158
+ return this.slotState;
9159
+ }
9160
+ },
9161
+ {
9162
+ key: "beginVmapBreak",
9163
+ value: function beginVmapBreak(breakKey) {
9164
+ this.breakSource = "vmap";
9165
+ this.followUpBaseVastUrl = void 0;
9166
+ this.unusableResponsesInBreak = 0;
9167
+ this.timing.totalAdRequestsInBreak = 0;
9168
+ this.setSlotState("NEEDS_NEXT_AD", "vmap_break_start");
9169
+ this.noteOpportunity("vmap", breakKey);
9170
+ }
9171
+ },
9172
+ {
9173
+ key: "handleAdStart",
9174
+ value: function handleAdStart(marker) {
8276
9175
  return _async_to_generator(function() {
8277
- var scheduled, tags, baseVastUrl, adBreakDurationMs, mode, currentMuted, currentVolume, podPlayed;
9176
+ var baseVastUrl, adBreakDurationMs, mode, currentMuted, currentVolume, epoch, podPlayed;
8278
9177
  return _ts_generator(this, function(_state) {
8279
9178
  switch(_state.label){
8280
9179
  case 0:
8281
- scheduled = this.adConfig.findCurrentOrNextBreak(this.host.video.currentTime * 1e3);
8282
- if (scheduled) {
8283
- this.adConfig.consumedVmapBreakIds.add(this.adConfig.getAdBreakKey(scheduled));
9180
+ if (this.slotState !== "IDLE") {
9181
+ this.logOrchestratorFunnel("duplicate_break_start", {
9182
+ source: "scte35",
9183
+ state: this.slotState
9184
+ });
9185
+ return [
9186
+ 2
9187
+ ];
8284
9188
  }
8285
- tags = this.adConfig.selectVastTagsForBreak(scheduled);
8286
- if (tags && tags.length > 0 && tags[0]) {
8287
- baseVastUrl = tags[0];
8288
- } else if (this.adConfig.apiVastTagUrl) {
8289
- baseVastUrl = this.adConfig.apiVastTagUrl;
8290
- } else {
9189
+ baseVastUrl = this.adConfig.apiVastTagUrl;
9190
+ if (!baseVastUrl) {
9191
+ console.warn("[AdBreak] SCTE-35 break started but no direct VAST tag is configured");
8291
9192
  this.clearPendingAdBreak();
8292
9193
  return [
8293
9194
  2
8294
9195
  ];
8295
9196
  }
8296
- adBreakDurationMs = _marker.durationSeconds != null ? _marker.durationSeconds * 1e3 : scheduled === null || scheduled === void 0 ? void 0 : scheduled.durationMs;
9197
+ adBreakDurationMs = marker.durationSeconds != null ? marker.durationSeconds * 1e3 : this.timing.expectedAdBreakDurationMs;
8297
9198
  if (this.debug) {
8298
9199
  mode = this.host.config.isLiveStream ? "LIVE" : "VOD";
8299
9200
  console.log("[CONTINUOUS-FETCH] ".concat(mode, " MODE: Target duration=").concat(adBreakDurationMs, "ms"));
@@ -8301,9 +9202,12 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8301
9202
  this.timing.failedVastUrls.clear();
8302
9203
  this.timing.temporaryFailureUrls.clear();
8303
9204
  this.timing.consecutiveFailures = 0;
8304
- this.continuousFetchingActive = true;
8305
9205
  this.isShowingPlaceholder = false;
8306
9206
  this.timing.totalAdRequestsInBreak = 0;
9207
+ this.breakSource = "scte35";
9208
+ this.followUpBaseVastUrl = baseVastUrl;
9209
+ this.unusableResponsesInBreak = 0;
9210
+ this.setSlotState("NEEDS_NEXT_AD", "scte35_break_start");
8307
9211
  if (this.adConfig.podAssignedByPrefetch) {
8308
9212
  this.adConfig.podAssignedByPrefetch = false;
8309
9213
  } else {
@@ -8321,29 +9225,18 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8321
9225
  if (this.timing.expectedAdBreakDurationMs == null && adBreakDurationMs != null) {
8322
9226
  this.timing.expectedAdBreakDurationMs = adBreakDurationMs;
8323
9227
  }
9228
+ this.noteOpportunity("scte35", this.cueManager.activeScte35BreakKey);
9229
+ epoch = this.timing.adBreakEpoch;
8324
9230
  return [
8325
9231
  4,
8326
- this.startOptimizedPod(baseVastUrl, adBreakDurationMs, currentMuted, currentVolume)
9232
+ this.startOptimizedPod(baseVastUrl, adBreakDurationMs)
8327
9233
  ];
8328
9234
  case 1:
8329
9235
  podPlayed = _state.sent();
8330
- if (!!podPlayed) return [
8331
- 3,
8332
- 3
8333
- ];
8334
- if (this.debug) {
8335
- console.log("[POD] Initial pod request did not fill; attempting top-up pod request");
9236
+ if (!podPlayed && this.inAdBreak && epoch === this.timing.adBreakEpoch) {
9237
+ this.setSlotState("NEEDS_NEXT_AD", "initial_request_failed");
9238
+ this.requestNextAd("initial_request_failed");
8336
9239
  }
8337
- this.continuousFetchingActive = true;
8338
- this.startContinuousFetching(baseVastUrl);
8339
- return [
8340
- 4,
8341
- this.tryNextAvailableAdWithRateLimit()
8342
- ];
8343
- case 2:
8344
- _state.sent();
8345
- _state.label = 3;
8346
- case 3:
8347
9240
  return [
8348
9241
  2
8349
9242
  ];
@@ -8357,12 +9250,13 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8357
9250
  value: // ───────────────────────────────────────────────────────────────
8358
9251
  // Optimized pod (single multi-ad request)
8359
9252
  // ───────────────────────────────────────────────────────────────
8360
- function startOptimizedPod(baseVastUrl, breakDurationMs, currentMuted, currentVolume) {
9253
+ function startOptimizedPod(baseVastUrl, breakDurationMs) {
8361
9254
  return _async_to_generator(function() {
8362
- var podUrl, adPlayer, requestToken, _ref, _adPlayer_getPodAdCount, podCount, error;
9255
+ var podUrl, prefetched, epoch, generation, adPlayer, requestToken, _ref, _adPlayer_getPodAdCount, podCount, error;
8363
9256
  return _ts_generator(this, function(_state) {
8364
9257
  switch(_state.label){
8365
9258
  case 0:
9259
+ prefetched = !!(this.pendingAdBreak && this.pendingAdBreak.vastUrls.length > 0);
8366
9260
  if (this.pendingAdBreak && this.pendingAdBreak.vastUrls.length > 0) {
8367
9261
  podUrl = this.pendingAdBreak.vastUrls[0];
8368
9262
  this.clearPendingAdBreak();
@@ -8375,12 +9269,16 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8375
9269
  false
8376
9270
  ];
8377
9271
  }
8378
- this.continuousFetchingActive = false;
8379
- this.recreateAdController();
9272
+ this.noteVastUrlGenerated(podUrl, prefetched ? "prefetch" : "break_start");
9273
+ epoch = this.timing.adBreakEpoch;
9274
+ this.recreateAdController("new_request");
9275
+ generation = this.controllerGeneration;
8380
9276
  adPlayer = this.host.getAdPlayer();
8381
9277
  requestToken = ++this.timing.adRequestTokenCounter;
8382
9278
  this.timing.activeAdRequestToken = requestToken;
8383
9279
  this.currentVastUrl = podUrl;
9280
+ this.setSlotState("REQUESTING", "initial_pod");
9281
+ this.beginFunnelRequest(adPlayer, requestToken, "initial_pod");
8384
9282
  _state.label = 1;
8385
9283
  case 1:
8386
9284
  _state.trys.push([
@@ -8395,16 +9293,24 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8395
9293
  ];
8396
9294
  case 2:
8397
9295
  _state.sent();
9296
+ if (this.isStale(epoch, generation)) return [
9297
+ 2,
9298
+ true
9299
+ ];
8398
9300
  this.timing.startAdRequestWatchdog(requestToken);
8399
- this.timing.lastAdRequestTime = Date.now();
8400
9301
  return [
8401
9302
  4,
8402
- adPlayer.requestAds(podUrl)
9303
+ this.callController(function() {
9304
+ return adPlayer.requestAds(podUrl);
9305
+ })
8403
9306
  ];
8404
9307
  case 3:
8405
9308
  _state.sent();
8406
9309
  this.timing.clearAdRequestWatchdog();
8407
- if (this.timing.activeAdRequestToken !== requestToken) {
9310
+ if (this.isStale(epoch, generation)) {
9311
+ this.logOrchestratorFunnel("stale_request_result_ignored", {
9312
+ requestId: requestToken
9313
+ });
8408
9314
  return [
8409
9315
  2,
8410
9316
  true
@@ -8412,11 +9318,16 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8412
9318
  }
8413
9319
  podCount = (_ref = (_adPlayer_getPodAdCount = adPlayer.getPodAdCount) === null || _adPlayer_getPodAdCount === void 0 ? void 0 : _adPlayer_getPodAdCount.call(adPlayer)) !== null && _ref !== void 0 ? _ref : 1;
8414
9320
  if (podCount < 1) {
9321
+ if (this.timing.activeAdRequestToken === requestToken) {
9322
+ this.timing.activeAdRequestToken = null;
9323
+ }
9324
+ this.recordRequestFailure(new Error("No ads available"), podUrl);
8415
9325
  return [
8416
9326
  2,
8417
9327
  false
8418
9328
  ];
8419
9329
  }
9330
+ this.setSlotState("READY", "vast_ready");
8420
9331
  if (this.debug) {
8421
9332
  console.log(podCount === 1 ? "[POD] Response contained a single ad; playing it and enabling pod top-up" : "[POD] Optimized pod returned ".concat(podCount, " ads; playing pod in one controller"));
8422
9333
  }
@@ -8428,18 +9339,20 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8428
9339
  this.timing.startAdFailsafeTimer(requestToken);
8429
9340
  return [
8430
9341
  4,
8431
- adPlayer.play()
9342
+ this.callController(function() {
9343
+ return adPlayer.play();
9344
+ })
8432
9345
  ];
8433
9346
  case 4:
8434
9347
  _state.sent();
8435
- this.timing.markAdStarted();
9348
+ if (this.isStale(epoch, generation)) return [
9349
+ 2,
9350
+ true
9351
+ ];
8436
9352
  if (this.timing.expectedAdBreakDurationMs != null && this.timing.getAdBreakEndWallClockMs() == null) {
8437
9353
  this.timing.scheduleAdStopAtBreakBoundary();
8438
9354
  }
8439
- adPlayer.setAdVolume(currentMuted ? 0 : currentVolume);
8440
- this.timing.consecutiveFailures = 0;
8441
- this.continuousFetchingActive = true;
8442
- this.startContinuousFetching(baseVastUrl);
9355
+ adPlayer.setAdVolume(getAdAudioVolume(adPlayer));
8443
9356
  return [
8444
9357
  2,
8445
9358
  true
@@ -8451,14 +9364,20 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8451
9364
  if (this.timing.activeAdRequestToken === requestToken) {
8452
9365
  this.timing.activeAdRequestToken = null;
8453
9366
  }
9367
+ if (this.isStale(epoch, generation)) {
9368
+ this.logOrchestratorFunnel("stale_request_result_ignored", {
9369
+ requestId: requestToken,
9370
+ errorMessage: error === null || error === void 0 ? void 0 : error.message
9371
+ });
9372
+ return [
9373
+ 2,
9374
+ true
9375
+ ];
9376
+ }
8454
9377
  if (this.debug) {
8455
9378
  console.warn("[POD] Optimized pod request/play failed:", error);
8456
9379
  }
8457
- if (this.timing.isTemporaryAdError(error)) {
8458
- this.timing.temporaryFailureUrls.set(podUrl, Date.now());
8459
- }
8460
- this.continuousFetchingActive = true;
8461
- this.recreateAdController();
9380
+ this.recordRequestFailure(error, podUrl);
8462
9381
  return [
8463
9382
  2,
8464
9383
  false
@@ -8474,168 +9393,204 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8474
9393
  },
8475
9394
  {
8476
9395
  // ───────────────────────────────────────────────────────────────
8477
- // Continuous fetching
9396
+ // Next-ad scheduling (single flight)
8478
9397
  // ───────────────────────────────────────────────────────────────
8479
- key: "startContinuousFetching",
8480
- value: function startContinuousFetching(baseVastUrl) {
8481
- if (!this.continuousFetchingActive) {
9398
+ key: "setSlotState",
9399
+ value: function setSlotState(next, reason) {
9400
+ if (this.slotState === next) return;
9401
+ var previous = this.slotState;
9402
+ this.slotState = next;
9403
+ if (this.debug) {
9404
+ console.log("[AdBreak][STATE] ".concat(previous, " -> ").concat(next), {
9405
+ reason: reason,
9406
+ breakId: this.timing.adBreakEpoch,
9407
+ requestId: this.currentRequestId,
9408
+ controllerId: this.controllerGeneration
9409
+ });
9410
+ }
9411
+ }
9412
+ },
9413
+ {
9414
+ key: "isStale",
9415
+ value: function isStale(epoch, generation) {
9416
+ return !this.inAdBreak || epoch !== this.timing.adBreakEpoch || generation !== this.controllerGeneration;
9417
+ }
9418
+ },
9419
+ {
9420
+ key: "getMinRemainingMsToRequestAd",
9421
+ value: function getMinRemainingMsToRequestAd() {
9422
+ var configured = this.host.config.minRemainingMsToRequestAd;
9423
+ var floor = this.timing.getMinRemainingMsToStartAd();
9424
+ if (typeof configured === "number" && configured >= 0) {
9425
+ return Math.max(configured, floor);
9426
+ }
9427
+ return Math.max(this.defaultMinRemainingMsToRequestAd, floor);
9428
+ }
9429
+ },
9430
+ {
9431
+ key: "getMaxNoFillsPerBreak",
9432
+ value: function getMaxNoFillsPerBreak() {
9433
+ var configured = this.host.config.maxNoFillsPerBreak;
9434
+ return typeof configured === "number" && configured > 0 ? configured : this.defaultMaxNoFillsPerBreak;
9435
+ }
9436
+ },
9437
+ {
9438
+ key: "isBreakTimeBounded",
9439
+ value: function isBreakTimeBounded() {
9440
+ return this.breakSource === "scte35" || this.timing.expectedAdBreakDurationMs != null;
9441
+ }
9442
+ },
9443
+ {
9444
+ key: "getStopRequestingReason",
9445
+ value: function getStopRequestingReason(remainingMs) {
9446
+ if (this.breakSource === "vmap") {
9447
+ if (this.adPodQueue.length === 0) return "vmap_queue_empty";
9448
+ } else if (this.breakSource !== "scte35" || !this.followUpBaseVastUrl) {
9449
+ return "no_follow_up_source";
9450
+ }
9451
+ if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {
9452
+ return "max_consecutive_failures";
9453
+ }
9454
+ if (this.unusableResponsesInBreak >= this.getMaxNoFillsPerBreak()) {
9455
+ return "unusable_response_limit";
9456
+ }
9457
+ if (this.timing.totalAdRequestsInBreak >= this.timing.maxTotalAdRequestsPerBreak) {
9458
+ return "request_cap";
9459
+ }
9460
+ if (this.timing.isGamInCooldown()) {
9461
+ return "gam_cooldown";
9462
+ }
9463
+ if (this.isBreakTimeBounded() && remainingMs < this.getMinRemainingMsToRequestAd()) {
9464
+ return "insufficient_break_time";
9465
+ }
9466
+ return void 0;
9467
+ }
9468
+ },
9469
+ {
9470
+ key: "getNextRequestDelayMs",
9471
+ value: function getNextRequestDelayMs() {
9472
+ var failures = this.timing.consecutiveFailures;
9473
+ var backoff = failures > 0 ? Math.min(this.timing.backoffBaseMs * Math.pow(2, failures), this.timing.maxBackoffMs) : 0;
9474
+ var minInterval = this.timing.minAdRequestIntervalMs + backoff;
9475
+ var sinceLast = Date.now() - this.timing.lastAdRequestTime;
9476
+ return Math.max(0, minInterval - sinceLast);
9477
+ }
9478
+ },
9479
+ {
9480
+ key: "requestNextAd",
9481
+ value: function requestNextAd(trigger) {
9482
+ var _this = this;
9483
+ if (!this.inAdBreak) return;
9484
+ if (this.slotState !== "NEEDS_NEXT_AD") {
9485
+ this.logOrchestratorFunnel("request_suppressed", {
9486
+ trigger: trigger,
9487
+ state: this.slotState,
9488
+ why: "slot_busy"
9489
+ });
8482
9490
  return;
8483
9491
  }
8484
- if (this.continuousFetchLoopRunning) {
8485
- if (this.debug) {
8486
- console.log("[CONTINUOUS-FETCH] Fetch loop already running, skipping duplicate start");
8487
- }
9492
+ if (this.nextAdTimerId != null) {
9493
+ this.logOrchestratorFunnel("request_suppressed", {
9494
+ trigger: trigger,
9495
+ state: this.slotState,
9496
+ why: "request_already_scheduled"
9497
+ });
8488
9498
  return;
8489
9499
  }
8490
- if (this.debug) {
8491
- console.log("[CONTINUOUS-FETCH] Starting continuous ad fetching loop");
9500
+ var remainingMs = this.timing.getRemainingAdMs();
9501
+ var stopReason = this.getStopRequestingReason(remainingMs);
9502
+ if (stopReason) {
9503
+ this.logOrchestratorFunnel("next_ad_decision", {
9504
+ trigger: trigger,
9505
+ decision: "end_break",
9506
+ reason: stopReason,
9507
+ remainingMs: remainingMs,
9508
+ requestsSent: this.timing.totalAdRequestsInBreak,
9509
+ unusableResponses: this.unusableResponsesInBreak,
9510
+ consecutiveFailures: this.timing.consecutiveFailures
9511
+ });
9512
+ this.handleAdPodComplete(stopReason);
9513
+ return;
9514
+ }
9515
+ var waitMs = this.getNextRequestDelayMs();
9516
+ if (waitMs > 0 && this.isBreakTimeBounded() && remainingMs - waitMs < this.getMinRemainingMsToRequestAd()) {
9517
+ this.logOrchestratorFunnel("next_ad_decision", {
9518
+ trigger: trigger,
9519
+ decision: "end_break",
9520
+ reason: "insufficient_break_time_after_backoff",
9521
+ remainingMs: remainingMs,
9522
+ waitMs: waitMs
9523
+ });
9524
+ this.handleAdPodComplete("insufficient_break_time_after_backoff");
9525
+ return;
9526
+ }
9527
+ this.logOrchestratorFunnel("next_ad_decision", {
9528
+ trigger: trigger,
9529
+ decision: waitMs > 0 ? "request_after_delay" : "request_now",
9530
+ waitMs: waitMs,
9531
+ remainingMs: remainingMs,
9532
+ consecutiveFailures: this.timing.consecutiveFailures
9533
+ });
9534
+ if (waitMs > 0) {
9535
+ if (!this.isShowingPlaceholder) {
9536
+ this.isShowingPlaceholder = true;
9537
+ this.host.getAdPlayer().showPlaceholder();
9538
+ }
9539
+ var epoch = this.timing.adBreakEpoch;
9540
+ this.nextAdTimerId = window.setTimeout(function() {
9541
+ _this.nextAdTimerId = void 0;
9542
+ if (!_this.inAdBreak || epoch !== _this.timing.adBreakEpoch) return;
9543
+ _this.requestNextAd("".concat(trigger, ":after_delay"));
9544
+ }, waitMs);
9545
+ return;
8492
9546
  }
8493
- this.continuousFetchLoopRunning = true;
8494
- this.continuousFetchLoop(baseVastUrl);
9547
+ void this.requestFollowUpAd(trigger);
8495
9548
  }
8496
9549
  },
8497
9550
  {
8498
- key: "continuousFetchLoop",
8499
- value: function continuousFetchLoop(baseVastUrl) {
9551
+ key: "requestFollowUpAd",
9552
+ value: function requestFollowUpAd(trigger) {
8500
9553
  return _async_to_generator(function() {
8501
- var _this, _loop, epoch, _ret;
9554
+ var url, epoch, unused;
8502
9555
  return _ts_generator(this, function(_state) {
8503
9556
  switch(_state.label){
8504
9557
  case 0:
8505
- _loop = function() {
8506
- var remaining, maxQueueSize, newAdUrl, queuedUrlsPreview, generationDelay;
8507
- return _ts_generator(this, function(_state) {
8508
- switch(_state.label){
8509
- case 0:
8510
- remaining = Math.min(_this.timing.getWallClockRemainingAdMs(), _this.timing.getDurationBudgetRemainingMs());
8511
- if (remaining <= _this.timing.getMinRemainingMsToStartAd()) {
8512
- if (_this.debug) {
8513
- console.log("[CONTINUOUS-FETCH] Not enough ad break time left (wall=".concat(_this.timing.getWallClockRemainingAdMs(), "ms, budget=").concat(_this.timing.getDurationBudgetRemainingMs(), "ms), stopping URL generation"));
8514
- }
8515
- return [
8516
- 2,
8517
- "break"
8518
- ];
8519
- }
8520
- if (_this.timing.isGamInCooldown()) {
8521
- if (_this.debug) {
8522
- console.log("[CIRCUIT-BREAKER] GAM in cooldown, stopping URL generation");
8523
- }
8524
- return [
8525
- 2,
8526
- "break"
8527
- ];
8528
- }
8529
- if (_this.timing.consecutiveFailures >= _this.timing.maxConsecutiveFailures) {
8530
- if (_this.debug) {
8531
- console.log("[CONTINUOUS-FETCH] Too many consecutive failures (".concat(_this.timing.consecutiveFailures, "), stopping URL generation"));
8532
- }
8533
- return [
8534
- 2,
8535
- "break"
8536
- ];
8537
- }
8538
- if (_this.timing.totalAdRequestsInBreak >= _this.timing.maxTotalAdRequestsPerBreak) {
8539
- if (_this.debug) {
8540
- console.log("[CONTINUOUS-FETCH] Maximum ad requests reached (".concat(_this.timing.maxTotalAdRequestsPerBreak, "), stopping"));
8541
- }
8542
- return [
8543
- 2,
8544
- "break"
8545
- ];
8546
- }
8547
- maxQueueSize = 5;
8548
- if (!(_this.adRequestQueue.length >= maxQueueSize)) return [
8549
- 3,
8550
- 2
8551
- ];
8552
- if (_this.debug) {
8553
- console.log("[CONTINUOUS-FETCH] URL queue full (".concat(_this.adRequestQueue.length, "), waiting..."));
8554
- }
8555
- return [
8556
- 4,
8557
- new Promise(function(resolve) {
8558
- return setTimeout(resolve, 1e3);
8559
- })
8560
- ];
8561
- case 1:
8562
- _state.sent();
8563
- return [
8564
- 2,
8565
- "continue"
8566
- ];
8567
- case 2:
8568
- newAdUrl = _this.nextAdRequestUrl(baseVastUrl);
8569
- if (!(!newAdUrl || _this.timing.failedVastUrls.has(newAdUrl) || _this.timing.isUrlInCooldown(newAdUrl))) return [
8570
- 3,
8571
- 4
8572
- ];
8573
- return [
8574
- 4,
8575
- new Promise(function(resolve) {
8576
- return setTimeout(resolve, 500);
8577
- })
8578
- ];
8579
- case 3:
8580
- _state.sent();
8581
- return [
8582
- 2,
8583
- "continue"
8584
- ];
8585
- case 4:
8586
- if (_this.debug) {
8587
- queuedUrlsPreview = _to_consumable_array(_this.adRequestQueue).concat([
8588
- newAdUrl
8589
- ]);
8590
- console.log("[CONTINUOUS-FETCH] Queued VAST URL (queue size: ".concat(queuedUrlsPreview.length, ")"), {
8591
- queuedUrls: queuedUrlsPreview
8592
- });
8593
- }
8594
- _this.adRequestQueue.push(newAdUrl);
8595
- generationDelay = _this.timing.consecutiveFailures > 0 ? Math.min(1e3 * Math.pow(2, _this.timing.consecutiveFailures), 5e3) : 500;
8596
- return [
8597
- 4,
8598
- new Promise(function(resolve) {
8599
- return setTimeout(resolve, generationDelay);
8600
- })
8601
- ];
8602
- case 5:
8603
- _state.sent();
8604
- return [
8605
- 2
8606
- ];
8607
- }
8608
- });
8609
- };
9558
+ if (this.breakSource === "vmap") {
9559
+ url = this.adPodQueue.shift();
9560
+ } else if (this.followUpBaseVastUrl) {
9561
+ url = this.nextAdRequestUrl(this.followUpBaseVastUrl);
9562
+ }
9563
+ if (!url) return [
9564
+ 2
9565
+ ];
9566
+ this.noteVastUrlGenerated(ensureVideoAdType(url), trigger);
8610
9567
  epoch = this.timing.adBreakEpoch;
8611
9568
  _state.label = 1;
8612
9569
  case 1:
8613
- if (!(this.continuousFetchingActive && this.inAdBreak && epoch === this.timing.adBreakEpoch)) return [
9570
+ _state.trys.push([
9571
+ 1,
8614
9572
  3,
8615
- 3
8616
- ];
8617
- _this = this;
8618
- return [
8619
- 5,
8620
- _ts_values(_loop())
9573
+ ,
9574
+ 4
9575
+ ]);
9576
+ return [
9577
+ 4,
9578
+ this.playSingleAd(url, trigger)
8621
9579
  ];
8622
9580
  case 2:
8623
- _ret = _state.sent();
8624
- if (_ret === "break") return [
9581
+ _state.sent();
9582
+ return [
8625
9583
  3,
8626
- 3
9584
+ 4
8627
9585
  ];
9586
+ case 3:
9587
+ unused = _state.sent();
9588
+ this.continueAfterRequestFailure(epoch);
8628
9589
  return [
8629
9590
  3,
8630
- 1
9591
+ 4
8631
9592
  ];
8632
- case 3:
8633
- this.continuousFetchLoopRunning = false;
8634
- if (this.debug) {
8635
- console.log("[CONTINUOUS-FETCH] URL generation loop ended (queued: ".concat(this.adRequestQueue.length, ")"), this.adRequestQueue.length > 0 ? {
8636
- queuedUrls: _to_consumable_array(this.adRequestQueue)
8637
- } : {});
8638
- }
9593
+ case 4:
8639
9594
  return [
8640
9595
  2
8641
9596
  ];
@@ -8645,236 +9600,318 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8645
9600
  }
8646
9601
  },
8647
9602
  {
8648
- key: "stopContinuousFetching",
8649
- value: function stopContinuousFetching() {
8650
- this.continuousFetchingActive = false;
8651
- this.continuousFetchLoopRunning = false;
8652
- this.placeholder.hide();
8653
- if (this.debug) {
8654
- console.log("[CONTINUOUS-FETCH] Stopping continuous ad fetching");
9603
+ key: "continueAfterRequestFailure",
9604
+ value: function continueAfterRequestFailure() {
9605
+ var epoch = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : this.timing.adBreakEpoch;
9606
+ if (!this.inAdBreak || epoch !== this.timing.adBreakEpoch) return;
9607
+ this.setSlotState("NEEDS_NEXT_AD", "request_failed");
9608
+ this.requestNextAd("after_failure");
9609
+ }
9610
+ },
9611
+ {
9612
+ key: "cancelScheduledRequest",
9613
+ value: function cancelScheduledRequest() {
9614
+ if (this.nextAdTimerId != null) {
9615
+ clearTimeout(this.nextAdTimerId);
9616
+ this.nextAdTimerId = void 0;
8655
9617
  }
8656
9618
  }
8657
9619
  },
8658
9620
  {
8659
- key: "tryNextAvailableAdWithRateLimit",
8660
- value: // ───────────────────────────────────────────────────────────────
8661
- // Ad iteration
9621
+ key: "noteVastUrlGenerated",
9622
+ value: function noteVastUrlGenerated(url, source) {
9623
+ var _ref, _ref1, _ref2, _ref3, _ref4;
9624
+ var params;
9625
+ try {
9626
+ params = new URL(url).searchParams;
9627
+ } catch (unused) {}
9628
+ var adType = (_ref = params === null || params === void 0 ? void 0 : params.get("ad_type")) !== null && _ref !== void 0 ? _ref : void 0;
9629
+ this.logOrchestratorFunnel("vast_url_generated", {
9630
+ source: source,
9631
+ pod: (_ref1 = params === null || params === void 0 ? void 0 : params.get("pod")) !== null && _ref1 !== void 0 ? _ref1 : void 0,
9632
+ pmad: (_ref2 = params === null || params === void 0 ? void 0 : params.get("pmad")) !== null && _ref2 !== void 0 ? _ref2 : void 0,
9633
+ pmnd: (_ref3 = params === null || params === void 0 ? void 0 : params.get("pmnd")) !== null && _ref3 !== void 0 ? _ref3 : void 0,
9634
+ pmxd: (_ref4 = params === null || params === void 0 ? void 0 : params.get("pmxd")) !== null && _ref4 !== void 0 ? _ref4 : void 0,
9635
+ adType: adType
9636
+ });
9637
+ if (adType === "audio" || adType === "audio_video") {
9638
+ console.warn("[AdBreak] VAST tag requests ad_type=".concat(adType, "; GAM may return audio-only creatives, which this video player rejects"));
9639
+ this.countFunnelStage("tag_allows_audio");
9640
+ }
9641
+ }
9642
+ },
9643
+ {
9644
+ key: "recordRequestFailure",
9645
+ value: function recordRequestFailure(error, vastTagUrl) {
9646
+ var _diag_vastAdCount;
9647
+ var diag = this.currentRequestId != null ? this.requestDiagnostics.get(this.currentRequestId) : void 0;
9648
+ var message = (error === null || error === void 0 ? void 0 : error.message) || "";
9649
+ var outcome;
9650
+ if (message.includes("ad_duration_exceeds_budget")) {
9651
+ outcome = "discarded_budget";
9652
+ } else if (message.includes("VAST fill rejected")) {
9653
+ outcome = "fill_rejected";
9654
+ } else if (/no ads available|no fill|nofill/i.test(message)) {
9655
+ outcome = "no_fill";
9656
+ } else if (/timeout/i.test(message)) {
9657
+ outcome = "request_timeout";
9658
+ } else if (/destroyed|aborted/i.test(message)) {
9659
+ outcome = "request_aborted";
9660
+ } else if (diag && ((_diag_vastAdCount = diag.vastAdCount) !== null && _diag_vastAdCount !== void 0 ? _diag_vastAdCount : 0) > 0 && !diag.impressionFired) {
9661
+ outcome = "playback_failed";
9662
+ } else {
9663
+ outcome = "request_failed";
9664
+ }
9665
+ this.timing.consecutiveFailures++;
9666
+ if (outcome === "no_fill" || outcome === "fill_rejected" || outcome === "discarded_budget") {
9667
+ this.unusableResponsesInBreak++;
9668
+ }
9669
+ if (outcome === "no_fill") {
9670
+ this.timing.recordGamNoFill();
9671
+ }
9672
+ if (diag && !diag.failureReason) {
9673
+ diag.failureReason = "".concat(outcome, ": ").concat(message);
9674
+ }
9675
+ if (this.timing.isTemporaryAdError(error)) {
9676
+ this.timing.temporaryFailureUrls.set(vastTagUrl, Date.now());
9677
+ } else if (outcome !== "discarded_budget") {
9678
+ this.timing.failedVastUrls.add(vastTagUrl);
9679
+ }
9680
+ this.countFunnelStage("request_outcome:".concat(outcome));
9681
+ this.logOrchestratorFunnel("request_outcome", {
9682
+ outcome: outcome,
9683
+ errorMessage: message,
9684
+ consecutiveFailures: this.timing.consecutiveFailures,
9685
+ unusableResponsesInBreak: this.unusableResponsesInBreak
9686
+ });
9687
+ }
9688
+ },
9689
+ {
8662
9690
  // ───────────────────────────────────────────────────────────────
8663
- function tryNextAvailableAdWithRateLimit() {
8664
- return _async_to_generator(function() {
8665
- var epoch, backoffMultiplier, backoffDelay, effectiveMinInterval, timeSinceLastRequest, waitTime;
8666
- return _ts_generator(this, function(_state) {
8667
- switch(_state.label){
8668
- case 0:
8669
- if (!this.inAdBreak) {
8670
- return [
8671
- 2
8672
- ];
8673
- }
8674
- epoch = this.timing.adBreakEpoch;
8675
- if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {
8676
- if (this.debug) {
8677
- console.log("[CONTINUOUS-FETCH] Too many consecutive failures (".concat(this.timing.consecutiveFailures, "), ending ad break gracefully"));
8678
- }
8679
- this.handleAdPodComplete();
8680
- return [
8681
- 2
8682
- ];
8683
- }
8684
- backoffMultiplier = Math.pow(2, this.timing.consecutiveFailures);
8685
- backoffDelay = Math.min(this.timing.backoffBaseMs * backoffMultiplier, this.timing.maxBackoffMs);
8686
- effectiveMinInterval = this.timing.minAdRequestIntervalMs + (this.timing.consecutiveFailures > 0 ? backoffDelay : 0);
8687
- timeSinceLastRequest = Date.now() - this.timing.lastAdRequestTime;
8688
- if (!(timeSinceLastRequest < effectiveMinInterval)) return [
8689
- 3,
8690
- 2
8691
- ];
8692
- waitTime = effectiveMinInterval - timeSinceLastRequest;
8693
- if (this.debug) {
8694
- console.log("[CONTINUOUS-FETCH] Rate limiting: waiting ".concat(waitTime, "ms before next request (backoff: ").concat(this.timing.consecutiveFailures, " failures)"));
8695
- }
8696
- return [
8697
- 4,
8698
- new Promise(function(resolve) {
8699
- return setTimeout(resolve, waitTime);
8700
- })
8701
- ];
8702
- case 1:
8703
- _state.sent();
8704
- _state.label = 2;
8705
- case 2:
8706
- if (!this.inAdBreak || epoch !== this.timing.adBreakEpoch) {
8707
- return [
8708
- 2
8709
- ];
8710
- }
8711
- return [
8712
- 2,
8713
- this.tryNextAvailableAd(0)
8714
- ];
9691
+ // Per-request diagnostics
9692
+ // ───────────────────────────────────────────────────────────────
9693
+ key: "recordRequestDiagnostic",
9694
+ value: function recordRequestDiagnostic(payload) {
9695
+ var requestId = payload.requestId;
9696
+ if (typeof requestId !== "number") return;
9697
+ var diag = this.requestDiagnostics.get(requestId);
9698
+ if (!diag) return;
9699
+ switch(payload.stage){
9700
+ case "gam_http_request_sent":
9701
+ diag.gamRequestSent++;
9702
+ break;
9703
+ case "gam_response_received":
9704
+ diag.vastHttpStatus = payload.httpStatus;
9705
+ break;
9706
+ case "vast_parsed":
9707
+ diag.vastAdCount = payload.adElementCount;
9708
+ break;
9709
+ case "wrapper_fetch":
9710
+ case "inline_resolved":
9711
+ if (typeof payload.depth === "number") {
9712
+ diag.wrapperDepth = Math.max(diag.wrapperDepth, payload.depth);
8715
9713
  }
9714
+ if (payload.stage === "inline_resolved") diag.inlineResolved = true;
9715
+ break;
9716
+ case "mediafile_evaluated":
9717
+ diag.mediaCandidateCount++;
9718
+ if (payload.whyAccepted) diag.supportedMediaCount++;
9719
+ break;
9720
+ case "playing":
9721
+ diag.playStarted = true;
9722
+ break;
9723
+ case "impression_fired":
9724
+ diag.impressionFired = true;
9725
+ break;
9726
+ default:
9727
+ if (REQUEST_FAILURE_STAGES.has(payload.stage) && !diag.failureReason) {
9728
+ diag.failureReason = payload.reason ? "".concat(payload.stage, ":").concat(payload.reason) : payload.stage;
9729
+ }
9730
+ }
9731
+ }
9732
+ },
9733
+ {
9734
+ key: "finalizeRequestDiagnostics",
9735
+ value: function finalizeRequestDiagnostics(requestId, endReason) {
9736
+ var _diag_vastAdCount;
9737
+ if (requestId == null) return;
9738
+ var diag = this.requestDiagnostics.get(requestId);
9739
+ if (!diag) return;
9740
+ this.requestDiagnostics.delete(requestId);
9741
+ if (!diag.impressionFired && !diag.failureReason && endReason) {
9742
+ diag.failureReason = endReason;
9743
+ }
9744
+ var gamReturnedAdWithoutImpression = ((_diag_vastAdCount = diag.vastAdCount) !== null && _diag_vastAdCount !== void 0 ? _diag_vastAdCount : 0) > 0 && !diag.impressionFired;
9745
+ if (gamReturnedAdWithoutImpression) {
9746
+ this.countFunnelStage("gam_ad_without_impression");
9747
+ }
9748
+ var startedAt = diag.startedAt, fields = _object_without_properties(diag, [
9749
+ "startedAt"
9750
+ ]);
9751
+ console.log("[AdBreak][REQUEST] summary", _object_spread_props(_object_spread({}, fields), {
9752
+ durationMs: Date.now() - startedAt,
9753
+ gamReturnedAdWithoutImpression: gamReturnedAdWithoutImpression
9754
+ }));
9755
+ }
9756
+ },
9757
+ {
9758
+ // ───────────────────────────────────────────────────────────────
9759
+ // Single ad playback
9760
+ // ───────────────────────────────────────────────────────────────
9761
+ key: "withCurrentPodBudget",
9762
+ value: function withCurrentPodBudget(rawVastTagUrl) {
9763
+ var vastTagUrl = ensureVideoAdType(rawVastTagUrl);
9764
+ var remaining = Math.min(this.timing.getWallClockRemainingAdMs(), this.timing.getDurationBudgetRemainingMs());
9765
+ if (!(remaining > 0)) return vastTagUrl;
9766
+ try {
9767
+ var url = new URL(vastTagUrl);
9768
+ if (!url.searchParams.has("pmxd")) return vastTagUrl;
9769
+ var maxMs = Math.round(remaining);
9770
+ url.searchParams.set("pmxd", String(maxMs));
9771
+ var minMs = Number(url.searchParams.get("pmnd"));
9772
+ if (Number.isFinite(minMs) && minMs > maxMs) {
9773
+ url.searchParams.set("pmnd", String(maxMs));
9774
+ }
9775
+ return url.toString();
9776
+ } catch (unused) {
9777
+ return vastTagUrl;
9778
+ }
9779
+ }
9780
+ },
9781
+ {
9782
+ key: "countFunnelStage",
9783
+ value: function countFunnelStage(stage) {
9784
+ var amount = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 1;
9785
+ var _this_breakFunnel_stage;
9786
+ this.breakFunnel[stage] = ((_this_breakFunnel_stage = this.breakFunnel[stage]) !== null && _this_breakFunnel_stage !== void 0 ? _this_breakFunnel_stage : 0) + amount;
9787
+ }
9788
+ },
9789
+ {
9790
+ key: "logOrchestratorFunnel",
9791
+ value: function logOrchestratorFunnel(stage) {
9792
+ var extra = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
9793
+ this.countFunnelStage(stage);
9794
+ console.log("[AdBreak][FUNNEL] ".concat(stage), _object_spread({
9795
+ breakId: this.timing.adBreakEpoch,
9796
+ requestId: this.currentRequestId,
9797
+ visibilityState: typeof document !== "undefined" ? document.visibilityState : void 0
9798
+ }, extra));
9799
+ }
9800
+ },
9801
+ {
9802
+ key: "noteOpportunity",
9803
+ value: function noteOpportunity(source, breakKey) {
9804
+ if (breakKey && breakKey === this.opportunityBreakKey && this.opportunityEpoch === this.timing.adBreakEpoch) {
9805
+ this.logOrchestratorFunnel("duplicate_break_start", {
9806
+ source: source,
9807
+ breakKey: breakKey
8716
9808
  });
8717
- }).call(this);
9809
+ return;
9810
+ }
9811
+ this.opportunityBreakKey = breakKey;
9812
+ this.opportunityEpoch = this.timing.adBreakEpoch;
9813
+ this.logOrchestratorFunnel("opportunity_created", {
9814
+ source: source,
9815
+ breakKey: breakKey,
9816
+ expectedDurationMs: this.timing.expectedAdBreakDurationMs
9817
+ });
9818
+ }
9819
+ },
9820
+ {
9821
+ key: "beginFunnelRequest",
9822
+ value: function beginFunnelRequest(adPlayer, requestToken, trigger) {
9823
+ var _adPlayer_setFunnelContext;
9824
+ if (this.controllerCallInFlight) {
9825
+ this.logOrchestratorFunnel("duplicate_request_detected", {
9826
+ newRequestId: requestToken
9827
+ });
9828
+ }
9829
+ this.finalizeRequestDiagnostics(this.currentRequestId);
9830
+ this.currentRequestId = requestToken;
9831
+ this.requestStartedAt = Date.now();
9832
+ this.requestDiagnostics.set(requestToken, {
9833
+ breakId: this.timing.adBreakEpoch,
9834
+ requestId: requestToken,
9835
+ controllerId: this.controllerGeneration,
9836
+ trigger: trigger,
9837
+ gamRequestSent: 0,
9838
+ wrapperDepth: 0,
9839
+ inlineResolved: false,
9840
+ mediaCandidateCount: 0,
9841
+ supportedMediaCount: 0,
9842
+ playStarted: false,
9843
+ impressionFired: false,
9844
+ startedAt: Date.now()
9845
+ });
9846
+ (_adPlayer_setFunnelContext = adPlayer.setFunnelContext) === null || _adPlayer_setFunnelContext === void 0 ? void 0 : _adPlayer_setFunnelContext.call(adPlayer, {
9847
+ breakId: this.timing.adBreakEpoch,
9848
+ requestId: requestToken,
9849
+ controllerId: this.controllerGeneration
9850
+ });
9851
+ }
9852
+ },
9853
+ {
9854
+ key: "isAdLoadingWithoutPlayback",
9855
+ value: function isAdLoadingWithoutPlayback() {
9856
+ return this.host.getAdPlayer().isAdPlaying() && !this.playbackStartedForCurrentRequest;
9857
+ }
9858
+ },
9859
+ {
9860
+ key: "noteStopBeforeStart",
9861
+ value: function noteStopBeforeStart(reason) {
9862
+ if (!this.isAdLoadingWithoutPlayback()) return;
9863
+ this.logOrchestratorFunnel("ad_stopped_before_start", {
9864
+ reason: reason,
9865
+ elapsedSinceRequestMs: this.requestStartedAt != null ? Date.now() - this.requestStartedAt : void 0
9866
+ });
9867
+ }
9868
+ },
9869
+ {
9870
+ key: "handleRequestWatchdogTimeout",
9871
+ value: function handleRequestWatchdogTimeout() {
9872
+ var adPlayer = this.host.getAdPlayer();
9873
+ if (this.controllerCallInFlight && adPlayer.abortPendingRequest) {
9874
+ this.logOrchestratorFunnel("request_aborted_timeout", {
9875
+ elapsedSinceRequestMs: this.requestStartedAt != null ? Date.now() - this.requestStartedAt : void 0
9876
+ });
9877
+ adPlayer.abortPendingRequest("VAST request aborted after request watchdog timeout");
9878
+ return;
9879
+ }
9880
+ this.handleAdFailure("request_watchdog_timeout");
8718
9881
  }
8719
9882
  },
8720
9883
  {
8721
- key: "tryNextAvailableAd",
8722
- value: function tryNextAvailableAd() {
8723
- var retryCount = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : 0;
9884
+ key: "callController",
9885
+ value: function callController(call) {
8724
9886
  return _async_to_generator(function() {
8725
- var remaining, nextAdUrl, error, errorMessage, maxRetries;
8726
9887
  return _ts_generator(this, function(_state) {
8727
9888
  switch(_state.label){
8728
9889
  case 0:
8729
- if (!this.inAdBreak) {
8730
- return [
8731
- 2
8732
- ];
8733
- }
8734
- remaining = this.timing.getRemainingAdMs();
8735
- if (!this.timing.hasTimeToStartAnotherAd()) {
8736
- if (this.debug) {
8737
- console.log("[CONTINUOUS-FETCH] Not enough time remaining (".concat(remaining, "ms) to start another ad, ending ad break"));
8738
- }
8739
- this.handleAdPodComplete();
8740
- return [
8741
- 2
8742
- ];
8743
- }
8744
- if (this.timing.isGamInCooldown()) {
8745
- if (this.debug) {
8746
- console.log("[CIRCUIT-BREAKER] GAM in cooldown, ending ad break gracefully");
8747
- }
8748
- this.handleAdPodComplete();
8749
- return [
8750
- 2
8751
- ];
8752
- }
8753
- if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {
8754
- if (this.debug) {
8755
- console.log("[CONTINUOUS-FETCH] Too many consecutive failures (".concat(this.timing.consecutiveFailures, "), ending ad break"));
8756
- }
8757
- this.handleAdPodComplete();
8758
- return [
8759
- 2
8760
- ];
8761
- }
8762
- this.timing.cleanupTemporaryFailures();
9890
+ this.controllerCallInFlight = true;
8763
9891
  _state.label = 1;
8764
9892
  case 1:
8765
- if (!(this.adRequestQueue.length > 0)) return [
8766
- 3,
8767
- 9
8768
- ];
8769
- nextAdUrl = this.adRequestQueue.shift();
8770
- if (!nextAdUrl) return [
8771
- 3,
8772
- 1
8773
- ];
8774
- if (this.timing.failedVastUrls.has(nextAdUrl)) {
8775
- if (this.debug) console.log("[CONTINUOUS-FETCH] Skipping permanently-failed URL, trying next...");
8776
- return [
8777
- 3,
8778
- 1
8779
- ];
8780
- }
8781
- if (this.timing.isUrlInCooldown(nextAdUrl)) {
8782
- if (this.debug) console.log("[CONTINUOUS-FETCH] Skipping URL in cooldown (recent no-fill), trying next...");
8783
- return [
8784
- 3,
8785
- 1
8786
- ];
8787
- }
8788
- if (this.debug) {
8789
- console.log("[CONTINUOUS-FETCH] Requesting next ad via HLS ad player (".concat(this.timing.currentAdIndex + 1, ", ").concat(this.adRequestQueue.length, " remaining in queue)"));
8790
- }
8791
- _state.label = 2;
8792
- case 2:
8793
9893
  _state.trys.push([
8794
- 2,
8795
- 4,
9894
+ 1,
8796
9895
  ,
8797
- 8
8798
- ]);
8799
- return [
8800
- 4,
8801
- this.playSingleAd(nextAdUrl)
8802
- ];
8803
- case 3:
8804
- _state.sent();
8805
- this.timing.consecutiveFailures = 0;
8806
- return [
8807
9896
  3,
8808
- 8
8809
- ];
8810
- case 4:
8811
- error = _state.sent();
8812
- errorMessage = error.message;
8813
- if (this.debug) console.log("[CONTINUOUS-FETCH] Ad request failed:", errorMessage);
8814
- if (!errorMessage.includes("ad_duration_exceeds_budget")) return [
8815
- 3,
8816
- 6
8817
- ];
8818
- return [
8819
- 4,
8820
- this.tryNextAvailableAdWithRateLimit()
8821
- ];
8822
- case 5:
8823
- _state.sent();
8824
- return [
8825
- 2
8826
- ];
8827
- case 6:
8828
- if (!errorMessage.includes("permanently failed") && !errorMessage.includes("in cooldown")) {
8829
- this.timing.consecutiveFailures++;
8830
- }
9897
+ 4
9898
+ ]);
8831
9899
  return [
8832
9900
  4,
8833
- this.tryNextAvailableAdWithRateLimit()
9901
+ call()
8834
9902
  ];
8835
- case 7:
9903
+ case 2:
8836
9904
  _state.sent();
8837
9905
  return [
8838
9906
  3,
8839
- 8
8840
- ];
8841
- case 8:
8842
- return [
8843
- 2
8844
- ];
8845
- case 9:
8846
- maxRetries = 3;
8847
- if (!(this.continuousFetchingActive && retryCount < maxRetries && remaining > 2e3)) return [
8848
- 3,
8849
- 12
8850
- ];
8851
- if (this.debug) {
8852
- console.log("[CONTINUOUS-FETCH] Queue empty, waiting for URLs... (".concat(retryCount + 1, "/").concat(maxRetries, ")"));
8853
- }
8854
- return [
8855
- 4,
8856
- new Promise(function(resolve) {
8857
- return setTimeout(resolve, 500);
8858
- })
8859
- ];
8860
- case 10:
8861
- _state.sent();
8862
- return [
8863
- 4,
8864
- this.tryNextAvailableAd(retryCount + 1)
9907
+ 4
8865
9908
  ];
8866
- case 11:
8867
- _state.sent();
9909
+ case 3:
9910
+ this.controllerCallInFlight = false;
8868
9911
  return [
8869
- 2
9912
+ 7
8870
9913
  ];
8871
- case 12:
8872
- if (!this.isShowingPlaceholder && remaining > 1e3) {
8873
- this.showPlaceholderAndWaitForAds();
8874
- } else {
8875
- if (this.debug) console.log("[CONTINUOUS-FETCH] No more ads available, ending ad break");
8876
- this.handleAdPodComplete();
8877
- }
9914
+ case 4:
8878
9915
  return [
8879
9916
  2
8880
9917
  ];
@@ -8883,47 +9920,33 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8883
9920
  }).call(this);
8884
9921
  }
8885
9922
  },
8886
- {
8887
- // ───────────────────────────────────────────────────────────────
8888
- // Single ad playback
8889
- // ───────────────────────────────────────────────────────────────
8890
- key: "withCurrentPodBudget",
8891
- value: function withCurrentPodBudget(vastTagUrl) {
8892
- var remaining = Math.min(this.timing.getWallClockRemainingAdMs(), this.timing.getDurationBudgetRemainingMs());
8893
- if (!(remaining > 0)) return vastTagUrl;
8894
- try {
8895
- var url = new URL(vastTagUrl);
8896
- if (!url.searchParams.has("pmxd")) return vastTagUrl;
8897
- var maxMs = Math.round(remaining);
8898
- url.searchParams.set("pmxd", String(maxMs));
8899
- var minMs = Number(url.searchParams.get("pmnd"));
8900
- if (Number.isFinite(minMs) && minMs > maxMs) {
8901
- url.searchParams.set("pmnd", String(maxMs));
8902
- }
8903
- return url.toString();
8904
- } catch (unused) {
8905
- return vastTagUrl;
8906
- }
8907
- }
8908
- },
8909
9923
  {
8910
9924
  key: "playSingleAd",
8911
9925
  value: function playSingleAd(vastTagUrl) {
9926
+ var trigger = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : "vmap";
8912
9927
  return _async_to_generator(function() {
8913
- var adPlayer, requestToken, ap, requestUrl, playError, error, errorMessage;
9928
+ var epoch, generation, requestToken, ap, requestUrl, _ap_getLoadedAdDuration, adDurationS, remainingMs, error;
8914
9929
  return _ts_generator(this, function(_state) {
8915
9930
  switch(_state.label){
8916
9931
  case 0:
8917
- adPlayer = this.host.getAdPlayer();
8918
- if (adPlayer.isAdPlaying()) return [
8919
- 2
8920
- ];
9932
+ if (this.slotState === "REQUESTING" || this.slotState === "READY" || this.slotState === "PLAYING" || this.slotState === "ENDING") {
9933
+ this.logOrchestratorFunnel("request_suppressed", {
9934
+ trigger: trigger,
9935
+ state: this.slotState,
9936
+ why: "request_in_flight"
9937
+ });
9938
+ return [
9939
+ 2
9940
+ ];
9941
+ }
8921
9942
  if (this.timing.failedVastUrls.has(vastTagUrl)) {
8922
9943
  if (this.debug) console.warn("[AD-ERROR] Skipping permanently-failed VAST URL:", vastTagUrl);
9944
+ this.timing.consecutiveFailures++;
8923
9945
  throw new Error("VAST URL permanently failed");
8924
9946
  }
8925
9947
  if (this.timing.isUrlInCooldown(vastTagUrl)) {
8926
9948
  if (this.debug) console.warn("[AD-ERROR] Skipping URL in cooldown (recent no-fill):", vastTagUrl);
9949
+ this.timing.consecutiveFailures++;
8927
9950
  throw new Error("VAST URL in cooldown after no-fill");
8928
9951
  }
8929
9952
  if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {
@@ -8934,16 +9957,23 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8934
9957
  if (this.debug) console.warn("[CIRCUIT-BREAKER] GAM in cooldown, skipping ad request");
8935
9958
  throw new Error("GAM in cooldown");
8936
9959
  }
8937
- this.recreateAdController();
9960
+ epoch = this.timing.adBreakEpoch;
9961
+ this.recreateAdController("new_request");
9962
+ generation = this.controllerGeneration;
8938
9963
  requestToken = ++this.timing.adRequestTokenCounter;
8939
9964
  this.timing.activeAdRequestToken = requestToken;
9965
+ ap = this.host.getAdPlayer();
9966
+ requestUrl = this.withCurrentPodBudget(vastTagUrl);
9967
+ this.currentVastUrl = requestUrl;
9968
+ this.setSlotState("REQUESTING", trigger);
9969
+ this.beginFunnelRequest(ap, requestToken, trigger);
8940
9970
  _state.label = 1;
8941
9971
  case 1:
8942
9972
  _state.trys.push([
8943
9973
  1,
8944
- 8,
9974
+ 5,
8945
9975
  ,
8946
- 9
9976
+ 6
8947
9977
  ]);
8948
9978
  return [
8949
9979
  4,
@@ -8951,265 +9981,87 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
8951
9981
  ];
8952
9982
  case 2:
8953
9983
  _state.sent();
9984
+ if (this.isStale(epoch, generation)) return [
9985
+ 2
9986
+ ];
8954
9987
  this.timing.startAdRequestWatchdog(requestToken);
8955
- this.timing.lastAdRequestTime = Date.now();
8956
- ap = this.host.getAdPlayer();
8957
- requestUrl = this.withCurrentPodBudget(vastTagUrl);
8958
- this.currentVastUrl = requestUrl;
8959
9988
  return [
8960
9989
  4,
8961
- ap.requestAds(requestUrl)
9990
+ this.callController(function() {
9991
+ return ap.requestAds(requestUrl);
9992
+ })
8962
9993
  ];
8963
9994
  case 3:
8964
9995
  _state.sent();
9996
+ this.timing.clearAdRequestWatchdog();
9997
+ if (this.isStale(epoch, generation)) {
9998
+ this.logOrchestratorFunnel("stale_request_result_ignored", {
9999
+ requestId: requestToken
10000
+ });
10001
+ return [
10002
+ 2
10003
+ ];
10004
+ }
8965
10005
  sendAdLoadedTracking(this.host.config.licenseKey, {
8966
10006
  source: "hls",
8967
10007
  vastUrl: requestUrl,
8968
10008
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
8969
10009
  }, this.analyticsContext).catch(function() {});
8970
- this.timing.clearAdRequestWatchdog();
8971
- if (this.timing.activeAdRequestToken !== requestToken) return [
8972
- 2
8973
- ];
8974
10010
  if (!this.timing.ensureLoadedAdFitsBudget(ap)) {
8975
- this.timing.rejectLoadedAdForDuration(ap);
8976
- this.recreateAdController();
10011
+ ;
10012
+ adDurationS = (_ap_getLoadedAdDuration = ap.getLoadedAdDuration) === null || _ap_getLoadedAdDuration === void 0 ? void 0 : _ap_getLoadedAdDuration.call(ap);
10013
+ remainingMs = Math.min(this.timing.getWallClockRemainingAdMs(), this.timing.getDurationBudgetRemainingMs());
10014
+ this.logOrchestratorFunnel("discarded_budget", {
10015
+ adDurationMs: adDurationS != null ? adDurationS * 1e3 : void 0,
10016
+ remainingMs: remainingMs
10017
+ });
8977
10018
  throw new Error("ad_duration_exceeds_budget");
8978
10019
  }
8979
- _state.label = 4;
8980
- case 4:
8981
- _state.trys.push([
8982
- 4,
8983
- 6,
8984
- ,
8985
- 7
8986
- ]);
10020
+ this.setSlotState("READY", "vast_ready");
8987
10021
  this.timing.startAdFailsafeTimer(requestToken);
8988
10022
  return [
8989
10023
  4,
8990
- ap.play()
10024
+ this.callController(function() {
10025
+ return ap.play();
10026
+ })
8991
10027
  ];
8992
- case 5:
10028
+ case 4:
8993
10029
  _state.sent();
8994
- this.timing.markAdStarted();
10030
+ if (this.isStale(epoch, generation)) return [
10031
+ 2
10032
+ ];
8995
10033
  if (this.timing.expectedAdBreakDurationMs != null && this.timing.getAdBreakEndWallClockMs() == null) {
8996
10034
  this.timing.scheduleAdStopAtBreakBoundary();
8997
10035
  }
8998
10036
  ap.setAdVolume(getAdAudioVolume(ap));
8999
- this.timing.consecutiveFailures = 0;
9000
10037
  this.timing.temporaryFailureUrls.delete(vastTagUrl);
9001
10038
  return [
9002
10039
  3,
9003
- 7
9004
- ];
9005
- case 6:
9006
- playError = _state.sent();
9007
- if (this.debug) console.error("[AD-ERROR] Failed to play ad:", playError);
9008
- if (this.timing.isTemporaryAdError(playError)) {
9009
- this.timing.temporaryFailureUrls.set(vastTagUrl, Date.now());
9010
- if (this.debug) console.log("[AD-ERROR] Temporary play error - URL can be retried after cooldown");
9011
- } else {
9012
- this.timing.failedVastUrls.add(vastTagUrl);
9013
- if (this.debug) console.log("[AD-ERROR] Permanent play error - URL blacklisted");
9014
- }
9015
- this.timing.clearAdFailsafeTimer();
9016
- if (this.timing.activeAdRequestToken === requestToken) {
9017
- this.timing.activeAdRequestToken = null;
9018
- }
9019
- throw playError;
9020
- case 7:
9021
- return [
9022
- 3,
9023
- 9
10040
+ 6
9024
10041
  ];
9025
- case 8:
10042
+ case 5:
9026
10043
  error = _state.sent();
9027
- errorMessage = (error === null || error === void 0 ? void 0 : error.message) || "";
9028
- if (this.debug) console.error("[AD-ERROR] Ad request failed:", errorMessage);
9029
- if (this.timing.isTemporaryAdError(error)) {
9030
- this.timing.temporaryFailureUrls.set(vastTagUrl, Date.now());
9031
- if (this.debug) console.log("[AD-ERROR] Temporary error (no-fill/timeout) - URL can be retried after cooldown");
9032
- } else {
9033
- this.timing.failedVastUrls.add(vastTagUrl);
9034
- if (this.debug) console.log("[AD-ERROR] Permanent error - URL blacklisted:", errorMessage);
9035
- }
9036
10044
  this.timing.clearAdRequestWatchdog();
9037
10045
  this.timing.clearAdFailsafeTimer();
9038
10046
  if (this.timing.activeAdRequestToken === requestToken) {
9039
10047
  this.timing.activeAdRequestToken = null;
9040
10048
  }
9041
- throw error;
9042
- case 9:
9043
- return [
9044
- 2
9045
- ];
9046
- }
9047
- });
9048
- }).call(this);
9049
- }
9050
- },
9051
- {
9052
- key: "showPlaceholderAndWaitForAds",
9053
- value: // ───────────────────────────────────────────────────────────────
9054
- // Placeholder wait
9055
- // ───────────────────────────────────────────────────────────────
9056
- function showPlaceholderAndWaitForAds() {
9057
- return _async_to_generator(function() {
9058
- var remaining, waitTime, checkInterval, maxChecks, i, nextAdUrl, error, errorMessage;
9059
- return _ts_generator(this, function(_state) {
9060
- switch(_state.label){
9061
- case 0:
9062
- remaining = this.timing.getRemainingAdMs();
9063
- waitTime = Math.min(this.maxPlaceholderDurationMs, remaining);
9064
- if (this.timing.isGamInCooldown()) {
9065
- if (this.debug) console.log("[CIRCUIT-BREAKER] GAM in cooldown, skipping placeholder wait");
9066
- this.handleAdPodComplete();
9067
- return [
9068
- 2
9069
- ];
9070
- }
9071
- if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {
9072
- if (this.debug) console.log("[CONTINUOUS-FETCH] Skipping placeholder - too many consecutive failures");
9073
- this.handleAdPodComplete();
9074
- return [
9075
- 2
9076
- ];
9077
- }
9078
- if (waitTime < 1e3) {
9079
- this.handleAdPodComplete();
10049
+ if (this.isStale(epoch, generation)) {
10050
+ this.logOrchestratorFunnel("stale_request_result_ignored", {
10051
+ requestId: requestToken,
10052
+ errorMessage: error === null || error === void 0 ? void 0 : error.message
10053
+ });
9080
10054
  return [
9081
10055
  2
9082
10056
  ];
9083
10057
  }
9084
- if (this.debug) {
9085
- console.log("[CONTINUOUS-FETCH] Showing placeholder for ".concat(waitTime, "ms while waiting for ad URLs"));
10058
+ if (this.debug) console.error("[AD-ERROR] Ad request failed:", error === null || error === void 0 ? void 0 : error.message);
10059
+ this.recordRequestFailure(error, vastTagUrl);
10060
+ if ((error === null || error === void 0 ? void 0 : error.message) === "ad_duration_exceeds_budget") {
10061
+ this.recreateAdController("discarded_budget");
9086
10062
  }
9087
- this.isShowingPlaceholder = true;
9088
- this.host.getAdPlayer().showPlaceholder();
9089
- checkInterval = 300;
9090
- maxChecks = Math.floor(waitTime / checkInterval);
9091
- i = 0;
9092
- _state.label = 1;
9093
- case 1:
9094
- if (!(i < maxChecks)) return [
9095
- 3,
9096
- 12
9097
- ];
9098
- return [
9099
- 4,
9100
- new Promise(function(resolve) {
9101
- return setTimeout(resolve, checkInterval);
9102
- })
9103
- ];
9104
- case 2:
9105
- _state.sent();
9106
- if (!this.inAdBreak) return [
9107
- 2
9108
- ];
9109
- if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {
9110
- if (this.debug) console.log("[CONTINUOUS-FETCH] Too many failures during placeholder wait");
9111
- return [
9112
- 3,
9113
- 12
9114
- ];
9115
- }
9116
- if (!this.timing.hasTimeToStartAnotherAd()) {
9117
- if (this.debug) console.log("[CONTINUOUS-FETCH] Not enough time remaining during placeholder wait, ending ad break");
9118
- return [
9119
- 3,
9120
- 12
9121
- ];
9122
- }
9123
- _state.label = 3;
9124
- case 3:
9125
- if (!(this.adRequestQueue.length > 0)) return [
9126
- 3,
9127
- 11
9128
- ];
9129
- if (!this.timing.hasTimeToStartAnotherAd()) return [
9130
- 3,
9131
- 11
9132
- ];
9133
- nextAdUrl = this.adRequestQueue.shift();
9134
- if (!nextAdUrl) return [
9135
- 3,
9136
- 3
9137
- ];
9138
- if (this.timing.failedVastUrls.has(nextAdUrl)) return [
9139
- 3,
9140
- 3
9141
- ];
9142
- if (this.timing.isUrlInCooldown(nextAdUrl)) return [
9143
- 3,
9144
- 3
9145
- ];
9146
- if (this.debug) console.log("[CONTINUOUS-FETCH] Ad URL available, requesting via HLS ad player");
9147
- this.isShowingPlaceholder = false;
9148
- this.host.getAdPlayer().hidePlaceholder();
9149
- _state.label = 4;
9150
- case 4:
9151
- _state.trys.push([
9152
- 4,
9153
- 6,
9154
- ,
9155
- 10
9156
- ]);
9157
- return [
9158
- 4,
9159
- this.playSingleAd(nextAdUrl)
9160
- ];
9161
- case 5:
9162
- _state.sent();
9163
- this.timing.consecutiveFailures = 0;
9164
- return [
9165
- 3,
9166
- 10
9167
- ];
10063
+ throw error;
9168
10064
  case 6:
9169
- error = _state.sent();
9170
- errorMessage = error.message;
9171
- if (!errorMessage.includes("ad_duration_exceeds_budget")) return [
9172
- 3,
9173
- 8
9174
- ];
9175
- return [
9176
- 4,
9177
- this.tryNextAvailableAdWithRateLimit()
9178
- ];
9179
- case 7:
9180
- _state.sent();
9181
- return [
9182
- 2
9183
- ];
9184
- case 8:
9185
- if (!errorMessage.includes("permanently failed") && !errorMessage.includes("in cooldown")) {
9186
- this.timing.consecutiveFailures++;
9187
- }
9188
- return [
9189
- 4,
9190
- this.tryNextAvailableAdWithRateLimit()
9191
- ];
9192
- case 9:
9193
- _state.sent();
9194
- return [
9195
- 3,
9196
- 10
9197
- ];
9198
- case 10:
9199
- return [
9200
- 2
9201
- ];
9202
- case 11:
9203
- i++;
9204
- return [
9205
- 3,
9206
- 1
9207
- ];
9208
- case 12:
9209
- if (this.debug) console.log("[CONTINUOUS-FETCH] Placeholder timeout, ending ad break");
9210
- this.isShowingPlaceholder = false;
9211
- this.host.getAdPlayer().hidePlaceholder();
9212
- this.handleAdPodComplete();
9213
10065
  return [
9214
10066
  2
9215
10067
  ];
@@ -9222,26 +10074,136 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
9222
10074
  // ───────────────────────────────────────────────────────────────
9223
10075
  // Ad break completion
9224
10076
  // ───────────────────────────────────────────────────────────────
10077
+ key: "logBreakFunnel",
10078
+ value: function logBreakFunnel(endReason) {
10079
+ var funnel = this.breakFunnel;
10080
+ this.breakFunnel = {};
10081
+ if (Object.keys(funnel).length === 0) return;
10082
+ var count = function count(stage) {
10083
+ var _funnel_stage;
10084
+ return (_funnel_stage = funnel[stage]) !== null && _funnel_stage !== void 0 ? _funnel_stage : 0;
10085
+ };
10086
+ var countPrefix = function countPrefix(prefix) {
10087
+ return Object.keys(funnel).reduce(function(total, stage) {
10088
+ var _funnel_stage;
10089
+ return stage.indexOf(prefix) === 0 ? total + ((_funnel_stage = funnel[stage]) !== null && _funnel_stage !== void 0 ? _funnel_stage : 0) : total;
10090
+ }, 0);
10091
+ };
10092
+ var breakId = this.opportunityEpoch;
10093
+ var requestRetries = count("gam_http_request_retry");
10094
+ var requests = count("gam_http_request_sent") - requestRetries;
10095
+ if (requests > 0 && count("impression_fired") === 0) {
10096
+ console.log("[AdBreak][FUNNEL] break_abandoned_before_start", {
10097
+ breakId: breakId,
10098
+ requests: requests,
10099
+ endReason: endReason
10100
+ });
10101
+ }
10102
+ console.log("[AdBreak][FUNNEL] Break summary", {
10103
+ breakId: breakId,
10104
+ endReason: endReason,
10105
+ opportunities: count("opportunity_created"),
10106
+ vastUrlsGenerated: count("vast_url_generated"),
10107
+ requests: requests,
10108
+ requestRetries: requestRetries,
10109
+ gamResponses: count("gam_response_received"),
10110
+ requestsSuppressed: count("request_suppressed"),
10111
+ duplicates: count("duplicate_request_detected") + count("duplicate_break_start"),
10112
+ filled: count("vast_received"),
10113
+ noFill: count("no_fill"),
10114
+ fillRejected: count("vast_fill_rejected"),
10115
+ gamAdWithoutImpression: count("gam_ad_without_impression"),
10116
+ playbackFailedAfterFill: count("request_outcome:playback_failed"),
10117
+ requestFailed: count("request_failed"),
10118
+ requestAbortedTimeout: count("request_aborted_timeout"),
10119
+ credentialsRetries: count("vast_credentials_retry"),
10120
+ wrapperFailures: count("wrapper_fetch:failure"),
10121
+ noSupportedMedia: count("vast_no_supported_media"),
10122
+ vpaidOnly: count("vast_no_supported_media:vpaid"),
10123
+ audioOnly: count("vast_no_supported_media:audio_only"),
10124
+ mediaFilesEvaluated: count("mediafile_evaluated"),
10125
+ mediaFilesAccepted: count("mediafile_evaluated:accepted"),
10126
+ controllerDestroys: countPrefix("controller_destroy:"),
10127
+ staleCallbacks: count("stale_callback_ignored") + count("stale_request_result_ignored"),
10128
+ tagAllowsAudio: count("tag_allows_audio"),
10129
+ missingImpression: count("vast_missing_impression"),
10130
+ discardedBudget: count("discarded_budget"),
10131
+ mediaCandidates: count("media_candidate:accepted") + count("media_candidate:rejected"),
10132
+ mediaRejected: count("media_candidate:rejected"),
10133
+ mediaFallbacks: count("media_fallback"),
10134
+ playCalled: count("play_called"),
10135
+ playRejected: count("play_rejected"),
10136
+ mutedRetry: count("muted_retry"),
10137
+ startTimeouts: count("play_resolved_but_never_started"),
10138
+ impressions: count("impression_fired"),
10139
+ impressionUrls: count("impression_urls"),
10140
+ trackingRequests: count("tracking_request_created"),
10141
+ trackingNotLoaded: count("tracking_request_settled:error") + count("tracking_request_settled:timeout"),
10142
+ trackingUnexpandedMacros: count("tracking_url_unexpanded_macro"),
10143
+ trackingInvalidUrls: count("tracking_url_invalid"),
10144
+ vastAdFallbacks: count("vast_ad_fallback"),
10145
+ mediaEvents: count("media_event"),
10146
+ quartile25: count("first_quartile"),
10147
+ quartile50: count("midpoint"),
10148
+ quartile75: count("third_quartile"),
10149
+ complete: count("complete"),
10150
+ stoppedBeforeStart: count("stopped_before_start"),
10151
+ stoppedBeforeStartByBreakEnd: count("ad_stopped_before_start"),
10152
+ unexpectedUnmutes: count("unexpected_unmute"),
10153
+ unmuteBlocked: count("unmute_blocked_without_gesture"),
10154
+ visibilityHidden: count("while_hidden"),
10155
+ playbackFailures: count("play_failed") + count("media_error") + count("hls_fatal") + count("stall") + count("decode_failure") + count("media_unsupported"),
10156
+ stages: funnel
10157
+ });
10158
+ }
10159
+ },
10160
+ {
9225
10161
  key: "handleAdPodComplete",
9226
10162
  value: function handleAdPodComplete() {
10163
+ var reason = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : "unspecified";
9227
10164
  if (this.debug) {
9228
- console.log("[StormcloudVideoPlayer] Ad pod complete - cleaning up");
10165
+ console.log("[StormcloudVideoPlayer] Ad pod complete - cleaning up", {
10166
+ reason: reason
10167
+ });
9229
10168
  }
10169
+ var previousState = this.slotState;
10170
+ var alreadyEnded = previousState === "IDLE" && !this.inAdBreak;
10171
+ this.setSlotState("ENDING", reason);
10172
+ this.cancelScheduledRequest();
10173
+ var adPlayer = this.host.getAdPlayer();
10174
+ if (previousState === "REQUESTING") {
10175
+ var _adPlayer_abortPendingRequest;
10176
+ (_adPlayer_abortPendingRequest = adPlayer.abortPendingRequest) === null || _adPlayer_abortPendingRequest === void 0 ? void 0 : _adPlayer_abortPendingRequest.call(adPlayer, "VAST request aborted: ad break ended (".concat(reason, ")"));
10177
+ }
10178
+ if (!alreadyEnded) {
10179
+ console.log("[AD-CONTROLLER] stop", {
10180
+ controllerId: this.controllerGeneration,
10181
+ requestId: this.currentRequestId,
10182
+ state: previousState,
10183
+ reason: reason
10184
+ });
10185
+ }
10186
+ this.finalizeRequestDiagnostics(this.currentRequestId, "break_ended:".concat(reason));
10187
+ this.currentRequestId = void 0;
9230
10188
  this.timing.resetForBreakEnd();
9231
- this.stopContinuousFetching();
10189
+ this.placeholder.hide();
9232
10190
  this.clearPendingAdBreak();
9233
10191
  if (this.isShowingPlaceholder) {
9234
- this.host.getAdPlayer().hidePlaceholder();
10192
+ adPlayer.hidePlaceholder();
9235
10193
  this.isShowingPlaceholder = false;
9236
10194
  }
9237
- this.adRequestQueue = [];
9238
10195
  this.inAdBreak = false;
9239
10196
  this.adDetectSentForCurrentBreak = false;
9240
10197
  this.cueManager.activeScte35BreakKey = void 0;
9241
10198
  this.cueManager.scheduledScte35BreakKey = void 0;
9242
10199
  this.adPodQueue = [];
9243
10200
  this.showAds = false;
9244
- this.host.getAdPlayer().stop().catch(function() {});
10201
+ this.breakSource = void 0;
10202
+ this.followUpBaseVastUrl = void 0;
10203
+ this.unusableResponsesInBreak = 0;
10204
+ adPlayer.stop().catch(function() {});
10205
+ if (!alreadyEnded) this.logBreakFunnel(reason);
10206
+ this.setSlotState("IDLE", "break_complete");
9245
10207
  var restoredMuted = this.host.getAdPlayer().getOriginalMutedState();
9246
10208
  var restoredVolume = this.host.getAdPlayer().getOriginalVolume();
9247
10209
  if (this.host.video.muted !== restoredMuted) {
@@ -9535,25 +10497,23 @@ var AdBreakOrchestrator = /*#__PURE__*/ function() {
9535
10497
  {
9536
10498
  key: "handleAdFailure",
9537
10499
  value: function handleAdFailure() {
9538
- this.timing.consecutiveFailures++;
9539
- this.timing.recordGamNoFill();
9540
- var remaining = this.timing.getRemainingAdMs();
9541
- if (this.debug) {
9542
- console.log("[CONTINUOUS-FETCH] Ad failure: remaining=".concat(remaining, "ms, queued ads=").concat(this.adRequestQueue.length, ", consecutiveFailures=").concat(this.timing.consecutiveFailures), this.adRequestQueue.length > 0 ? {
9543
- queuedUrls: _to_consumable_array(this.adRequestQueue)
9544
- } : {});
9545
- }
9546
- if (this.timing.consecutiveFailures >= this.timing.maxConsecutiveFailures) {
9547
- if (this.debug) console.log("[CONTINUOUS-FETCH] Max consecutive failures reached (".concat(this.timing.consecutiveFailures, "), ending ad break gracefully"));
9548
- this.handleAdPodComplete();
10500
+ var reason = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : "ad_failure";
10501
+ if (!this.inAdBreak) return;
10502
+ if (this.slotState === "REQUESTING" || this.slotState === "ENDING") {
10503
+ this.logOrchestratorFunnel("failure_deferred_to_request", {
10504
+ reason: reason,
10505
+ state: this.slotState
10506
+ });
9549
10507
  return;
9550
10508
  }
9551
- if (this.timing.hasTimeToStartAnotherAd()) {
9552
- this.tryNextAvailableAdWithRateLimit();
9553
- } else {
9554
- if (this.debug) console.log("[AD-ERROR] Ad failed and not enough time remaining for another ad. Failed URLs:", this.timing.failedVastUrls.size);
9555
- this.handleAdPodComplete();
10509
+ this.timing.consecutiveFailures++;
10510
+ var diag = this.currentRequestId != null ? this.requestDiagnostics.get(this.currentRequestId) : void 0;
10511
+ if (diag && !diag.failureReason) diag.failureReason = reason;
10512
+ if (this.debug) {
10513
+ console.log("[AdBreak] Ad failure (".concat(reason, "): remaining=").concat(this.timing.getRemainingAdMs(), "ms, consecutiveFailures=").concat(this.timing.consecutiveFailures));
9556
10514
  }
10515
+ this.setSlotState("NEEDS_NEXT_AD", reason);
10516
+ this.requestNextAd(reason);
9557
10517
  }
9558
10518
  }
9559
10519
  ]);
@@ -9593,10 +10553,10 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
9593
10553
  _this.startScte35AdBreak(marker, cueKey, marker.durationSeconds != null ? marker.durationSeconds * 1e3 : _this.timing.expectedAdBreakDurationMs);
9594
10554
  },
9595
10555
  onWatchdogTimeout: function onWatchdogTimeout() {
9596
- return _this.adBreak.handleAdFailure();
10556
+ return _this.adBreak.handleRequestWatchdogTimeout();
9597
10557
  },
9598
10558
  onFailsafeTimeout: function onFailsafeTimeout() {
9599
- return _this.adBreak.handleAdFailure();
10559
+ return _this.adBreak.handleAdFailure("failsafe_timeout");
9600
10560
  },
9601
10561
  getAdState: function getAdState() {
9602
10562
  return {
@@ -9698,6 +10658,8 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
9698
10658
  licenseKey: this.config.licenseKey
9699
10659
  } : {}, ((_this_hlsEngine = this.hlsEngine) === null || _this_hlsEngine === void 0 ? void 0 : _this_hlsEngine.hls) ? {
9700
10660
  mainHlsInstance: this.hlsEngine.hls
10661
+ } : {}, this.config.adMediaStartTimeoutMs != null ? {
10662
+ mediaStartTimeoutMs: this.config.adMediaStartTimeoutMs
9701
10663
  } : {}));
9702
10664
  }
9703
10665
  },
@@ -9844,6 +10806,21 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
9844
10806
  adBehavior: adBehavior
9845
10807
  });
9846
10808
  }
10809
+ if (this.adBreak.isBreakActive()) {
10810
+ console.log("[AD-CONTROLLER] destroy skipped", {
10811
+ reason: "manifest_parsed_during_break",
10812
+ state: this.adBreak.getSlotState()
10813
+ });
10814
+ return [
10815
+ 2
10816
+ ];
10817
+ }
10818
+ if (this.debug) {
10819
+ console.log("[AD-CONTROLLER] destroy", {
10820
+ reason: "manifest_parsed",
10821
+ state: "IDLE"
10822
+ });
10823
+ }
9847
10824
  this.adPlayer.destroy();
9848
10825
  this.adPlayer = this.createAdPlayer(this.shouldContinueLiveStreamDuringAds());
9849
10826
  this.adPlayer.initialize();
@@ -10025,9 +11002,6 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
10025
11002
  this.timing.setAdBreakDurationBoundary(marker.durationSeconds * 1e3);
10026
11003
  }
10027
11004
  this.timing.scheduleAdStopAtBreakBoundary();
10028
- if (!this.adPlayer.isAdPlaying() && this.timing.activeAdRequestToken === null && this.adBreak.adRequestQueue.length > 0 && this.timing.hasTimeToStartAnotherAd()) {
10029
- this.adBreak.tryNextAvailableAdWithRateLimit();
10030
- }
10031
11005
  return;
10032
11006
  }
10033
11007
  if (marker.type === "end") {
@@ -10039,12 +11013,11 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
10039
11013
  }
10040
11014
  var remaining = this.timing.getRemainingAdMs();
10041
11015
  var adPlaying = this.adPlayer.isAdPlaying();
10042
- var hasQueuedAds = this.adBreak.adRequestQueue.length > 0;
10043
11016
  if (this.debug) {
10044
11017
  console.log("[StormcloudVideoPlayer] SCTE-35 end marker received:", {
10045
11018
  remaining: remaining,
10046
11019
  adPlaying: adPlaying,
10047
- hasQueuedAds: hasQueuedAds,
11020
+ adSlotState: this.adBreak.getSlotState(),
10048
11021
  activeAdRequest: this.timing.activeAdRequestToken !== null
10049
11022
  });
10050
11023
  }
@@ -10052,9 +11025,10 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
10052
11025
  this.timing.clearAdStartTimer();
10053
11026
  this.timing.clearAdStopTimer();
10054
11027
  if (adPlaying) {
11028
+ this.adBreak.noteStopBeforeStart("scte_end");
10055
11029
  this.adPlayer.stop().catch(function() {});
10056
11030
  }
10057
- this.adBreak.handleAdPodComplete();
11031
+ this.adBreak.handleAdPodComplete("scte_end");
10058
11032
  return;
10059
11033
  }
10060
11034
  }
@@ -10062,6 +11036,15 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
10062
11036
  {
10063
11037
  key: "startScte35AdBreak",
10064
11038
  value: function startScte35AdBreak(marker, cueKey, durationMs) {
11039
+ if (this.adBreak.isBreakActive()) {
11040
+ if (this.debug) {
11041
+ console.log("[StormcloudVideoPlayer] Ignoring SCTE-35 break start: a break is already active", {
11042
+ state: this.adBreak.getSlotState(),
11043
+ cueKey: cueKey
11044
+ });
11045
+ }
11046
+ return;
11047
+ }
10065
11048
  this.adBreak.inAdBreak = true;
10066
11049
  this.cueManager.activeScte35BreakKey = cueKey !== null && cueKey !== void 0 ? cueKey : this.cueManager.pendingScte35CueKey;
10067
11050
  this.cueManager.scheduledScte35BreakKey = void 0;
@@ -10091,9 +11074,10 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
10091
11074
  console.log("[StormcloudVideoPlayer] Ad break boundary reached (overrun=".concat(overrunMs, "ms) - hard-stopping ads and resuming stream"));
10092
11075
  }
10093
11076
  if (adPlaying) {
11077
+ this.adBreak.noteStopBeforeStart("break_boundary");
10094
11078
  this.adPlayer.stop().catch(function() {});
10095
11079
  }
10096
- this.adBreak.handleAdPodComplete();
11080
+ this.adBreak.handleAdPodComplete("break_boundary");
10097
11081
  }
10098
11082
  },
10099
11083
  {
@@ -10103,14 +11087,8 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
10103
11087
  key: "startAdPrefetch",
10104
11088
  value: function startAdPrefetch(marker, fragmentSn, cueKey) {
10105
11089
  if (this.adBreak.pendingAdBreak || this.adBreak.inAdBreak) return;
10106
- var scheduled = this.adConfig.findCurrentOrNextBreak(this.video.currentTime * 1e3);
10107
- var tags = this.adConfig.selectVastTagsForBreak(scheduled);
10108
- var baseVastUrl;
10109
- if (tags && tags.length > 0 && tags[0]) {
10110
- baseVastUrl = tags[0];
10111
- } else if (this.adConfig.apiVastTagUrl) {
10112
- baseVastUrl = this.adConfig.apiVastTagUrl;
10113
- } else {
11090
+ var baseVastUrl = this.adConfig.apiVastTagUrl;
11091
+ if (!baseVastUrl) {
10114
11092
  if (this.debug) console.warn("[StormcloudVideoPlayer] No VAST URL available for prefetch");
10115
11093
  return;
10116
11094
  }
@@ -10140,8 +11118,7 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
10140
11118
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
10141
11119
  }, detectPayload), buildAnalyticsContext(this.config)).catch(function() {});
10142
11120
  if (this.debug) {
10143
- console.log("[PREFETCH] Starting ad prefetch for upcoming ad break");
10144
- console.log("[PREFETCH] Pre-generated pod request URL");
11121
+ console.log("[PREFETCH] Pre-generated pod request URL for upcoming ad break");
10145
11122
  }
10146
11123
  }
10147
11124
  },
@@ -10152,7 +11129,7 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
10152
11129
  key: "onTimeUpdate",
10153
11130
  value: function onTimeUpdate(currentTimeSec) {
10154
11131
  var _this = this;
10155
- if (!this.adConfig.isVmapEnabled() || this.adConfig.vmapBreaks.length === 0) return;
11132
+ if (this.adConfig.vmapBreaks.length === 0) return;
10156
11133
  if (this.adPlayer.isAdPlaying() || this.adBreak.inAdBreak) return;
10157
11134
  var nowMs = currentTimeSec * 1e3;
10158
11135
  var breakToPlay = this.adConfig.findBreakForTime(nowMs);
@@ -10169,7 +11146,7 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
10169
11146
  key: "onVideoEnded",
10170
11147
  value: function onVideoEnded() {
10171
11148
  var _this = this;
10172
- if (!this.adConfig.isVmapEnabled() || this.adConfig.vmapBreaks.length === 0) return;
11149
+ if (this.adConfig.vmapBreaks.length === 0) return;
10173
11150
  if (this.adPlayer.isAdPlaying() || this.adBreak.inAdBreak) return;
10174
11151
  var durationMs = Number.isFinite(this.video.duration) ? Math.floor(this.video.duration * 1e3) : 0;
10175
11152
  var postroll = this.adConfig.vmapBreaks.find(function(b) {
@@ -10219,6 +11196,10 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
10219
11196
  this.adBreak.showAds = true;
10220
11197
  this.adBreak.inAdBreak = true;
10221
11198
  this.timing.currentAdBreakStartWallClockMs = Date.now();
11199
+ if (durationMs > 0) {
11200
+ this.timing.setAdBreakDurationBoundary(durationMs);
11201
+ }
11202
+ this.adBreak.beginVmapBreak(key);
10222
11203
  _state.label = 1;
10223
11204
  case 1:
10224
11205
  _state.trys.push([
@@ -10229,7 +11210,7 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
10229
11210
  ]);
10230
11211
  return [
10231
11212
  4,
10232
- this.adBreak.playSingleAd(first)
11213
+ this.adBreak.playSingleAd(first, "vmap")
10233
11214
  ];
10234
11215
  case 2:
10235
11216
  _state.sent();
@@ -10242,7 +11223,7 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
10242
11223
  if (this.debug) {
10243
11224
  console.warn("[StormcloudVideoPlayer] VMAP ad request failed:", error);
10244
11225
  }
10245
- this.adBreak.handleAdPodComplete();
11226
+ this.adBreak.continueAfterRequestFailure();
10246
11227
  return [
10247
11228
  3,
10248
11229
  4
@@ -10384,7 +11365,7 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
10384
11365
  key: "destroy",
10385
11366
  value: function destroy() {
10386
11367
  var _this_adPlayer;
10387
- this.adBreak.stopContinuousFetching();
11368
+ this.adBreak.cancelScheduledRequest();
10388
11369
  this.timing.destroy();
10389
11370
  this.adBreak.clearPendingAdBreak();
10390
11371
  this.placeholder.destroy();
@@ -10408,7 +11389,6 @@ var StormcloudVideoPlayer = /*#__PURE__*/ function() {
10408
11389
  this.palNonce.sendPlaybackEnd();
10409
11390
  }
10410
11391
  this.palNonce.reset();
10411
- this.adBreak.adRequestQueue = [];
10412
11392
  this.timing.consecutiveFailures = 0;
10413
11393
  }
10414
11394
  }