-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
Copy pathrubiconBidAdapter.js
1359 lines (1214 loc) · 45.6 KB
/
rubiconBidAdapter.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 { ortbConverter } from '../libraries/ortbConverter/converter.js';
import { pbsExtensions } from '../libraries/pbsExtensions/pbsExtensions.js';
import { registerBidder } from '../src/adapters/bidderFactory.js';
import { config } from '../src/config.js';
import { BANNER, NATIVE, VIDEO } from '../src/mediaTypes.js';
import { getGlobal } from '../src/prebidGlobal.js';
import { Renderer } from '../src/Renderer.js';
import {
deepAccess,
deepSetValue,
formatQS,
isArray,
isNumber,
isStr,
logError,
logMessage,
logWarn,
mergeDeep,
parseSizesInput,
pick,
_each,
isPlainObject
} from '../src/utils.js';
import {getAllOrtbKeywords} from '../libraries/keywords/keywords.js';
import {getUserSyncParams} from '../libraries/userSyncUtils/userSyncUtils.js';
/**
* @typedef {import('../src/adapters/bidderFactory.js').BidRequest} BidRequest
*/
const DEFAULT_INTEGRATION = 'pbjs_lite';
const DEFAULT_PBS_INTEGRATION = 'pbjs';
const DEFAULT_RENDERER_URL = 'https://video-outstream.rubiconproject.com/apex-2.2.1.js';
// renderer code at https://github.com/rubicon-project/apex2
let rubiConf = config.getConfig('rubicon') || {};
// we are saving these as global to this module so that if a pub accidentally overwrites the entire
// rubicon object, then we do not lose other data
config.getConfig('rubicon', config => {
mergeDeep(rubiConf, config.rubicon);
});
const GVLID = 52;
let impIdMap = {};
var sizeMap = {
1: '468x60',
2: '728x90',
5: '120x90',
7: '125x125',
8: '120x600',
9: '160x600',
10: '300x600',
13: '200x200',
14: '250x250',
15: '300x250',
16: '336x280',
17: '240x400',
19: '300x100',
31: '980x120',
32: '250x360',
33: '180x500',
35: '980x150',
37: '468x400',
38: '930x180',
39: '750x100',
40: '750x200',
41: '750x300',
42: '2x4',
43: '320x50',
44: '300x50',
48: '300x300',
53: '1024x768',
54: '300x1050',
55: '970x90',
57: '970x250',
58: '1000x90',
59: '320x80',
60: '320x150',
61: '1000x1000',
64: '580x500',
65: '640x480',
66: '930x600',
67: '320x480',
68: '1800x1000',
72: '320x320',
73: '320x160',
78: '980x240',
79: '980x300',
80: '980x400',
83: '480x300',
85: '300x120',
90: '548x150',
94: '970x310',
95: '970x100',
96: '970x210',
101: '480x320',
102: '768x1024',
103: '480x280',
105: '250x800',
108: '320x240',
113: '1000x300',
117: '320x100',
125: '800x250',
126: '200x600',
144: '980x600',
145: '980x150',
152: '1000x250',
156: '640x320',
159: '320x250',
179: '250x600',
195: '600x300',
198: '640x360',
199: '640x200',
213: '1030x590',
214: '980x360',
221: '1x1',
229: '320x180',
230: '2000x1400',
232: '580x400',
234: '6x6',
251: '2x2',
256: '480x820',
257: '400x600',
258: '500x200',
259: '998x200',
261: '480x480',
264: '970x1000',
265: '1920x1080',
274: '1800x200',
278: '320x500',
282: '320x400',
288: '640x380',
484: '720x1280',
524: '1x2',
548: '500x1000',
550: '980x480',
552: '300x200',
558: '640x640',
562: '300x431',
564: '320x431',
566: '320x300',
568: '300x150',
570: '300x125',
572: '250x350',
574: '620x891',
576: '610x877',
578: '980x552',
580: '505x656',
622: '192x160',
632: '1200x450',
634: '340x450',
680: '970x570',
682: '300x240',
684: '970x550',
686: '300x210',
688: '300x220',
690: '970x170'
};
_each(sizeMap, (item, key) => sizeMap[item] = key);
export const converter = ortbConverter({
request(buildRequest, imps, bidderRequest, context) {
const {bidRequests} = context;
const data = buildRequest(imps, bidderRequest, context);
data.cur = ['USD'];
data.test = config.getConfig('debug') ? 1 : 0;
deepSetValue(data, 'ext.prebid.cache', {
vastxml: {
returnCreative: rubiConf.returnVast === true
}
});
deepSetValue(data, 'ext.prebid.bidders', {
rubicon: {
integration: rubiConf.int_type || DEFAULT_PBS_INTEGRATION,
}
});
deepSetValue(data, 'ext.prebid.targeting.pricegranularity', getPriceGranularity(config));
let modules = (getGlobal()).installedModules;
if (modules && (!modules.length || modules.indexOf('rubiconAnalyticsAdapter') !== -1)) {
deepSetValue(data, 'ext.prebid.analytics', {'rubicon': {'client-analytics': true}});
}
addOrtbFirstPartyData(data, bidRequests, bidderRequest.ortb2);
delete data?.ext?.prebid?.storedrequest;
// floors
if (rubiConf.disableFloors === true) {
delete data.ext.prebid.floors;
}
// If the price floors module is active, then we need to signal to PBS! If floorData obj is present is best way to check
const haveFloorDataBidRequests = bidRequests.filter(bidRequest => typeof bidRequest.floorData === 'object');
if (haveFloorDataBidRequests.length > 0) {
data.ext.prebid.floors = { enabled: false };
}
return data;
},
imp(buildImp, bidRequest, context) {
// skip banner-only requests
const bidRequestType = bidType(bidRequest);
if (bidRequestType.includes(BANNER) && bidRequestType.length == 1) return;
const imp = buildImp(bidRequest, context);
imp.id = bidRequest.adUnitCode;
delete imp.banner;
bidRequest.params.position === 'atf' && imp.video && (imp.video.pos = 1);
bidRequest.params.position === 'btf' && imp.video && (imp.video.pos = 3);
delete imp.ext?.prebid?.storedrequest;
if (bidRequest.params.bidonmultiformat === true && bidRequestType.length > 1) {
deepSetValue(imp, 'ext.prebid.bidder.rubicon.formats', bidRequestType);
}
setBidFloors(bidRequest, imp);
// ensure unique imp IDs for twin adunits
imp.id = impIdMap[imp.id] ? imp.id + impIdMap[imp.id]++ : (impIdMap[imp.id] = 2, imp.id);
return imp;
},
bidResponse(buildBidResponse, bid, context) {
const bidResponse = buildBidResponse(bid, context);
bidResponse.meta.mediaType = deepAccess(bid, 'ext.prebid.type');
const {bidRequest} = context;
let [parseSizeWidth, parseSizeHeight] = bidRequest.mediaTypes.video?.context === 'outstream' ? parseSizes(bidRequest, VIDEO) : [undefined, undefined];
// 0 by default to avoid undefined size
bidResponse.width = bid.w || parseSizeWidth || bidResponse.playerWidth || 0;
bidResponse.height = bid.h || parseSizeHeight || bidResponse.playerHeight || 0;
if (bidResponse.mediaType === VIDEO && bidRequest.mediaTypes.video.context === 'outstream') {
bidResponse.renderer = outstreamRenderer(bidResponse);
}
if (deepAccess(bid, 'ext.bidder.rp.advid')) {
deepSetValue(bidResponse, 'meta.advertiserId', bid.ext.bidder.rp.advid);
}
return bidResponse;
},
context: {
netRevenue: rubiConf.netRevenue !== false, // If anything other than false, netRev is true
ttl: 360,
},
processors: pbsExtensions
});
export const spec = {
code: 'rubicon',
gvlid: GVLID,
supportedMediaTypes: [BANNER, VIDEO, NATIVE],
/**
* @param {object} bid
* @return boolean
*/
isBidRequestValid: function (bid) {
let valid = true;
if (typeof bid.params !== 'object') {
return false;
}
// validate account, site, zone have numeric values
for (let i = 0, props = ['accountId', 'siteId', 'zoneId']; i < props.length; i++) {
bid.params[props[i]] = parseInt(bid.params[props[i]])
if (isNaN(bid.params[props[i]])) {
logError('Rubicon: wrong format of accountId or siteId or zoneId.')
return false
}
}
let bidFormats = bidType(bid, true);
// bidType is undefined? Return false
if (!bidFormats.length) {
return false;
} else if (bidFormats.includes(VIDEO)) { // bidType is video, make sure it has required params
valid = hasValidVideoParams(bid);
}
const hasBannerOrNativeMediaType = [BANNER, NATIVE].filter(mediaType => bidFormats.includes(mediaType)).length > 0;
if (!hasBannerOrNativeMediaType) return valid;
return valid && hasBannerOrNativeMediaType;
},
/**
* @param {BidRequest[]} bidRequests
* @param bidderRequest
* @return BidRequest[]
*/
buildRequests: function (bidRequests, bidderRequest) {
// separate video bids because the requests are structured differently
let requests = [];
let filteredHttpRequest = [];
let filteredRequests;
filteredRequests = bidRequests.filter(req => {
const mediaTypes = bidType(req) || [];
const { length } = mediaTypes;
const { bidonmultiformat, video } = req.params || {};
return (
// if there's just one mediaType and it's video or native, just send it!
(length === 1 && (mediaTypes.includes(VIDEO) || mediaTypes.includes(NATIVE))) ||
// if it's two mediaTypes, and they don't contain banner, send to PBS both native & video
(length === 2 && !mediaTypes.includes(BANNER)) ||
// if it contains the video param and the Video mediaType, send Video to PBS (not native!)
(video && mediaTypes.includes(VIDEO)) ||
// if bidonmultiformat is on, send everything to PBS
(bidonmultiformat && (mediaTypes.includes(VIDEO) || mediaTypes.includes(NATIVE)))
)
});
if (filteredRequests && filteredRequests.length) {
const data = converter.toORTB({bidRequests: filteredRequests, bidderRequest});
resetImpIdMap();
filteredHttpRequest.push({
method: 'POST',
url: `https://${rubiConf.videoHost || 'prebid-server'}.rubiconproject.com/openrtb2/auction`,
data,
bidRequest: filteredRequests
});
}
const bannerBidRequests = bidRequests.filter((req) => {
const mediaTypes = bidType(req) || [];
const {bidonmultiformat, video} = req.params || {};
return (
// Send to fastlane if: it must include BANNER and...
mediaTypes.includes(BANNER) && (
// if it's just banner
(mediaTypes.length === 1) ||
// if bidonmultiformat is true
bidonmultiformat ||
// if bidonmultiformat is false and there's no video parameter
(!bidonmultiformat && !video) ||
// if there's video parameter, but there's no video mediatype
(!bidonmultiformat && video && !mediaTypes.includes(VIDEO))
)
);
});
if (rubiConf.singleRequest !== true) {
// bids are not grouped if single request mode is not enabled
requests = filteredHttpRequest.concat(bannerBidRequests.map(bidRequest => {
const bidParams = spec.createSlotParams(bidRequest, bidderRequest);
return {
method: 'GET',
url: `https://${rubiConf.bannerHost || 'fastlane'}.rubiconproject.com/a/api/fastlane.json`,
data: spec.getOrderedParams(bidParams).reduce((paramString, key) => {
const propValue = bidParams[key];
return ((isStr(propValue) && propValue !== '') || isNumber(propValue)) ? `${paramString}${encodeParam(key, propValue)}&` : paramString;
}, '') + `slots=1&rand=${Math.random()}`,
bidRequest
};
}));
} else {
// single request requires bids to be grouped by site id into a single request
// note: groupBy wasn't used because deep property access was needed
const groupedBidRequests = bannerBidRequests.reduce((groupedBids, bid) => {
(groupedBids[bid.params['siteId']] = groupedBids[bid.params['siteId']] || []).push(bid);
return groupedBids;
}, {});
// fastlane SRA has a limit of 10 slots
const SRA_BID_LIMIT = 10;
// multiple requests are used if bids groups have more than 10 bids
requests = filteredHttpRequest.concat(Object.keys(groupedBidRequests).reduce((aggregate, bidGroupKey) => {
// for each partioned bidGroup, append a bidRequest to requests list
partitionArray(groupedBidRequests[bidGroupKey], SRA_BID_LIMIT).forEach(bidsInGroup => {
const combinedSlotParams = spec.combineSlotUrlParams(bidsInGroup.map(bidRequest => {
return spec.createSlotParams(bidRequest, bidderRequest);
}));
// SRA request returns grouped bidRequest arrays not a plain bidRequest
aggregate.push({
method: 'GET',
url: `https://${rubiConf.bannerHost || 'fastlane'}.rubiconproject.com/a/api/fastlane.json`,
data: spec.getOrderedParams(combinedSlotParams).reduce((paramString, key) => {
const propValue = combinedSlotParams[key];
return ((isStr(propValue) && propValue !== '') || isNumber(propValue)) ? `${paramString}${encodeParam(key, propValue)}&` : paramString;
}, '') + `slots=${bidsInGroup.length}&rand=${Math.random()}`,
bidRequest: bidsInGroup
});
});
return aggregate;
}, []));
}
return requests;
},
getOrderedParams: function(params) {
const containsTgV = /^tg_v/
const containsTgI = /^tg_i/
const containsUId = /^eid_|^tpid_/
const orderedParams = [
'account_id',
'site_id',
'zone_id',
'size_id',
'alt_size_ids',
'p_pos',
'gdpr',
'gdpr_consent',
'us_privacy',
'gpp',
'gpp_sid',
'rp_schain',
].concat(Object.keys(params).filter(item => containsUId.test(item)))
.concat([
'x_liverampidl',
'ppuid',
'rf',
'p_geo.latitude',
'p_geo.longitude',
'kw'
]).concat(Object.keys(params).filter(item => containsTgV.test(item)))
.concat(Object.keys(params).filter(item => containsTgI.test(item)))
.concat([
'tk_flint',
'x_source.tid',
'l_pb_bid_id',
'p_screen_res',
'o_ae',
'o_cdep',
'rp_floor',
'rp_secure',
'tk_user_key'
]);
return orderedParams.concat(Object.keys(params).filter(item => (orderedParams.indexOf(item) === -1)));
},
/**
* @summary combines param values from an array of slots into a single semicolon delineated value
* or just one value if they are all the same.
* @param {Object[]} aSlotUrlParams - example [{p1: 'foo', p2: 'test'}, {p2: 'test'}, {p1: 'bar', p2: 'test'}]
* @return {Object} - example {p1: 'foo;;bar', p2: 'test'}
*/
combineSlotUrlParams: function(aSlotUrlParams) {
// if only have params for one slot, return those params
if (aSlotUrlParams.length === 1) {
return aSlotUrlParams[0];
}
// reduce param values from all slot objects into an array of values in a single object
const oCombinedSlotUrlParams = aSlotUrlParams.reduce(function(oCombinedParams, oSlotUrlParams, iIndex) {
Object.keys(oSlotUrlParams).forEach(function(param) {
if (!oCombinedParams.hasOwnProperty(param)) {
oCombinedParams[param] = new Array(aSlotUrlParams.length); // initialize array;
}
// insert into the proper element of the array
oCombinedParams[param].splice(iIndex, 1, oSlotUrlParams[param]);
});
return oCombinedParams;
}, {});
// convert arrays into semicolon delimited strings
const re = new RegExp('^([^;]*)(;\\1)+$'); // regex to test for duplication
Object.keys(oCombinedSlotUrlParams).forEach(function(param) {
const sValues = oCombinedSlotUrlParams[param].join(';');
// consolidate param values into one value if they are all the same
const match = sValues.match(re);
oCombinedSlotUrlParams[param] = match ? match[1] : sValues;
});
return oCombinedSlotUrlParams;
},
/**
* @param {BidRequest} bidRequest
* @param {Object} bidderRequest
* @returns {Object} - object key values named and formatted as slot params
*/
createSlotParams: function(bidRequest, bidderRequest) {
bidRequest.startTime = new Date().getTime();
const params = bidRequest.params;
// use rubicon sizes if provided, otherwise adUnit.sizes
const parsedSizes = parseSizes(bidRequest, 'banner');
const [latitude, longitude] = params.latLong || [];
const data = {
'account_id': params.accountId,
'site_id': params.siteId,
'zone_id': params.zoneId,
'size_id': parsedSizes[0],
'alt_size_ids': parsedSizes.slice(1).join(',') || undefined,
'rp_floor': (params.floor = parseFloat(params.floor)) >= 0.01 ? params.floor : undefined,
'rp_secure': '1',
'tk_flint': `${rubiConf.int_type || DEFAULT_INTEGRATION}_v$prebid.version$`,
'x_source.tid': bidderRequest.ortb2?.source?.tid,
'x_imp.ext.tid': bidRequest.ortb2Imp?.ext?.tid,
'l_pb_bid_id': bidRequest.bidId,
'o_cdep': bidRequest.ortb2?.device?.ext?.cdep,
'ip': bidRequest.ortb2?.device?.ip,
'ipv6': bidRequest.ortb2?.device?.ipv6,
'p_screen_res': _getScreenResolution(),
'tk_user_key': params.userId,
'p_geo.latitude': isNaN(parseFloat(latitude)) ? undefined : parseFloat(latitude).toFixed(4),
'p_geo.longitude': isNaN(parseFloat(longitude)) ? undefined : parseFloat(longitude).toFixed(4),
'tg_fl.eid': bidRequest.code,
'rf': _getPageUrl(bidRequest, bidderRequest)
};
// If floors module is enabled and we get USD floor back, send it in rp_hard_floor else undfined
if (typeof bidRequest.getFloor === 'function' && !rubiConf.disableFloors) {
let floorInfo;
try {
floorInfo = bidRequest.getFloor({
currency: 'USD',
mediaType: 'banner',
size: '*'
});
} catch (e) {
logError('Rubicon: getFloor threw an error: ', e);
}
data['rp_hard_floor'] = isPlainObject(floorInfo) && floorInfo.currency === 'USD' && !isNaN(parseInt(floorInfo.floor)) ? floorInfo.floor : undefined;
}
// Send multiformat data if requested
if (params.bidonmultiformat === true && deepAccess(bidRequest, 'mediaTypes') && Object.keys(bidRequest.mediaTypes).length > 1) {
data['p_formats'] = Object.keys(bidRequest.mediaTypes).join(',');
}
// add p_pos only if specified and valid
// For SRA we need to explicitly put empty semi colons so AE treats it as empty, instead of copying the latter value
let posMapping = {1: 'atf', 3: 'btf'};
let pos = posMapping[deepAccess(bidRequest, 'mediaTypes.banner.pos')] || '';
data['p_pos'] = (params.position === 'atf' || params.position === 'btf') ? params.position : pos;
// pass publisher provided userId if configured
const configUserId = config.getConfig('user.id');
if (configUserId) {
data['ppuid'] = configUserId;
}
if (bidRequest?.ortb2Imp?.ext?.ae) {
data['o_ae'] = 1;
}
// If the bid request contains a 'mobile' property under 'ortb2.site', add it to 'data' as 'p_site.mobile'.
if (typeof bidRequest?.ortb2?.site?.mobile === 'number') {
data['p_site.mobile'] = bidRequest.ortb2.site.mobile
}
addDesiredSegtaxes(bidderRequest, data);
// loop through userIds and add to request
if (bidRequest?.ortb2?.user?.ext?.eids) {
bidRequest.ortb2.user.ext.eids.forEach(({ source, uids = [], inserter, matcher, mm, ext = {} }) => {
try {
// Ensure there is at least one valid UID in the 'uids' array
const uidData = uids[0];
if (!uidData) return; // Skip processing if no valid UID exists
// Function to build the EID value in the required format
const buildEidValue = (uidData) => [
uidData.id, // uid: The user ID
uidData.atype || '',
'', // third: Always empty, as specified in the requirement
inserter || '',
matcher || '',
mm || '',
uidData?.ext?.rtipartner || ''
].join('^'); // Return a single string formatted with '^' delimiter
const eidValue = buildEidValue(uidData); // Build the EID value string
// Store the constructed EID value for the given source
data[`eid_${source}`] = eidValue;
// Handle the "ppuid" signal, ensuring it is set only once
if (!data['ppuid']) {
// Search for a UID with the 'stype' field equal to 'ppuid' in its extension
const ppId = uids.find(uid => uid.ext?.stype === 'ppuid');
if (ppId?.id) {
data['ppuid'] = ppId.id; // Store the ppuid if found
}
}
} catch (e) {
// Log any errors encountered during processing
logWarn('Rubicon: error reading eid:', { source, uids }, e);
}
});
}
if (bidderRequest.gdprConsent) {
// add 'gdpr' only if 'gdprApplies' is defined
if (typeof bidderRequest.gdprConsent.gdprApplies === 'boolean') {
data['gdpr'] = Number(bidderRequest.gdprConsent.gdprApplies);
}
data['gdpr_consent'] = bidderRequest.gdprConsent.consentString;
}
if (bidderRequest.uspConsent) {
data['us_privacy'] = encodeURIComponent(bidderRequest.uspConsent);
}
if (bidderRequest.gppConsent?.gppString) {
data['gpp'] = bidderRequest.gppConsent.gppString;
data['gpp_sid'] = bidderRequest.gppConsent?.applicableSections?.toString();
}
data['rp_maxbids'] = bidderRequest.bidLimit || 1;
applyFPD(bidRequest, BANNER, data);
if (config.getConfig('coppa') === true) {
data['coppa'] = 1;
}
// if SupplyChain is supplied and contains all required fields
if (bidRequest.schain && hasValidSupplyChainParams(bidRequest.schain)) {
data.rp_schain = spec.serializeSupplyChain(bidRequest.schain);
}
return data;
},
/**
* Serializes schain params according to OpenRTB requirements
* @param {Object} supplyChain
* @returns {String}
*/
serializeSupplyChain: function (supplyChain) {
const supplyChainIsValid = hasValidSupplyChainParams(supplyChain);
if (!supplyChainIsValid) return '';
const { ver, complete, nodes } = supplyChain;
return `${ver},${complete}!${spec.serializeSupplyChainNodes(nodes)}`;
},
/**
* Properly sorts schain object params
* @param {Array} nodes
* @returns {String}
*/
serializeSupplyChainNodes: function (nodes) {
const nodePropOrder = ['asi', 'sid', 'hp', 'rid', 'name', 'domain'];
return nodes.map(node => {
return nodePropOrder.map(prop => encodeURIComponent(node[prop] || '')).join(',');
}).join('!');
},
/**
* @param {*} responseObj
* @param {BidRequest|Object.<string, BidRequest[]>} request - if request was SRA the bidRequest argument will be a keyed BidRequest array object,
* non-SRA responses return a plain BidRequest object
* @return {{fledgeAuctionConfigs: *, bids: *}} An array of bids which
*/
interpretResponse: function (responseObj, request) {
responseObj = responseObj.body;
const {data} = request;
// check overall response
if (!responseObj || typeof responseObj !== 'object') {
return [];
}
// Response from PBS Java openRTB
if (responseObj.seatbid) {
const responseErrors = deepAccess(responseObj, 'ext.errors.rubicon');
if (Array.isArray(responseErrors) && responseErrors.length > 0) {
logWarn('Rubicon: Error in video response');
}
const bids = converter.fromORTB({request: data, response: responseObj}).bids;
return bids;
}
let ads = responseObj.ads;
let lastImpId;
let multibid = 0;
const {bidRequest} = request;
// video ads array is wrapped in an object
if (typeof bidRequest === 'object' && !Array.isArray(bidRequest) && bidType(bidRequest).includes(VIDEO) && typeof ads === 'object') {
ads = ads[bidRequest.adUnitCode];
}
// check the ad response
if (!Array.isArray(ads) || ads.length < 1) {
return [];
}
let bids = ads.reduce((bids, ad, i) => {
(ad.impression_id && lastImpId === ad.impression_id) ? multibid++ : lastImpId = ad.impression_id;
if (ad.status !== 'ok') {
return bids;
}
// associate bidRequests; assuming ads matches bidRequest
const associatedBidRequest = Array.isArray(bidRequest) ? bidRequest[i - multibid] : bidRequest;
if (associatedBidRequest && typeof associatedBidRequest === 'object') {
let bid = {
requestId: associatedBidRequest.bidId,
currency: 'USD',
creativeId: ad.creative_id || `${ad.network || ''}-${ad.advertiser || ''}`,
cpm: ad.cpm || 0,
dealId: ad.deal,
ttl: 360, // 6 minutes
netRevenue: rubiConf.netRevenue !== false, // If anything other than false, netRev is true
rubicon: {
advertiserId: ad.advertiser, networkId: ad.network
},
meta: {
advertiserId: ad.advertiser, networkId: ad.network, mediaType: BANNER
}
};
if (ad.creative_type) {
bid.mediaType = ad.creative_type;
}
if (ad.dsa && Object.keys(ad.dsa).length) {
bid.meta.dsa = ad.dsa;
}
if (ad.adomain) {
bid.meta.advertiserDomains = Array.isArray(ad.adomain) ? ad.adomain : [ad.adomain];
}
if (ad.emulated_format) {
bid.meta.mediaType = ad.emulated_format;
}
if (ad.creative_type === VIDEO) {
bid.width = associatedBidRequest.params.video.playerWidth;
bid.height = associatedBidRequest.params.video.playerHeight;
bid.vastUrl = ad.creative_depot_url;
bid.impression_id = ad.impression_id;
bid.videoCacheKey = ad.impression_id;
} else {
bid.ad = _renderCreative(ad.script, ad.impression_id);
[bid.width, bid.height] = sizeMap[ad.size_id].split('x').map(num => Number(num));
}
// add server-side targeting
bid.rubiconTargeting = (Array.isArray(ad.targeting) ? ad.targeting : [])
.reduce((memo, item) => {
memo[item.key] = item.values[0];
return memo;
}, {'rpfl_elemid': associatedBidRequest.adUnitCode});
bids.push(bid);
} else {
logError(`Rubicon: bidRequest undefined at index position:${i}`, bidRequest, responseObj);
}
return bids;
}, []).sort((adA, adB) => {
return (adB.cpm || 0.0) - (adA.cpm || 0.0);
});
let fledgeAuctionConfigs = responseObj.component_auction_config?.map(config => {
return { config, bidId: config.bidId }
});
if (fledgeAuctionConfigs) {
return { bids, paapi: fledgeAuctionConfigs };
} else {
return bids;
}
},
getUserSyncs: function (syncOptions, responses, gdprConsent, uspConsent, gppConsent) {
if (!hasSynced && syncOptions.iframeEnabled) {
// data is only assigned if params are available to pass to syncEndpoint
let params = getUserSyncParams(gdprConsent, uspConsent, gppConsent);
params = Object.keys(params).length ? `?${formatQS(params)}` : '';
hasSynced = true;
return {
type: 'iframe',
url: `https://${rubiConf.syncHost || 'eus'}.rubiconproject.com/usync.html` + params
};
}
}
};
function _getScreenResolution() {
return [window.screen.width, window.screen.height].join('x');
}
/**
* @param {BidRequest} bidRequest
* @param bidderRequest
* @returns {string}
*/
function _getPageUrl(bidRequest, bidderRequest) {
let pageUrl;
if (bidRequest.params.referrer) {
pageUrl = bidRequest.params.referrer;
} else {
pageUrl = bidderRequest.refererInfo.page;
}
return bidRequest.params.secure ? pageUrl.replace(/^http:/i, 'https:') : pageUrl;
}
function _renderCreative(script, impId) {
return `<html>
<head><script type='text/javascript'>inDapIF=true;</script></head>
<body style='margin : 0; padding: 0;'>
<!-- Rubicon Project Ad Tag -->
<div data-rp-impression-id='${impId}'>
<script type='text/javascript'>${script}</script>
</div>
</body>
</html>`;
}
function hideGoogleAdsDiv(adUnit) {
const el = adUnit.querySelector("div[id^='google_ads']");
if (el) {
el.style.setProperty('display', 'none');
}
}
function hideSmartAdServerIframe(adUnit) {
const el = adUnit.querySelector("script[id^='sas_script']");
const nextSibling = el && el.nextSibling;
if (nextSibling && nextSibling.localName === 'iframe') {
nextSibling.style.setProperty('display', 'none');
}
}
function renderBid(bid) {
// hide existing ad units
const adUnitElement = document.getElementById(bid.adUnitCode);
hideGoogleAdsDiv(adUnitElement);
hideSmartAdServerIframe(adUnitElement);
// configure renderer
const defaultConfig = {
align: 'center',
position: 'append',
closeButton: false,
label: undefined,
collapse: true
};
const config = { ...defaultConfig, ...bid.renderer.getConfig() };
bid.renderer.push(() => {
window.MagniteApex.renderAd({
width: bid.width,
height: bid.height,
vastUrl: bid.vastUrl,
placement: {
attachTo: `#${bid.adUnitCode}`,
align: config.align,
position: config.position
},
closeButton: config.closeButton,
label: config.label,
collapse: config.collapse
});
});
}
function outstreamRenderer(rtbBid) {
const renderer = Renderer.install({
id: rtbBid.adId,
url: rubiConf.rendererUrl || DEFAULT_RENDERER_URL,
config: rubiConf.rendererConfig || {},
loaded: false,
adUnitCode: rtbBid.adUnitCode
});
try {
renderer.setRender(renderBid);
} catch (err) {
logWarn('Prebid Error calling setRender on renderer', err);
}
return renderer;
}
function parseSizes(bid, mediaType) {
let params = bid.params;
if (mediaType === VIDEO) {
let size = [];
if (params.video && params.video.playerWidth && params.video.playerHeight) {
size = [
params.video.playerWidth,
params.video.playerHeight
];
} else if (Array.isArray(deepAccess(bid, 'mediaTypes.video.playerSize')) && bid.mediaTypes.video.playerSize.length === 1) {
size = bid.mediaTypes.video.playerSize[0];
} else if (Array.isArray(bid.sizes) && bid.sizes.length > 0 && Array.isArray(bid.sizes[0]) && bid.sizes[0].length > 1) {
size = bid.sizes[0];
}
return size;
}
// deprecated: temp legacy support
let sizes = [];
if (Array.isArray(params.sizes)) {
sizes = params.sizes;
} else if (typeof deepAccess(bid, 'mediaTypes.banner.sizes') !== 'undefined') {
sizes = mapSizes(bid.mediaTypes.banner.sizes);
} else if (Array.isArray(bid.sizes) && bid.sizes.length > 0) {
sizes = mapSizes(bid.sizes);
} else {
logWarn('Rubicon: no sizes are setup or found');
}
return masSizeOrdering(sizes);
}
function applyFPD(bidRequest, mediaType, data) {
const BID_FPD = {
user: {ext: {data: {...bidRequest.params.visitor}}},
site: {ext: {data: {...bidRequest.params.inventory}}}
};
if (bidRequest.params.keywords) BID_FPD.site.keywords = (isArray(bidRequest.params.keywords)) ? bidRequest.params.keywords.join(',') : bidRequest.params.keywords;
let fpd = mergeDeep({}, bidRequest.ortb2 || {}, BID_FPD);
let impExt = deepAccess(bidRequest.ortb2Imp, 'ext') || {};
let impExtData = deepAccess(bidRequest.ortb2Imp, 'ext.data') || {};
const gpid = deepAccess(bidRequest, 'ortb2Imp.ext.gpid');
const dsa = deepAccess(fpd, 'regs.ext.dsa');
const SEGTAX = {user: [4], site: [1, 2, 5, 6]};
const MAP = {user: 'tg_v.', site: 'tg_i.', adserver: 'tg_i.dfp_ad_unit_code', pbadslot: 'tg_i.pbadslot', keywords: 'kw'};
const validate = function(prop, key, parentName) {
if (key === 'data' && Array.isArray(prop)) {
return prop.filter(name => name.segment && deepAccess(name, 'ext.segtax') && SEGTAX[parentName] &&
SEGTAX[parentName].indexOf(deepAccess(name, 'ext.segtax')) !== -1).map(value => {
let segments = value.segment.filter(obj => obj.id).reduce((result, obj) => {
result.push(obj.id);
return result;
}, []);
if (segments.length > 0) return segments.toString();
}).toString();
} else if (typeof prop === 'object' && !Array.isArray(prop)) {
return undefined;
} else if (typeof prop !== 'undefined') {
return (Array.isArray(prop)) ? prop.filter(value => {
if (typeof value !== 'object' && typeof value !== 'undefined') return value.toString();
logWarn('Rubicon: Filtered value: ', value, 'for key', key, ': Expected value to be string, integer, or an array of strings/ints');
}).toString() : prop.toString();
}
};
const addBannerData = function(obj, name, key, isParent = true) {
let val = validate(obj, key, name);
let loc = (MAP[key] && isParent) ? `${MAP[key]}` : (key === 'data') ? `${MAP[name]}iab` : `${MAP[name]}${key}`;
data[loc] = (data[loc]) ? data[loc].concat(',', val) : val;
};
if (mediaType === BANNER) {
['site', 'user'].forEach(name => {
Object.keys(fpd[name]).forEach((key) => {
if (name === 'site' && key === 'content' && fpd[name][key].data) {
addBannerData(fpd[name][key].data, name, 'data');
} else if (key !== 'ext') {
addBannerData(fpd[name][key], name, key);
} else if (fpd[name][key].data) {
Object.keys(fpd[name].ext.data).forEach((key) => {
addBannerData(fpd[name].ext.data[key], name, key, false);
});
}
});
});
Object.keys(impExtData).forEach((key) => {
if (key !== 'adserver') {
addBannerData(impExtData[key], 'site', key);
} else if (impExtData[key].name === 'gam') {
addBannerData(impExtData[key].adslot, name, key)
}
});
// add in gpid
if (gpid) {
data['p_gpid'] = gpid;
}
// add dsa signals
if (dsa && Object.keys(dsa).length) {
pick(dsa, [
'dsainfo', (dsainfo) => data['dsainfo'] = dsainfo,
'dsarequired', (required) => data['dsarequired'] = required,
'pubrender', (pubrender) => data['dsapubrender'] = pubrender,
'datatopub', (datatopub) => data['dsadatatopubs'] = datatopub,
'transparency', (transparency) => {
if (Array.isArray(transparency) && transparency.length) {
data['dsatransparency'] = transparency.reduce((param, transp) => {
// make sure domain is there, otherwise skip entry
const domain = transp.domain || '';
if (!domain) {
return param;
}
// make sure dsaParam array is there (try both 'dsaparams' and 'params', but prefer dsaparams)
const dsaParamArray = transp.dsaparams || transp.params;
if (!Array.isArray(dsaParamArray) || dsaParamArray.length === 0) {
return param;
}