forked from prebid/Prebid.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.js
1336 lines (1170 loc) · 37.3 KB
/
utils.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
import { config } from './config';
import clone from 'just-clone';
import find from 'core-js/library/fn/array/find';
import includes from 'core-js/library/fn/array/includes';
import { parse } from './url';
const CONSTANTS = require('./constants');
export { default as deepAccess } from 'dlv/index';
export { default as deepSetValue } from 'dset';
var tArr = 'Array';
var tStr = 'String';
var tFn = 'Function';
var tNumb = 'Number';
var tObject = 'Object';
var tBoolean = 'Boolean';
var toString = Object.prototype.toString;
let consoleExists = Boolean(window.console);
let consoleLogExists = Boolean(consoleExists && window.console.log);
let consoleInfoExists = Boolean(consoleExists && window.console.info);
let consoleWarnExists = Boolean(consoleExists && window.console.warn);
let consoleErrorExists = Boolean(consoleExists && window.console.error);
// this allows stubbing of utility functions that are used internally by other utility functions
export const internal = {
checkCookieSupport,
createTrackPixelIframeHtml,
getWindowSelf,
getWindowTop,
getAncestorOrigins,
getTopFrameReferrer,
getWindowLocation,
getTopWindowLocation,
insertUserSyncIframe,
insertElement,
isFn,
triggerPixel,
logError,
logWarn,
logMessage,
logInfo
};
var uniqueRef = {};
export let bind = function(a, b) { return b; }.bind(null, 1, uniqueRef)() === uniqueRef
? Function.prototype.bind
: function(bind) {
var self = this;
var args = Array.prototype.slice.call(arguments, 1);
return function() {
return self.apply(bind, args.concat(Array.prototype.slice.call(arguments)));
};
};
/*
* Substitutes into a string from a given map using the token
* Usage
* var str = 'text %%REPLACE%% this text with %%SOMETHING%%';
* var map = {};
* map['replace'] = 'it was subbed';
* map['something'] = 'something else';
* console.log(replaceTokenInString(str, map, '%%')); => "text it was subbed this text with something else"
*/
export function replaceTokenInString(str, map, token) {
_each(map, function (value, key) {
value = (value === undefined) ? '' : value;
var keyString = token + key.toUpperCase() + token;
var re = new RegExp(keyString, 'g');
str = str.replace(re, value);
});
return str;
}
/* utility method to get incremental integer starting from 1 */
var getIncrementalInteger = (function () {
var count = 0;
return function () {
count++;
return count;
};
})();
// generate a random string (to be used as a dynamic JSONP callback)
export function getUniqueIdentifierStr() {
return getIncrementalInteger() + Math.random().toString(16).substr(2);
}
/**
* Returns a random v4 UUID of the form xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx,
* where each x is replaced with a random hexadecimal digit from 0 to f,
* and y is replaced with a random hexadecimal digit from 8 to b.
* https://gist.github.com/jed/982883 via node-uuid
*/
export function generateUUID(placeholder) {
return placeholder
? (placeholder ^ _getRandomData() >> placeholder / 4).toString(16)
: ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, generateUUID);
}
/**
* Returns random data using the Crypto API if available and Math.random if not
* Method is from https://gist.github.com/jed/982883 like generateUUID, direct link https://gist.github.com/jed/982883#gistcomment-45104
*/
function _getRandomData() {
if (window && window.crypto && window.crypto.getRandomValues) {
return crypto.getRandomValues(new Uint8Array(1))[0] % 16;
} else {
return Math.random() * 16;
}
}
export function getBidIdParameter(key, paramsObj) {
if (paramsObj && paramsObj[key]) {
return paramsObj[key];
}
return '';
}
export function tryAppendQueryString(existingUrl, key, value) {
if (value) {
return existingUrl += key + '=' + encodeURIComponent(value) + '&';
}
return existingUrl;
}
// parse a query string object passed in bid params
// bid params should be an object such as {key: "value", key1 : "value1"}
export function parseQueryStringParameters(queryObj) {
let result = '';
for (var k in queryObj) {
if (queryObj.hasOwnProperty(k)) { result += k + '=' + encodeURIComponent(queryObj[k]) + '&'; }
}
return result;
}
// transform an AdServer targeting bids into a query string to send to the adserver
export function transformAdServerTargetingObj(targeting) {
// we expect to receive targeting for a single slot at a time
if (targeting && Object.getOwnPropertyNames(targeting).length > 0) {
return getKeys(targeting)
.map(key => `${key}=${encodeURIComponent(getValue(targeting, key))}`).join('&');
} else {
return '';
}
}
/**
* Read an adUnit object and return the sizes used in an [[728, 90]] format (even if they had [728, 90] defined)
* Preference is given to the `adUnit.mediaTypes.banner.sizes` object over the `adUnit.sizes`
* @param {object} adUnit one adUnit object from the normal list of adUnits
* @returns {Array.<number[]>} array of arrays containing numeric sizes
*/
export function getAdUnitSizes(adUnit) {
if (!adUnit) {
return;
}
let sizes = [];
if (adUnit.mediaTypes && adUnit.mediaTypes.banner && Array.isArray(adUnit.mediaTypes.banner.sizes)) {
let bannerSizes = adUnit.mediaTypes.banner.sizes;
if (Array.isArray(bannerSizes[0])) {
sizes = bannerSizes;
} else {
sizes.push(bannerSizes);
}
} else if (Array.isArray(adUnit.sizes)) {
if (Array.isArray(adUnit.sizes[0])) {
sizes = adUnit.sizes;
} else {
sizes.push(adUnit.sizes);
}
}
return sizes;
}
/**
* Parse a GPT-Style general size Array like `[[300, 250]]` or `"300x250,970x90"` into an array of sizes `["300x250"]` or '['300x250', '970x90']'
* @param {(Array.<number[]>|Array.<number>)} sizeObj Input array or double array [300,250] or [[300,250], [728,90]]
* @return {Array.<string>} Array of strings like `["300x250"]` or `["300x250", "728x90"]`
*/
export function parseSizesInput(sizeObj) {
var parsedSizes = [];
// if a string for now we can assume it is a single size, like "300x250"
if (typeof sizeObj === 'string') {
// multiple sizes will be comma-separated
var sizes = sizeObj.split(',');
// regular expression to match strigns like 300x250
// start of line, at least 1 number, an "x" , then at least 1 number, and the then end of the line
var sizeRegex = /^(\d)+x(\d)+$/i;
if (sizes) {
for (var curSizePos in sizes) {
if (hasOwn(sizes, curSizePos) && sizes[curSizePos].match(sizeRegex)) {
parsedSizes.push(sizes[curSizePos]);
}
}
}
} else if (typeof sizeObj === 'object') {
var sizeArrayLength = sizeObj.length;
// don't process empty array
if (sizeArrayLength > 0) {
// if we are a 2 item array of 2 numbers, we must be a SingleSize array
if (sizeArrayLength === 2 && typeof sizeObj[0] === 'number' && typeof sizeObj[1] === 'number') {
parsedSizes.push(parseGPTSingleSizeArray(sizeObj));
} else {
// otherwise, we must be a MultiSize array
for (var i = 0; i < sizeArrayLength; i++) {
parsedSizes.push(parseGPTSingleSizeArray(sizeObj[i]));
}
}
}
}
return parsedSizes;
}
// Parse a GPT style single size array, (i.e [300, 250])
// into an AppNexus style string, (i.e. 300x250)
export function parseGPTSingleSizeArray(singleSize) {
if (isValidGPTSingleSize(singleSize)) {
return singleSize[0] + 'x' + singleSize[1];
}
}
// Parse a GPT style single size array, (i.e [300, 250])
// into OpenRTB-compatible (imp.banner.w/h, imp.banner.format.w/h, imp.video.w/h) object(i.e. {w:300, h:250})
export function parseGPTSingleSizeArrayToRtbSize(singleSize) {
if (isValidGPTSingleSize(singleSize)) {
return {w: singleSize[0], h: singleSize[1]};
}
}
function isValidGPTSingleSize(singleSize) {
// if we aren't exactly 2 items in this array, it is invalid
return isArray(singleSize) && singleSize.length === 2 && (!isNaN(singleSize[0]) && !isNaN(singleSize[1]));
}
/**
* @deprecated This function will be removed soon. Use http://prebid.org/dev-docs/bidder-adaptor.html#referrers
*/
export function getTopWindowLocation() {
if (inIframe()) {
let loc;
try {
loc = internal.getAncestorOrigins() || internal.getTopFrameReferrer();
} catch (e) {
logInfo('could not obtain top window location', e);
}
if (loc) return parse(loc, {'decodeSearchAsString': true});
}
return internal.getWindowLocation();
}
/**
* @deprecated This function will be removed soon. Use http://prebid.org/dev-docs/bidder-adaptor.html#referrers
*/
export function getTopFrameReferrer() {
try {
// force an exception in x-domain environments. #1509
window.top.location.toString();
let referrerLoc = '';
let currentWindow;
do {
currentWindow = currentWindow ? currentWindow.parent : window;
if (currentWindow.document && currentWindow.document.referrer) {
referrerLoc = currentWindow.document.referrer;
}
}
while (currentWindow !== window.top);
return referrerLoc;
} catch (e) {
return window.document.referrer;
}
}
/**
* @deprecated This function will be removed soon. Use http://prebid.org/dev-docs/bidder-adaptor.html#referrers
*/
export function getAncestorOrigins() {
if (window.document.location && window.document.location.ancestorOrigins &&
window.document.location.ancestorOrigins.length >= 1) {
return window.document.location.ancestorOrigins[window.document.location.ancestorOrigins.length - 1];
}
}
export function getWindowTop() {
return window.top;
}
export function getWindowSelf() {
return window.self;
}
export function getWindowLocation() {
return window.location;
}
/**
* @deprecated This function will be removed soon. Use http://prebid.org/dev-docs/bidder-adaptor.html#referrers
*/
export function getTopWindowUrl() {
let href;
try {
href = internal.getTopWindowLocation().href;
} catch (e) {
href = '';
}
return href;
}
/**
* @deprecated This function will be removed soon. Use http://prebid.org/dev-docs/bidder-adaptor.html#referrers
*/
export function getTopWindowReferrer() {
try {
return window.top.document.referrer;
} catch (e) {
return document.referrer;
}
}
/**
* Wrappers to console.(log | info | warn | error). Takes N arguments, the same as the native methods
*/
export function logMessage() {
if (debugTurnedOn() && consoleLogExists) {
console.log.apply(console, decorateLog(arguments, 'MESSAGE:'));
}
}
export function logInfo() {
if (debugTurnedOn() && consoleInfoExists) {
console.info.apply(console, decorateLog(arguments, 'INFO:'));
}
}
export function logWarn() {
if (debugTurnedOn() && consoleWarnExists) {
console.warn.apply(console, decorateLog(arguments, 'WARNING:'));
}
}
export function logError() {
if (debugTurnedOn() && consoleErrorExists) {
console.error.apply(console, decorateLog(arguments, 'ERROR:'));
}
}
function decorateLog(args, prefix) {
args = [].slice.call(args);
prefix && args.unshift(prefix);
args.unshift('display: inline-block; color: #fff; background: #3b88c3; padding: 1px 4px; border-radius: 3px;');
args.unshift('%cPrebid');
return args;
}
export function hasConsoleLogger() {
return consoleLogExists;
}
export function debugTurnedOn() {
return !!config.getConfig('debug');
}
export function createInvisibleIframe() {
var f = document.createElement('iframe');
f.id = getUniqueIdentifierStr();
f.height = 0;
f.width = 0;
f.border = '0px';
f.hspace = '0';
f.vspace = '0';
f.marginWidth = '0';
f.marginHeight = '0';
f.style.border = '0';
f.scrolling = 'no';
f.frameBorder = '0';
f.src = 'about:blank';
f.style.display = 'none';
return f;
}
/*
* Check if a given parameter name exists in query string
* and if it does return the value
*/
export function getParameterByName(name) {
var regexS = '[\\?&]' + name + '=([^&#]*)';
var regex = new RegExp(regexS);
var results = regex.exec(window.location.search);
if (results === null) {
return '';
}
return decodeURIComponent(results[1].replace(/\+/g, ' '));
}
/**
* This function validates paramaters.
* @param {Object} paramObj [description]
* @param {string[]} requiredParamsArr [description]
* @return {boolean} Bool if paramaters are valid
*/
export function hasValidBidRequest(paramObj, requiredParamsArr, adapter) {
var found = false;
function findParam(value, key) {
if (key === requiredParamsArr[i]) {
found = true;
}
}
for (var i = 0; i < requiredParamsArr.length; i++) {
found = false;
_each(paramObj, findParam);
if (!found) {
logError('Params are missing for bid request. One of these required paramaters are missing: ' + requiredParamsArr, adapter);
return false;
}
}
return true;
}
// Handle addEventListener gracefully in older browsers
export function addEventHandler(element, event, func) {
if (element.addEventListener) {
element.addEventListener(event, func, true);
} else if (element.attachEvent) {
element.attachEvent('on' + event, func);
}
}
/**
* Return if the object is of the
* given type.
* @param {*} object to test
* @param {String} _t type string (e.g., Array)
* @return {Boolean} if object is of type _t
*/
export function isA(object, _t) {
return toString.call(object) === '[object ' + _t + ']';
}
export function isFn(object) {
return isA(object, tFn);
}
export function isStr(object) {
return isA(object, tStr);
}
export function isArray(object) {
return isA(object, tArr);
}
export function isNumber(object) {
return isA(object, tNumb);
}
export function isPlainObject(object) {
return isA(object, tObject);
}
export function isBoolean(object) {
return isA(object, tBoolean);
}
/**
* Return if the object is "empty";
* this includes falsey, no keys, or no items at indices
* @param {*} object object to test
* @return {Boolean} if object is empty
*/
export function isEmpty(object) {
if (!object) return true;
if (isArray(object) || isStr(object)) {
return !(object.length > 0);
}
for (var k in object) {
if (hasOwnProperty.call(object, k)) return false;
}
return true;
}
/**
* Return if string is empty, null, or undefined
* @param str string to test
* @returns {boolean} if string is empty
*/
export function isEmptyStr(str) {
return isStr(str) && (!str || str.length === 0);
}
/**
* Iterate object with the function
* falls back to es5 `forEach`
* @param {Array|Object} object
* @param {Function(value, key, object)} fn
*/
export function _each(object, fn) {
if (isEmpty(object)) return;
if (isFn(object.forEach)) return object.forEach(fn, this);
var k = 0;
var l = object.length;
if (l > 0) {
for (; k < l; k++) fn(object[k], k, object);
} else {
for (k in object) {
if (hasOwnProperty.call(object, k)) fn.call(this, object[k], k);
}
}
}
export function contains(a, obj) {
if (isEmpty(a)) {
return false;
}
if (isFn(a.indexOf)) {
return a.indexOf(obj) !== -1;
}
var i = a.length;
while (i--) {
if (a[i] === obj) {
return true;
}
}
return false;
}
export let indexOf = (function () {
if (Array.prototype.indexOf) {
return Array.prototype.indexOf;
}
// ie8 no longer supported
// return polyfills.indexOf;
}());
/**
* Map an array or object into another array
* given a function
* @param {Array|Object} object
* @param {Function(value, key, object)} callback
* @return {Array}
*/
export function _map(object, callback) {
if (isEmpty(object)) return [];
if (isFn(object.map)) return object.map(callback);
var output = [];
_each(object, function (value, key) {
output.push(callback(value, key, object));
});
return output;
}
export function hasOwn(objectToCheck, propertyToCheckFor) {
if (objectToCheck.hasOwnProperty) {
return objectToCheck.hasOwnProperty(propertyToCheckFor);
} else {
return (typeof objectToCheck[propertyToCheckFor] !== 'undefined') && (objectToCheck.constructor.prototype[propertyToCheckFor] !== objectToCheck[propertyToCheckFor]);
}
};
/*
* Inserts an element(elm) as targets child, by default as first child
* @param {HTMLElement} elm
* @param {HTMLElement} [doc]
* @param {HTMLElement} [target]
* @param {Boolean} [asLastChildChild]
* @return {HTMLElement}
*/
export function insertElement(elm, doc, target, asLastChildChild) {
doc = doc || document;
let parentEl;
if (target) {
parentEl = doc.getElementsByTagName(target);
} else {
parentEl = doc.getElementsByTagName('head');
}
try {
parentEl = parentEl.length ? parentEl : doc.getElementsByTagName('body');
if (parentEl.length) {
parentEl = parentEl[0];
let insertBeforeEl = asLastChildChild ? null : parentEl.firstChild;
return parentEl.insertBefore(elm, insertBeforeEl);
}
} catch (e) {}
}
/**
* Inserts an image pixel with the specified `url` for cookie sync
* @param {string} url URL string of the image pixel to load
* @param {function} [done] an optional exit callback, used when this usersync pixel is added during an async process
*/
export function triggerPixel(url, done) {
const img = new Image();
if (done && internal.isFn(done)) {
img.addEventListener('load', done);
img.addEventListener('error', done);
}
img.src = url;
}
export function callBurl({ source, burl }) {
if (source === CONSTANTS.S2S.SRC && burl) {
internal.triggerPixel(burl);
}
}
/**
* Inserts an empty iframe with the specified `html`, primarily used for tracking purposes
* (though could be for other purposes)
* @param {string} htmlCode snippet of HTML code used for tracking purposes
*/
export function insertHtmlIntoIframe(htmlCode) {
if (!htmlCode) {
return;
}
let iframe = document.createElement('iframe');
iframe.id = getUniqueIdentifierStr();
iframe.width = 0;
iframe.height = 0;
iframe.hspace = '0';
iframe.vspace = '0';
iframe.marginWidth = '0';
iframe.marginHeight = '0';
iframe.style.display = 'none';
iframe.style.height = '0px';
iframe.style.width = '0px';
iframe.scrolling = 'no';
iframe.frameBorder = '0';
iframe.allowtransparency = 'true';
internal.insertElement(iframe, document, 'body');
iframe.contentWindow.document.open();
iframe.contentWindow.document.write(htmlCode);
iframe.contentWindow.document.close();
}
/**
* Inserts empty iframe with the specified `url` for cookie sync
* @param {string} url URL to be requested
* @param {string} encodeUri boolean if URL should be encoded before inserted. Defaults to true
* @param {function} [done] an optional exit callback, used when this usersync pixel is added during an async process
*/
export function insertUserSyncIframe(url, done) {
let iframeHtml = internal.createTrackPixelIframeHtml(url, false, 'allow-scripts allow-same-origin');
let div = document.createElement('div');
div.innerHTML = iframeHtml;
let iframe = div.firstChild;
if (done && internal.isFn(done)) {
iframe.addEventListener('load', done);
iframe.addEventListener('error', done);
}
internal.insertElement(iframe, document, 'html', true);
};
/**
* Creates a snippet of HTML that retrieves the specified `url`
* @param {string} url URL to be requested
* @return {string} HTML snippet that contains the img src = set to `url`
*/
export function createTrackPixelHtml(url) {
if (!url) {
return '';
}
let escapedUrl = encodeURI(url);
let img = '<div style="position:absolute;left:0px;top:0px;visibility:hidden;">';
img += '<img src="' + escapedUrl + '"></div>';
return img;
};
/**
* Creates a snippet of Iframe HTML that retrieves the specified `url`
* @param {string} url plain URL to be requested
* @param {string} encodeUri boolean if URL should be encoded before inserted. Defaults to true
* @param {string} sandbox string if provided the sandbox attribute will be included with the given value
* @return {string} HTML snippet that contains the iframe src = set to `url`
*/
export function createTrackPixelIframeHtml(url, encodeUri = true, sandbox = '') {
if (!url) {
return '';
}
if (encodeUri) {
url = encodeURI(url);
}
if (sandbox) {
sandbox = `sandbox="${sandbox}"`;
}
return `<iframe ${sandbox} id="${getUniqueIdentifierStr()}"
frameborder="0"
allowtransparency="true"
marginheight="0" marginwidth="0"
width="0" hspace="0" vspace="0" height="0"
style="height:0px;width:0px;display:none;"
scrolling="no"
src="${url}">
</iframe>`;
}
/**
* Returns iframe document in a browser agnostic way
* @param {Object} iframe reference
* @return {Object} iframe `document` reference
*/
export function getIframeDocument(iframe) {
if (!iframe) {
return;
}
let doc;
try {
if (iframe.contentWindow) {
doc = iframe.contentWindow.document;
} else if (iframe.contentDocument.document) {
doc = iframe.contentDocument.document;
} else {
doc = iframe.contentDocument;
}
} catch (e) {
internal.logError('Cannot get iframe document', e);
}
return doc;
}
export function getValueString(param, val, defaultValue) {
if (val === undefined || val === null) {
return defaultValue;
}
if (isStr(val)) {
return val;
}
if (isNumber(val)) {
return val.toString();
}
internal.logWarn('Unsuported type for param: ' + param + ' required type: String');
}
export function uniques(value, index, arry) {
return arry.indexOf(value) === index;
}
export function flatten(a, b) {
return a.concat(b);
}
export function getBidRequest(id, bidderRequests) {
if (!id) {
return;
}
let bidRequest;
bidderRequests.some(bidderRequest => {
let result = find(bidderRequest.bids, bid => ['bidId', 'adId', 'bid_id'].some(type => bid[type] === id));
if (result) {
bidRequest = result;
}
return result;
});
return bidRequest;
}
export function getKeys(obj) {
return Object.keys(obj);
}
export function getValue(obj, key) {
return obj[key];
}
/**
* Get the key of an object for a given value
*/
export function getKeyByValue(obj, value) {
for (let prop in obj) {
if (obj.hasOwnProperty(prop)) {
if (obj[prop] === value) {
return prop;
}
}
}
}
export function getBidderCodes(adUnits = $$PREBID_GLOBAL$$.adUnits) {
// this could memoize adUnits
return adUnits.map(unit => unit.bids.map(bid => bid.bidder)
.reduce(flatten, [])).reduce(flatten).filter(uniques);
}
export function isGptPubadsDefined() {
if (window.googletag && isFn(window.googletag.pubads) && isFn(window.googletag.pubads().getSlots)) {
return true;
}
}
// This function will get highest cpm value bid, in case of tie it will return the bid with lowest timeToRespond
export const getHighestCpm = getHighestCpmCallback('timeToRespond', (previous, current) => previous > current);
// This function will get the oldest hightest cpm value bid, in case of tie it will return the bid which came in first
// Use case for tie: https://github.com/prebid/Prebid.js/issues/2448
export const getOldestHighestCpmBid = getHighestCpmCallback('responseTimestamp', (previous, current) => previous > current);
// This function will get the latest hightest cpm value bid, in case of tie it will return the bid which came in last
// Use case for tie: https://github.com/prebid/Prebid.js/issues/2539
export const getLatestHighestCpmBid = getHighestCpmCallback('responseTimestamp', (previous, current) => previous < current);
function getHighestCpmCallback(useTieBreakerProperty, tieBreakerCallback) {
return (previous, current) => {
if (previous.cpm === current.cpm) {
return tieBreakerCallback(previous[useTieBreakerProperty], current[useTieBreakerProperty]) ? current : previous;
}
return previous.cpm < current.cpm ? current : previous;
}
}
/**
* Fisher–Yates shuffle
* http://stackoverflow.com/a/6274398
* https://bost.ocks.org/mike/shuffle/
* istanbul ignore next
*/
export function shuffle(array) {
let counter = array.length;
// while there are elements in the array
while (counter > 0) {
// pick a random index
let index = Math.floor(Math.random() * counter);
// decrease counter by 1
counter--;
// and swap the last element with it
let temp = array[counter];
array[counter] = array[index];
array[index] = temp;
}
return array;
}
export function adUnitsFilter(filter, bid) {
return includes(filter, bid && bid.adUnitCode);
}
/**
* Check if parent iframe of passed document supports content rendering via 'srcdoc' property
* @param {HTMLDocument} doc document to check support of 'srcdoc'
*/
export function isSrcdocSupported(doc) {
// Firefox is excluded due to https://bugzilla.mozilla.org/show_bug.cgi?id=1265961
return doc.defaultView && doc.defaultView.frameElement &&
'srcdoc' in doc.defaultView.frameElement && !/firefox/i.test(navigator.userAgent);
}
export function deepClone(obj) {
return clone(obj);
}
export function inIframe() {
try {
return internal.getWindowSelf() !== internal.getWindowTop();
} catch (e) {
return true;
}
}
export function isSafariBrowser() {
return /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
}
export function replaceAuctionPrice(str, cpm) {
if (!str) return;
return str.replace(/\$\{AUCTION_PRICE\}/g, cpm);
}
export function timestamp() {
return new Date().getTime();
}
export function checkCookieSupport() {
if (window.navigator.cookieEnabled || !!document.cookie.length) {
return true;
}
}
export function cookiesAreEnabled() {
if (internal.checkCookieSupport()) {
return true;
}
window.document.cookie = 'prebid.cookieTest';
return window.document.cookie.indexOf('prebid.cookieTest') != -1;
}
export function getCookie(name) {
let m = window.document.cookie.match('(^|;)\\s*' + name + '\\s*=\\s*([^;]*)\\s*(;|$)');
return m ? decodeURIComponent(m[2]) : null;
}
export function setCookie(key, value, expires) {
document.cookie = `${key}=${encodeURIComponent(value)}${(expires !== '') ? `; expires=${expires}` : ''}; path=/`;
}
/**
* @returns {boolean}
*/
export function localStorageIsEnabled () {
try {
localStorage.setItem('prebid.cookieTest', '1');
return localStorage.getItem('prebid.cookieTest') === '1';
} catch (error) {
return false;
}
}
/**
* Given a function, return a function which only executes the original after
* it's been called numRequiredCalls times.
*
* Note that the arguments from the previous calls will *not* be forwarded to the original function.
* Only the final call's arguments matter.
*
* @param {function} func The function which should be executed, once the returned function has been executed
* numRequiredCalls times.
* @param {int} numRequiredCalls The number of times which the returned function needs to be called before
* func is.
*/
export function delayExecution(func, numRequiredCalls) {
if (numRequiredCalls < 1) {
throw new Error(`numRequiredCalls must be a positive number. Got ${numRequiredCalls}`);
}
let numCalls = 0;
return function () {
numCalls++;
if (numCalls === numRequiredCalls) {
func.apply(null, arguments);
}
}
}
/**
* https://stackoverflow.com/a/34890276/428704
* @export
* @param {array} xs
* @param {string} key
* @returns {Object} {${key_value}: ${groupByArray}, key_value: {groupByArray}}
*/
export function groupBy(xs, key) {
return xs.reduce(function(rv, x) {
(rv[x[key]] = rv[x[key]] || []).push(x);
return rv;
}, {});
}
/**
* Returns content for a friendly iframe to execute a URL in script tag
* @param {string} url URL to be executed in a script tag in a friendly iframe
* <!--PRE_SCRIPT_TAG_MACRO--> and <!--POST_SCRIPT_TAG_MACRO--> are macros left to be replaced if required
*/
export function createContentToExecuteExtScriptInFriendlyFrame(url) {
if (!url) {
return '';
}
return `<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><base target="_top" /><script>inDapIF=true;</script></head><body><!--PRE_SCRIPT_TAG_MACRO--><script src="${url}"></script><!--POST_SCRIPT_TAG_MACRO--></body></html>`;
}
/**
* Build an object consisting of only defined parameters to avoid creating an
* object with defined keys and undefined values.
* @param {Object} object The object to pick defined params out of
* @param {string[]} params An array of strings representing properties to look for in the object
* @returns {Object} An object containing all the specified values that are defined
*/
export function getDefinedParams(object, params) {
return params
.filter(param => object[param])
.reduce((bid, param) => Object.assign(bid, { [param]: object[param] }), {});
}