stormcloud-video-player 0.3.17 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,908 @@
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 _iterable_to_array(iter) {
40
+ if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
41
+ }
42
+ function _non_iterable_spread() {
43
+ throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
44
+ }
45
+ function _to_consumable_array(arr) {
46
+ return _array_without_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_spread();
47
+ }
48
+ function _type_of(obj) {
49
+ "@swc/helpers - typeof";
50
+ return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
51
+ }
52
+ function _unsupported_iterable_to_array(o, minLen) {
53
+ if (!o) return;
54
+ if (typeof o === "string") return _array_like_to_array(o, minLen);
55
+ var n = Object.prototype.toString.call(o).slice(8, -1);
56
+ if (n === "Object" && o.constructor) n = o.constructor.name;
57
+ if (n === "Map" || n === "Set") return Array.from(n);
58
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
59
+ }
60
+ function _ts_generator(thisArg, body) {
61
+ var f, y, t, _ = {
62
+ label: 0,
63
+ sent: function() {
64
+ if (t[0] & 1) throw t[1];
65
+ return t[1];
66
+ },
67
+ trys: [],
68
+ ops: []
69
+ }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
70
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() {
71
+ return this;
72
+ }), g;
73
+ function verb(n) {
74
+ return function(v) {
75
+ return step([
76
+ n,
77
+ v
78
+ ]);
79
+ };
80
+ }
81
+ function step(op) {
82
+ if (f) throw new TypeError("Generator is already executing.");
83
+ while(g && (g = 0, op[0] && (_ = 0)), _)try {
84
+ 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;
85
+ if (y = 0, t) op = [
86
+ op[0] & 2,
87
+ t.value
88
+ ];
89
+ switch(op[0]){
90
+ case 0:
91
+ case 1:
92
+ t = op;
93
+ break;
94
+ case 4:
95
+ _.label++;
96
+ return {
97
+ value: op[1],
98
+ done: false
99
+ };
100
+ case 5:
101
+ _.label++;
102
+ y = op[1];
103
+ op = [
104
+ 0
105
+ ];
106
+ continue;
107
+ case 7:
108
+ op = _.ops.pop();
109
+ _.trys.pop();
110
+ continue;
111
+ default:
112
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
113
+ _ = 0;
114
+ continue;
115
+ }
116
+ if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
117
+ _.label = op[1];
118
+ break;
119
+ }
120
+ if (op[0] === 6 && _.label < t[1]) {
121
+ _.label = t[1];
122
+ t = op;
123
+ break;
124
+ }
125
+ if (t && _.label < t[2]) {
126
+ _.label = t[2];
127
+ _.ops.push(op);
128
+ break;
129
+ }
130
+ if (t[2]) _.ops.pop();
131
+ _.trys.pop();
132
+ continue;
133
+ }
134
+ op = body.call(thisArg, _);
135
+ } catch (e) {
136
+ op = [
137
+ 6,
138
+ e
139
+ ];
140
+ y = 0;
141
+ } finally{
142
+ f = t = 0;
143
+ }
144
+ if (op[0] & 5) throw op[1];
145
+ return {
146
+ value: op[0] ? op[1] : void 0,
147
+ done: true
148
+ };
149
+ }
150
+ }
151
+ var __defProp = Object.defineProperty;
152
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
153
+ var __getOwnPropNames = Object.getOwnPropertyNames;
154
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
155
+ var __export = function(target, all) {
156
+ for(var name in all)__defProp(target, name, {
157
+ get: all[name],
158
+ enumerable: true
159
+ });
160
+ };
161
+ var __copyProps = function(to, from, except, desc) {
162
+ if (from && (typeof from === "undefined" ? "undefined" : _type_of(from)) === "object" || typeof from === "function") {
163
+ var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
164
+ try {
165
+ var _loop = function() {
166
+ var key = _step.value;
167
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
168
+ get: function() {
169
+ return from[key];
170
+ },
171
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
172
+ });
173
+ };
174
+ for(var _iterator = __getOwnPropNames(from)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true)_loop();
175
+ } catch (err) {
176
+ _didIteratorError = true;
177
+ _iteratorError = err;
178
+ } finally{
179
+ try {
180
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
181
+ _iterator.return();
182
+ }
183
+ } finally{
184
+ if (_didIteratorError) {
185
+ throw _iteratorError;
186
+ }
187
+ }
188
+ }
189
+ }
190
+ return to;
191
+ };
192
+ var __toCommonJS = function(mod) {
193
+ return __copyProps(__defProp({}, "__esModule", {
194
+ value: true
195
+ }), mod);
196
+ };
197
+ // src/sdk/adstormPlayer.ts
198
+ var adstormPlayer_exports = {};
199
+ __export(adstormPlayer_exports, {
200
+ createAdStormPlayer: function() {
201
+ return createAdStormPlayer;
202
+ }
203
+ });
204
+ module.exports = __toCommonJS(adstormPlayer_exports);
205
+ var SUPPORTED_VIDEO_EXTENSIONS = [
206
+ ".mp4",
207
+ ".webm",
208
+ ".ogg",
209
+ ".m3u8",
210
+ ".ts"
211
+ ];
212
+ var UNSUPPORTED_VIDEO_EXTENSIONS = [
213
+ ".flv",
214
+ ".f4v",
215
+ ".swf",
216
+ ".wmv",
217
+ ".avi",
218
+ ".mov",
219
+ ".mkv"
220
+ ];
221
+ function getFileExtension(url) {
222
+ try {
223
+ var pathname = new URL(url, "http://dummy").pathname;
224
+ var lastDot = pathname.lastIndexOf(".");
225
+ if (lastDot === -1) return "";
226
+ return pathname.slice(lastDot).toLowerCase();
227
+ } catch (e) {
228
+ var lastDot1 = url.lastIndexOf(".");
229
+ if (lastDot1 === -1) return "";
230
+ var ext = url.slice(lastDot1).split(/[?#]/)[0];
231
+ return (ext || "").toLowerCase();
232
+ }
233
+ }
234
+ function isUnsupportedFormat(url) {
235
+ var ext = getFileExtension(url);
236
+ return UNSUPPORTED_VIDEO_EXTENSIONS.indexOf(ext) !== -1;
237
+ }
238
+ function replaceFlvExtension(url) {
239
+ var ext = getFileExtension(url);
240
+ if (ext === ".flv") {
241
+ return url.replace(/\.flv(\?|$)/i, ".mp4$1");
242
+ }
243
+ return url;
244
+ }
245
+ function isSupportedFormat(url, mimeType) {
246
+ if (isUnsupportedFormat(url)) {
247
+ return false;
248
+ }
249
+ var ext = getFileExtension(url);
250
+ if (SUPPORTED_VIDEO_EXTENSIONS.indexOf(ext) !== -1) {
251
+ return true;
252
+ }
253
+ if (ext === "" || ext === ".") {
254
+ return mimeType.includes("video/mp4") || mimeType.includes("video/webm") || mimeType.includes("m3u8") || mimeType.includes("application/x-mpegurl");
255
+ }
256
+ return false;
257
+ }
258
+ function createAdStormPlayer(contentVideo, options) {
259
+ var licenseKey = options.licenseKey, _options_debug = options.debug, debug = _options_debug === void 0 ? false : _options_debug;
260
+ var adPlaying = false;
261
+ var originalMutedState = false;
262
+ var originalVolume = Math.max(0, Math.min(1, contentVideo.volume || 1));
263
+ var listeners = /* @__PURE__ */ new Map();
264
+ var adVideoElement;
265
+ var adContainerEl;
266
+ var currentAd;
267
+ var destroyed = false;
268
+ var trackingFired = {
269
+ impression: false,
270
+ start: false,
271
+ firstQuartile: false,
272
+ midpoint: false,
273
+ thirdQuartile: false,
274
+ complete: false
275
+ };
276
+ function log() {
277
+ for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
278
+ args[_key] = arguments[_key];
279
+ }
280
+ if (debug) {
281
+ var _console;
282
+ (_console = console).log.apply(_console, [
283
+ "[AdStormPlayer]"
284
+ ].concat(_to_consumable_array(args)));
285
+ }
286
+ }
287
+ function emit(event, payload) {
288
+ var set = listeners.get(event);
289
+ if (!set) return;
290
+ var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
291
+ try {
292
+ for(var _iterator = Array.from(set)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
293
+ var fn = _step.value;
294
+ try {
295
+ fn(payload);
296
+ } catch (error) {
297
+ console.warn("[AdStormPlayer] Error in event listener for ".concat(event, ":"), error);
298
+ }
299
+ }
300
+ } catch (err) {
301
+ _didIteratorError = true;
302
+ _iteratorError = err;
303
+ } finally{
304
+ try {
305
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
306
+ _iterator.return();
307
+ }
308
+ } finally{
309
+ if (_didIteratorError) {
310
+ throw _iteratorError;
311
+ }
312
+ }
313
+ }
314
+ }
315
+ function fireTrackingPixels(urls) {
316
+ if (!urls || urls.length === 0) return;
317
+ urls.forEach(function(url) {
318
+ try {
319
+ var img = new Image(1, 1);
320
+ img.src = url;
321
+ log("Fired tracking pixel:", url);
322
+ } catch (error) {
323
+ console.warn("[AdStormPlayer] Error firing tracking pixel:", error);
324
+ }
325
+ });
326
+ }
327
+ function buildVastUrl(durationSeconds, metadata) {
328
+ var baseUrl = "https://adstorm.co/api-adstorm-dev/adstorm/vast/".concat(licenseKey, "/pod");
329
+ var defaultMetadata = {
330
+ video: {
331
+ codec: "h264",
332
+ width: contentVideo.videoWidth || 1280,
333
+ height: contentVideo.videoHeight || 720,
334
+ fps: 29.97,
335
+ bitrate: 5e3,
336
+ profile: "high",
337
+ pix_fmt: "yuv420p",
338
+ has_b_frames: 0
339
+ },
340
+ audio: {
341
+ codec: "aac",
342
+ sample_rate: 48e3,
343
+ bitrate: 128
344
+ }
345
+ };
346
+ var finalMetadata = metadata || defaultMetadata;
347
+ var metadataStr = encodeURIComponent(JSON.stringify(finalMetadata));
348
+ return "".concat(baseUrl, "?duration=").concat(Math.ceil(durationSeconds), "&metadata=").concat(metadataStr);
349
+ }
350
+ function parseVastXml(xmlString) {
351
+ var ads = [];
352
+ try {
353
+ var parser = new DOMParser();
354
+ var xmlDoc = parser.parseFromString(xmlString, "text/xml");
355
+ var parserError = xmlDoc.querySelector("parsererror");
356
+ if (parserError) {
357
+ console.error("[AdStormPlayer] XML parsing error:", parserError.textContent);
358
+ return [];
359
+ }
360
+ var adElements = xmlDoc.querySelectorAll("Ad");
361
+ adElements.forEach(function(adElement) {
362
+ var _adElement_querySelector, _adElement_querySelector1, _adElement_querySelector_textContent, _adElement_querySelector2;
363
+ var adId = adElement.getAttribute("id") || "unknown";
364
+ var title = ((_adElement_querySelector = adElement.querySelector("AdTitle")) === null || _adElement_querySelector === void 0 ? void 0 : _adElement_querySelector.textContent) || "Ad";
365
+ var durationText = ((_adElement_querySelector1 = adElement.querySelector("Duration")) === null || _adElement_querySelector1 === void 0 ? void 0 : _adElement_querySelector1.textContent) || "00:00:30";
366
+ var durationParts = durationText.split(":");
367
+ var duration = parseInt(durationParts[0] || "0", 10) * 3600 + parseInt(durationParts[1] || "0", 10) * 60 + parseFloat(durationParts[2] || "0");
368
+ var mediaFileElements = adElement.querySelectorAll("MediaFile");
369
+ var mediaFiles = [];
370
+ mediaFileElements.forEach(function(mf) {
371
+ var _mf_textContent;
372
+ var type = mf.getAttribute("type") || "";
373
+ var url = ((_mf_textContent = mf.textContent) === null || _mf_textContent === void 0 ? void 0 : _mf_textContent.trim()) || "";
374
+ var width = parseInt(mf.getAttribute("width") || "1920", 10);
375
+ var height = parseInt(mf.getAttribute("height") || "1080", 10);
376
+ var bitrate = mf.getAttribute("bitrate") ? parseInt(mf.getAttribute("bitrate"), 10) : void 0;
377
+ if (!url) {
378
+ log("Skipping empty MediaFile URL");
379
+ return;
380
+ }
381
+ var originalUrl = url;
382
+ url = replaceFlvExtension(url);
383
+ if (url !== originalUrl) {
384
+ log("Converted FLV to MP4: ".concat(originalUrl, " -> ").concat(url));
385
+ }
386
+ if (isUnsupportedFormat(url)) {
387
+ var ext = getFileExtension(url);
388
+ log("Skipping unsupported format: ".concat(url, " (extension: ").concat(ext, ", declared type: ").concat(type, ")"));
389
+ return;
390
+ }
391
+ if (isSupportedFormat(url, type)) {
392
+ mediaFiles.push({
393
+ url: url,
394
+ type: type,
395
+ width: width,
396
+ height: height,
397
+ bitrate: bitrate
398
+ });
399
+ log("Found media file: ".concat(url, " (").concat(type, ", ").concat(width, "x").concat(height, ")"));
400
+ } else {
401
+ log("Skipping incompatible media file: ".concat(url, " (type: ").concat(type, ")"));
402
+ }
403
+ });
404
+ if (mediaFiles.length === 0) {
405
+ log("No valid media files found in ad:", adId);
406
+ return;
407
+ }
408
+ var trackingUrls = {
409
+ impression: [],
410
+ start: [],
411
+ firstQuartile: [],
412
+ midpoint: [],
413
+ thirdQuartile: [],
414
+ complete: [],
415
+ error: []
416
+ };
417
+ adElement.querySelectorAll("Impression").forEach(function(el) {
418
+ var _el_textContent;
419
+ var url = (_el_textContent = el.textContent) === null || _el_textContent === void 0 ? void 0 : _el_textContent.trim();
420
+ if (url) trackingUrls.impression.push(url);
421
+ });
422
+ adElement.querySelectorAll("Tracking").forEach(function(el) {
423
+ var _el_textContent;
424
+ var event = el.getAttribute("event");
425
+ var url = (_el_textContent = el.textContent) === null || _el_textContent === void 0 ? void 0 : _el_textContent.trim();
426
+ if (event && url) {
427
+ var eventKey = event;
428
+ if (trackingUrls[eventKey]) {
429
+ trackingUrls[eventKey].push(url);
430
+ }
431
+ }
432
+ });
433
+ 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();
434
+ ads.push({
435
+ id: adId,
436
+ title: title,
437
+ duration: duration,
438
+ mediaFiles: mediaFiles,
439
+ trackingUrls: trackingUrls,
440
+ clickThrough: clickThrough
441
+ });
442
+ log("Parsed ad: ".concat(title, ", duration: ").concat(duration, "s, media files: ").concat(mediaFiles.length));
443
+ });
444
+ } catch (error) {
445
+ console.error("[AdStormPlayer] Error parsing VAST XML:", error);
446
+ }
447
+ return ads;
448
+ }
449
+ function selectBestMediaFile(mediaFiles) {
450
+ if (mediaFiles.length === 0) return null;
451
+ if (mediaFiles.length === 1) return mediaFiles[0];
452
+ var mp4Files = mediaFiles.filter(function(mf) {
453
+ return mf.type.includes("video/mp4");
454
+ });
455
+ var candidates = mp4Files.length > 0 ? mp4Files : mediaFiles;
456
+ var targetWidth = contentVideo.videoWidth || 1280;
457
+ var targetHeight = contentVideo.videoHeight || 720;
458
+ candidates.sort(function(a, b) {
459
+ var diffA = Math.abs(a.width - targetWidth) + Math.abs(a.height - targetHeight);
460
+ var diffB = Math.abs(b.width - targetWidth) + Math.abs(b.height - targetHeight);
461
+ return diffA - diffB;
462
+ });
463
+ return candidates[0] || null;
464
+ }
465
+ function createAdVideoElement() {
466
+ var video = document.createElement("video");
467
+ video.style.position = "absolute";
468
+ video.style.left = "0";
469
+ video.style.top = "0";
470
+ video.style.width = "100%";
471
+ video.style.height = "100%";
472
+ video.style.objectFit = "contain";
473
+ video.style.backgroundColor = "#000";
474
+ video.style.zIndex = "15";
475
+ video.playsInline = true;
476
+ video.muted = false;
477
+ video.volume = originalMutedState ? 0 : originalVolume;
478
+ return video;
479
+ }
480
+ function setAdPlayingFlag(isPlaying) {
481
+ if (isPlaying) {
482
+ contentVideo.dataset.stormcloudAdPlaying = "true";
483
+ } else {
484
+ delete contentVideo.dataset.stormcloudAdPlaying;
485
+ }
486
+ }
487
+ function setupAdEventListeners() {
488
+ if (!adVideoElement || !currentAd) return;
489
+ var ad = currentAd;
490
+ adVideoElement.addEventListener("timeupdate", function() {
491
+ if (!ad || !adVideoElement) return;
492
+ var progress = adVideoElement.currentTime / ad.duration;
493
+ if (progress >= 0.25 && !trackingFired.firstQuartile) {
494
+ trackingFired.firstQuartile = true;
495
+ fireTrackingPixels(ad.trackingUrls.firstQuartile);
496
+ }
497
+ if (progress >= 0.5 && !trackingFired.midpoint) {
498
+ trackingFired.midpoint = true;
499
+ fireTrackingPixels(ad.trackingUrls.midpoint);
500
+ }
501
+ if (progress >= 0.75 && !trackingFired.thirdQuartile) {
502
+ trackingFired.thirdQuartile = true;
503
+ fireTrackingPixels(ad.trackingUrls.thirdQuartile);
504
+ }
505
+ });
506
+ adVideoElement.addEventListener("playing", function() {
507
+ if (!ad || trackingFired.start) return;
508
+ trackingFired.start = true;
509
+ fireTrackingPixels(ad.trackingUrls.start);
510
+ log("Ad started playing");
511
+ });
512
+ adVideoElement.addEventListener("ended", function() {
513
+ if (!ad || trackingFired.complete) return;
514
+ trackingFired.complete = true;
515
+ fireTrackingPixels(ad.trackingUrls.complete);
516
+ log("Ad completed");
517
+ handleAdComplete();
518
+ });
519
+ adVideoElement.addEventListener("error", function(e) {
520
+ console.error("[AdStormPlayer] Ad video error:", e);
521
+ if (ad) {
522
+ fireTrackingPixels(ad.trackingUrls.error);
523
+ }
524
+ handleAdError();
525
+ });
526
+ }
527
+ function handleAdComplete() {
528
+ log("Handling ad completion");
529
+ adPlaying = false;
530
+ setAdPlayingFlag(false);
531
+ if (adContainerEl) {
532
+ adContainerEl.style.opacity = "0";
533
+ setTimeout(function() {
534
+ if (adContainerEl) {
535
+ adContainerEl.style.display = "none";
536
+ adContainerEl.style.pointerEvents = "none";
537
+ }
538
+ }, 300);
539
+ }
540
+ contentVideo.style.visibility = "visible";
541
+ contentVideo.style.opacity = "1";
542
+ contentVideo.muted = originalMutedState;
543
+ contentVideo.volume = originalVolume;
544
+ emit("content_resume");
545
+ emit("all_ads_completed");
546
+ }
547
+ function handleAdError() {
548
+ log("Handling ad error");
549
+ adPlaying = false;
550
+ setAdPlayingFlag(false);
551
+ contentVideo.muted = originalMutedState;
552
+ contentVideo.volume = originalVolume;
553
+ contentVideo.style.visibility = "visible";
554
+ contentVideo.style.opacity = "1";
555
+ if (adContainerEl) {
556
+ adContainerEl.style.display = "none";
557
+ adContainerEl.style.pointerEvents = "none";
558
+ }
559
+ emit("ad_error");
560
+ }
561
+ function fetchVast(durationSeconds) {
562
+ return _async_to_generator(function() {
563
+ var vastUrl, response, xmlText;
564
+ return _ts_generator(this, function(_state) {
565
+ switch(_state.label){
566
+ case 0:
567
+ vastUrl = buildVastUrl(durationSeconds);
568
+ log("Fetching VAST from:", vastUrl);
569
+ return [
570
+ 4,
571
+ fetch(vastUrl, {
572
+ headers: {
573
+ "Accept": "application/xml"
574
+ }
575
+ })
576
+ ];
577
+ case 1:
578
+ response = _state.sent();
579
+ if (!response.ok) {
580
+ throw new Error("Failed to fetch VAST: ".concat(response.status, " ").concat(response.statusText));
581
+ }
582
+ return [
583
+ 4,
584
+ response.text()
585
+ ];
586
+ case 2:
587
+ xmlText = _state.sent();
588
+ log("VAST response received, length:", xmlText.length);
589
+ return [
590
+ 2,
591
+ parseVastXml(xmlText)
592
+ ];
593
+ }
594
+ });
595
+ })();
596
+ }
597
+ return {
598
+ initialize: function initialize() {
599
+ log("Initializing");
600
+ if (!adContainerEl) {
601
+ var _contentVideo_parentElement;
602
+ var container = document.createElement("div");
603
+ container.style.position = "absolute";
604
+ container.style.left = "0";
605
+ container.style.top = "0";
606
+ container.style.right = "0";
607
+ container.style.bottom = "0";
608
+ container.style.display = "none";
609
+ container.style.alignItems = "center";
610
+ container.style.justifyContent = "center";
611
+ container.style.pointerEvents = "none";
612
+ container.style.zIndex = "10";
613
+ container.style.backgroundColor = "#000";
614
+ container.style.transition = "opacity 0.3s ease-in-out";
615
+ container.style.opacity = "0";
616
+ (_contentVideo_parentElement = contentVideo.parentElement) === null || _contentVideo_parentElement === void 0 ? void 0 : _contentVideo_parentElement.appendChild(container);
617
+ adContainerEl = container;
618
+ }
619
+ },
620
+ requestAds: function requestAds(duration) {
621
+ return _async_to_generator(function() {
622
+ var durationSeconds, parsed, ads, error;
623
+ return _ts_generator(this, function(_state) {
624
+ switch(_state.label){
625
+ case 0:
626
+ log("Requesting ads for duration:", duration);
627
+ if (adPlaying) {
628
+ return [
629
+ 2,
630
+ Promise.reject(new Error("Ad already playing"))
631
+ ];
632
+ }
633
+ _state.label = 1;
634
+ case 1:
635
+ _state.trys.push([
636
+ 1,
637
+ 3,
638
+ ,
639
+ 4
640
+ ]);
641
+ durationSeconds = 30;
642
+ parsed = parseInt(duration, 10);
643
+ if (!isNaN(parsed) && parsed > 0) {
644
+ durationSeconds = parsed;
645
+ }
646
+ return [
647
+ 4,
648
+ fetchVast(durationSeconds)
649
+ ];
650
+ case 2:
651
+ ads = _state.sent();
652
+ if (ads.length === 0) {
653
+ log("No ads available from VAST response");
654
+ emit("ad_error");
655
+ return [
656
+ 2,
657
+ Promise.resolve()
658
+ ];
659
+ }
660
+ currentAd = ads[0];
661
+ log("Ad loaded: ".concat(currentAd.title, ", duration: ").concat(currentAd.duration, "s"));
662
+ fireTrackingPixels(currentAd.trackingUrls.impression);
663
+ trackingFired.impression = true;
664
+ return [
665
+ 2,
666
+ Promise.resolve()
667
+ ];
668
+ case 3:
669
+ error = _state.sent();
670
+ console.error("[AdStormPlayer] Error requesting ads:", error);
671
+ emit("ad_error");
672
+ return [
673
+ 2,
674
+ Promise.reject(error)
675
+ ];
676
+ case 4:
677
+ return [
678
+ 2
679
+ ];
680
+ }
681
+ });
682
+ })();
683
+ },
684
+ play: function play() {
685
+ return _async_to_generator(function() {
686
+ var mediaFile, error;
687
+ return _ts_generator(this, function(_state) {
688
+ switch(_state.label){
689
+ case 0:
690
+ if (!currentAd) {
691
+ return [
692
+ 2,
693
+ Promise.reject(new Error("No ad loaded"))
694
+ ];
695
+ }
696
+ log("Starting ad playback");
697
+ _state.label = 1;
698
+ case 1:
699
+ _state.trys.push([
700
+ 1,
701
+ 3,
702
+ ,
703
+ 4
704
+ ]);
705
+ if (!adVideoElement) {
706
+ adVideoElement = createAdVideoElement();
707
+ adContainerEl === null || adContainerEl === void 0 ? void 0 : adContainerEl.appendChild(adVideoElement);
708
+ setupAdEventListeners();
709
+ }
710
+ trackingFired = {
711
+ impression: trackingFired.impression,
712
+ start: false,
713
+ firstQuartile: false,
714
+ midpoint: false,
715
+ thirdQuartile: false,
716
+ complete: false
717
+ };
718
+ contentVideo.style.transition = "opacity 0.3s ease-in-out";
719
+ contentVideo.style.opacity = "0";
720
+ setTimeout(function() {
721
+ contentVideo.style.visibility = "hidden";
722
+ }, 300);
723
+ contentVideo.muted = true;
724
+ contentVideo.volume = 0;
725
+ contentVideo.pause();
726
+ adPlaying = true;
727
+ setAdPlayingFlag(true);
728
+ if (adVideoElement) {
729
+ adVideoElement.volume = originalMutedState ? 0 : originalVolume;
730
+ adVideoElement.muted = originalMutedState;
731
+ }
732
+ if (adContainerEl) {
733
+ adContainerEl.style.display = "flex";
734
+ adContainerEl.style.pointerEvents = "auto";
735
+ adContainerEl.offsetHeight;
736
+ adContainerEl.style.opacity = "1";
737
+ }
738
+ emit("content_pause");
739
+ mediaFile = selectBestMediaFile(currentAd.mediaFiles);
740
+ if (!mediaFile) {
741
+ throw new Error("No media file available");
742
+ }
743
+ log("Playing media file:", mediaFile.url);
744
+ adVideoElement.src = mediaFile.url;
745
+ return [
746
+ 4,
747
+ adVideoElement.play()
748
+ ];
749
+ case 2:
750
+ _state.sent();
751
+ return [
752
+ 2,
753
+ Promise.resolve()
754
+ ];
755
+ case 3:
756
+ error = _state.sent();
757
+ console.error("[AdStormPlayer] Error playing ad:", error);
758
+ handleAdError();
759
+ return [
760
+ 2,
761
+ Promise.reject(error)
762
+ ];
763
+ case 4:
764
+ return [
765
+ 2
766
+ ];
767
+ }
768
+ });
769
+ })();
770
+ },
771
+ stop: function stop() {
772
+ return _async_to_generator(function() {
773
+ return _ts_generator(this, function(_state) {
774
+ log("Stopping ad");
775
+ adPlaying = false;
776
+ setAdPlayingFlag(false);
777
+ if (adContainerEl) {
778
+ adContainerEl.style.opacity = "0";
779
+ setTimeout(function() {
780
+ if (adContainerEl) {
781
+ adContainerEl.style.display = "none";
782
+ adContainerEl.style.pointerEvents = "none";
783
+ }
784
+ }, 300);
785
+ }
786
+ if (adVideoElement) {
787
+ adVideoElement.pause();
788
+ adVideoElement.src = "";
789
+ }
790
+ contentVideo.style.visibility = "visible";
791
+ contentVideo.style.opacity = "1";
792
+ currentAd = void 0;
793
+ return [
794
+ 2
795
+ ];
796
+ });
797
+ })();
798
+ },
799
+ destroy: function destroy() {
800
+ log("Destroying");
801
+ destroyed = true;
802
+ adPlaying = false;
803
+ setAdPlayingFlag(false);
804
+ contentVideo.muted = originalMutedState;
805
+ contentVideo.volume = originalVolume;
806
+ contentVideo.style.visibility = "visible";
807
+ contentVideo.style.opacity = "1";
808
+ if (adVideoElement) {
809
+ adVideoElement.pause();
810
+ adVideoElement.src = "";
811
+ adVideoElement.remove();
812
+ adVideoElement = void 0;
813
+ }
814
+ if (adContainerEl === null || adContainerEl === void 0 ? void 0 : adContainerEl.parentElement) {
815
+ adContainerEl.parentElement.removeChild(adContainerEl);
816
+ }
817
+ adContainerEl = void 0;
818
+ currentAd = void 0;
819
+ listeners.clear();
820
+ },
821
+ isAdPlaying: function isAdPlaying() {
822
+ return adPlaying;
823
+ },
824
+ resize: function resize(width, height) {
825
+ log("Resizing to ".concat(width, "x").concat(height));
826
+ if (adContainerEl) {
827
+ adContainerEl.style.width = "".concat(width, "px");
828
+ adContainerEl.style.height = "".concat(height, "px");
829
+ }
830
+ if (adVideoElement) {
831
+ adVideoElement.style.width = "".concat(width, "px");
832
+ adVideoElement.style.height = "".concat(height, "px");
833
+ }
834
+ },
835
+ on: function on(event, listener) {
836
+ if (!listeners.has(event)) listeners.set(event, /* @__PURE__ */ new Set());
837
+ listeners.get(event).add(listener);
838
+ },
839
+ off: function off(event, listener) {
840
+ var _listeners_get;
841
+ (_listeners_get = listeners.get(event)) === null || _listeners_get === void 0 ? void 0 : _listeners_get.delete(listener);
842
+ },
843
+ updateOriginalMutedState: function updateOriginalMutedState(muted, volume) {
844
+ var nextVolume = typeof volume === "number" && !Number.isNaN(volume) ? Math.max(0, Math.min(1, volume)) : originalVolume;
845
+ log("updateOriginalMutedState: muted=".concat(muted, ", volume=").concat(nextVolume));
846
+ originalMutedState = muted;
847
+ originalVolume = nextVolume;
848
+ },
849
+ getOriginalMutedState: function getOriginalMutedState() {
850
+ return originalMutedState;
851
+ },
852
+ getOriginalVolume: function getOriginalVolume() {
853
+ return originalVolume;
854
+ },
855
+ setAdVolume: function setAdVolume(volume) {
856
+ if (adVideoElement && adPlaying) {
857
+ adVideoElement.volume = Math.max(0, Math.min(1, volume));
858
+ adVideoElement.muted = volume === 0;
859
+ }
860
+ },
861
+ getAdVolume: function getAdVolume() {
862
+ if (adVideoElement && adPlaying) {
863
+ return adVideoElement.volume;
864
+ }
865
+ return 1;
866
+ },
867
+ showPlaceholder: function showPlaceholder() {
868
+ if (!adContainerEl) {
869
+ var _contentVideo_parentElement;
870
+ var container = document.createElement("div");
871
+ container.style.position = "absolute";
872
+ container.style.left = "0";
873
+ container.style.top = "0";
874
+ container.style.right = "0";
875
+ container.style.bottom = "0";
876
+ container.style.display = "none";
877
+ container.style.alignItems = "center";
878
+ container.style.justifyContent = "center";
879
+ container.style.pointerEvents = "none";
880
+ container.style.zIndex = "10";
881
+ container.style.backgroundColor = "#000";
882
+ (_contentVideo_parentElement = contentVideo.parentElement) === null || _contentVideo_parentElement === void 0 ? void 0 : _contentVideo_parentElement.appendChild(container);
883
+ adContainerEl = container;
884
+ }
885
+ if (adContainerEl) {
886
+ adContainerEl.style.display = "flex";
887
+ adContainerEl.style.opacity = "1";
888
+ adContainerEl.style.pointerEvents = "auto";
889
+ }
890
+ },
891
+ hidePlaceholder: function hidePlaceholder() {
892
+ if (adContainerEl) {
893
+ adContainerEl.style.opacity = "0";
894
+ setTimeout(function() {
895
+ if (adContainerEl) {
896
+ adContainerEl.style.display = "none";
897
+ adContainerEl.style.pointerEvents = "none";
898
+ }
899
+ }, 300);
900
+ }
901
+ }
902
+ };
903
+ }
904
+ // Annotate the CommonJS export names for ESM import in node:
905
+ 0 && (module.exports = {
906
+ createAdStormPlayer: createAdStormPlayer
907
+ });
908
+ //# sourceMappingURL=adstormPlayer.cjs.map