-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
Copy pathpermutiveRtdProvider.js
359 lines (312 loc) · 11.3 KB
/
permutiveRtdProvider.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
/**
* This module adds permutive provider to the real time data module
* The {@link module:modules/realTimeData} module is required
* The module will add custom segment targeting to ad units of specific bidders
* @module modules/permutiveRtdProvider
* @requires module:modules/realTimeData
*/
import {getGlobal} from '../src/prebidGlobal.js';
import {submodule} from '../src/hook.js';
import {getStorageManager} from '../src/storageManager.js';
import {deepAccess, deepSetValue, isFn, logError, mergeDeep, isPlainObject, safeJSONParse} from '../src/utils.js';
import {includes} from '../src/polyfill.js';
const MODULE_NAME = 'permutive'
export const PERMUTIVE_SUBMODULE_CONFIG_KEY = 'permutive-prebid-rtd'
export const storage = getStorageManager({gvlid: null, moduleName: MODULE_NAME})
function init(moduleConfig, userConsent) {
readPermutiveModuleConfigFromCache()
return true
}
/**
* Set segment targeting from cache and then try to wait for Permutive
* to initialise to get realtime segment targeting
* @param {Object} reqBidsConfigObj
* @param {function} callback - Called when submodule is done
* @param {customModuleConfig} reqBidsConfigObj - Publisher config for module
*/
export function initSegments (reqBidsConfigObj, callback, customModuleConfig) {
const permutiveOnPage = isPermutiveOnPage()
const moduleConfig = getModuleConfig(customModuleConfig)
const segmentData = getSegments(moduleConfig.params.maxSegs)
setSegments(reqBidsConfigObj, moduleConfig, segmentData)
if (moduleConfig.waitForIt && permutiveOnPage) {
window.permutive.ready(function () {
setSegments(reqBidsConfigObj, moduleConfig, segmentData)
callback()
}, 'realtime')
} else {
callback()
}
}
function liftIntoParams(params) {
return isPlainObject(params) ? { params } : {}
}
let cachedPermutiveModuleConfig = {}
/**
* Access the submodules RTD params that are cached to LocalStorage by the Permutive SDK. This lets the RTD submodule
* apply publisher defined params set in the Permutive platform, so they may still be applied if the Permutive SDK has
* not initialised before this submodule is initialised.
*/
function readPermutiveModuleConfigFromCache() {
const params = safeJSONParse(storage.getDataFromLocalStorage(PERMUTIVE_SUBMODULE_CONFIG_KEY))
return cachedPermutiveModuleConfig = liftIntoParams(params)
}
/**
* Access the submodules RTD params attached to the Permutive SDK.
*
* @return The Permutive config available by the Permutive SDK or null if the operation errors.
*/
function getParamsFromPermutive() {
try {
return liftIntoParams(window.permutive.addons.prebid.getPermutiveRtdConfig())
} catch (e) {
return null
}
}
/**
* Merges segments into existing bidder config in reverse priority order. The highest priority is 1.
*
* 1. customModuleConfig <- set by publisher with pbjs.setConfig
* 2. permutiveRtdConfig <- set by the publisher using the Permutive platform
* 3. defaultConfig
*
* As items with a higher priority will be deeply merged into the previous config, deep merges are performed by
* reversing the priority order.
*
* @param {Object} customModuleConfig - Publisher config for module
* @return {Object} Deep merges of the default, Permutive and custom config.
*/
export function getModuleConfig(customModuleConfig) {
// Use the params from Permutive if available, otherwise fallback to the cached value set by Permutive.
const permutiveModuleConfig = getParamsFromPermutive() || cachedPermutiveModuleConfig
return mergeDeep({
waitForIt: false,
params: {
maxSegs: 500,
acBidders: [],
overwrites: {},
},
},
permutiveModuleConfig,
customModuleConfig,
)
}
/**
* Sets ortb2 config for ac bidders
* @param {Object} bidderOrtb2
* @param {Object} customModuleConfig - Publisher config for module
*/
export function setBidderRtb (bidderOrtb2, customModuleConfig) {
const moduleConfig = getModuleConfig(customModuleConfig)
const acBidders = deepAccess(moduleConfig, 'params.acBidders')
const maxSegs = deepAccess(moduleConfig, 'params.maxSegs')
const transformationConfigs = deepAccess(moduleConfig, 'params.transformations') || []
const segmentData = getSegments(maxSegs)
acBidders.forEach(function (bidder) {
const currConfig = { ortb2: bidderOrtb2[bidder] || {} }
const nextConfig = updateOrtbConfig(currConfig, segmentData.ac, transformationConfigs) // ORTB2 uses the `ac` segment IDs
bidderOrtb2[bidder] = nextConfig.ortb2;
})
}
/**
* Updates `user.data` object in existing bidder config with Permutive segments
* @param {Object} currConfig - Current bidder config
* @param {Object[]} transformationConfigs - array of objects with `id` and `config` properties, used to determine
* the transformations on user data to include the ORTB2 object
* @param {string[]} segmentIDs - Permutive segment IDs
* @return {Object} Merged ortb2 object
*/
function updateOrtbConfig (currConfig, segmentIDs, transformationConfigs) {
const name = 'permutive.com'
const permutiveUserData = {
name,
segment: segmentIDs.map(segmentId => ({ id: segmentId })),
}
const transformedUserData = transformationConfigs
.filter(({ id }) => ortb2UserDataTransformations.hasOwnProperty(id))
.map(({ id, config }) => ortb2UserDataTransformations[id](permutiveUserData, config))
const ortbConfig = mergeDeep({}, currConfig)
const currentUserData = deepAccess(ortbConfig, 'ortb2.user.data') || []
const updatedUserData = currentUserData
.filter(el => el.name !== name)
.concat(permutiveUserData, transformedUserData)
deepSetValue(ortbConfig, 'ortb2.user.data', updatedUserData)
return ortbConfig
}
/**
* Set segments on bid request object
* @param {Object} reqBidsConfigObj - Bid request object
* @param {Object} moduleConfig - Module configuration
* @param {Object} segmentData - Segment object
*/
function setSegments (reqBidsConfigObj, moduleConfig, segmentData) {
const adUnits = (reqBidsConfigObj && reqBidsConfigObj.adUnits) || getGlobal().adUnits
const utils = { deepSetValue, deepAccess, isFn, mergeDeep }
const aliasMap = {
appnexusAst: 'appnexus'
}
if (!adUnits) {
return
}
adUnits.forEach(adUnit => {
adUnit.bids.forEach(bid => {
let { bidder } = bid
if (typeof aliasMap[bidder] !== 'undefined') {
bidder = aliasMap[bidder]
}
const acEnabled = isAcEnabled(moduleConfig, bidder)
const customFn = getCustomBidderFn(moduleConfig, bidder)
const defaultFn = getDefaultBidderFn(bidder)
if (customFn) {
customFn(bid, segmentData, acEnabled, utils, defaultFn)
} else if (defaultFn) {
defaultFn(bid, segmentData, acEnabled)
}
})
})
}
/**
* Catch and log errors
* @param {function} fn - Function to safely evaluate
*/
function makeSafe (fn) {
try {
fn()
} catch (e) {
logError(e)
}
}
function getCustomBidderFn (moduleConfig, bidder) {
const overwriteFn = deepAccess(moduleConfig, `params.overwrites.${bidder}`)
if (overwriteFn && isFn(overwriteFn)) {
return overwriteFn
} else {
return null
}
}
/**
* Returns a function that receives a `bid` object, a `data` object and a `acEnabled` boolean
* and which will set the right segment targeting keys for `bid` based on `data` and `acEnabled`
* @param {string} bidder - Bidder name
* @return {Object} Bidder function
*/
function getDefaultBidderFn (bidder) {
const bidderMap = {
appnexus: function (bid, data, acEnabled) {
if (acEnabled && data.ac && data.ac.length) {
deepSetValue(bid, 'params.keywords.p_standard', data.ac)
}
if (data.appnexus && data.appnexus.length) {
deepSetValue(bid, 'params.keywords.permutive', data.appnexus)
}
return bid
},
rubicon: function (bid, data, acEnabled) {
if (acEnabled && data.ac && data.ac.length) {
deepSetValue(bid, 'params.visitor.p_standard', data.ac)
}
if (data.rubicon && data.rubicon.length) {
deepSetValue(bid, 'params.visitor.permutive', data.rubicon)
}
return bid
},
ozone: function (bid, data, acEnabled) {
if (acEnabled && data.ac && data.ac.length) {
deepSetValue(bid, 'params.customData.0.targeting.p_standard', data.ac)
}
return bid
}
}
return bidderMap[bidder]
}
/**
* Check whether ac is enabled for bidder
* @param {Object} moduleConfig - Module configuration
* @param {string} bidder - Bidder name
* @return {boolean}
*/
export function isAcEnabled (moduleConfig, bidder) {
const acBidders = deepAccess(moduleConfig, 'params.acBidders') || []
return includes(acBidders, bidder)
}
/**
* Check whether Permutive is on page
* @return {boolean}
*/
export function isPermutiveOnPage () {
return typeof window.permutive !== 'undefined' && typeof window.permutive.ready === 'function'
}
/**
* Get all relevant segment IDs in an object
* @param {number} maxSegs - Maximum number of segments to be included
* @return {Object}
*/
export function getSegments (maxSegs) {
const legacySegs = readSegments('_psegs').map(Number).filter(seg => seg >= 1000000).map(String)
const _ppam = readSegments('_ppam')
const _pcrprs = readSegments('_pcrprs')
const segments = {
ac: [..._pcrprs, ..._ppam, ...legacySegs],
rubicon: readSegments('_prubicons'),
appnexus: readSegments('_papns'),
gam: readSegments('_pdfps'),
}
for (const bidder in segments) {
segments[bidder] = segments[bidder].slice(0, maxSegs)
}
return segments
}
/**
* Gets an array of segment IDs from LocalStorage
* or returns an empty array
* @param {string} key
* @return {string[]|number[]}
*/
function readSegments (key) {
try {
return JSON.parse(storage.getDataFromLocalStorage(key) || '[]')
} catch (e) {
return []
}
}
const unknownIabSegmentId = '_unknown_'
/**
* Functions to apply to ORT2B2 `user.data` objects.
* Each function should return an a new object containing a `name`, (optional) `ext` and `segment`
* properties. The result of the each transformation defined here will be appended to the array
* under `user.data` in the bid request.
*/
const ortb2UserDataTransformations = {
iab: (userData, config) => ({
name: userData.name,
ext: { segtax: config.segtax },
segment: (userData.segment || [])
.map(segment => ({ id: iabSegmentId(segment.id, config.iabIds) }))
.filter(segment => segment.id !== unknownIabSegmentId)
})
}
/**
* Transform a Permutive segment ID into an IAB audience taxonomy ID.
* @param {string} permutiveSegmentId
* @param {Object} iabIds object of mappings between Permutive and IAB segment IDs (key: permutive ID, value: IAB ID)
* @return {string} IAB audience taxonomy ID associated with the Permutive segment ID
*/
function iabSegmentId(permutiveSegmentId, iabIds) {
return iabIds[permutiveSegmentId] || unknownIabSegmentId
}
/** @type {RtdSubmodule} */
export const permutiveSubmodule = {
name: MODULE_NAME,
getBidRequestData: function (reqBidsConfigObj, callback, customModuleConfig) {
makeSafe(function () {
// Legacy route with custom parameters
initSegments(reqBidsConfigObj, callback, customModuleConfig)
});
makeSafe(function () {
// Route for bidders supporting ORTB2
setBidderRtb(reqBidsConfigObj.ortb2Fragments?.bidder, customModuleConfig)
})
},
init: init
}
submodule('realTimeData', permutiveSubmodule)