• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

prebid / Prebid.js / 22632526804

03 Mar 2026 04:27PM UTC coverage: 96.232% (-0.09%) from 96.325%
22632526804

Pull #14545

github

8385ad
mfitzgerald_dmd
Remove dmd userId module test coverage
Pull Request #14545: Module: Remove dmd userid module

55020 of 67421 branches covered (81.61%)

210402 of 218641 relevant lines covered (96.23%)

71.79 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

81.88
/modules/datablocksBidAdapter.js
1
import {getDevicePixelRatio} from '../libraries/devicePixelRatio/devicePixelRatio.js';
1✔
2
import {deepAccess, getWinDimensions, getWindowTop, isGptPubadsDefined} from '../src/utils.js';
3
import {registerBidder} from '../src/adapters/bidderFactory.js';
4
import {config} from '../src/config.js';
5
import {BANNER, NATIVE} from '../src/mediaTypes.js';
6
import {getStorageManager} from '../src/storageManager.js';
7
import {ajax} from '../src/ajax.js';
8
import {convertOrtbRequestToProprietaryNative} from '../src/native.js';
9
import {getAdUnitSizes} from '../libraries/sizeUtils/sizeUtils.js';
10
import {isWebdriverEnabled} from '../libraries/webdriver/webdriver.js';
11
import { buildNativeRequest, parseNativeResponse } from '../libraries/nativeAssetsUtils.js';
12

13
export const storage = getStorageManager({bidderCode: 'datablocks'});
1✔
14

15
// DEFINE THE PREBID BIDDER SPEC
16
export const spec = {
1✔
17
  supportedMediaTypes: [BANNER, NATIVE],
18
  code: 'datablocks',
19

20
  // DATABLOCKS SCOPED OBJECT
21
  db_obj: {metrics_host: 'prebid.dblks.net', metrics: [], metrics_timer: null, metrics_queue_time: 1000, vis_optout: false, source_id: 0},
22

23
  // STORE THE DATABLOCKS BUYERID IN STORAGE
24
  store_dbid: function(dbid) {
25
    let stored = false;
2✔
26

27
    // CREATE 1 YEAR EXPIRY DATE
28
    const d = new Date();
2✔
29
    d.setTime(Date.now() + (365 * 24 * 60 * 60 * 1000));
2✔
30

31
    // TRY TO STORE IN COOKIE
32
    if (storage.cookiesAreEnabled) {
2✔
33
      storage.setCookie('_db_dbid', dbid, d.toUTCString(), 'None', null);
2✔
34
      stored = true;
2✔
35
    }
36

37
    // TRY TO STORE IN LOCAL STORAGE
38
    if (storage.localStorageIsEnabled) {
2✔
39
      storage.setDataInLocalStorage('_db_dbid', dbid);
2✔
40
      stored = true;
2✔
41
    }
42

43
    return stored;
2✔
44
  },
45

46
  // FETCH DATABLOCKS BUYERID FROM STORAGE
47
  get_dbid: function() {
48
    let dbId = '';
3✔
49
    if (storage.cookiesAreEnabled) {
3✔
50
      dbId = storage.getCookie('_db_dbid') || '';
3✔
51
    }
52

53
    if (!dbId && storage.localStorageIsEnabled) {
3✔
54
      dbId = storage.getDataFromLocalStorage('_db_dbid') || '';
3✔
55
    }
56
    return dbId;
3✔
57
  },
58

59
  // STORE SYNCS IN STORAGE
60
  store_syncs: function(syncs) {
61
    if (storage.localStorageIsEnabled) {
1✔
62
      const syncObj = {};
1✔
63
      syncs.forEach(sync => {
1✔
64
        syncObj[sync.id] = sync.uid;
1✔
65
      });
66

67
      // FETCH EXISTING SYNCS AND MERGE NEW INTO STORAGE
68
      const storedSyncs = this.get_syncs();
1✔
69
      storage.setDataInLocalStorage('_db_syncs', JSON.stringify(Object.assign(storedSyncs, syncObj)));
1✔
70

71
      return true;
1✔
72
    }
73
  },
74

75
  // GET SYNCS FROM STORAGE
76
  get_syncs: function() {
77
    if (storage.localStorageIsEnabled) {
3!
78
      const syncData = storage.getDataFromLocalStorage('_db_syncs');
3✔
79
      if (syncData) {
3!
80
        return JSON.parse(syncData);
×
81
      } else {
82
        return {};
3✔
83
      }
84
    } else {
85
      return {};
×
86
    }
87
  },
88

89
  // ADD METRIC DATA TO THE METRICS RESPONSE QUEUE
90
  queue_metric: function(metric) {
91
    if (typeof metric === 'object') {
×
92
      // PUT METRICS IN THE QUEUE
93
      this.db_obj.metrics.push(metric);
×
94

95
      // RESET PREVIOUS TIMER
96
      if (this.db_obj.metrics_timer) {
×
97
        clearTimeout(this.db_obj.metrics_timer);
×
98
      }
99

100
      // SETUP THE TIMER TO FIRE BACK THE DATA
101
      const scope = this;
×
102
      this.db_obj.metrics_timer = setTimeout(function() {
×
103
        scope.send_metrics();
×
104
      }, this.db_obj.metrics_queue_time);
105

106
      return true;
×
107
    } else {
108
      return false;
×
109
    }
110
  },
111

112
  // POST CONSOLIDATED METRICS BACK TO SERVER
113
  send_metrics: function() {
114
    // POST TO SERVER
115
    ajax(`https://${this.db_obj.metrics_host}/a/pb/`, null, JSON.stringify(this.db_obj.metrics), {method: 'POST', withCredentials: true});
×
116

117
    // RESET THE QUEUE OF METRIC DATA
118
    this.db_obj.metrics = [];
×
119

120
    return true;
×
121
  },
122

123
  // GET BASIC CLIENT INFORMATION
124
  get_client_info: function () {
125
    const botTest = new BotClientTests();
2✔
126
    const win = getWindowTop();
2✔
127
    const windowDimensions = getWinDimensions();
2✔
128
    return {
2✔
129
      'wiw': windowDimensions.innerWidth,
130
      'wih': windowDimensions.innerHeight,
131
      'saw': null,
132
      'sah': null,
133
      'scd': null,
134
      'sw': windowDimensions.screen.width,
135
      'sh': windowDimensions.screen.height,
136
      'whl': win.history.length,
137
      'wxo': win.pageXOffset,
138
      'wyo': win.pageYOffset,
139
      'wpr': getDevicePixelRatio(win),
140
      'is_bot': botTest.doTests(),
141
      'is_hid': win.document.hidden,
142
      'vs': win.document.visibilityState
143
    };
144
  },
145

146
  // LISTEN FOR GPT VIEWABILITY EVENTS
147
  get_viewability: function(bid) {
148
    // ONLY RUN ONCE IF PUBLISHER HAS OPTED IN
149
    if (!this.db_obj.vis_optout && !this.db_obj.vis_run) {
2✔
150
      this.db_obj.vis_run = true;
1✔
151

152
      // ADD GPT EVENT LISTENERS
153
      const scope = this;
1✔
154
      if (isGptPubadsDefined()) {
1✔
155
        if (typeof window['googletag'].pubads().addEventListener === 'function') {
1✔
156
          // TODO: fix auctionId leak: https://github.com/prebid/Prebid.js/issues/9781
157
          window['googletag'].pubads().addEventListener('impressionViewable', function(event) {
1✔
158
            scope.queue_metric({type: 'slot_view', source_id: scope.db_obj.source_id, auction_id: bid.auctionId, div_id: event.slot.getSlotElementId(), slot_id: event.slot.getSlotId().getAdUnitPath()});
×
159
          });
160
          window['googletag'].pubads().addEventListener('slotRenderEnded', function(event) {
1✔
161
            scope.queue_metric({type: 'slot_render', source_id: scope.db_obj.source_id, auction_id: bid.auctionId, div_id: event.slot.getSlotElementId(), slot_id: event.slot.getSlotId().getAdUnitPath()});
×
162
          })
163
        }
164
      }
165
    }
166
  },
167

168
  // VALIDATE THE BID REQUEST
169
  isBidRequestValid: function(bid) {
170
    // SET GLOBAL VARS FROM BIDDER CONFIG
171
    this.db_obj.source_id = bid.params.source_id;
3✔
172
    if (bid.params.vis_optout) {
3✔
173
      this.db_obj.vis_optout = true;
1✔
174
    }
175

176
    return !!(bid.params.source_id && bid.mediaTypes && (bid.mediaTypes.banner || bid.mediaTypes.native));
3!
177
  },
178

179
  // GENERATE THE RTB REQUEST
180
  buildRequests: function(validRequests, bidderRequest) {
181
    // convert Native ORTB definition to old-style prebid native definition
182
    validRequests = convertOrtbRequestToProprietaryNative(validRequests);
2✔
183

184
    // RETURN EMPTY IF THERE ARE NO VALID REQUESTS
185
    if (!validRequests.length) {
2✔
186
      return [];
1✔
187
    }
188

189
    const imps = [];
1✔
190
    // ITERATE THE VALID REQUESTS AND GENERATE IMP OBJECT
191
    validRequests.forEach(bidRequest => {
1✔
192
      // BUILD THE IMP OBJECT
193
      const imp = {
3✔
194
        id: bidRequest.bidId,
195
        tagid: bidRequest.params.tagid || bidRequest.adUnitCode,
6✔
196
        placement_id: bidRequest.params.placement_id || 0,
6✔
197
        secure: window.location.protocol === 'https:',
198
        ortb2: deepAccess(bidRequest, `ortb2Imp`) || {},
6✔
199
        floor: {}
200
      }
201

202
      // CHECK FOR FLOORS
203
      if (typeof bidRequest.getFloor === 'function') {
3!
204
        imp.floor = bidRequest.getFloor({
×
205
          currency: 'USD',
206
          mediaType: '*',
207
          size: '*'
208
        });
209
      }
210

211
      // BUILD THE SIZES
212
      if (deepAccess(bidRequest, `mediaTypes.banner`)) {
3✔
213
        const sizes = getAdUnitSizes(bidRequest);
2✔
214
        if (sizes.length) {
2✔
215
          imp.banner = {
2✔
216
            w: sizes[0][0],
217
            h: sizes[0][1],
218
            format: sizes.map(size => ({ w: size[0], h: size[1] }))
2✔
219
          };
220

221
          // ADD TO THE LIST OF IMP REQUESTS
222
          imps.push(imp);
2✔
223
        }
224
      } else if (deepAccess(bidRequest, `mediaTypes.native`)) {
1✔
225
        // ADD TO THE LIST OF IMP REQUESTS
226
        imp.native = buildNativeRequest(bidRequest.nativeParams);
1✔
227
        imps.push(imp);
1✔
228
      }
229
    });
230

231
    // RETURN EMPTY IF THERE WERE NO PROPER ADUNIT REQUESTS TO BE MADE
232
    if (!imps.length) {
1!
233
      return [];
×
234
    }
235

236
    // GENERATE SITE OBJECT
237
    const site = {
1✔
238
      domain: window.location.host,
239
      // TODO: is 'page' the right value here?
240
      page: bidderRequest.refererInfo.page,
241
      schain: validRequests[0]?.ortb2?.source?.ext?.schain || {},
7!
242
      ext: {
243
        p_domain: bidderRequest.refererInfo.domain,
244
        rt: bidderRequest.refererInfo.reachedTop,
245
        frames: bidderRequest.refererInfo.numIframes,
246
        stack: bidderRequest.refererInfo.stack,
247
        timeout: config.getConfig('bidderTimeout')
248
      },
249
    };
250

251
    // ADD REF URL IF FOUND
252
    if (self === top && document.referrer) {
1!
253
      site.ref = document.referrer;
×
254
    }
255

256
    // ADD META KEYWORDS IF FOUND
257
    const keywords = document.getElementsByTagName('meta')['keywords'];
1✔
258
    if (keywords && keywords.content) {
1!
259
      site.keywords = keywords.content;
×
260
    }
261

262
    // GENERATE DEVICE OBJECT
263
    const device = {
1✔
264
      ip: 'peer',
265
      ua: window.navigator.userAgent,
266
      js: 1,
267
      language: ((navigator.language || navigator.userLanguage || '').split('-'))[0] || 'en',
2!
268
      buyerid: this.get_dbid() || 0,
2✔
269
      ext: {
270
        pb_eids: validRequests[0].userIdAsEids || {},
2✔
271
        syncs: this.get_syncs() || {},
1!
272
        coppa: config.getConfig('coppa') || 0,
2✔
273
        gdpr: bidderRequest.gdprConsent || {},
2✔
274
        usp: bidderRequest.uspConsent || {},
2✔
275
        client_info: this.get_client_info(),
276
        ortb2: bidderRequest.ortb2 || {}
2✔
277
      }
278
    };
279

280
    const sourceId = validRequests[0].params.source_id || 0;
1!
281
    const host = validRequests[0].params.host || 'prebid.dblks.net';
1!
282

283
    // RETURN WITH THE REQUEST AND PAYLOAD
284
    return {
1✔
285
      method: 'POST',
286
      url: `https://${host}/openrtb/?sid=${sourceId}`,
287
      data: {
288
        id: bidderRequest.bidderRequestId,
289
        imp: imps,
290
        site: site,
291
        device: device
292
      },
293
      options: {
294
        withCredentials: true
295
      }
296
    };
297
  },
298

299
  // INITIATE USER SYNCING
300
  getUserSyncs: function(options, rtbResponse, gdprConsent) {
301
    const syncs = [];
1✔
302
    const bidResponse = rtbResponse?.[0]?.body ?? null;
1!
303
    const scope = this;
1✔
304

305
    // LISTEN FOR SYNC DATA FROM IFRAME TYPE SYNC
306
    window.addEventListener('message', function (event) {
1✔
307
      if (event.data.sentinel && event.data.sentinel === 'dblks_syncData') {
×
308
        // STORE FOUND SYNCS
309
        if (event.data.syncs) {
×
310
          scope.store_syncs(event.data.syncs);
×
311
        }
312
      }
313
    });
314

315
    // POPULATE GDPR INFORMATION
316
    const gdprData = {
1✔
317
      gdpr: 0,
318
      gdprConsent: ''
319
    }
320
    if (typeof gdprConsent === 'object') {
1✔
321
      if (typeof gdprConsent.gdprApplies === 'boolean') {
1!
322
        gdprData.gdpr = Number(gdprConsent.gdprApplies);
1✔
323
        gdprData.gdprConsent = gdprConsent.consentString;
1✔
324
      } else {
325
        gdprData.gdprConsent = gdprConsent.consentString;
×
326
      }
327
    }
328

329
    // EXTRACT BUYERID COOKIE VALUE FROM BID RESPONSE AND PUT INTO STORAGE
330
    let dbBuyerId = this.get_dbid() || '';
1✔
331
    if (bidResponse.ext && bidResponse.ext.buyerid) {
1✔
332
      dbBuyerId = bidResponse.ext.buyerid;
1✔
333
      this.store_dbid(dbBuyerId);
1✔
334
    }
335

336
    // EXTRACT USERSYNCS FROM BID RESPONSE
337
    if (bidResponse.ext && bidResponse.ext.syncs) {
1✔
338
      bidResponse.ext.syncs.forEach(sync => {
1✔
339
        if (checkValid(sync)) {
2✔
340
          syncs.push(addParams(sync));
2✔
341
        }
342
      })
343
    }
344

345
    // APPEND PARAMS TO SYNC URL
346
    function addParams(sync) {
347
      // PARSE THE URL
348
      try {
2✔
349
        const url = new URL(sync.url);
2✔
350
        const urlParams = {};
2✔
351
        for (const [key, value] of url.searchParams.entries()) {
2✔
352
          urlParams[key] = value;
×
353
        };
354

355
        // APPLY EXTRA VARS
356
        urlParams.gdpr = gdprData.gdpr;
2✔
357
        urlParams.gdprConsent = gdprData.gdprConsent;
2✔
358
        urlParams.bidid = bidResponse.bidid;
2✔
359
        urlParams.id = bidResponse.id;
2✔
360
        urlParams.uid = dbBuyerId;
2✔
361

362
        // REBUILD URL
363
        sync.url = `${url.origin}${url.pathname}?${Object.keys(urlParams).map(key => key + '=' + encodeURIComponent(urlParams[key])).join('&')}`;
10✔
364
      } catch (e) {};
365

366
      // RETURN THE REBUILT URL
367
      return sync;
2✔
368
    }
369

370
    // ENSURE THAT THE SYNC TYPE IS VALID AND HAS PERMISSION
371
    function checkValid(sync) {
372
      if (!sync.type || !sync.url) {
2!
373
        return false;
×
374
      }
375
      switch (sync.type) {
2!
376
        case 'iframe':
377
          return options.iframeEnabled;
1✔
378
        case 'image':
379
          return options.pixelEnabled;
1✔
380
        default:
381
          return false;
×
382
      }
383
    }
384
    return syncs;
1✔
385
  },
386

387
  // DATABLOCKS WON THE AUCTION - REPORT SUCCESS
388
  onBidWon: function(bid) {
389
    this.queue_metric({type: 'bid_won', source_id: bid.params[0].source_id, req_id: bid.requestId, slot_id: bid.adUnitCode, auction_id: bid.auctionId, size: bid.size, cpm: bid.cpm, pb: bid.adserverTargeting.hb_pb, rt: bid.timeToRespond, ttl: bid.ttl});
1✔
390
  },
391

392
  // TARGETING HAS BEEN SET
393
  onSetTargeting: function(bid) {
394
    // LISTEN FOR VIEWABILITY EVENTS
395
    this.get_viewability(bid);
1✔
396
  },
397

398
  // PARSE THE RTB RESPONSE AND RETURN FINAL RESULTS
399
  interpretResponse: function(rtbResponse, bidRequest) {
400
    const bids = [];
1✔
401
    const resBids = deepAccess(rtbResponse, 'body.seatbid') || [];
1!
402
    resBids.forEach(bid => {
1✔
403
      const resultItem = {requestId: bid.id, cpm: bid.price, creativeId: bid.crid, currency: bid.currency || 'USD', netRevenue: true, ttl: bid.ttl || 360, meta: {advertiserDomains: bid.adomain}};
3✔
404

405
      const mediaType = deepAccess(bid, 'ext.mtype') || '';
3!
406
      switch (mediaType) {
3!
407
        case 'banner':
408
          bids.push(Object.assign({}, resultItem, {mediaType: BANNER, width: bid.w, height: bid.h, ad: bid.adm}));
2✔
409
          break;
2✔
410

411
        case 'native':
412
          const nativeResult = JSON.parse(bid.adm);
1✔
413
          bids.push(Object.assign({}, resultItem, {mediaType: NATIVE, native: parseNativeResponse(nativeResult.native)}));
1✔
414
          break;
1✔
415

416
        default:
417
          break;
×
418
      }
419
    })
420

421
    return bids;
1✔
422
  }
423
};
424

425
// DETECT BOTS
426
export class BotClientTests {
427
  constructor() {
428
    this.tests = {
3✔
429
      headless_chrome: function() {
430
        // Warning: accessing navigator.webdriver may impact fingerprinting scores when this API is included in the built script.
431
        return isWebdriverEnabled();
3✔
432
      },
433

434
      selenium: function () {
435
        let response = false;
3✔
436

437
        if (window && document) {
3✔
438
          const results = [
3✔
439
            'webdriver' in window,
440
            '_Selenium_IDE_Recorder' in window,
441
            'callSelenium' in window,
442
            '_selenium' in window,
443
            '__webdriver_script_fn' in document,
444
            '__driver_evaluate' in document,
445
            '__webdriver_evaluate' in document,
446
            '__selenium_evaluate' in document,
447
            '__fxdriver_evaluate' in document,
448
            '__driver_unwrapped' in document,
449
            '__webdriver_unwrapped' in document,
450
            '__selenium_unwrapped' in document,
451
            '__fxdriver_unwrapped' in document,
452
            '__webdriver_script_func' in document,
453
            document.documentElement.getAttribute('selenium') !== null,
454
            document.documentElement.getAttribute('webdriver') !== null,
455
            document.documentElement.getAttribute('driver') !== null
456
          ];
457

458
          results.forEach(result => {
3✔
459
            if (result === true) {
51!
460
              response = true;
×
461
            }
462
          })
463
        }
464

465
        return response;
3✔
466
      },
467
    }
468
  }
469
  doTests() {
470
    let response = false;
3✔
471
    for (const i of Object.keys(this.tests)) {
3✔
472
      if (this.tests[i]() === true) {
6✔
473
        response = true;
3✔
474
      }
475
    }
476
    return response;
3✔
477
  }
478
}
479

480
// INIT OUR BIDDER WITH PREBID
481
registerBidder(spec);
1✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc