stormcloud-video-player 0.7.3 → 0.7.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1573 @@
1
+ "use strict";
2
+ function _array_like_to_array(arr, len) {
3
+ if (len == null || len > arr.length) len = arr.length;
4
+ for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
5
+ return arr2;
6
+ }
7
+ function _array_without_holes(arr) {
8
+ if (Array.isArray(arr)) return _array_like_to_array(arr);
9
+ }
10
+ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
11
+ try {
12
+ var info = gen[key](arg);
13
+ var value = info.value;
14
+ } catch (error) {
15
+ reject(error);
16
+ return;
17
+ }
18
+ if (info.done) {
19
+ resolve(value);
20
+ } else {
21
+ Promise.resolve(value).then(_next, _throw);
22
+ }
23
+ }
24
+ function _async_to_generator(fn) {
25
+ return function() {
26
+ var self = this, args = arguments;
27
+ return new Promise(function(resolve, reject) {
28
+ var gen = fn.apply(self, args);
29
+ function _next(value) {
30
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
31
+ }
32
+ function _throw(err) {
33
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
34
+ }
35
+ _next(undefined);
36
+ });
37
+ };
38
+ }
39
+ function _instanceof(left, right) {
40
+ if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
41
+ return !!right[Symbol.hasInstance](left);
42
+ } else {
43
+ return left instanceof right;
44
+ }
45
+ }
46
+ function _iterable_to_array(iter) {
47
+ if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
48
+ }
49
+ function _non_iterable_spread() {
50
+ throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
51
+ }
52
+ function _to_consumable_array(arr) {
53
+ return _array_without_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_spread();
54
+ }
55
+ function _type_of(obj) {
56
+ "@swc/helpers - typeof";
57
+ return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
58
+ }
59
+ function _unsupported_iterable_to_array(o, minLen) {
60
+ if (!o) return;
61
+ if (typeof o === "string") return _array_like_to_array(o, minLen);
62
+ var n = Object.prototype.toString.call(o).slice(8, -1);
63
+ if (n === "Object" && o.constructor) n = o.constructor.name;
64
+ if (n === "Map" || n === "Set") return Array.from(n);
65
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
66
+ }
67
+ function _ts_generator(thisArg, body) {
68
+ var f, y, t, _ = {
69
+ label: 0,
70
+ sent: function() {
71
+ if (t[0] & 1) throw t[1];
72
+ return t[1];
73
+ },
74
+ trys: [],
75
+ ops: []
76
+ }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype), d = Object.defineProperty;
77
+ return d(g, "next", {
78
+ value: verb(0)
79
+ }), d(g, "throw", {
80
+ value: verb(1)
81
+ }), d(g, "return", {
82
+ value: verb(2)
83
+ }), typeof Symbol === "function" && d(g, Symbol.iterator, {
84
+ value: function() {
85
+ return this;
86
+ }
87
+ }), g;
88
+ function verb(n) {
89
+ return function(v) {
90
+ return step([
91
+ n,
92
+ v
93
+ ]);
94
+ };
95
+ }
96
+ function step(op) {
97
+ if (f) throw new TypeError("Generator is already executing.");
98
+ while(g && (g = 0, op[0] && (_ = 0)), _)try {
99
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
100
+ if (y = 0, t) op = [
101
+ op[0] & 2,
102
+ t.value
103
+ ];
104
+ switch(op[0]){
105
+ case 0:
106
+ case 1:
107
+ t = op;
108
+ break;
109
+ case 4:
110
+ _.label++;
111
+ return {
112
+ value: op[1],
113
+ done: false
114
+ };
115
+ case 5:
116
+ _.label++;
117
+ y = op[1];
118
+ op = [
119
+ 0
120
+ ];
121
+ continue;
122
+ case 7:
123
+ op = _.ops.pop();
124
+ _.trys.pop();
125
+ continue;
126
+ default:
127
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
128
+ _ = 0;
129
+ continue;
130
+ }
131
+ if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
132
+ _.label = op[1];
133
+ break;
134
+ }
135
+ if (op[0] === 6 && _.label < t[1]) {
136
+ _.label = t[1];
137
+ t = op;
138
+ break;
139
+ }
140
+ if (t && _.label < t[2]) {
141
+ _.label = t[2];
142
+ _.ops.push(op);
143
+ break;
144
+ }
145
+ if (t[2]) _.ops.pop();
146
+ _.trys.pop();
147
+ continue;
148
+ }
149
+ op = body.call(thisArg, _);
150
+ } catch (e) {
151
+ op = [
152
+ 6,
153
+ e
154
+ ];
155
+ y = 0;
156
+ } finally{
157
+ f = t = 0;
158
+ }
159
+ if (op[0] & 5) throw op[1];
160
+ return {
161
+ value: op[0] ? op[1] : void 0,
162
+ done: true
163
+ };
164
+ }
165
+ }
166
+ function _ts_values(o) {
167
+ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
168
+ if (m) return m.call(o);
169
+ if (o && typeof o.length === "number") return {
170
+ next: function() {
171
+ if (o && i >= o.length) o = void 0;
172
+ return {
173
+ value: o && o[i++],
174
+ done: !o
175
+ };
176
+ }
177
+ };
178
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
179
+ }
180
+ var __defProp = Object.defineProperty;
181
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
182
+ var __getOwnPropNames = Object.getOwnPropertyNames;
183
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
184
+ var __export = function __export(target, all) {
185
+ for(var name in all)__defProp(target, name, {
186
+ get: all[name],
187
+ enumerable: true
188
+ });
189
+ };
190
+ var __copyProps = function __copyProps(to, from, except, desc) {
191
+ if (from && (typeof from === "undefined" ? "undefined" : _type_of(from)) === "object" || typeof from === "function") {
192
+ var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
193
+ try {
194
+ var _loop = function() {
195
+ var key = _step.value;
196
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
197
+ get: function get() {
198
+ return from[key];
199
+ },
200
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
201
+ });
202
+ };
203
+ for(var _iterator = __getOwnPropNames(from)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true)_loop();
204
+ } catch (err) {
205
+ _didIteratorError = true;
206
+ _iteratorError = err;
207
+ } finally{
208
+ try {
209
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
210
+ _iterator.return();
211
+ }
212
+ } finally{
213
+ if (_didIteratorError) {
214
+ throw _iteratorError;
215
+ }
216
+ }
217
+ }
218
+ }
219
+ return to;
220
+ };
221
+ var __toCommonJS = function __toCommonJS(mod) {
222
+ return __copyProps(__defProp({}, "__esModule", {
223
+ value: true
224
+ }), mod);
225
+ };
226
+ // src/sdk/adstormPlayer.ts
227
+ var adstormPlayer_exports = {};
228
+ __export(adstormPlayer_exports, {
229
+ createAdStormPlayer: function createAdStormPlayer1() {
230
+ return createAdStormPlayer;
231
+ }
232
+ });
233
+ module.exports = __toCommonJS(adstormPlayer_exports);
234
+ // src/sdk/vastParser.ts
235
+ function firePixelWithRetry(url) {
236
+ var retries = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 2, delayMs = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : 500, logPrefix = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : "[VastParser]";
237
+ return _async_to_generator(function() {
238
+ var _loop, attempt, _ret;
239
+ return _ts_generator(this, function(_state) {
240
+ switch(_state.label){
241
+ case 0:
242
+ _loop = function(attempt) {
243
+ var unused;
244
+ return _ts_generator(this, function(_state) {
245
+ switch(_state.label){
246
+ case 0:
247
+ _state.trys.push([
248
+ 0,
249
+ 2,
250
+ ,
251
+ 6
252
+ ]);
253
+ return [
254
+ 4,
255
+ fetch(url, {
256
+ method: "GET",
257
+ mode: "no-cors",
258
+ cache: "no-cache",
259
+ keepalive: true
260
+ })
261
+ ];
262
+ case 1:
263
+ _state.sent();
264
+ return [
265
+ 2,
266
+ {
267
+ v: void void 0
268
+ }
269
+ ];
270
+ case 2:
271
+ unused = _state.sent();
272
+ if (!(attempt < retries)) return [
273
+ 3,
274
+ 4
275
+ ];
276
+ return [
277
+ 4,
278
+ new Promise(function(r) {
279
+ return setTimeout(r, delayMs * Math.pow(2, attempt));
280
+ })
281
+ ];
282
+ case 3:
283
+ _state.sent();
284
+ return [
285
+ 3,
286
+ 5
287
+ ];
288
+ case 4:
289
+ console.warn("".concat(logPrefix, " Tracking pixel failed after ").concat(retries + 1, " attempts: ").concat(url));
290
+ _state.label = 5;
291
+ case 5:
292
+ return [
293
+ 3,
294
+ 6
295
+ ];
296
+ case 6:
297
+ return [
298
+ 2
299
+ ];
300
+ }
301
+ });
302
+ };
303
+ attempt = 0;
304
+ _state.label = 1;
305
+ case 1:
306
+ if (!(attempt <= retries)) return [
307
+ 3,
308
+ 4
309
+ ];
310
+ return [
311
+ 5,
312
+ _ts_values(_loop(attempt))
313
+ ];
314
+ case 2:
315
+ _ret = _state.sent();
316
+ if (_type_of(_ret) === "object") return [
317
+ 2,
318
+ _ret.v
319
+ ];
320
+ _state.label = 3;
321
+ case 3:
322
+ attempt++;
323
+ return [
324
+ 3,
325
+ 1
326
+ ];
327
+ case 4:
328
+ return [
329
+ 2
330
+ ];
331
+ }
332
+ });
333
+ })();
334
+ }
335
+ function fireTrackingPixels(urls, sessionId) {
336
+ var logPrefix = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : "[VastParser]";
337
+ if (!urls || urls.length === 0) return;
338
+ urls.forEach(function(url) {
339
+ try {
340
+ var trackingUrl = url;
341
+ if (sessionId) {
342
+ trackingUrl = "".concat(trackingUrl).concat(trackingUrl.includes("?") ? "&" : "?", "session_id=").concat(sessionId);
343
+ }
344
+ if (typeof fetch !== "undefined") {
345
+ firePixelWithRetry(trackingUrl, 2, 500, logPrefix).catch(function() {});
346
+ } else {
347
+ var img = new Image(1, 1);
348
+ img.onerror = function() {};
349
+ img.src = trackingUrl;
350
+ }
351
+ console.log("".concat(logPrefix, " Fired tracking pixel: ").concat(trackingUrl));
352
+ } catch (error) {
353
+ console.warn("".concat(logPrefix, " Error firing tracking pixel:"), error);
354
+ }
355
+ });
356
+ }
357
+ // src/sdk/adstormPlayer.ts
358
+ var SUPPORTED_VIDEO_EXTENSIONS = [
359
+ ".mp4",
360
+ ".webm",
361
+ ".ogg",
362
+ ".m3u8",
363
+ ".ts"
364
+ ];
365
+ var UNSUPPORTED_VIDEO_EXTENSIONS = [
366
+ ".flv",
367
+ ".f4v",
368
+ ".swf",
369
+ ".wmv",
370
+ ".avi",
371
+ ".mov",
372
+ ".mkv"
373
+ ];
374
+ var REQUEST_TIMEOUT_MS = 5e3;
375
+ var REQUEST_MAX_RETRIES = 3;
376
+ var REQUEST_RETRY_BACKOFF_MS = 1500;
377
+ var AD_LAYER_Z_INDEX = "2147483646";
378
+ var COUNTDOWN_Z_INDEX = "2147483647";
379
+ var STALL_TIMEOUT_MS = 8e3;
380
+ function getFileExtension(url) {
381
+ try {
382
+ var pathname = new URL(url, "http://dummy").pathname;
383
+ var lastDot = pathname.lastIndexOf(".");
384
+ if (lastDot === -1) return "";
385
+ return pathname.slice(lastDot).toLowerCase();
386
+ } catch (unused) {
387
+ var lastDot1 = url.lastIndexOf(".");
388
+ if (lastDot1 === -1) return "";
389
+ var ext = url.slice(lastDot1).split(/[?#]/)[0];
390
+ return (ext || "").toLowerCase();
391
+ }
392
+ }
393
+ function isUnsupportedFormat(url) {
394
+ var ext = getFileExtension(url);
395
+ return UNSUPPORTED_VIDEO_EXTENSIONS.indexOf(ext) !== -1;
396
+ }
397
+ function replaceFlvExtension(url) {
398
+ var ext = getFileExtension(url);
399
+ if (ext === ".flv") {
400
+ return url.replace(/\.flv(\?|$)/i, ".mp4$1");
401
+ }
402
+ return url;
403
+ }
404
+ function isSupportedFormat(url, mimeType) {
405
+ if (isUnsupportedFormat(url)) {
406
+ return false;
407
+ }
408
+ var ext = getFileExtension(url);
409
+ if (SUPPORTED_VIDEO_EXTENSIONS.indexOf(ext) !== -1) {
410
+ return true;
411
+ }
412
+ if (ext === "" || ext === ".") {
413
+ return mimeType.includes("video/mp4") || mimeType.includes("video/webm") || mimeType.includes("m3u8") || mimeType.includes("application/x-mpegurl");
414
+ }
415
+ return false;
416
+ }
417
+ function createAdStormPlayer(contentVideo, options) {
418
+ var licenseKey = options.licenseKey, _options_debug = options.debug, debug = _options_debug === void 0 ? false : _options_debug;
419
+ var adPlaying = false;
420
+ var originalMutedState = false;
421
+ var originalVolume = Math.max(0, Math.min(1, contentVideo.volume || 1));
422
+ var listeners = /* @__PURE__ */ new Map();
423
+ var adVideoElement;
424
+ var adContainerEl;
425
+ var adCountdownEl;
426
+ var currentAd;
427
+ var destroyed = false;
428
+ var tornDown = false;
429
+ var continueLiveStreamDuringAds = false;
430
+ var sessionId;
431
+ var adStallTimerId;
432
+ var adCountdownTimerId;
433
+ var adHideTimerId;
434
+ var lastCountdownSecond = -1;
435
+ var adListenersBound = false;
436
+ var parentPositionOverridden = false;
437
+ var adHandlers = {
438
+ timeupdate: function timeupdate() {
439
+ if (!currentAd || !adVideoElement || destroyed || tornDown) return;
440
+ var progress = adVideoElement.currentTime / currentAd.duration;
441
+ if (progress >= 0.25 && !trackingFired.firstQuartile) {
442
+ trackingFired.firstQuartile = true;
443
+ fireTrackingPixels2(currentAd.trackingUrls.firstQuartile);
444
+ }
445
+ if (progress >= 0.5 && !trackingFired.midpoint) {
446
+ trackingFired.midpoint = true;
447
+ fireTrackingPixels2(currentAd.trackingUrls.midpoint);
448
+ }
449
+ if (progress >= 0.75 && !trackingFired.thirdQuartile) {
450
+ trackingFired.thirdQuartile = true;
451
+ fireTrackingPixels2(currentAd.trackingUrls.thirdQuartile);
452
+ }
453
+ updateAdCountdown();
454
+ },
455
+ playing: function playing() {
456
+ clearAdStallTimer();
457
+ if (!currentAd || trackingFired.start || destroyed || tornDown) return;
458
+ trackingFired.start = true;
459
+ fireTrackingPixels2(currentAd.trackingUrls.start);
460
+ startAdCountdown();
461
+ log("Ad started playing");
462
+ },
463
+ ended: function ended() {
464
+ if (!currentAd || trackingFired.complete || destroyed || tornDown) return;
465
+ trackingFired.complete = true;
466
+ fireTrackingPixels2(currentAd.trackingUrls.complete);
467
+ log("Ad completed");
468
+ handleAdComplete();
469
+ },
470
+ error: function error(e) {
471
+ if (destroyed || tornDown) return;
472
+ console.error("[AdStormPlayer] Ad video error:", e);
473
+ if (currentAd) fireTrackingPixels2(currentAd.trackingUrls.error);
474
+ handleAdError();
475
+ },
476
+ waiting: function waiting() {
477
+ clearAdStallTimer();
478
+ adStallTimerId = setTimeout(function() {
479
+ adStallTimerId = void 0;
480
+ if (!adPlaying || destroyed || tornDown) return;
481
+ console.warn("[AdStormPlayer] Ad playback stalled too long");
482
+ handleAdError();
483
+ }, STALL_TIMEOUT_MS);
484
+ },
485
+ volumechange: function volumechange() {
486
+ if (!currentAd || !adVideoElement || destroyed || tornDown) return;
487
+ if (adVideoElement.muted || adVideoElement.volume <= 0) {
488
+ fireTrackingPixels2(currentAd.trackingUrls.mute);
489
+ } else {
490
+ fireTrackingPixels2(currentAd.trackingUrls.unmute);
491
+ }
492
+ },
493
+ pause: function pause() {
494
+ if (!currentAd || !adVideoElement || destroyed || tornDown) return;
495
+ if (!adVideoElement.ended) {
496
+ fireTrackingPixels2(currentAd.trackingUrls.pause);
497
+ }
498
+ },
499
+ play: function play() {
500
+ if (!currentAd || !adVideoElement || destroyed || tornDown) return;
501
+ if (adVideoElement.currentTime > 0) {
502
+ fireTrackingPixels2(currentAd.trackingUrls.resume);
503
+ }
504
+ }
505
+ };
506
+ var trackingFired = {
507
+ impression: false,
508
+ start: false,
509
+ firstQuartile: false,
510
+ midpoint: false,
511
+ thirdQuartile: false,
512
+ complete: false
513
+ };
514
+ var preloadSlots = /* @__PURE__ */ new Map();
515
+ function log() {
516
+ for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
517
+ args[_key] = arguments[_key];
518
+ }
519
+ if (debug) {
520
+ var _console;
521
+ (_console = console).log.apply(_console, [
522
+ "[AdStormPlayer]"
523
+ ].concat(_to_consumable_array(args)));
524
+ }
525
+ }
526
+ function emit(event, payload) {
527
+ var set = listeners.get(event);
528
+ if (!set) return;
529
+ var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
530
+ try {
531
+ for(var _iterator = Array.from(set)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
532
+ var fn = _step.value;
533
+ try {
534
+ fn(payload);
535
+ } catch (error) {
536
+ console.warn("[AdStormPlayer] Error in event listener for ".concat(event, ":"), error);
537
+ }
538
+ }
539
+ } catch (err) {
540
+ _didIteratorError = true;
541
+ _iteratorError = err;
542
+ } finally{
543
+ try {
544
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
545
+ _iterator.return();
546
+ }
547
+ } finally{
548
+ if (_didIteratorError) {
549
+ throw _iteratorError;
550
+ }
551
+ }
552
+ }
553
+ }
554
+ function fireTrackingPixels2(urls) {
555
+ fireTrackingPixels(urls, sessionId, "[AdStormPlayer]");
556
+ }
557
+ function clearAdStallTimer() {
558
+ if (adStallTimerId) {
559
+ clearTimeout(adStallTimerId);
560
+ adStallTimerId = void 0;
561
+ }
562
+ }
563
+ function clearAdCountdownTimer() {
564
+ if (adCountdownTimerId) {
565
+ clearInterval(adCountdownTimerId);
566
+ adCountdownTimerId = void 0;
567
+ }
568
+ lastCountdownSecond = -1;
569
+ }
570
+ function updateAdCountdown() {
571
+ if (!adCountdownEl || !adVideoElement || !currentAd || !adPlaying) return;
572
+ var remainingSec = Math.max(0, Math.ceil((currentAd.duration || 0) - adVideoElement.currentTime));
573
+ if (remainingSec === lastCountdownSecond) return;
574
+ lastCountdownSecond = remainingSec;
575
+ adCountdownEl.textContent = "Ad ".concat(remainingSec, "s");
576
+ emit("ad_countdown", {
577
+ remainingSec: remainingSec,
578
+ durationSec: currentAd.duration,
579
+ currentTimeSec: adVideoElement.currentTime
580
+ });
581
+ }
582
+ function startAdCountdown() {
583
+ clearAdCountdownTimer();
584
+ updateAdCountdown();
585
+ adCountdownTimerId = setInterval(updateAdCountdown, 250);
586
+ }
587
+ function generateSessionId() {
588
+ return "adstorm-".concat(Date.now(), "-").concat(Math.random().toString(36).slice(2, 10));
589
+ }
590
+ function bindAdEventListeners() {
591
+ if (!adVideoElement || adListenersBound) return;
592
+ adVideoElement.addEventListener("timeupdate", adHandlers.timeupdate);
593
+ adVideoElement.addEventListener("playing", adHandlers.playing);
594
+ adVideoElement.addEventListener("ended", adHandlers.ended);
595
+ adVideoElement.addEventListener("error", adHandlers.error);
596
+ adVideoElement.addEventListener("waiting", adHandlers.waiting);
597
+ adVideoElement.addEventListener("volumechange", adHandlers.volumechange);
598
+ adVideoElement.addEventListener("pause", adHandlers.pause);
599
+ adVideoElement.addEventListener("play", adHandlers.play);
600
+ adListenersBound = true;
601
+ }
602
+ function unbindAdEventListeners() {
603
+ if (!adVideoElement || !adListenersBound) return;
604
+ adVideoElement.removeEventListener("timeupdate", adHandlers.timeupdate);
605
+ adVideoElement.removeEventListener("playing", adHandlers.playing);
606
+ adVideoElement.removeEventListener("ended", adHandlers.ended);
607
+ adVideoElement.removeEventListener("error", adHandlers.error);
608
+ adVideoElement.removeEventListener("waiting", adHandlers.waiting);
609
+ adVideoElement.removeEventListener("volumechange", adHandlers.volumechange);
610
+ adVideoElement.removeEventListener("pause", adHandlers.pause);
611
+ adVideoElement.removeEventListener("play", adHandlers.play);
612
+ adListenersBound = false;
613
+ }
614
+ function teardownCurrentPlayback() {
615
+ unbindAdEventListeners();
616
+ clearAdStallTimer();
617
+ clearAdCountdownTimer();
618
+ if (!adVideoElement) return;
619
+ adVideoElement.pause();
620
+ adVideoElement.removeAttribute("src");
621
+ adVideoElement.load();
622
+ }
623
+ function buildVastUrl(durationSeconds, metadata) {
624
+ var baseUrl = "https://adstorm.co/api-adstorm-dev/adstorm/vast/".concat(licenseKey, "/pod");
625
+ var defaultMetadata = {
626
+ video: {
627
+ codec: "h264",
628
+ width: contentVideo.videoWidth || 1280,
629
+ height: contentVideo.videoHeight || 720,
630
+ fps: 29.97,
631
+ bitrate: 5e3,
632
+ profile: "high",
633
+ pix_fmt: "yuv420p",
634
+ has_b_frames: 0
635
+ },
636
+ audio: {
637
+ codec: "aac",
638
+ sample_rate: 48e3,
639
+ bitrate: 128
640
+ }
641
+ };
642
+ var finalMetadata = metadata || defaultMetadata;
643
+ var metadataStr = encodeURIComponent(JSON.stringify(finalMetadata));
644
+ return "".concat(baseUrl, "?duration=").concat(Math.ceil(durationSeconds), "&metadata=").concat(metadataStr);
645
+ }
646
+ function parseVastXml(xmlString) {
647
+ var ads = [];
648
+ try {
649
+ var parser = new DOMParser();
650
+ var xmlDoc = parser.parseFromString(xmlString, "text/xml");
651
+ var parserError = xmlDoc.querySelector("parsererror");
652
+ if (parserError) {
653
+ console.error("[AdStormPlayer] XML parsing error:", parserError.textContent);
654
+ return [];
655
+ }
656
+ var adElements = xmlDoc.querySelectorAll("Ad");
657
+ adElements.forEach(function(adElement) {
658
+ var _adElement_querySelector, _adElement_querySelector1, _adElement_querySelector_textContent, _adElement_querySelector2;
659
+ var adId = adElement.getAttribute("id") || "unknown";
660
+ var title = ((_adElement_querySelector = adElement.querySelector("AdTitle")) === null || _adElement_querySelector === void 0 ? void 0 : _adElement_querySelector.textContent) || "Ad";
661
+ var durationText = ((_adElement_querySelector1 = adElement.querySelector("Duration")) === null || _adElement_querySelector1 === void 0 ? void 0 : _adElement_querySelector1.textContent) || "00:00:30";
662
+ var durationParts = durationText.split(":");
663
+ var duration = parseInt(durationParts[0] || "0", 10) * 3600 + parseInt(durationParts[1] || "0", 10) * 60 + parseFloat(durationParts[2] || "0");
664
+ var mediaFileElements = adElement.querySelectorAll("MediaFile");
665
+ var mediaFiles = [];
666
+ mediaFileElements.forEach(function(mf) {
667
+ var _mf_textContent;
668
+ var type = mf.getAttribute("type") || "";
669
+ var url = ((_mf_textContent = mf.textContent) === null || _mf_textContent === void 0 ? void 0 : _mf_textContent.trim()) || "";
670
+ var width = parseInt(mf.getAttribute("width") || "1920", 10);
671
+ var height = parseInt(mf.getAttribute("height") || "1080", 10);
672
+ var bitrate = mf.getAttribute("bitrate") ? parseInt(mf.getAttribute("bitrate"), 10) : void 0;
673
+ if (!url) {
674
+ log("Skipping empty MediaFile URL");
675
+ return;
676
+ }
677
+ var originalUrl = url;
678
+ url = replaceFlvExtension(url);
679
+ if (url !== originalUrl) {
680
+ log("Converted FLV to MP4: ".concat(originalUrl, " -> ").concat(url));
681
+ }
682
+ if (isUnsupportedFormat(url)) {
683
+ var ext = getFileExtension(url);
684
+ log("Skipping unsupported format: ".concat(url, " (extension: ").concat(ext, ", declared type: ").concat(type, ")"));
685
+ return;
686
+ }
687
+ if (isSupportedFormat(url, type)) {
688
+ mediaFiles.push({
689
+ url: url,
690
+ type: type,
691
+ width: width,
692
+ height: height,
693
+ bitrate: bitrate
694
+ });
695
+ log("Found media file: ".concat(url, " (").concat(type, ", ").concat(width, "x").concat(height, ")"));
696
+ } else {
697
+ log("Skipping incompatible media file: ".concat(url, " (type: ").concat(type, ")"));
698
+ }
699
+ });
700
+ if (mediaFiles.length === 0) {
701
+ log("No valid media files found in ad:", adId);
702
+ return;
703
+ }
704
+ var trackingUrls = {
705
+ impression: [],
706
+ start: [],
707
+ firstQuartile: [],
708
+ midpoint: [],
709
+ thirdQuartile: [],
710
+ complete: [],
711
+ mute: [],
712
+ unmute: [],
713
+ pause: [],
714
+ resume: [],
715
+ error: []
716
+ };
717
+ adElement.querySelectorAll("Impression").forEach(function(el) {
718
+ var _el_textContent;
719
+ var url = (_el_textContent = el.textContent) === null || _el_textContent === void 0 ? void 0 : _el_textContent.trim();
720
+ if (url) trackingUrls.impression.push(url);
721
+ });
722
+ adElement.querySelectorAll("Tracking").forEach(function(el) {
723
+ var _el_textContent;
724
+ var event = el.getAttribute("event");
725
+ var url = (_el_textContent = el.textContent) === null || _el_textContent === void 0 ? void 0 : _el_textContent.trim();
726
+ if (event && url) {
727
+ var eventKey = event;
728
+ if (trackingUrls[eventKey]) {
729
+ trackingUrls[eventKey].push(url);
730
+ }
731
+ }
732
+ });
733
+ var clickThrough = (_adElement_querySelector2 = adElement.querySelector("ClickThrough")) === null || _adElement_querySelector2 === void 0 ? void 0 : (_adElement_querySelector_textContent = _adElement_querySelector2.textContent) === null || _adElement_querySelector_textContent === void 0 ? void 0 : _adElement_querySelector_textContent.trim();
734
+ ads.push({
735
+ id: adId,
736
+ title: title,
737
+ duration: duration,
738
+ mediaFiles: mediaFiles,
739
+ trackingUrls: trackingUrls,
740
+ clickThrough: clickThrough
741
+ });
742
+ log("Parsed ad: ".concat(title, ", duration: ").concat(duration, "s, media files: ").concat(mediaFiles.length));
743
+ });
744
+ } catch (error) {
745
+ console.error("[AdStormPlayer] Error parsing VAST XML:", error);
746
+ }
747
+ return ads;
748
+ }
749
+ function selectBestMediaFile(mediaFiles) {
750
+ if (mediaFiles.length === 0) return null;
751
+ if (mediaFiles.length === 1) return mediaFiles[0];
752
+ var mp4Files = mediaFiles.filter(function(mf) {
753
+ return mf.type.includes("video/mp4");
754
+ });
755
+ var candidates = mp4Files.length > 0 ? mp4Files : mediaFiles;
756
+ var targetWidth = contentVideo.videoWidth || 1280;
757
+ var targetHeight = contentVideo.videoHeight || 720;
758
+ candidates.sort(function(a, b) {
759
+ var diffA = Math.abs(a.width - targetWidth) + Math.abs(a.height - targetHeight);
760
+ var diffB = Math.abs(b.width - targetWidth) + Math.abs(b.height - targetHeight);
761
+ return diffA - diffB;
762
+ });
763
+ return candidates[0] || null;
764
+ }
765
+ function createAdVideoElement() {
766
+ var video = document.createElement("video");
767
+ video.style.position = "absolute";
768
+ video.style.left = "0";
769
+ video.style.top = "0";
770
+ video.style.width = "100%";
771
+ video.style.height = "100%";
772
+ video.style.objectFit = "contain";
773
+ video.style.backgroundColor = "#000";
774
+ video.style.zIndex = "1";
775
+ video.playsInline = true;
776
+ video.preload = "auto";
777
+ video.muted = originalMutedState;
778
+ video.volume = originalMutedState ? 0 : originalVolume;
779
+ return video;
780
+ }
781
+ function setAdPlayingFlag(isPlaying) {
782
+ if (isPlaying) {
783
+ contentVideo.dataset.stormcloudAdPlaying = "true";
784
+ } else {
785
+ delete contentVideo.dataset.stormcloudAdPlaying;
786
+ }
787
+ }
788
+ function setupAdEventListeners() {
789
+ bindAdEventListeners();
790
+ }
791
+ function handleAdComplete() {
792
+ if (destroyed || tornDown) return;
793
+ log("Handling ad completion");
794
+ adPlaying = false;
795
+ setAdPlayingFlag(false);
796
+ clearAdStallTimer();
797
+ clearAdCountdownTimer();
798
+ if (adContainerEl) {
799
+ adContainerEl.style.opacity = "0";
800
+ adHideTimerId = setTimeout(function() {
801
+ if (adContainerEl) {
802
+ adContainerEl.style.display = "none";
803
+ adContainerEl.style.pointerEvents = "none";
804
+ }
805
+ }, 300);
806
+ }
807
+ contentVideo.style.visibility = "visible";
808
+ contentVideo.style.opacity = "1";
809
+ contentVideo.muted = originalMutedState;
810
+ contentVideo.volume = originalVolume;
811
+ currentAd = void 0;
812
+ emit("content_resume");
813
+ emit("all_ads_completed");
814
+ }
815
+ function handleAdError() {
816
+ if (destroyed || tornDown) return;
817
+ log("Handling ad error");
818
+ if (!adPlaying) return;
819
+ adPlaying = false;
820
+ setAdPlayingFlag(false);
821
+ clearAdStallTimer();
822
+ clearAdCountdownTimer();
823
+ contentVideo.muted = originalMutedState;
824
+ contentVideo.volume = originalVolume;
825
+ contentVideo.style.visibility = "visible";
826
+ contentVideo.style.opacity = "1";
827
+ if (adContainerEl) {
828
+ adContainerEl.style.display = "none";
829
+ adContainerEl.style.pointerEvents = "none";
830
+ }
831
+ currentAd = void 0;
832
+ emit("ad_error");
833
+ emit("content_resume");
834
+ }
835
+ function fetchVastOnce(durationSeconds) {
836
+ return _async_to_generator(function() {
837
+ var vastUrl, controller, timeoutId, requestInit, response, xmlText;
838
+ return _ts_generator(this, function(_state) {
839
+ switch(_state.label){
840
+ case 0:
841
+ vastUrl = buildVastUrl(durationSeconds);
842
+ log("Fetching VAST from:", vastUrl);
843
+ controller = typeof AbortController !== "undefined" ? new AbortController() : null;
844
+ timeoutId = setTimeout(function() {
845
+ return controller === null || controller === void 0 ? void 0 : controller.abort();
846
+ }, REQUEST_TIMEOUT_MS);
847
+ _state.label = 1;
848
+ case 1:
849
+ _state.trys.push([
850
+ 1,
851
+ ,
852
+ 4,
853
+ 5
854
+ ]);
855
+ requestInit = {
856
+ method: "GET",
857
+ mode: "cors",
858
+ credentials: "omit",
859
+ headers: {
860
+ Accept: "application/xml, text/xml, */*"
861
+ },
862
+ referrerPolicy: "no-referrer-when-downgrade"
863
+ };
864
+ if (controller) {
865
+ requestInit.signal = controller.signal;
866
+ }
867
+ return [
868
+ 4,
869
+ fetch(vastUrl, requestInit)
870
+ ];
871
+ case 2:
872
+ response = _state.sent();
873
+ if (!response.ok) {
874
+ throw new Error("Failed to fetch VAST: ".concat(response.status, " ").concat(response.statusText));
875
+ }
876
+ return [
877
+ 4,
878
+ response.text()
879
+ ];
880
+ case 3:
881
+ xmlText = _state.sent();
882
+ log("VAST response received, length:", xmlText.length);
883
+ return [
884
+ 2,
885
+ parseVastXml(xmlText)
886
+ ];
887
+ case 4:
888
+ clearTimeout(timeoutId);
889
+ return [
890
+ 7
891
+ ];
892
+ case 5:
893
+ return [
894
+ 2
895
+ ];
896
+ }
897
+ });
898
+ })();
899
+ }
900
+ function fetchVast(durationSeconds) {
901
+ return _async_to_generator(function() {
902
+ var _loop, lastError, attempt, _ret;
903
+ return _ts_generator(this, function(_state) {
904
+ switch(_state.label){
905
+ case 0:
906
+ _loop = function(attempt) {
907
+ var ads, error, delay;
908
+ return _ts_generator(this, function(_state) {
909
+ switch(_state.label){
910
+ case 0:
911
+ _state.trys.push([
912
+ 0,
913
+ 2,
914
+ ,
915
+ 3
916
+ ]);
917
+ return [
918
+ 4,
919
+ fetchVastOnce(durationSeconds)
920
+ ];
921
+ case 1:
922
+ ads = _state.sent();
923
+ if (ads.length > 0) return [
924
+ 2,
925
+ {
926
+ v: ads
927
+ }
928
+ ];
929
+ log("No ad returned from VAST on attempt ".concat(attempt, "/").concat(REQUEST_MAX_RETRIES));
930
+ return [
931
+ 3,
932
+ 3
933
+ ];
934
+ case 2:
935
+ error = _state.sent();
936
+ lastError = error;
937
+ if ((error === null || error === void 0 ? void 0 : error.name) === "AbortError") {
938
+ console.warn("[AdStormPlayer] VAST request timed out (".concat(REQUEST_TIMEOUT_MS, "ms), attempt ").concat(attempt, "/").concat(REQUEST_MAX_RETRIES));
939
+ } else {
940
+ console.warn("[AdStormPlayer] VAST request failed on attempt ".concat(attempt, "/").concat(REQUEST_MAX_RETRIES, ":"), error);
941
+ }
942
+ return [
943
+ 3,
944
+ 3
945
+ ];
946
+ case 3:
947
+ if (!(attempt < REQUEST_MAX_RETRIES)) return [
948
+ 3,
949
+ 5
950
+ ];
951
+ delay = REQUEST_RETRY_BACKOFF_MS * attempt;
952
+ return [
953
+ 4,
954
+ new Promise(function(resolve) {
955
+ return setTimeout(resolve, delay);
956
+ })
957
+ ];
958
+ case 4:
959
+ _state.sent();
960
+ _state.label = 5;
961
+ case 5:
962
+ return [
963
+ 2
964
+ ];
965
+ }
966
+ });
967
+ };
968
+ attempt = 1;
969
+ _state.label = 1;
970
+ case 1:
971
+ if (!(attempt <= REQUEST_MAX_RETRIES)) return [
972
+ 3,
973
+ 4
974
+ ];
975
+ return [
976
+ 5,
977
+ _ts_values(_loop(attempt))
978
+ ];
979
+ case 2:
980
+ _ret = _state.sent();
981
+ if (_type_of(_ret) === "object") return [
982
+ 2,
983
+ _ret.v
984
+ ];
985
+ _state.label = 3;
986
+ case 3:
987
+ attempt++;
988
+ return [
989
+ 3,
990
+ 1
991
+ ];
992
+ case 4:
993
+ if (_instanceof(lastError, Error)) {
994
+ throw lastError;
995
+ }
996
+ return [
997
+ 2,
998
+ []
999
+ ];
1000
+ }
1001
+ });
1002
+ })();
1003
+ }
1004
+ function getDurationSecondsFromContext(requestContext) {
1005
+ var _ctx_remainingBreakSec;
1006
+ if (!requestContext || (typeof requestContext === "undefined" ? "undefined" : _type_of(requestContext)) !== "object") {
1007
+ return 30;
1008
+ }
1009
+ var ctx = requestContext;
1010
+ var value = (_ctx_remainingBreakSec = ctx.remainingBreakSec) !== null && _ctx_remainingBreakSec !== void 0 ? _ctx_remainingBreakSec : ctx.breakDurationSec;
1011
+ if (typeof value !== "number" || Number.isNaN(value)) {
1012
+ return 30;
1013
+ }
1014
+ return Math.max(1, Math.ceil(value));
1015
+ }
1016
+ function requestAdFromApi(requestContext) {
1017
+ return _async_to_generator(function() {
1018
+ var durationSeconds, ads;
1019
+ return _ts_generator(this, function(_state) {
1020
+ switch(_state.label){
1021
+ case 0:
1022
+ durationSeconds = getDurationSecondsFromContext(requestContext);
1023
+ return [
1024
+ 4,
1025
+ fetchVast(durationSeconds)
1026
+ ];
1027
+ case 1:
1028
+ ads = _state.sent();
1029
+ return [
1030
+ 2,
1031
+ ads[0] || null
1032
+ ];
1033
+ }
1034
+ });
1035
+ })();
1036
+ }
1037
+ function assignCurrentAd(ad) {
1038
+ currentAd = ad;
1039
+ sessionId = generateSessionId();
1040
+ trackingFired = {
1041
+ impression: false,
1042
+ start: false,
1043
+ firstQuartile: false,
1044
+ midpoint: false,
1045
+ thirdQuartile: false,
1046
+ complete: false
1047
+ };
1048
+ fireTrackingPixels2(currentAd.trackingUrls.impression);
1049
+ trackingFired.impression = true;
1050
+ emit("ad_impression");
1051
+ }
1052
+ return {
1053
+ initialize: function initialize() {
1054
+ log("Initializing");
1055
+ if (!adContainerEl) {
1056
+ var _contentVideo_parentElement;
1057
+ var parent = contentVideo.parentElement;
1058
+ if (parent) {
1059
+ var computed = window.getComputedStyle(parent).position;
1060
+ if (computed === "static") {
1061
+ parent.style.position = "relative";
1062
+ parentPositionOverridden = true;
1063
+ }
1064
+ }
1065
+ var container = document.createElement("div");
1066
+ container.style.position = "absolute";
1067
+ container.style.left = "0";
1068
+ container.style.top = "0";
1069
+ container.style.right = "0";
1070
+ container.style.bottom = "0";
1071
+ container.style.display = "none";
1072
+ container.style.alignItems = "center";
1073
+ container.style.justifyContent = "center";
1074
+ container.style.pointerEvents = "none";
1075
+ container.style.zIndex = AD_LAYER_Z_INDEX;
1076
+ container.style.backgroundColor = "#000";
1077
+ container.style.transition = "opacity 0.3s ease-in-out";
1078
+ container.style.opacity = "0";
1079
+ container.style.isolation = "isolate";
1080
+ var countdown = document.createElement("div");
1081
+ countdown.style.position = "absolute";
1082
+ countdown.style.right = "12px";
1083
+ countdown.style.top = "12px";
1084
+ countdown.style.padding = "4px 8px";
1085
+ countdown.style.borderRadius = "4px";
1086
+ countdown.style.background = "rgba(0,0,0,0.75)";
1087
+ countdown.style.color = "#fff";
1088
+ countdown.style.fontFamily = "sans-serif";
1089
+ countdown.style.fontSize = "12px";
1090
+ countdown.style.lineHeight = "1.2";
1091
+ countdown.style.pointerEvents = "none";
1092
+ countdown.style.zIndex = COUNTDOWN_Z_INDEX;
1093
+ countdown.textContent = "Ad";
1094
+ container.appendChild(countdown);
1095
+ (_contentVideo_parentElement = contentVideo.parentElement) === null || _contentVideo_parentElement === void 0 ? void 0 : _contentVideo_parentElement.appendChild(container);
1096
+ adContainerEl = container;
1097
+ adCountdownEl = countdown;
1098
+ }
1099
+ },
1100
+ requestAds: function requestAds(duration) {
1101
+ return _async_to_generator(function() {
1102
+ var durationSeconds, parsed, ads, error;
1103
+ return _ts_generator(this, function(_state) {
1104
+ switch(_state.label){
1105
+ case 0:
1106
+ log("Requesting ads for duration:", duration);
1107
+ if (adPlaying) {
1108
+ return [
1109
+ 2,
1110
+ Promise.reject(new Error("Ad already playing"))
1111
+ ];
1112
+ }
1113
+ if (destroyed) {
1114
+ return [
1115
+ 2,
1116
+ Promise.reject(new Error("Player has been destroyed"))
1117
+ ];
1118
+ }
1119
+ _state.label = 1;
1120
+ case 1:
1121
+ _state.trys.push([
1122
+ 1,
1123
+ 3,
1124
+ ,
1125
+ 4
1126
+ ]);
1127
+ tornDown = false;
1128
+ durationSeconds = 30;
1129
+ parsed = parseInt(duration || "", 10);
1130
+ if (!isNaN(parsed) && parsed > 0) {
1131
+ durationSeconds = parsed;
1132
+ }
1133
+ return [
1134
+ 4,
1135
+ fetchVast(durationSeconds)
1136
+ ];
1137
+ case 2:
1138
+ ads = _state.sent();
1139
+ if (ads.length === 0) {
1140
+ log("No ads available from VAST response");
1141
+ emit("ad_error");
1142
+ return [
1143
+ 2,
1144
+ Promise.resolve()
1145
+ ];
1146
+ }
1147
+ assignCurrentAd(ads[0]);
1148
+ log("Ad loaded: ".concat(currentAd.title, ", duration: ").concat(currentAd.duration, "s"));
1149
+ return [
1150
+ 2,
1151
+ Promise.resolve()
1152
+ ];
1153
+ case 3:
1154
+ error = _state.sent();
1155
+ console.error("[AdStormPlayer] Error requesting ads:", error);
1156
+ emit("ad_error");
1157
+ return [
1158
+ 2,
1159
+ Promise.reject(error)
1160
+ ];
1161
+ case 4:
1162
+ return [
1163
+ 2
1164
+ ];
1165
+ }
1166
+ });
1167
+ })();
1168
+ },
1169
+ play: function play() {
1170
+ return _async_to_generator(function() {
1171
+ var mediaFile, error;
1172
+ return _ts_generator(this, function(_state) {
1173
+ switch(_state.label){
1174
+ case 0:
1175
+ if (!currentAd) {
1176
+ return [
1177
+ 2,
1178
+ Promise.reject(new Error("No ad loaded"))
1179
+ ];
1180
+ }
1181
+ if (destroyed) {
1182
+ return [
1183
+ 2,
1184
+ Promise.reject(new Error("Player has been destroyed"))
1185
+ ];
1186
+ }
1187
+ log("Starting ad playback");
1188
+ _state.label = 1;
1189
+ case 1:
1190
+ _state.trys.push([
1191
+ 1,
1192
+ 3,
1193
+ ,
1194
+ 4
1195
+ ]);
1196
+ tornDown = false;
1197
+ if (adHideTimerId) {
1198
+ clearTimeout(adHideTimerId);
1199
+ adHideTimerId = void 0;
1200
+ }
1201
+ if (!adVideoElement) {
1202
+ adVideoElement = createAdVideoElement();
1203
+ adContainerEl === null || adContainerEl === void 0 ? void 0 : adContainerEl.appendChild(adVideoElement);
1204
+ } else {
1205
+ teardownCurrentPlayback();
1206
+ }
1207
+ setupAdEventListeners();
1208
+ trackingFired = {
1209
+ impression: trackingFired.impression,
1210
+ start: false,
1211
+ firstQuartile: false,
1212
+ midpoint: false,
1213
+ thirdQuartile: false,
1214
+ complete: false
1215
+ };
1216
+ contentVideo.style.transition = "opacity 0.3s ease-in-out";
1217
+ contentVideo.style.opacity = "0";
1218
+ setTimeout(function() {
1219
+ contentVideo.style.visibility = "hidden";
1220
+ }, 300);
1221
+ contentVideo.muted = true;
1222
+ contentVideo.volume = 0;
1223
+ if (!continueLiveStreamDuringAds) {
1224
+ contentVideo.pause();
1225
+ }
1226
+ adPlaying = true;
1227
+ setAdPlayingFlag(true);
1228
+ if (adVideoElement) {
1229
+ adVideoElement.volume = originalMutedState ? 0 : originalVolume;
1230
+ adVideoElement.muted = originalMutedState;
1231
+ }
1232
+ if (adContainerEl) {
1233
+ adContainerEl.style.display = "flex";
1234
+ adContainerEl.style.pointerEvents = "auto";
1235
+ adContainerEl.offsetHeight;
1236
+ adContainerEl.style.opacity = "1";
1237
+ }
1238
+ emit("content_pause");
1239
+ mediaFile = selectBestMediaFile(currentAd.mediaFiles);
1240
+ if (!mediaFile) {
1241
+ throw new Error("No media file available");
1242
+ }
1243
+ log("Playing media file:", mediaFile.url);
1244
+ adVideoElement.src = mediaFile.url;
1245
+ adVideoElement.load();
1246
+ return [
1247
+ 4,
1248
+ adVideoElement.play()
1249
+ ];
1250
+ case 2:
1251
+ _state.sent();
1252
+ return [
1253
+ 2,
1254
+ Promise.resolve()
1255
+ ];
1256
+ case 3:
1257
+ error = _state.sent();
1258
+ console.error("[AdStormPlayer] Error playing ad:", error);
1259
+ handleAdError();
1260
+ return [
1261
+ 2,
1262
+ Promise.reject(error)
1263
+ ];
1264
+ case 4:
1265
+ return [
1266
+ 2
1267
+ ];
1268
+ }
1269
+ });
1270
+ })();
1271
+ },
1272
+ stop: function stop() {
1273
+ return _async_to_generator(function() {
1274
+ return _ts_generator(this, function(_state) {
1275
+ log("Stopping ad");
1276
+ tornDown = true;
1277
+ adPlaying = false;
1278
+ setAdPlayingFlag(false);
1279
+ clearAdStallTimer();
1280
+ clearAdCountdownTimer();
1281
+ if (adContainerEl) {
1282
+ adContainerEl.style.opacity = "0";
1283
+ adHideTimerId = setTimeout(function() {
1284
+ if (adContainerEl) {
1285
+ adContainerEl.style.display = "none";
1286
+ adContainerEl.style.pointerEvents = "none";
1287
+ }
1288
+ }, 300);
1289
+ }
1290
+ teardownCurrentPlayback();
1291
+ contentVideo.style.visibility = "visible";
1292
+ contentVideo.style.opacity = "1";
1293
+ contentVideo.muted = originalMutedState;
1294
+ contentVideo.volume = originalVolume;
1295
+ currentAd = void 0;
1296
+ tornDown = false;
1297
+ return [
1298
+ 2,
1299
+ Promise.resolve()
1300
+ ];
1301
+ });
1302
+ })();
1303
+ },
1304
+ pause: function pause() {
1305
+ if (!adPlaying || !adVideoElement) return;
1306
+ try {
1307
+ if (!adVideoElement.paused) adVideoElement.pause();
1308
+ } catch (error) {
1309
+ console.warn("[AdStormPlayer] Error pausing ad:", error);
1310
+ }
1311
+ },
1312
+ resume: function resume() {
1313
+ if (!adPlaying || !adVideoElement) return;
1314
+ try {
1315
+ if (adVideoElement.paused) adVideoElement.play().catch(function() {});
1316
+ } catch (error) {
1317
+ console.warn("[AdStormPlayer] Error resuming ad:", error);
1318
+ }
1319
+ },
1320
+ destroy: function destroy() {
1321
+ log("Destroying");
1322
+ destroyed = true;
1323
+ tornDown = true;
1324
+ adPlaying = false;
1325
+ setAdPlayingFlag(false);
1326
+ clearAdStallTimer();
1327
+ clearAdCountdownTimer();
1328
+ if (adHideTimerId) {
1329
+ clearTimeout(adHideTimerId);
1330
+ adHideTimerId = void 0;
1331
+ }
1332
+ contentVideo.muted = originalMutedState;
1333
+ contentVideo.volume = originalVolume;
1334
+ contentVideo.style.visibility = "visible";
1335
+ contentVideo.style.opacity = "1";
1336
+ teardownCurrentPlayback();
1337
+ adVideoElement === null || adVideoElement === void 0 ? void 0 : adVideoElement.remove();
1338
+ adVideoElement = void 0;
1339
+ if (adContainerEl === null || adContainerEl === void 0 ? void 0 : adContainerEl.parentElement) {
1340
+ adContainerEl.parentElement.removeChild(adContainerEl);
1341
+ }
1342
+ adContainerEl = void 0;
1343
+ adCountdownEl = void 0;
1344
+ currentAd = void 0;
1345
+ sessionId = void 0;
1346
+ preloadSlots.clear();
1347
+ listeners.clear();
1348
+ if (parentPositionOverridden && contentVideo.parentElement) {
1349
+ contentVideo.parentElement.style.position = "";
1350
+ parentPositionOverridden = false;
1351
+ }
1352
+ },
1353
+ updateOptions: function updateOptions(opts) {
1354
+ if (opts.continueLiveStreamDuringAds !== void 0) {
1355
+ continueLiveStreamDuringAds = opts.continueLiveStreamDuringAds;
1356
+ }
1357
+ },
1358
+ playAd: function playAd(requestContext) {
1359
+ return _async_to_generator(function() {
1360
+ var ad;
1361
+ return _ts_generator(this, function(_state) {
1362
+ switch(_state.label){
1363
+ case 0:
1364
+ if (destroyed) return [
1365
+ 2,
1366
+ Promise.reject(new Error("Player has been destroyed"))
1367
+ ];
1368
+ if (!!currentAd) return [
1369
+ 3,
1370
+ 2
1371
+ ];
1372
+ return [
1373
+ 4,
1374
+ requestAdFromApi(requestContext)
1375
+ ];
1376
+ case 1:
1377
+ ad = _state.sent();
1378
+ if (!ad) {
1379
+ emit("ad_error", {
1380
+ message: "No valid ad from AdStorm API"
1381
+ });
1382
+ return [
1383
+ 2,
1384
+ Promise.reject(new Error("No valid ad from AdStorm API"))
1385
+ ];
1386
+ }
1387
+ assignCurrentAd(ad);
1388
+ _state.label = 2;
1389
+ case 2:
1390
+ return [
1391
+ 2,
1392
+ this.play()
1393
+ ];
1394
+ }
1395
+ });
1396
+ }).call(this);
1397
+ },
1398
+ preloadAd: function preloadAd(arg1, arg2) {
1399
+ return _async_to_generator(function() {
1400
+ var token, requestContext, ad;
1401
+ return _ts_generator(this, function(_state) {
1402
+ switch(_state.label){
1403
+ case 0:
1404
+ if (destroyed) return [
1405
+ 2
1406
+ ];
1407
+ token = typeof arg1 === "string" ? arg1 : typeof arg2 === "string" ? arg2 : void 0;
1408
+ if (!token) return [
1409
+ 2
1410
+ ];
1411
+ requestContext = typeof arg1 === "string" ? arg2 : arg1;
1412
+ return [
1413
+ 4,
1414
+ requestAdFromApi(requestContext)
1415
+ ];
1416
+ case 1:
1417
+ ad = _state.sent();
1418
+ if (!ad) return [
1419
+ 2
1420
+ ];
1421
+ preloadSlots.set(token, {
1422
+ ad: ad
1423
+ });
1424
+ return [
1425
+ 2
1426
+ ];
1427
+ }
1428
+ });
1429
+ })();
1430
+ },
1431
+ playPreloaded: function playPreloaded(token) {
1432
+ return _async_to_generator(function() {
1433
+ var slot;
1434
+ return _ts_generator(this, function(_state) {
1435
+ if (destroyed) return [
1436
+ 2,
1437
+ Promise.reject(new Error("Player has been destroyed"))
1438
+ ];
1439
+ slot = preloadSlots.get(token);
1440
+ if (!slot) {
1441
+ return [
1442
+ 2,
1443
+ Promise.reject(new Error("No preloaded ad for token ".concat(token)))
1444
+ ];
1445
+ }
1446
+ preloadSlots.delete(token);
1447
+ assignCurrentAd(slot.ad);
1448
+ return [
1449
+ 2,
1450
+ this.play()
1451
+ ];
1452
+ });
1453
+ }).call(this);
1454
+ },
1455
+ hasPreloaded: function hasPreloaded(token) {
1456
+ return preloadSlots.has(token);
1457
+ },
1458
+ cancelPreload: function cancelPreload(token) {
1459
+ preloadSlots.delete(token);
1460
+ },
1461
+ isAdPlaying: function isAdPlaying() {
1462
+ return adPlaying;
1463
+ },
1464
+ resize: function resize(width, height) {
1465
+ log("Resizing to ".concat(width, "x").concat(height));
1466
+ if (adContainerEl) {
1467
+ adContainerEl.style.width = "".concat(width, "px");
1468
+ adContainerEl.style.height = "".concat(height, "px");
1469
+ }
1470
+ if (adVideoElement) {
1471
+ adVideoElement.style.width = "".concat(width, "px");
1472
+ adVideoElement.style.height = "".concat(height, "px");
1473
+ }
1474
+ },
1475
+ on: function on(event, listener) {
1476
+ if (!listeners.has(event)) listeners.set(event, /* @__PURE__ */ new Set());
1477
+ listeners.get(event).add(listener);
1478
+ },
1479
+ off: function off(event, listener) {
1480
+ var _listeners_get;
1481
+ (_listeners_get = listeners.get(event)) === null || _listeners_get === void 0 ? void 0 : _listeners_get.delete(listener);
1482
+ },
1483
+ updateOriginalMutedState: function updateOriginalMutedState(muted, volume) {
1484
+ var nextVolume = typeof volume === "number" && !Number.isNaN(volume) ? Math.max(0, Math.min(1, volume)) : originalVolume;
1485
+ log("updateOriginalMutedState: muted=".concat(muted, ", volume=").concat(nextVolume));
1486
+ originalMutedState = muted;
1487
+ originalVolume = nextVolume;
1488
+ },
1489
+ getOriginalMutedState: function getOriginalMutedState() {
1490
+ return originalMutedState;
1491
+ },
1492
+ getOriginalVolume: function getOriginalVolume() {
1493
+ return originalVolume;
1494
+ },
1495
+ setAdVolume: function setAdVolume(volume) {
1496
+ if (adVideoElement && adPlaying) {
1497
+ adVideoElement.volume = Math.max(0, Math.min(1, volume));
1498
+ adVideoElement.muted = volume === 0;
1499
+ }
1500
+ },
1501
+ getAdVolume: function getAdVolume() {
1502
+ if (adVideoElement && adPlaying) {
1503
+ return adVideoElement.volume;
1504
+ }
1505
+ return 1;
1506
+ },
1507
+ showPlaceholder: function showPlaceholder() {
1508
+ if (!adContainerEl) {
1509
+ var _contentVideo_parentElement;
1510
+ var parent = contentVideo.parentElement;
1511
+ if (parent) {
1512
+ var computed = window.getComputedStyle(parent).position;
1513
+ if (computed === "static") {
1514
+ parent.style.position = "relative";
1515
+ parentPositionOverridden = true;
1516
+ }
1517
+ }
1518
+ var container = document.createElement("div");
1519
+ container.style.position = "absolute";
1520
+ container.style.left = "0";
1521
+ container.style.top = "0";
1522
+ container.style.right = "0";
1523
+ container.style.bottom = "0";
1524
+ container.style.display = "none";
1525
+ container.style.alignItems = "center";
1526
+ container.style.justifyContent = "center";
1527
+ container.style.pointerEvents = "none";
1528
+ container.style.zIndex = AD_LAYER_Z_INDEX;
1529
+ container.style.backgroundColor = "#000";
1530
+ container.style.isolation = "isolate";
1531
+ var countdown = document.createElement("div");
1532
+ countdown.style.position = "absolute";
1533
+ countdown.style.right = "12px";
1534
+ countdown.style.top = "12px";
1535
+ countdown.style.padding = "4px 8px";
1536
+ countdown.style.borderRadius = "4px";
1537
+ countdown.style.background = "rgba(0,0,0,0.75)";
1538
+ countdown.style.color = "#fff";
1539
+ countdown.style.fontFamily = "sans-serif";
1540
+ countdown.style.fontSize = "12px";
1541
+ countdown.style.lineHeight = "1.2";
1542
+ countdown.style.pointerEvents = "none";
1543
+ countdown.style.zIndex = COUNTDOWN_Z_INDEX;
1544
+ countdown.textContent = "Ad";
1545
+ container.appendChild(countdown);
1546
+ (_contentVideo_parentElement = contentVideo.parentElement) === null || _contentVideo_parentElement === void 0 ? void 0 : _contentVideo_parentElement.appendChild(container);
1547
+ adContainerEl = container;
1548
+ adCountdownEl = countdown;
1549
+ }
1550
+ if (adContainerEl) {
1551
+ adContainerEl.style.display = "flex";
1552
+ adContainerEl.style.opacity = "1";
1553
+ adContainerEl.style.pointerEvents = "auto";
1554
+ }
1555
+ },
1556
+ hidePlaceholder: function hidePlaceholder() {
1557
+ if (adContainerEl) {
1558
+ adContainerEl.style.opacity = "0";
1559
+ setTimeout(function() {
1560
+ if (adContainerEl) {
1561
+ adContainerEl.style.display = "none";
1562
+ adContainerEl.style.pointerEvents = "none";
1563
+ }
1564
+ }, 300);
1565
+ }
1566
+ }
1567
+ };
1568
+ }
1569
+ // Annotate the CommonJS export names for ESM import in node:
1570
+ 0 && (module.exports = {
1571
+ createAdStormPlayer: createAdStormPlayer
1572
+ });
1573
+ //# sourceMappingURL=adstormPlayer.cjs.map