-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
index.js
389 lines (352 loc) · 9.95 KB
/
index.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
/**
* This module adds Real time data support to prebid.js
* @module modules/realTimeData
*/
/**
* @interface UserConsentData
*/
/**
* @property
* @summary gdpr consent
* @name UserConsentData#gdpr
* @type {Object}
*/
/**
* @property
* @summary usp consent
* @name UserConsentData#usp
* @type {Object}
*/
/**
* @property
* @summary coppa
* @name UserConsentData#coppa
* @type {boolean}
*/
/**
* @interface RtdSubmodule
*/
/**
* @function?
* @summary return real time data
* @name RtdSubmodule#getTargetingData
* @param {string[]} adUnitsCodes
* @param {SubmoduleConfig} config
* @param {UserConsentData} userConsent
* @param {auction} auction
*/
/**
* @function?
* @summary modify bid request data
* @name RtdSubmodule#getBidRequestData
* @param {Object} reqBidsConfigObj
* @param {function} callback
* @param {SubmoduleConfig} config
* @param {UserConsentData} userConsent
*/
/**
* @property
* @summary used to link submodule with config
* @name RtdSubmodule#name
* @type {string}
*/
/**
* @property
* @summary used to link submodule with config
* @name RtdSubmodule#config
* @type {Object}
*/
/**
* @function
* @summary init sub module
* @name RtdSubmodule#init
* @param {SubmoduleConfig} config
* @param {UserConsentData} user consent
* @return {boolean} false to remove sub module
*/
/**
* @function?
* @summary on auction init event
* @name RtdSubmodule#onAuctionInitEvent
* @param {Object} data
* @param {SubmoduleConfig} config
* @param {UserConsentData} userConsent
*/
/**
* @function?
* @summary on auction end event
* @name RtdSubmodule#onAuctionEndEvent
* @param {Object} data
* @param {SubmoduleConfig} config
* @param {UserConsentData} userConsent
*/
/**
* @function?
* @summary on bid response event
* @name RtdSubmodule#onBidResponseEvent
* @param {Object} data
* @param {SubmoduleConfig} config
* @param {UserConsentData} userConsent
*/
/**
* @function?
* @summary on bid requested event
* @name RtdSubmodule#onBidRequestEvent
* @param {Object} data
* @param {SubmoduleConfig} config
* @param {UserConsentData} userConsent
*/
/**
* @interface ModuleConfig
*/
/**
* @property
* @summary auction delay
* @name ModuleConfig#auctionDelay
* @type {number}
*/
/**
* @property
* @summary list of sub modules
* @name ModuleConfig#dataProviders
* @type {SubmoduleConfig[]}
*/
/**
* @interface SubModuleConfig
*/
/**
* @property
* @summary params for provide (sub module)
* @name SubModuleConfig#params
* @type {Object}
*/
/**
* @property
* @summary name
* @name ModuleConfig#name
* @type {string}
*/
/**
* @property
* @summary delay auction for this sub module
* @name ModuleConfig#waitForIt
* @type {boolean}
*/
import {config} from '../../src/config.js';
import {getHook, module} from '../../src/hook.js';
import {logError, logInfo, logWarn} from '../../src/utils.js';
import * as events from '../../src/events.js';
import CONSTANTS from '../../src/constants.json';
import {gdprDataHandler, uspDataHandler} from '../../src/adapterManager.js';
import {find} from '../../src/polyfill.js';
/** @type {string} */
const MODULE_NAME = 'realTimeData';
/** @type {RtdSubmodule[]} */
let registeredSubModules = [];
/** @type {RtdSubmodule[]} */
export let subModules = [];
/** @type {ModuleConfig} */
let _moduleConfig;
/** @type {SubmoduleConfig[]} */
let _dataProviders = [];
/** @type {UserConsentData} */
let _userConsent;
/**
* Register a RTD submodule.
*
* @param {RtdSubmodule} submodule
* @returns {function()} a de-registration function that will unregister the module when called.
*/
export function attachRealTimeDataProvider(submodule) {
registeredSubModules.push(submodule);
return function detach() {
const idx = registeredSubModules.indexOf(submodule)
if (idx >= 0) {
registeredSubModules.splice(idx, 1);
initSubModules();
}
}
}
/**
* call each sub module event function by config order
*/
const setEventsListeners = (function () {
let registered = false;
return function setEventsListeners() {
if (!registered) {
Object.entries({
[CONSTANTS.EVENTS.AUCTION_INIT]: ['onAuctionInitEvent'],
[CONSTANTS.EVENTS.AUCTION_END]: ['onAuctionEndEvent', getAdUnitTargeting],
[CONSTANTS.EVENTS.BID_RESPONSE]: ['onBidResponseEvent'],
[CONSTANTS.EVENTS.BID_REQUESTED]: ['onBidRequestEvent']
}).forEach(([ev, [handler, preprocess]]) => {
events.on(ev, (args) => {
preprocess && preprocess(args);
subModules.forEach(sm => {
try {
sm[handler] && sm[handler](args, sm.config, _userConsent)
} catch (e) {
logError(`RTD provider '${sm.name}': error in '${handler}':`, e);
}
});
})
});
registered = true;
}
}
})();
export function init(config) {
const confListener = config.getConfig(MODULE_NAME, ({realTimeData}) => {
if (!realTimeData.dataProviders) {
logError('missing parameters for real time module');
return;
}
confListener(); // unsubscribe config listener
_moduleConfig = realTimeData;
_dataProviders = realTimeData.dataProviders;
setEventsListeners();
getHook('startAuction').before(setBidRequestsData, 20); // RTD should run before FPD
initSubModules();
});
}
function getConsentData() {
return {
gdpr: gdprDataHandler.getConsentData(),
usp: uspDataHandler.getConsentData(),
coppa: !!(config.getConfig('coppa'))
}
}
/**
* call each sub module init function by config order
* if no init function / init return failure / module not configured - remove it from submodules list
*/
function initSubModules() {
_userConsent = getConsentData();
let subModulesByOrder = [];
_dataProviders.forEach(provider => {
const sm = find(registeredSubModules, s => s.name === provider.name);
const initResponse = sm && sm.init && sm.init(provider, _userConsent);
if (initResponse) {
subModulesByOrder.push(Object.assign(sm, {config: provider}));
}
});
subModules = subModulesByOrder;
logInfo(`Real time data module enabled, using submodules: ${subModules.map((m) => m.name).join(', ')}`);
}
/**
* loop through configured data providers If the data provider has registered getBidRequestData,
* call it, providing reqBidsConfigObj, consent data and module params
* this allows submodules to modify bidders
* @param {Object} reqBidsConfigObj required; This is the same param that's used in pbjs.requestBids.
* @param {function} fn required; The next function in the chain, used by hook.js
*/
export function setBidRequestsData(fn, reqBidsConfigObj) {
_userConsent = getConsentData();
const relevantSubModules = [];
const prioritySubModules = [];
subModules.forEach(sm => {
if (typeof sm.getBidRequestData !== 'function') {
return;
}
relevantSubModules.push(sm);
const config = sm.config;
if (config && config.waitForIt) {
prioritySubModules.push(sm);
}
});
const shouldDelayAuction = prioritySubModules.length && _moduleConfig.auctionDelay && _moduleConfig.auctionDelay > 0;
let callbacksExpected = prioritySubModules.length;
let isDone = false;
let waitTimeout;
if (!relevantSubModules.length) {
return exitHook();
}
waitTimeout = setTimeout(exitHook, shouldDelayAuction ? _moduleConfig.auctionDelay : 0);
relevantSubModules.forEach(sm => {
sm.getBidRequestData(reqBidsConfigObj, onGetBidRequestDataCallback.bind(sm), sm.config, _userConsent)
});
function onGetBidRequestDataCallback() {
if (isDone) {
return;
}
if (this.config && this.config.waitForIt) {
callbacksExpected--;
}
if (callbacksExpected === 0) {
setTimeout(exitHook, 0);
}
}
function exitHook() {
if (isDone) {
return;
}
isDone = true;
clearTimeout(waitTimeout);
fn.call(this, reqBidsConfigObj);
}
}
/**
* loop through configured data providers If the data provider has registered getTargetingData,
* call it, providing ad unit codes, consent data and module params
* the sub mlodle will return data to set on the ad unit
* this function used to place key values on primary ad server per ad unit
* @param {Object} auction object received on auction end event
*/
export function getAdUnitTargeting(auction) {
const relevantSubModules = subModules.filter(sm => typeof sm.getTargetingData === 'function');
if (!relevantSubModules.length) {
return;
}
// get data
const adUnitCodes = auction.adUnitCodes;
if (!adUnitCodes) {
return;
}
let targeting = [];
for (let i = relevantSubModules.length - 1; i >= 0; i--) {
const smTargeting = relevantSubModules[i].getTargetingData(adUnitCodes, relevantSubModules[i].config, _userConsent, auction);
if (smTargeting && typeof smTargeting === 'object') {
targeting.push(smTargeting);
} else {
logWarn('invalid getTargetingData response for sub module', relevantSubModules[i].name);
}
}
// place data on auction adUnits
const mergedTargeting = deepMerge(targeting);
auction.adUnits.forEach(adUnit => {
const kv = adUnit.code && mergedTargeting[adUnit.code];
if (!kv) {
return
}
logInfo('RTD set ad unit targeting of', kv, 'for', adUnit);
adUnit[CONSTANTS.JSON_MAPPING.ADSERVER_TARGETING] = Object.assign(adUnit[CONSTANTS.JSON_MAPPING.ADSERVER_TARGETING] || {}, kv);
});
return auction.adUnits;
}
/**
* deep merge array of objects
* @param {array} arr - objects array
* @return {Object} merged object
*/
export function deepMerge(arr) {
if (!Array.isArray(arr) || !arr.length) {
return {};
}
return arr.reduce((merged, obj) => {
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
if (!merged.hasOwnProperty(key)) merged[key] = obj[key];
else {
// duplicate key - merge values
const dp = obj[key];
for (let dk in dp) {
if (dp.hasOwnProperty(dk)) merged[key][dk] = dp[dk];
}
}
}
}
return merged;
}, {});
}
module('realTimeData', attachRealTimeDataProvider);
init(config);