forked from prebid/Prebid.js
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprebid.ts
More file actions
1290 lines (1146 loc) · 44.8 KB
/
Copy pathprebid.ts
File metadata and controls
1290 lines (1146 loc) · 44.8 KB
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
/** @module pbjs */
import { getGlobal, type PrebidJS } from './prebidGlobal.js';
import {
deepAccess,
deepClone,
deepEqual,
deepSetValue,
flatten,
generateUUID,
isArray,
isArrayOfNums,
isEmpty,
isFn,
isGptPubadsDefined,
isNumber,
isPlainObject,
logError,
logInfo,
logMessage,
logWarn,
mergeDeep,
transformAdServerTargetingObj,
uniques,
unsupportedBidderMessage
} from './utils.js';
import { listenMessagesFromCreative } from './secureCreatives.js';
import { userSync } from './userSync.js';
import { config } from './config.js';
import { auctionManager } from './auctionManager.js';
import { isBidUsable, targeting } from './targeting.js';
import { hook, wrapHook } from './hook.js';
import { loadSession } from './debugging.js';
import { storageCallbacks } from './storageManager.js';
import adapterManager, { type AliasBidderOptions, type BidRequest, getS2SBidderSet } from './adapterManager.js';
import { BID_STATUS, EVENTS, NATIVE_KEYS } from './constants.js';
import type { Event, EventHandler, EventIDs } from "./events.js";
import * as events from './events.js';
import { type Metrics, newMetrics, useMetrics } from './utils/perfMetrics.js';
import { type Defer, defer, PbPromise } from './utils/promise.js';
import { enrichFPD } from './fpd/enrichment.js';
import { allConsent } from './consentHandler.js';
import {
insertLocatorFrame,
markBidAsRendered,
markWinningBid,
renderAdDirect,
renderIfDeferred
} from './adRendering.js';
import { getHighestCpm } from './utils/reducers.js';
import { fillVideoDefaults, ORTB_VIDEO_PARAMS } from './video.js';
import { ORTB_BANNER_PARAMS } from './banner.js';
import { BANNER, VIDEO } from './mediaTypes.js';
import { delayIfPrerendering } from './utils/prerendering.js';
import { type BidAdapter, type BidderSpec, newBidder } from './adapters/bidderFactory.js';
import { normalizeFPD } from './fpd/normalize.js';
import type { Bid } from "./bidfactory.ts";
import type { AdUnit, AdUnitDefinition, BidderParams } from "./adUnits.ts";
import type { AdUnitCode, BidderCode, ByAdUnit, Identifier, ORTBFragments } from "./types/common.d.ts";
import type { ORTBRequest } from "./types/ortb/request.d.ts";
import type { DeepPartial } from "./types/objects.d.ts";
import type { AnyFunction, Wraps } from "./types/functions.d.ts";
import type { BidderScopedSettings, BidderSettings } from "./bidderSettings.ts";
import { fillAudioDefaults, ORTB_AUDIO_PARAMS } from './audio.ts';
import { getGlobalVarName } from "./buildOptions.ts";
import { yieldAll } from "./utils/yield.ts";
const pbjsInstance = getGlobal();
const { triggerUserSyncs } = userSync;
/* private variables */
const { REQUEST_BIDS, SET_TARGETING } = EVENTS;
// initialize existing debugging sessions if present
loadSession();
declare module './prebidGlobal' {
interface PrebidJS {
bidderSettings: {
standard?: BidderSettings<BidderCode>
} & {
[B in BidderCode]?: BidderScopedSettings<B>
} & {
[B in keyof BidderParams]?: BidderScopedSettings<B>
};
/**
* True once Prebid is loaded.
*/
libLoaded?: true;
/**
* Prebid version.
*/
version: string;
/**
* Set this to true to delay processing of `que` / `cmd` until prerendering is complete
* (applies only when the page is prerendering).
*/
delayPrerendering?: boolean
adUnits: AdUnitDefinition[];
pageViewIdPerBidder: Map<string | null, string>
}
}
pbjsInstance.bidderSettings = pbjsInstance.bidderSettings || {};
pbjsInstance.libLoaded = true;
// version auto generated from build
pbjsInstance.version = 'v$prebid.version$';
logInfo('Prebid.js v$prebid.version$ loaded');
// create adUnit array
pbjsInstance.adUnits = pbjsInstance.adUnits || [];
pbjsInstance.pageViewIdPerBidder = pbjsInstance.pageViewIdPerBidder || new Map<string | null, string>();
function validateSizes(sizes, targLength?: number) {
let cleanSizes = [];
if (isArray(sizes) && ((targLength) ? sizes.length === targLength : sizes.length > 0)) {
// check if an array of arrays or array of numbers
if (sizes.every(sz => isArrayOfNums(sz, 2))) {
cleanSizes = sizes;
} else if (isArrayOfNums(sizes, 2)) {
cleanSizes.push(sizes);
}
}
return cleanSizes;
}
// synchronize fields between mediaTypes[mediaType] and ortb2Imp[mediaType]
export function syncOrtb2(adUnit, mediaType) {
const ortb2Imp = deepAccess(adUnit, `ortb2Imp.${mediaType}`);
const mediaTypes = deepAccess(adUnit, `mediaTypes.${mediaType}`);
if (!ortb2Imp && !mediaTypes) {
// omitting sync due to not present mediaType
return;
}
const fields = {
[VIDEO]: FEATURES.VIDEO && ORTB_VIDEO_PARAMS,
[BANNER]: ORTB_BANNER_PARAMS
}[mediaType];
if (!fields) {
return;
}
[...fields].forEach(([key, validator]) => {
const mediaTypesFieldValue = deepAccess(adUnit, `mediaTypes.${mediaType}.${key}`);
const ortbFieldValue = deepAccess(adUnit, `ortb2Imp.${mediaType}.${key}`);
if (mediaTypesFieldValue === undefined && ortbFieldValue === undefined) {
// omitting the params if it's not defined on either of sides
} else if (mediaTypesFieldValue === undefined) {
deepSetValue(adUnit, `mediaTypes.${mediaType}.${key}`, ortbFieldValue);
} else if (ortbFieldValue === undefined) {
deepSetValue(adUnit, `ortb2Imp.${mediaType}.${key}`, mediaTypesFieldValue);
} else if (!deepEqual(mediaTypesFieldValue, ortbFieldValue)) {
logWarn(`adUnit ${adUnit.code}: specifies conflicting ortb2Imp.${mediaType}.${key} and mediaTypes.${mediaType}.${key}, the latter will be ignored`, adUnit);
deepSetValue(adUnit, `mediaTypes.${mediaType}.${key}`, ortbFieldValue);
}
});
}
function validateBannerMediaType(adUnit: AdUnit) {
const validatedAdUnit = deepClone(adUnit);
const banner = validatedAdUnit.mediaTypes.banner;
const bannerSizes = banner.sizes == null ? null : validateSizes(banner.sizes);
const format = adUnit.ortb2Imp?.banner?.format ?? banner?.format;
let formatSizes;
if (format != null) {
deepSetValue(validatedAdUnit, 'ortb2Imp.banner.format', format);
banner.format = format;
try {
formatSizes = format
.filter(({ w, h, wratio, hratio }) => {
if ((w ?? h) != null && (wratio ?? hratio) != null) {
logWarn(`Ad unit banner.format specifies both w/h and wratio/hratio`, adUnit);
return false;
}
return (w != null && h != null) || (wratio != null && hratio != null);
})
.map(({ w, h, wratio, hratio }) => [w ?? wratio, h ?? hratio]);
} catch (e) {
logError(`Invalid format definition on ad unit ${adUnit.code}`, format);
}
if (formatSizes != null && bannerSizes != null && !deepEqual(bannerSizes, formatSizes)) {
logWarn(`Ad unit ${adUnit.code} has conflicting sizes and format definitions`, adUnit);
}
}
const sizes = formatSizes ?? bannerSizes ?? [];
const expdir = adUnit.ortb2Imp?.banner?.expdir ?? banner.expdir;
if (expdir != null) {
banner.expdir = expdir;
deepSetValue(validatedAdUnit, 'ortb2Imp.banner.expdir', expdir);
}
if (sizes.length > 0) {
banner.sizes = sizes;
// Deprecation Warning: This property will be deprecated in next release in favor of adUnit.mediaTypes.banner.sizes
validatedAdUnit.sizes = sizes;
} else {
logError('Detected a mediaTypes.banner object without a proper sizes field. Please ensure the sizes are listed like: [[300, 250], ...]. Removing invalid mediaTypes.banner object from request.');
delete validatedAdUnit.mediaTypes.banner
}
validateOrtbFields(validatedAdUnit, 'banner');
syncOrtb2(validatedAdUnit, 'banner')
return validatedAdUnit;
}
function validateAudioMediaType(adUnit: AdUnit) {
const validatedAdUnit = deepClone(adUnit);
validateOrtbFields(validatedAdUnit, 'audio');
syncOrtb2(validatedAdUnit, 'audio');
return validatedAdUnit;
}
function validateVideoMediaType(adUnit: AdUnit) {
const validatedAdUnit = deepClone(adUnit);
const video = validatedAdUnit.mediaTypes.video;
if (video.playerSize) {
const tarPlayerSizeLen = (typeof video.playerSize[0] === 'number') ? 2 : 1;
const videoSizes = validateSizes(video.playerSize, tarPlayerSizeLen);
if (videoSizes.length > 0) {
if (tarPlayerSizeLen === 2) {
logInfo('Transforming video.playerSize from [640,480] to [[640,480]] so it\'s in the proper format.');
}
video.playerSize = videoSizes;
// Deprecation Warning: This property will be deprecated in next release in favor of adUnit.mediaTypes.video.playerSize
validatedAdUnit.sizes = videoSizes;
} else {
logError('Detected incorrect configuration of mediaTypes.video.playerSize. Please specify only one set of dimensions in a format like: [[640, 480]]. Removing invalid mediaTypes.video.playerSize property from request.');
delete validatedAdUnit.mediaTypes.video.playerSize;
}
}
validateOrtbFields(validatedAdUnit, 'video');
syncOrtb2(validatedAdUnit, 'video');
return validatedAdUnit;
}
export function validateOrtbFields(adUnit, type, onInvalidParam?) {
const mediaTypes = adUnit?.mediaTypes || {};
const params = mediaTypes[type];
const ORTB_PARAMS = {
banner: ORTB_BANNER_PARAMS,
audio: ORTB_AUDIO_PARAMS,
video: ORTB_VIDEO_PARAMS
}[type]
if (!isPlainObject(params)) {
logWarn(`validateOrtb${type}Fields: ${type}Params must be an object.`);
return;
}
if (params != null) {
Object.entries(params)
.forEach(([key, value]: any) => {
if (!ORTB_PARAMS.has(key)) {
return
}
const isValid = ORTB_PARAMS.get(key)(value);
if (!isValid) {
if (typeof onInvalidParam === 'function') {
onInvalidParam(key, value, adUnit);
} else {
delete params[key];
logWarn(`Invalid prop in adUnit "${adUnit.code}": Invalid value for mediaTypes.${type}.${key} ORTB property. The property has been removed.`);
}
}
});
}
}
function validateNativeMediaType(adUnit: AdUnit) {
function err(msg) {
logError(`Error in adUnit "${adUnit.code}": ${msg}. Removing native request from ad unit`, adUnit);
delete validatedAdUnit.mediaTypes.native;
return validatedAdUnit;
}
function checkDeprecated(onDeprecated) {
for (const key of ['types']) {
if (native.hasOwnProperty(key)) {
const res = onDeprecated(key);
if (res) return res;
}
}
}
const validatedAdUnit = deepClone(adUnit);
const native = validatedAdUnit.mediaTypes.native;
// if native assets are specified in OpenRTB format, remove legacy assets and print a warn.
if (native.ortb) {
if (native.ortb.assets?.some(asset => !isNumber(asset.id) || asset.id < 0 || asset.id % 1 !== 0)) {
return err('native asset ID must be a nonnegative integer');
}
if (checkDeprecated(key => err(`ORTB native requests cannot specify "${key}"`))) {
return validatedAdUnit;
}
const legacyNativeKeys = Object.keys(NATIVE_KEYS).filter(key => NATIVE_KEYS[key].includes('hb_native_'));
const nativeKeys = Object.keys(native);
const intersection = nativeKeys.filter(nativeKey => legacyNativeKeys.includes(nativeKey));
if (intersection.length > 0) {
logError(`when using native OpenRTB format, you cannot use legacy native properties. Deleting ${intersection} keys from request.`);
intersection.forEach(legacyKey => delete validatedAdUnit.mediaTypes.native[legacyKey]);
}
} else {
checkDeprecated(key => logWarn(`mediaTypes.native.${key} is deprecated, consider using native ORTB instead`, adUnit));
}
if (native.image && native.image.sizes && !Array.isArray(native.image.sizes)) {
logError('Please use an array of sizes for native.image.sizes field. Removing invalid mediaTypes.native.image.sizes property from request.');
delete validatedAdUnit.mediaTypes.native.image.sizes;
}
if (native.image && native.image.aspect_ratios && !Array.isArray(native.image.aspect_ratios)) {
logError('Please use an array of sizes for native.image.aspect_ratios field. Removing invalid mediaTypes.native.image.aspect_ratios property from request.');
delete validatedAdUnit.mediaTypes.native.image.aspect_ratios;
}
if (native.icon && native.icon.sizes && !Array.isArray(native.icon.sizes)) {
logError('Please use an array of sizes for native.icon.sizes field. Removing invalid mediaTypes.native.icon.sizes property from request.');
delete validatedAdUnit.mediaTypes.native.icon.sizes;
}
return validatedAdUnit;
}
function validateAdUnitPos(adUnit, mediaType) {
const pos = adUnit?.mediaTypes?.[mediaType]?.pos;
if (!isNumber(pos) || isNaN(pos) || !isFinite(pos)) {
const warning = `Value of property 'pos' on ad unit ${adUnit.code} should be of type: Number`;
logWarn(warning);
delete adUnit.mediaTypes[mediaType].pos;
}
return adUnit
}
function validateAdUnit(adUnitDef: AdUnitDefinition): AdUnit {
const msg = (msg) => `adUnit.code '${adUnit.code}' ${msg}`;
const adUnit = adUnitDef as AdUnit;
const mediaTypes = adUnit.mediaTypes;
const bids = adUnit.bids;
if (bids != null && !isArray(bids)) {
logError(msg(`defines 'adUnit.bids' that is not an array. Removing adUnit from auction`));
return null;
}
if (bids == null && adUnit.ortb2Imp == null) {
logError(msg(`has no 'adUnit.bids' and no 'adUnit.ortb2Imp'. Removing adUnit from auction`));
return null;
}
if (!mediaTypes || Object.keys(mediaTypes).length === 0) {
logError(msg(`does not define a 'mediaTypes' object. This is a required field for the auction, so this adUnit has been removed.`));
return null;
}
if (adUnit.ortb2Imp != null && (bids == null || bids.length === 0)) {
adUnit.bids = [{ bidder: null }]; // the 'null' bidder is treated as an s2s-only placeholder by adapterManager
logMessage(msg(`defines 'adUnit.ortb2Imp' with no 'adUnit.bids'; it will be seen only by S2S adapters`));
}
return adUnit;
}
export const adUnitSetupChecks = {
validateAdUnit,
validateBannerMediaType,
validateSizes
};
if (FEATURES.NATIVE) {
Object.assign(adUnitSetupChecks, { validateNativeMediaType });
}
if (FEATURES.VIDEO) {
Object.assign(adUnitSetupChecks, { validateVideoMediaType });
}
if (FEATURES.AUDIO) {
Object.assign(adUnitSetupChecks, { validateAudioMediaType });
}
export const checkAdUnitSetup = hook('sync', function (adUnits: AdUnitDefinition[]) {
const validatedAdUnits = [];
adUnits.forEach(adUnitDef => {
const adUnit = validateAdUnit(adUnitDef);
if (adUnit == null) return;
const mediaTypes = adUnit.mediaTypes;
let validatedBanner, validatedVideo, validatedNative, validatedAudio;
if (mediaTypes.banner) {
validatedBanner = validateBannerMediaType(adUnit);
if (mediaTypes.banner.hasOwnProperty('pos')) validatedBanner = validateAdUnitPos(validatedBanner, 'banner');
}
if (FEATURES.VIDEO && mediaTypes.video) {
validatedVideo = validatedBanner ? validateVideoMediaType(validatedBanner) : validateVideoMediaType(adUnit);
if (mediaTypes.video.hasOwnProperty('pos')) validatedVideo = validateAdUnitPos(validatedVideo, 'video');
}
if (FEATURES.NATIVE && mediaTypes.native) {
validatedNative = validatedVideo ? validateNativeMediaType(validatedVideo) : validatedBanner ? validateNativeMediaType(validatedBanner) : validateNativeMediaType(adUnit);
}
if (FEATURES.AUDIO && mediaTypes.audio) {
validatedAudio = validatedNative ? validateAudioMediaType(validatedNative) : validateAudioMediaType(adUnit);
}
const validatedAdUnit = Object.assign({}, validatedBanner, validatedVideo, validatedNative, validatedAudio);
validatedAdUnits.push(validatedAdUnit);
});
return validatedAdUnits;
}, 'checkAdUnitSetup');
function fillAdUnitDefaults(adUnits: AdUnitDefinition[]) {
if (FEATURES.VIDEO) {
adUnits.forEach(au => fillVideoDefaults(au))
}
if (FEATURES.AUDIO) {
adUnits.forEach(au => fillAudioDefaults(au))
}
}
function logInvocation<T extends AnyFunction>(name: string, fn: T): Wraps<T> {
return function (...args) {
logInfo(`Invoking ${getGlobalVarName()}.${name}`, args);
return fn.apply(this, args);
}
}
export function addApiMethod<N extends keyof PrebidJS>(name: N, method: PrebidJS[N], log = true) {
getGlobal()[name] = log ? logInvocation(name, method) as PrebidJS[N] : method;
}
/// ///////////////////////////////
// //
// Start Public APIs //
// //
/// ///////////////////////////////
declare module './prebidGlobal' {
interface PrebidJS {
/**
* Re-trigger user syncs. Requires the `userSync.enableOverride` config to be set.
*/
triggerUserSyncs: typeof triggerUserSyncs;
getAdserverTargetingForAdUnitCodeStr: typeof getAdserverTargetingForAdUnitCodeStr;
getHighestUnusedBidResponseForAdUnitCode: typeof getHighestUnusedBidResponseForAdUnitCode;
getAdserverTargetingForAdUnitCode: typeof getAdserverTargetingForAdUnitCode;
getAdserverTargeting: typeof getAdserverTargeting;
getConsentMetadata: typeof getConsentMetadata;
getNoBids: typeof getNoBids;
getNoBidsForAdUnitCode: typeof getNoBidsForAdUnitCode;
getBidResponses: typeof getBidResponses;
getBidResponsesForAdUnitCode: typeof getBidResponsesForAdUnitCode;
setTargetingForGPTAsync: typeof setTargetingForGPTAsync;
setTargetingForAst: typeof setTargetingForAst;
renderAd: typeof renderAd;
removeAdUnit: typeof removeAdUnit;
requestBids: RequestBids;
addAdUnits: typeof addAdUnits;
onEvent: typeof onEvent;
offEvent: typeof offEvent;
getEvents: typeof getEvents;
registerBidAdapter: typeof registerBidAdapter;
registerAnalyticsAdapter: typeof adapterManager.registerAnalyticsAdapter;
enableAnalytics: typeof adapterManager.enableAnalytics;
aliasBidder: typeof aliasBidder;
aliasRegistry: typeof adapterManager.aliasRegistry;
getAllWinningBids: typeof getAllWinningBids;
getAllPrebidWinningBids: typeof getAllPrebidWinningBids;
getHighestCpmBids: typeof getHighestCpmBids;
clearAllAuctions: typeof clearAllAuctions;
markWinningBidAsUsed: typeof markWinningBidAsUsed;
getConfig: typeof config.getConfig;
readConfig: typeof config.readConfig;
mergeConfig: typeof config.mergeConfig;
mergeBidderConfig: typeof config.mergeBidderConfig;
setConfig: typeof config.setConfig;
setBidderConfig: typeof config.setBidderConfig;
processQueue: typeof processQueue;
triggerBilling: typeof triggerBilling;
refreshPageViewId: typeof refreshPageViewId;
}
}
// Allow publishers who enable user sync override to trigger their sync
addApiMethod('triggerUserSyncs', triggerUserSyncs);
/**
* Return a query string with all available targeting parameters for the given ad unit.
*
* @param adUnitCode ad unit code to target
*/
function getAdserverTargetingForAdUnitCodeStr(adUnitCode: AdUnitCode): string {
if (adUnitCode) {
const res = getAdserverTargetingForAdUnitCode(adUnitCode);
return transformAdServerTargetingObj(res);
} else {
logMessage('Need to call getAdserverTargetingForAdUnitCodeStr with adunitCode');
}
}
addApiMethod('getAdserverTargetingForAdUnitCodeStr', getAdserverTargetingForAdUnitCodeStr);
/**
* Return the highest cpm, unused bid for the given ad unit.
* @param adUnitCode
*/
function getHighestUnusedBidResponseForAdUnitCode(adUnitCode: AdUnitCode): Bid {
if (adUnitCode) {
const bid = auctionManager.getAllBidsForAdUnitCode(adUnitCode)
.filter(isBidUsable)
return bid.length ? bid.reduce(getHighestCpm) : null
} else {
logMessage('Need to call getHighestUnusedBidResponseForAdUnitCode with adunitCode');
}
}
addApiMethod('getHighestUnusedBidResponseForAdUnitCode', getHighestUnusedBidResponseForAdUnitCode);
/**
* Returns targeting key-value pairs available at this moment for a given ad unit.
* @param adUnitCode adUnitCode to get the bid responses for
*/
function getAdserverTargetingForAdUnitCode(adUnitCode) {
return getAdserverTargeting(adUnitCode)[adUnitCode];
}
addApiMethod('getAdserverTargetingForAdUnitCode', getAdserverTargetingForAdUnitCode);
/**
* returns all ad server targeting, optionally scoped to the given ad unit(s).
* @return Map of adUnitCodes to targeting key-value pairs
*/
function getAdserverTargeting(adUnitCode?: AdUnitCode | AdUnitCode[]) {
return targeting.getAllTargeting(adUnitCode);
}
addApiMethod('getAdserverTargeting', getAdserverTargeting);
function getConsentMetadata() {
return allConsent.getConsentMeta()
}
addApiMethod('getConsentMetadata', getConsentMetadata);
type WrapsInBids<T> = T[] & {
bids: T[]
}
function wrapInBids(arr) {
arr = arr.slice();
arr.bids = arr;
return arr;
}
function getBids<T>(type): ByAdUnit<WrapsInBids<T>> {
const responses = auctionManager[type]()
.filter(bid => auctionManager.getAdUnitCodes().includes(bid.adUnitCode))
// find the last auction id to get responses for most recent auction only
const currentAuctionId = auctionManager.getLastAuctionId();
return responses
.map(bid => bid.adUnitCode)
.filter(uniques).map(adUnitCode => responses
.filter(bid => bid.auctionId === currentAuctionId && bid.adUnitCode === adUnitCode))
.filter(bids => bids && bids[0] && bids[0].adUnitCode)
.map(bids => {
return {
[bids[0].adUnitCode]: wrapInBids(bids)
};
})
.reduce((a, b) => Object.assign(a, b), {});
}
/**
* @returns the bids requests involved in an auction but not bid on
*/
function getNoBids() {
return getBids<BidRequest<BidderCode>>('getNoBids');
}
addApiMethod('getNoBids', getNoBids);
/**
* @returns the bids requests involved in an auction but not bid on or the specified adUnitCode
*/
function getNoBidsForAdUnitCode(adUnitCode: AdUnitCode): WrapsInBids<BidRequest<BidderCode>> {
const bids = auctionManager.getNoBids().filter(bid => bid.adUnitCode === adUnitCode);
return wrapInBids(bids);
}
addApiMethod('getNoBidsForAdUnitCode', getNoBidsForAdUnitCode);
/**
* @return a map from ad unit code to all bids received for that ad unit code.
*/
function getBidResponses() {
return getBids<Bid>('getBidsReceived');
}
addApiMethod('getBidResponses', getBidResponses);
/**
* Returns bids received for the specified ad unit.
* @param adUnitCode ad unit code
*/
function getBidResponsesForAdUnitCode(adUnitCode: AdUnitCode): WrapsInBids<Bid> {
const bids = auctionManager.getBidsReceived().filter(bid => bid.adUnitCode === adUnitCode);
return wrapInBids(bids);
}
addApiMethod('getBidResponsesForAdUnitCode', getBidResponsesForAdUnitCode);
/**
* Set query string targeting on one or more GPT ad units.
* @param adUnit a single `adUnit.code` or multiple.
*/
function setTargetingForGPTAsync(adUnit?: AdUnitCode | AdUnitCode[]) {
if (!isGptPubadsDefined()) {
logError('window.googletag is not defined on the page');
return;
}
targeting.setTargetingForGPT(adUnit);
}
addApiMethod('setTargetingForGPTAsync', setTargetingForGPTAsync);
/**
* Set query string targeting on all AST (AppNexus Seller Tag) ad units. Note that this function has to be called after all ad units on page are defined. For working example code, see [Using Prebid.js with AppNexus Publisher Ad Server](http://prebid.org/dev-docs/examples/use-prebid-with-appnexus-ad-server.html).
* @param adUnitCodes adUnitCode or array of adUnitCodes
*/
function setTargetingForAst(adUnitCodes?: AdUnitCode | AdUnitCode[]) {
if (!targeting.isApntagDefined()) {
logError('window.apntag is not defined on the page');
return;
}
targeting.setTargetingForAst(adUnitCodes);
events.emit(SET_TARGETING, targeting.getAllTargeting());
}
addApiMethod('setTargetingForAst', setTargetingForAst);
type RenderAdOptions = {
/**
* Click through URL. Used to replace ${CLICKTHROUGH} macro in ad markup.
*/
clickThrough?: string;
}
/**
* This function will render the ad (based on params) in the given iframe document passed through.
* Note that doc SHOULD NOT be the parent document page as we can't doc.write() asynchronously
* @param doc document
* @param id adId of the bid to render
* @param options
*/
function renderAd(doc: Document, id: Bid['adId'], options?: RenderAdOptions) {
renderAdDirect(doc, id, options);
}
addApiMethod('renderAd', renderAd);
/**
* Remove adUnit from the $$PREBID_GLOBAL$$ configuration, if there are no addUnitCode(s) it will remove all
* @param adUnitCode the adUnitCode(s) to remove
* @alias module:pbjs.removeAdUnit
*/
function removeAdUnit(adUnitCode?: AdUnitCode) {
if (!adUnitCode) {
pbjsInstance.adUnits = [];
return;
}
let adUnitCodes;
if (isArray(adUnitCode)) {
adUnitCodes = adUnitCode;
} else {
adUnitCodes = [adUnitCode];
}
adUnitCodes.forEach((adUnitCode) => {
for (let i = pbjsInstance.adUnits.length - 1; i >= 0; i--) {
if (pbjsInstance.adUnits[i].code === adUnitCode) {
pbjsInstance.adUnits.splice(i, 1);
}
}
});
}
addApiMethod('removeAdUnit', removeAdUnit);
export type RequestBidsOptions = {
/**
* Callback to execute when all the bid responses are back or the timeout hits. Parameters may be undefined
* in situations where the auction is canceled prematurely (e.g. CMP errors)
*/
bidsBackHandler?: (bids?: RequestBidsResult['bids'], timedOut?: RequestBidsResult['timedOut'], auctionId?: RequestBidsResult['auctionId']) => void;
/**
* TTL buffer override for this auction.
*/
ttlBuffer?: number;
/**
* Timeout for requesting the bids specified in milliseconds
*/
timeout?: number;
/**
* AdUnit definitions to request. Use this or adUnitCodes. Default to all adUnits if empty.
*/
adUnits?: AdUnitDefinition[];
/**
* adUnit codes to request. Use this or adUnits. Default to all adUnits if empty.
*/
adUnitCodes?: AdUnitCode[];
/**
* Defines labels that may be matched on ad unit targeting conditions.
*/
labels?: string[];
/**
* Defines an auction ID to be used rather than having Prebid generate one.
* This can be useful if there are multiple wrappers on a page and a single auction ID
* is desired to tie them together in analytics.
*/
auctionId?: string;
/**
* Additional first-party data to use for this auction only
*/
ortb2?: DeepPartial<ORTBRequest>;
}
type RequestBidsResult = {
/**
* Bids received, grouped by ad unit.
*/
bids?: ByAdUnit<WrapsInBids<Bid>>;
/**
* True if any bidder timed out.
*/
timedOut?: boolean;
/**
* The auction's ID
*/
auctionId?: Identifier;
}
export type PrivRequestBidsOptions = RequestBidsOptions & {
defer: Defer<RequestBidsResult>;
metrics: Metrics;
/**
* Ad units are always defined and fixed here (as opposed to the public API where we may fall back to
* the global array).
*/
adUnits: AdUnitDefinition[];
}
export type StartAuctionOptions = Omit<PrivRequestBidsOptions, 'ortb2'> & {
ortb2Fragments: ORTBFragments
}
declare module './hook' {
interface NamedHooks {
requestBids: typeof requestBids;
startAuction: typeof startAuction;
}
}
interface RequestBids {
(options?: RequestBidsOptions): Promise<RequestBidsResult>;
}
declare module './events' {
interface Events {
/**
* Fired when `requestBids` is called.
*/
[REQUEST_BIDS]: [RequestBidsOptions];
}
}
export const requestBids = (function() {
function filterAdUnits(adUnits, adUnitCodes) {
if (adUnitCodes != null && !Array.isArray(adUnitCodes)) {
adUnitCodes = [adUnitCodes];
}
if (adUnitCodes == null || (Array.isArray(adUnitCodes) && adUnitCodes.length === 0)) {
return {
included: adUnits,
excluded: [],
adUnitCodes: adUnits.map(au => au.code).filter(uniques)
}
} else {
adUnitCodes = adUnitCodes.filter(uniques);
return Object.assign({
adUnitCodes
}, adUnits.reduce(({ included, excluded }, adUnit) => {
(adUnitCodes.includes(adUnit.code) ? included : excluded).push(adUnit);
return { included, excluded };
}, { included: [], excluded: [] }))
}
}
const delegate = hook('async', function (reqBidOptions: PrivRequestBidsOptions): void {
let { bidsBackHandler, timeout, adUnits, adUnitCodes, labels, auctionId, ttlBuffer, ortb2, metrics, defer } = reqBidOptions ?? {};
const cbTimeout = timeout || config.getConfig('bidderTimeout');
({ included: adUnits, adUnitCodes } = filterAdUnits(adUnits, adUnitCodes));
let ortb2Fragments = {
global: mergeDeep({}, config.getAnyConfig('ortb2') || {}, ortb2 || {}),
bidder: Object.fromEntries(Object.entries<any>(config.getBidderConfig()).map(([bidder, cfg]) => [bidder, deepClone(cfg.ortb2)]).filter(([_, ortb2]) => ortb2 != null))
}
ortb2Fragments = normalizeFPD(ortb2Fragments);
enrichFPD(PbPromise.resolve(ortb2Fragments.global)).then(global => {
ortb2Fragments.global = global;
return startAuction({ bidsBackHandler, timeout: cbTimeout, adUnits, adUnitCodes, labels, auctionId, ttlBuffer, ortb2Fragments, metrics, defer });
})
}, 'requestBids');
return wrapHook(delegate, logInvocation('requestBids', delayIfPrerendering(() => !config.getConfig('allowPrerendering'), function requestBids(options: RequestBidsOptions = {}) {
// unlike the main body of `delegate`, this runs before any other hook has a chance to;
// it's also not restricted in its return value in the way `async` hooks are.
// if the request does not specify adUnits, clone the global adUnit array;
// otherwise, if the caller goes on to use addAdUnits/removeAdUnits, any asynchronous logic
// in any hook might see their effects.
const adUnits = options.adUnits || pbjsInstance.adUnits;
options.adUnits = (Array.isArray(adUnits) ? adUnits.slice() : [adUnits]);
const metrics = newMetrics();
metrics.checkpoint('requestBids');
const { included, excluded, adUnitCodes } = filterAdUnits(adUnits, options.adUnitCodes);
events.emit(REQUEST_BIDS, Object.assign(options, {
adUnits: included,
adUnitCodes
}));
// ad units that were filtered out are re-included here, then filtered out again in `delegate`
// this is to avoid breaking requestBids hook that expect all ad units in the request (such as priceFloors)
const req = Object.assign({}, options, {
adUnits: options.adUnits.slice().concat(excluded),
// because of this double filtering logic, it's not clear
// what it means for an event handler to modify adUnitCodes - so don't allow it
adUnitCodes,
metrics,
defer: defer({ promiseFactory: (r) => new Promise(r) })
});
delegate.call(this, req);
return req.defer.promise;
})));
})();
addApiMethod('requestBids', requestBids as unknown as RequestBids, false);
export const startAuction = hook('async', function ({ bidsBackHandler, timeout: cbTimeout, adUnits: adUnitDefs, ttlBuffer, adUnitCodes, labels, auctionId, ortb2Fragments, metrics, defer }: StartAuctionOptions = {} as any) {
const s2sBidders = getS2SBidderSet(config.getConfig('s2sConfig') || []);
fillAdUnitDefaults(adUnitDefs);
const adUnits: AdUnit[] = useMetrics(metrics).measureTime('requestBids.validate', () => checkAdUnitSetup(adUnitDefs));
function auctionDone(bids?, timedOut?: boolean, auctionId?: string) {
if (typeof bidsBackHandler === 'function') {
try {
bidsBackHandler(bids, timedOut, auctionId);
} catch (e) {
logError('Error executing bidsBackHandler', null, e);
}
}
defer.resolve({ bids, timedOut, auctionId })
}
const tids = {};
/*
* for a given adunit which supports a set of mediaTypes
* and a given bidder which supports a set of mediaTypes
* a bidder is eligible to participate on the adunit
* if it supports at least one of the mediaTypes on the adunit
*/
adUnits.forEach(adUnit => {
// get the adunit's mediaTypes, defaulting to banner if mediaTypes isn't present
const adUnitMediaTypes = Object.keys(adUnit.mediaTypes || { 'banner': 'banner' });
// get the bidder's mediaTypes
const allBidders = adUnit.bids.map(bid => bid.bidder).filter(Boolean);
const bidderRegistry = adapterManager.bidderRegistry;
const bidders = allBidders.filter(bidder => !s2sBidders.has(bidder));
adUnit.adUnitId = generateUUID();
const tid = adUnit.ortb2Imp?.ext?.tid;
if (tid) {
if (tids.hasOwnProperty(adUnit.code)) {
logWarn(`Multiple distinct ortb2Imp.ext.tid were provided for twin ad units '${adUnit.code}'`)
} else {
tids[adUnit.code] = tid;
}
}
if (ttlBuffer != null && !adUnit.hasOwnProperty('ttlBuffer')) {
adUnit.ttlBuffer = ttlBuffer;
}
bidders.forEach(bidder => {
const adapter = bidderRegistry[bidder];
const spec = adapter && adapter.getSpec && adapter.getSpec();
// banner is default if not specified in spec
const bidderMediaTypes = (spec && spec.supportedMediaTypes) || ['banner'];
// check if the bidder's mediaTypes are not in the adUnit's mediaTypes
const bidderEligible = adUnitMediaTypes.some(type => bidderMediaTypes.includes(type));
if (!bidderEligible) {
// drop the bidder from the ad unit if it's not compatible
logWarn(unsupportedBidderMessage(adUnit, bidder));
adUnit.bids = adUnit.bids.filter(bid => bid.bidder !== bidder);
}
});
});
if (!adUnits || adUnits.length === 0) {
logMessage('No adUnits configured. No bids requested.');
auctionDone();
} else {
adUnits.forEach(au => {
const tid = au.ortb2Imp?.ext?.tid || tids[au.code] || generateUUID();
if (!tids.hasOwnProperty(au.code)) {
tids[au.code] = tid;
}
au.transactionId = tid;
});
const auction = auctionManager.createAuction({
adUnits,
adUnitCodes,
callback: auctionDone,
cbTimeout,
labels,
auctionId,
ortb2Fragments,
metrics,
});
const adUnitsLen = adUnits.length;
if (adUnitsLen > 15) {
logInfo(`Current auction ${auction.getAuctionId()} contains ${adUnitsLen} adUnits.`, adUnits);
}
adUnitCodes.forEach(code => targeting.setLatestAuctionForAdUnit(code, auction.getAuctionId()));
auction.callBids();
}
}, 'startAuction');
export function executeCallbacks(fn, reqBidsConfigObj) {
runAll(storageCallbacks);
runAll(enableAnalyticsCallbacks);
fn.call(this, reqBidsConfigObj);
function runAll(queue) {
let queued;
while ((queued = queue.shift())) {
queued();
}
}
}
// This hook will execute all storage callbacks which were registered before gdpr enforcement hook was added. Some bidders, user id modules use storage functions when module is parsed but gdpr enforcement hook is not added at that stage as setConfig callbacks are yet to be called. Hence for such calls we execute all the stored callbacks just before requestBids. At this hook point we will know for sure that tcfControl module is added or not
requestBids.before(executeCallbacks, 49);
/**
* Add ad unit(s)
* @param adUnits
*/
function addAdUnits(adUnits: AdUnitDefinition | AdUnitDefinition[]) {
pbjsInstance.adUnits.push(...(Array.isArray(adUnits) ? adUnits : [adUnits]))
}
addApiMethod('addAdUnits', addAdUnits);
const eventIdValidators = {
bidWon(id) {
const adUnitCodes = auctionManager.getBidsRequested().map(bidSet => bidSet.bids.map(bid => bid.adUnitCode))
.reduce(flatten)
.filter(uniques);
if (!adUnitCodes.includes(id)) {
logError('The "' + id + '" placement is not defined.');
return;
}
return true;
}
};
function validateEventId(event, id) {
return eventIdValidators.hasOwnProperty(event) && eventIdValidators[event](id);
}
/**
* @param event the name of the event
* @param handler a callback to set on event
* @param id an identifier in the context of the event
*
* This API call allows you to register a callback to handle a Prebid.js event.
* An optional `id` parameter provides more finely-grained event callback registration.
* This makes it possible to register callback events for a specific item in the
* event context. For example, `bidWon` events will accept an `id` for ad unit code.
* `bidWon` callbacks registered with an ad unit code id will be called when a bid
* for that ad unit code wins the auction. Without an `id` this method registers the
* callback for every `bidWon` event.
*
* Currently `bidWon` is the only event that accepts an `id` parameter.
*/
function onEvent<E extends Event>(event: E, handler: EventHandler<E>, id?: EventIDs[E]) {