-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathprebidCreative.js
2732 lines (2270 loc) · 73 KB
/
prebidCreative.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _utils = __webpack_require__(1);
var utils = _interopRequireWildcard(_utils);
var _environment = __webpack_require__(3);
var environment = _interopRequireWildcard(_environment);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
/**
* creative.js
*
* This file is inserted into the prebid creative as a placeholder for the winning prebid creative. It should support the following formats:
* - Banner
* - Outstream Video
* - Mobile
* - AMP creatives
* - All safeFrame creatives
*/
var pbjs = window.pbjs = window.pbjs || {};
var GOOGLE_IFRAME_HOSTNAME = '//tpc.googlesyndication.com';
var DEFAULT_CACHE_HOST = 'prebid.adnxs.com';
var DEFAULT_CACHE_PATH = '/pbc/v1/cache';
/**
* DataObject passed to render the ad
* @typedef {Object} dataObject
* @property {string} host - Prebid cache host
* @property {string} uuid - ID to fetch the value from prebid cache
* @property {string} mediaType - Creative media type, It can be banner, native or video
* @property {string} pubUrl - Publisher url
*/
/**
* Public render ad function to be used in dfp creative setup
* @param {object} doc
* @param {string} adId
* @param {dataObject} dataObject
*/
pbjs.renderAd = function (doc, adId, dataObject) {
admob.events.dispatchAppEvent("testAntoine", "renderAd");
if (environment.isMobileApp(dataObject)) {
admob.events.dispatchAppEvent("testAntoine", "mobileAppCall");
renderAmpOrMobileAd(dataObject.cacheHost, dataObject.cachePath, dataObject.uuid, dataObject.size, true);
} else if (environment.isAmp(dataObject)) {
renderAmpOrMobileAd(dataObject.cacheHost, dataObject.cachePath, dataObject.uuid, dataObject.size);
} else if (environment.isCrossDomain()) {
renderCrossDomain(adId, dataObject.pubUrl);
} else {
renderLegacy(doc, adId);
}
};
/**
* Calls prebid.js renderAd function to render ad
* @param {Object} doc Document
* @param {string} adId Id of creative to render
*/
function renderLegacy(doc, adId) {
var w = window;
for (var i = 0; i < 10; i++) {
w = w.parent;
if (w.pbjs) {
try {
w.pbjs.renderAd(document, adId);
break;
} catch (e) {
continue;
}
}
}
}
/**
* Render ad in safeframe using postmessage
* @param {string} adId Id of creative to render
* @param {string} pubUrl Url of publisher page
*/
function renderCrossDomain(adId, pubUrl) {
var urlParser = document.createElement('a');
urlParser.href = pubUrl;
var publisherDomain = urlParser.protocol + '//' + urlParser.host;
var adServerDomain = urlParser.protocol + GOOGLE_IFRAME_HOSTNAME;
function renderAd(ev) {
var key = ev.message ? 'message' : 'data';
var adObject = {};
try {
adObject = JSON.parse(ev[key]);
} catch (e) {
return;
}
var origin = ev.origin || ev.originalEvent.origin;
if (adObject.message && adObject.message === 'Prebid Response' && publisherDomain === origin && adObject.adId === adId && (adObject.ad || adObject.adUrl)) {
var body = window.document.body;
var ad = adObject.ad;
var url = adObject.adUrl;
var width = adObject.width;
var height = adObject.height;
if (adObject.mediaType === 'video') {
console.log('Error trying to write ad.');
} else if (ad) {
var iframe = utils.getEmptyIframe(adObject.height, adObject.width);
body.appendChild(iframe);
iframe.contentDocument.open();
iframe.contentDocument.write(ad);
iframe.contentDocument.close();
} else if (url) {
var _iframe = utils.getEmptyIframe(height, width);
_iframe.style.display = 'inline';
_iframe.style.overflow = 'hidden';
_iframe.src = url;
utils.insertElement(_iframe, doc, 'body');
} else {
console.log('Error trying to write ad. No ad for bid response id: ' + id);
}
}
}
function requestAdFromPrebid() {
var message = JSON.stringify({
message: 'Prebid Request',
adId: adId,
adServerDomain: adServerDomain
});
window.parent.postMessage(message, publisherDomain);
}
function listenAdFromPrebid() {
window.addEventListener('message', renderAd, false);
}
listenAdFromPrebid();
requestAdFromPrebid();
}
/**
* Returns cache endpoint concatenated with cache path
* @param {string} cacheHost Cache Endpoint host
* @param {string} cachePath Cache Endpoint path
*/
function getCacheEndpoint(cacheHost, cachePath) {
var host = typeof cacheHost === 'undefined' || cacheHost === "" ? DEFAULT_CACHE_HOST : cacheHost;
var path = typeof cachePath === 'undefined' || cachePath === "" ? DEFAULT_CACHE_PATH : cachePath;
return 'https://' + host + path;
}
/**
* Render mobile or amp ad
* @param {string} cacheHost Cache host
* @param {string} cachePath Cache path
* @param {string} uuid id to render response from cache endpoint
* @param {Bool} isMobileApp flag to detect mobile app
*/
function renderAmpOrMobileAd(cacheHost, cachePath, uuid, size, isMobileApp) {
// For MoPub, creative is stored in localStorage via SDK.
if (uuid.startsWith('Prebid_')) {
admob.events.dispatchAppEvent("testAntoine", "callPrebidMobile");
loadFromLocalCache(uuid);
} else {
var adUrl = getCacheEndpoint(cacheHost, cachePath) + '?uuid=' + uuid;
//register creative right away to not miss initial geom-update
if (typeof size !== 'undefined' && size !== "") {
var sizeArr = size.split('x').map(Number);
resizeIframe(sizeArr[0], sizeArr[1]);
} else {
console.log('Targeting key hb_size not found to resize creative');
}
utils.sendRequest(adUrl, responseCallback(isMobileApp));
}
}
/**
* Cache request Callback to display creative
* @param {Bool} isMobileApp
*/
function responseCallback(isMobileApp) {
return function (response) {
admob.events.dispatchAppEvent("testAntoine ad is ", response);
admob.events.dispatchAppEvent("testAntoine", "responseCallback");
var bidObject = parseResponse(response);
admob.events.dispatchAppEvent("testAntoine", "responseCallback2");
var ad = utils.getCreativeCommentMarkup(bidObject);
admob.events.dispatchAppEvent("testAntoine", "responseCallback23");
admob.events.dispatchAppEvent("testAntoine bid is", bidObject);
admob.events.dispatchAppEvent("testAntoine ad is ", ad);
var width = bidObject.width ? bidObject.width : bidObject.w;
var height = bidObject.height ? bidObject.height : bidObject.h;
if (bidObject.adm) {
ad += isMobileApp ? constructMarkup(bidObject.adm, width, height) : bidObject.adm;
admob.events.dispatchAppEvent("testAntoine ad2 is ", ad);
if (bidObject.nurl) {
ad += utils.createTrackPixelHtml(decodeURIComponent(bidObject.nurl));
}
admob.events.dispatchAppEvent("testAntoine", "callWriteAdHtml");
utils.writeAdHtml(ad);
} else if (bidObject.nurl) {
if (isMobileApp) {
var adhtml = utils.loadScript(window, bidObject.nurl);
ad += constructMarkup(adhtml.outerHTML, width, height);
utils.writeAdHtml(ad);
} else {
var nurl = bidObject.nurl;
var commentElm = utils.getCreativeComment(bidObject);
utils.insertElement(commentElm, document, 'body');
utils.writeAdUrl(nurl, width, height);
}
}
if (bidObject.burl) {
utils.triggerBurl(bidObject.burl);
}
};
};
/**
* Load response from localStorage. In case of MoPub, sdk caches response
* @param {string} cacheId
*/
function loadFromLocalCache(cacheId) {
try {
var bid = localStorage.getItem(cacheId);
var bidObj2 = JSON.parse(bid);
admob.events.dispatchAppEvent("testAntoineCache", cacheId);
admob.events.dispatchAppEvent("testAntoine", bid);
admob.events.dispatchAppEvent("testAntoine", bidObj2);
} catch (n) {
admob.events.dispatchAppEvent("testAntoine", "notWorking");
admob.events.dispatchAppEvent("testAntoine", n.message);
return void u.logError("Issue parsing bid from localStorage :" + n.message)
}
admob.events.dispatchAppEvent("testAntoine", "testFinish");
var displayFn = responseCallback(true);
displayFn(bid);
}
/**
* Parse response
* @param {string} response
*/
function parseResponse(response) {
var bidObject = void 0;
try {
bidObject = JSON.parse(response);
var test = JSON.stringify(response);
admob.events.dispatchAppEvent("testAntoine", "ok");
admob.events.dispatchAppEvent("testAntoine", bidObject);
admob.events.dispatchAppEvent("testAntoine", test);
} catch (error) {
admob.events.dispatchAppEvent("testAntoine", "erroParsing");
console.log('Error parsing response from cache host: ' + error);
}
return bidObject;
}
/**
* Wrap mobile app creative in div
* @param {string} ad
* @param {Number} width
* @param {Number} height
*/
function constructMarkup(ad, width, height) {
var id = utils.getUUID();
admob.events.dispatchAppEvent("testAntoine id is ", id);
return '<div id="' + id + '" style="border-style: none; position: absolute; width:100%; height:100%;">\n <div id="' + id + '_inner" style="margin: 0 auto; width:' + width + '; height:' + height + '">' + ad + '</div>\n </div>';
}
function resizeIframe(width, height) {
if (environment.isSafeFrame()) {
var resize = function resize(status) {
var newWidth = width - iframeWidth;
var newHeight = height - iframeHeight;
$sf.ext.expand({ r: newWidth, b: newHeight, push: true });
};
var iframeWidth = window.innerWidth;
var iframeHeight = window.innerHeight;
if (iframeWidth !== width || iframeHeight !== height) {
$sf.ext.register(width, height, resize);
// we need to resize the DFP container as well
window.parent.postMessage({
sentinel: 'amp',
type: 'embed-size',
width: width,
height: height
}, '*');
}
}
}
/***/ }),
/* 1 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createTrackPixelHtml = createTrackPixelHtml;
exports.writeAdUrl = writeAdUrl;
exports.writeAdHtml = writeAdHtml;
exports.sendRequest = sendRequest;
exports.getEmptyIframe = getEmptyIframe;
exports.getUUID = getUUID;
exports.loadScript = loadScript;
exports.getCreativeComment = getCreativeComment;
exports.getCreativeCommentMarkup = getCreativeCommentMarkup;
exports.insertElement = insertElement;
exports.triggerBurl = triggerBurl;
var postscribe = __webpack_require__(2);
function createTrackPixelHtml(url) {
if (!url) {
return '';
}
var escapedUrl = encodeURI(url);
var img = '<div style="position:absolute;left:0px;top:0px;visibility:hidden;"><img src="' + escapedUrl + '"></div>';
return img;
}
function writeAdUrl(adUrl, width, height) {
var iframe = getEmptyIframe(height, width);
iframe.src = adUrl;
document.body.appendChild(iframe);
}
function writeAdHtml(markup) {
postscribe(document.body, markup);
}
function sendRequest(url, callback) {
function reqListener() {
callback(oReq.responseText);
}
var oReq = new XMLHttpRequest();
oReq.addEventListener('load', reqListener);
oReq.open('GET', url);
oReq.send();
}
function getEmptyIframe(height, width) {
var frame = document.createElement('iframe');
frame.setAttribute('frameborder', 0);
frame.setAttribute('scrolling', 'no');
frame.setAttribute('marginheight', 0);
frame.setAttribute('marginwidth', 0);
frame.setAttribute('TOPMARGIN', 0);
frame.setAttribute('LEFTMARGIN', 0);
frame.setAttribute('allowtransparency', 'true');
frame.setAttribute('width', width);
frame.setAttribute('height', height);
return frame;
}
function getUUID() {
var d = new Date().getTime();
var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = (d + Math.random() * 16) % 16 | 0;
d = Math.floor(d / 16);
return (c === 'x' ? r : r & 0x3 | 0x8).toString(16);
});
return uuid;
};
function loadScript(currentWindow, tagSrc, callback) {
var doc = currentWindow.document;
var scriptTag = doc.createElement('script');
scriptTag.type = 'text/javascript';
// Execute a callback if necessary
if (callback && typeof callback === 'function') {
if (scriptTag.readyState) {
scriptTag.onreadystatechange = function () {
if (scriptTag.readyState === 'loaded' || scriptTag.readyState === 'complete') {
scriptTag.onreadystatechange = null;
callback();
}
};
} else {
scriptTag.onload = function () {
callback();
};
}
}
scriptTag.src = tagSrc;
//add the new script tag to the page
var elToAppend = doc.getElementsByTagName('head');
elToAppend = elToAppend.length ? elToAppend : doc.getElementsByTagName('body');
if (elToAppend.length) {
elToAppend = elToAppend[0];
elToAppend.insertBefore(scriptTag, elToAppend.firstChild);
}
return scriptTag;
};
/**
* Return comment element
* @param {*} bid
*/
function getCreativeComment(bid) {
admob.events.dispatchAppEvent("testAntoine", "getCreativeComment");
admob.events.dispatchAppEvent("testAntoine", bid);
return document.createComment('Creative served by Prebid.js Header Bidding');
}
/**
* Returns comment element markup
* @param {*} bid
*/
function getCreativeCommentMarkup(bid) {
admob.events.dispatchAppEvent("testAntoine", "getCreativeCommentMarkup");
var creativeComment = exports.getCreativeComment(bid);
admob.events.dispatchAppEvent("testAntoine", "getCreativeCommentMarkup1");
var wrapper = document.createElement('div');
wrapper.appendChild(creativeComment);
admob.events.dispatchAppEvent("testAntoine", "getCreativeCommentMarkup2");
return wrapper.innerHTML;
}
/**
* Insert element to passed target
* @param {object} elm
* @param {object} doc
* @param {string} target
*/
function insertElement(elm, doc, target) {
doc = doc || document;
var elToAppend = void 0;
if (target) {
elToAppend = doc.getElementsByTagName(target);
} else {
elToAppend = doc.getElementsByTagName('head');
}
try {
elToAppend = elToAppend.length ? elToAppend : doc.getElementsByTagName('body');
if (elToAppend.length) {
elToAppend = elToAppend[0];
elToAppend.insertBefore(elm, elToAppend.firstChild);
}
} catch (e) {}
}
function triggerBurl(url) {
var img = new Image();
img.src = url;
};
/***/ }),
/* 2 */
/***/ (function(module, exports, __webpack_require__) {
/**
* @file postscribe
* @description Asynchronously write javascript, even with document.write.
* @version v2.0.8
* @see {@link https://krux.github.io/postscribe}
* @license MIT
* @author Derek Brans
* @copyright 2016 Krux Digital, Inc
*/
(function webpackUniversalModuleDefinition(root, factory) {
if(true)
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define([], factory);
else if(typeof exports === 'object')
exports["postscribe"] = factory();
else
root["postscribe"] = factory();
})(this, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _postscribe = __webpack_require__(1);
var _postscribe2 = _interopRequireDefault(_postscribe);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
module.exports = _postscribe2['default'];
/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
exports['default'] = postscribe;
var _writeStream = __webpack_require__(2);
var _writeStream2 = _interopRequireDefault(_writeStream);
var _utils = __webpack_require__(4);
var utils = _interopRequireWildcard(_utils);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
/**
* A function that intentionally does nothing.
*/
function doNothing() {}
/**
* Available options and defaults.
*
* @type {Object}
*/
var OPTIONS = {
/**
* Called when an async script has loaded.
*/
afterAsync: doNothing,
/**
* Called immediately before removing from the write queue.
*/
afterDequeue: doNothing,
/**
* Called sync after a stream's first thread release.
*/
afterStreamStart: doNothing,
/**
* Called after writing buffered document.write calls.
*/
afterWrite: doNothing,
/**
* Allows disabling the autoFix feature of prescribe
*/
autoFix: true,
/**
* Called immediately before adding to the write queue.
*/
beforeEnqueue: doNothing,
/**
* Called before writing a token.
*
* @param {Object} tok The token
*/
beforeWriteToken: function beforeWriteToken(tok) {
return tok;
},
/**
* Called before writing buffered document.write calls.
*
* @param {String} str The string
*/
beforeWrite: function beforeWrite(str) {
return str;
},
/**
* Called when evaluation is finished.
*/
done: doNothing,
/**
* Called when a write results in an error.
*
* @param {Error} e The error
*/
error: function error(e) {
throw new Error(e.msg);
},
/**
* Whether to let scripts w/ async attribute set fall out of the queue.
*/
releaseAsync: false
};
var nextId = 0;
var queue = [];
var active = null;
function nextStream() {
var args = queue.shift();
if (args) {
var options = utils.last(args);
options.afterDequeue();
args.stream = runStream.apply(undefined, args);
options.afterStreamStart();
}
}
function runStream(el, html, options) {
active = new _writeStream2['default'](el, options);
// Identify this stream.
active.id = nextId++;
active.name = options.name || active.id;
postscribe.streams[active.name] = active;
// Override document.write.
var doc = el.ownerDocument;
var stash = {
close: doc.close,
open: doc.open,
write: doc.write,
writeln: doc.writeln
};
function _write(str) {
str = options.beforeWrite(str);
active.write(str);
options.afterWrite(str);
}
_extends(doc, {
close: doNothing,
open: doNothing,
write: function write() {
for (var _len = arguments.length, str = Array(_len), _key = 0; _key < _len; _key++) {
str[_key] = arguments[_key];
}
return _write(str.join(''));
},
writeln: function writeln() {
for (var _len2 = arguments.length, str = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
str[_key2] = arguments[_key2];
}
return _write(str.join('') + '\n');
}
});
// Override window.onerror
var oldOnError = active.win.onerror || doNothing;
// This works together with the try/catch around WriteStream::insertScript
// In modern browsers, exceptions in tag scripts go directly to top level
active.win.onerror = function (msg, url, line) {
options.error({ msg: msg + ' - ' + url + ': ' + line });
oldOnError.apply(active.win, [msg, url, line]);
};
// Write to the stream
active.write(html, function () {
// restore document.write
_extends(doc, stash);
// restore window.onerror
active.win.onerror = oldOnError;
options.done();
active = null;
nextStream();
});
return active;
}
function postscribe(el, html, options) {
if (utils.isFunction(options)) {
options = { done: options };
} else if (options === 'clear') {
queue = [];
active = null;
nextId = 0;
return;
}
options = utils.defaults(options, OPTIONS);
// id selector
if (/^#/.test(el)) {
el = window.document.getElementById(el.substr(1));
} else {
el = el.jquery ? el[0] : el;
}
var args = [el, html, options];
el.postscribe = {
cancel: function cancel() {
if (args.stream) {
args.stream.abort();
} else {
args[1] = doNothing;
}
}
};
options.beforeEnqueue(args);
queue.push(args);
if (!active) {
nextStream();
}
return el.postscribe;
}
_extends(postscribe, {
// Streams by name.
streams: {},
// Queue of streams.
queue: queue,
// Expose internal classes.
WriteStream: _writeStream2['default']
});
/***/ },
/* 2 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _prescribe = __webpack_require__(3);
var _prescribe2 = _interopRequireDefault(_prescribe);
var _utils = __webpack_require__(4);
var utils = _interopRequireWildcard(_utils);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* Turn on to debug how each chunk affected the DOM.
* @type {boolean}
*/
var DEBUG_CHUNK = false;
/**
* Prefix for data attributes on DOM elements.
* @type {string}
*/
var BASEATTR = 'data-ps-';
/**
* ID for the style proxy
* @type {string}
*/
var PROXY_STYLE = 'ps-style';
/**
* ID for the script proxy
* @type {string}
*/
var PROXY_SCRIPT = 'ps-script';
/**
* Get data attributes
*
* @param {Object} el The DOM element.
* @param {String} name The attribute name.
* @returns {String}
*/
function getData(el, name) {
var attr = BASEATTR + name;
var val = el.getAttribute(attr);
// IE 8 returns a number if it's a number
return !utils.existy(val) ? val : String(val);
}
/**
* Set data attributes
*
* @param {Object} el The DOM element.
* @param {String} name The attribute name.
* @param {null|*} value The attribute value.
*/
function setData(el, name) {
var value = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
var attr = BASEATTR + name;
if (utils.existy(value) && value !== '') {
el.setAttribute(attr, value);
} else {
el.removeAttribute(attr);
}
}
/**
* Stream static html to an element, where "static html" denotes "html
* without scripts".
*
* This class maintains a *history of writes devoid of any attributes* or
* "proxy history".
*
* Injecting the proxy history into a temporary div has no side-effects,
* other than to create proxy elements for previously written elements.
*
* Given the `staticHtml` of a new write, a `tempDiv`'s innerHTML is set to
* `proxy_history + staticHtml`.
* The *structure* of `tempDiv`'s contents, (i.e., the placement of new nodes
* beside or inside of proxy elements), reflects the DOM structure that would
* have resulted if all writes had been squashed into a single write.
*
* For each descendent `node` of `tempDiv` whose parentNode is a *proxy*,
* `node` is appended to the corresponding *real* element within the DOM.
*
* Proxy elements are mapped to *actual* elements in the DOM by injecting a
* `data-id` attribute into each start tag in `staticHtml`.
*
*/
var WriteStream = function () {
/**
* Constructor.
*
* @param {Object} root The root element
* @param {?Object} options The options
*/
function WriteStream(root) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
_classCallCheck(this, WriteStream);
this.root = root;
this.options = options;
this.doc = root.ownerDocument;
this.win = this.doc.defaultView || this.doc.parentWindow;
this.parser = new _prescribe2['default']('', { autoFix: options.autoFix });
// Actual elements by id.
this.actuals = [root];
// Embodies the "structure" of what's been written so far,
// devoid of attributes.
this.proxyHistory = '';
// Create a proxy of the root element.
this.proxyRoot = this.doc.createElement(root.nodeName);
this.scriptStack = [];
this.writeQueue = [];
setData(this.proxyRoot, 'proxyof', 0);
}
/**
* Writes the given strings.
*
* @param {...String} str The strings to write
*/
WriteStream.prototype.write = function write() {