Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

PBjs Core : clean up utils.js #10441

Merged
merged 24 commits into from
Sep 21, 2023
Merged
Show file tree
Hide file tree
Changes from 23 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {_each, deepAccess, getValueString, isArray, isStr, mergeDeep, isNumber} from '../../src/utils.js';
import {_each, deepAccess, isArray, isNumber, isStr, mergeDeep, logWarn} from '../../src/utils.js';
import {getAllOrtbKeywords} from '../keywords/keywords.js';
import {CLIENT_SECTIONS} from '../../src/fpd/oneClient.js';

Expand All @@ -12,6 +12,19 @@ const ORTB_SEG_PATHS = ['user.data'].concat(
CLIENT_SECTIONS.map((prefix) => `${prefix}.content.data`)
);

function getValueString(param, val, defaultValue) {
if (val === undefined || val === null) {
return defaultValue;
}
if (isStr(val)) {
return val;
}
if (isNumber(val)) {
return val.toString();
}
logWarn('Unsuported type for param: ' + param + ' required type: String');
}

/**
* Converts an object of arrays (either strings or numbers) into an array of objects containing key and value properties
* normally read from bidder params
Expand Down
25 changes: 25 additions & 0 deletions libraries/appnexusUtils/anUtils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/**
* Converts a string value in camel-case to underscore eg 'placementId' becomes 'placement_id'
* @param {string} value string value to convert
*/
import {deepClone, isPlainObject} from '../../src/utils.js';

export function convertCamelToUnderscore(value) {
return value.replace(/(?:^|\.?)([A-Z])/g, function (x, y) {
return '_' + y.toLowerCase();
}).replace(/^_/, '');
}

/**
* Creates an array of n length and fills each item with the given value
*/
export function fill(value, length) {
let newArray = [];

for (let i = 0; i < length; i++) {
let valueToPush = isPlainObject(value) ? deepClone(value) : value;
newArray.push(valueToPush);
}

return newArray;
}
19 changes: 19 additions & 0 deletions libraries/chunk/chunk.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
/**
* http://npm.im/chunk
* Returns an array with *size* chunks from given array
*
* Example:
* ['a', 'b', 'c', 'd', 'e'] chunked by 2 =>
* [['a', 'b'], ['c', 'd'], ['e']]
*/
export function chunk(array, size) {
let newArray = [];

for (let i = 0; i < Math.ceil(array.length / size); i++) {
let start = i * size;
let end = start + size;
newArray.push(array.slice(start, end));
}

return newArray;
}
37 changes: 37 additions & 0 deletions libraries/gptUtils/gptUtils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import {find} from '../../src/polyfill.js';
import {compareCodeAndSlot, isGptPubadsDefined} from '../../src/utils.js';

/**
* Returns filter function to match adUnitCode in slot
* @param {string} adUnitCode AdUnit code
* @return {function} filter function
*/
export function isSlotMatchingAdUnitCode(adUnitCode) {
return (slot) => compareCodeAndSlot(slot, adUnitCode);
}

/**
* @summary Uses the adUnit's code in order to find a matching gpt slot object on the page
*/
export function getGptSlotForAdUnitCode(adUnitCode) {
let matchingSlot;
if (isGptPubadsDefined()) {
// find the first matching gpt slot on the page
matchingSlot = find(window.googletag.pubads().getSlots(), isSlotMatchingAdUnitCode(adUnitCode));
}
return matchingSlot;
}

/**
* @summary Uses the adUnit's code in order to find a matching gptSlot on the page
*/
export function getGptSlotInfoForAdUnitCode(adUnitCode) {
const matchingSlot = getGptSlotForAdUnitCode(adUnitCode);
if (matchingSlot) {
return {
gptSlot: matchingSlot.getAdUnitPath(),
divId: matchingSlot.getSlotElementId()
};
}
return {};
}
26 changes: 26 additions & 0 deletions libraries/htmlEscape/htmlEscape.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/**
* Encode a string for inclusion in HTML.
* See https://pragmaticwebsecurity.com/articles/spasecurity/json-stringify-xss.html and
* https://codeql.github.com/codeql-query-help/javascript/js-bad-code-sanitization/
* @return {string}
*/
export const escapeUnsafeChars = (() => {
const escapes = {
'<': '\\u003C',
'>': '\\u003E',
'/': '\\u002F',
'\\': '\\\\',
'\b': '\\b',
'\f': '\\f',
'\n': '\\n',
'\r': '\\r',
'\t': '\\t',
'\0': '\\0',
'\u2028': '\\u2028',
'\u2029': '\\u2029'
};

return function (str) {
return str.replace(/[<>\b\f\n\r\t\0\u2028\u2029\\]/g, x => escapes[x]);
};
})();
29 changes: 29 additions & 0 deletions libraries/sizeUtils/sizeUtils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/**
* Read an adUnit object and return the sizes used in an [[728, 90]] format (even if they had [728, 90] defined)
* Preference is given to the `adUnit.mediaTypes.banner.sizes` object over the `adUnit.sizes`
* @param {object} adUnit one adUnit object from the normal list of adUnits
* @returns {Array.<number[]>} array of arrays containing numeric sizes
*/
export function getAdUnitSizes(adUnit) {
if (!adUnit) {
return;
}

let sizes = [];
if (adUnit.mediaTypes && adUnit.mediaTypes.banner && Array.isArray(adUnit.mediaTypes.banner.sizes)) {
let bannerSizes = adUnit.mediaTypes.banner.sizes;
if (Array.isArray(bannerSizes[0])) {
sizes = bannerSizes;
} else {
sizes.push(bannerSizes);
}
// TODO - remove this else block when we're ready to deprecate adUnit.sizes for bidders
} else if (Array.isArray(adUnit.sizes)) {
if (Array.isArray(adUnit.sizes[0])) {
sizes = adUnit.sizes;
} else {
sizes.push(adUnit.sizes);
}
}
return sizes;
}
36 changes: 36 additions & 0 deletions libraries/transformParamsUtils/convertTypes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import {isFn} from '../../src/utils.js';

/**
* Try to convert a value to a type.
* If it can't be done, the value will be returned.
*
* @param {string} typeToConvert The target type. e.g. "string", "number", etc.
* @param {*} value The value to be converted into typeToConvert.
*/
function tryConvertType(typeToConvert, value) {
if (typeToConvert === 'string') {
return value && value.toString();
} else if (typeToConvert === 'number') {
return Number(value);
} else {
return value;
}
}

export function convertTypes(types, params) {
Object.keys(types).forEach(key => {
if (params[key]) {
if (isFn(types[key])) {
params[key] = types[key](params[key]);
} else {
params[key] = tryConvertType(types[key], params[key]);
}

// don't send invalid values
if (isNaN(params[key])) {
delete params.key;
}
}
});
return params;
}
7 changes: 7 additions & 0 deletions libraries/urlUtils/urlUtils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export function tryAppendQueryString(existingUrl, key, value) {
if (value) {
return existingUrl + key + '=' + encodeURIComponent(value) + '&';
}

return existingUrl;
}
2 changes: 1 addition & 1 deletion modules/33acrossBidAdapter.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,14 @@ import {
getWindowTop,
isArray,
isGptPubadsDefined,
isSlotMatchingAdUnitCode,
logInfo,
logWarn,
mergeDeep,
pick,
uniques
} from '../src/utils.js';
import {BANNER, VIDEO} from '../src/mediaTypes.js';
import {isSlotMatchingAdUnitCode} from '../libraries/gptUtils/gptUtils.js';

// **************************** UTILS *************************** //
const BIDDER_CODE = '33across';
Expand Down
2 changes: 1 addition & 1 deletion modules/adWMGBidAdapter.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
'use strict';

import { tryAppendQueryString } from '../src/utils.js';
import { registerBidder } from '../src/adapters/bidderFactory.js';
import { config } from '../src/config.js';
import { BANNER } from '../src/mediaTypes.js';
import {tryAppendQueryString} from '../libraries/urlUtils/urlUtils.js';

const BIDDER_CODE = 'adWMG';
const ENDPOINT = 'https://hb.adwmg.com/hb';
Expand Down
2 changes: 1 addition & 1 deletion modules/adagioBidAdapter.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import {
deepClone,
generateUUID,
getDNT,
getGptSlotInfoForAdUnitCode,
getUniqueIdentifierStr,
getWindowSelf,
getWindowTop,
Expand Down Expand Up @@ -34,6 +33,7 @@ import {OUTSTREAM} from '../src/video.js';
import { getGlobal } from '../src/prebidGlobal.js';
import { convertOrtbRequestToProprietaryNative } from '../src/native.js';
import { userSync } from '../src/userSync.js';
import {getGptSlotInfoForAdUnitCode} from '../libraries/gptUtils/gptUtils.js';

const BIDDER_CODE = 'adagio';
const LOG_PREFIX = 'Adagio:';
Expand Down
4 changes: 3 additions & 1 deletion modules/adgenerationBidAdapter.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import {tryAppendQueryString, getBidIdParameter, escapeUnsafeChars, deepAccess} from '../src/utils.js';
import {deepAccess, getBidIdParameter} from '../src/utils.js';
import {registerBidder} from '../src/adapters/bidderFactory.js';
import {BANNER, NATIVE} from '../src/mediaTypes.js';
import {config} from '../src/config.js';
import {convertOrtbRequestToProprietaryNative} from '../src/native.js';
import {tryAppendQueryString} from '../libraries/urlUtils/urlUtils.js';
import {escapeUnsafeChars} from '../libraries/htmlEscape/htmlEscape.js';

const ADG_BIDDER_CODE = 'adgeneration';

Expand Down
2 changes: 1 addition & 1 deletion modules/adkernelBidAdapter.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import {
createTrackPixelHtml,
deepAccess,
deepSetValue,
getAdUnitSizes,
getDefinedParams,
getDNT,
isArray,
Expand All @@ -22,6 +21,7 @@ import {registerBidder} from '../src/adapters/bidderFactory.js';
import {find} from '../src/polyfill.js';
import {config} from '../src/config.js';
import {convertOrtbRequestToProprietaryNative} from '../src/native.js';
import {getAdUnitSizes} from '../libraries/sizeUtils/sizeUtils.js';

/*
* In case you're AdKernel whitelable platform's client who needs branded adapter to
Expand Down
2 changes: 1 addition & 1 deletion modules/adlooxAnalyticsAdapter.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import {find} from '../src/polyfill.js';
import {getRefererInfo} from '../src/refererDetection.js';
import {
deepAccess,
getGptSlotInfoForAdUnitCode,
getUniqueIdentifierStr,
insertElement,
isFn,
Expand All @@ -28,6 +27,7 @@ import {
mergeDeep,
parseUrl
} from '../src/utils.js';
import {getGptSlotInfoForAdUnitCode} from '../libraries/gptUtils/gptUtils.js';

const MODULE = 'adlooxAnalyticsAdapter';

Expand Down
2 changes: 1 addition & 1 deletion modules/adlooxRtdProvider.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ import {
deepAccess,
deepClone,
deepSetValue,
getGptSlotInfoForAdUnitCode,
isArray,
isBoolean,
isInteger,
Expand All @@ -37,6 +36,7 @@ import {
parseUrl,
safeJSONParse
} from '../src/utils.js';
import {getGptSlotInfoForAdUnitCode} from '../libraries/gptUtils/gptUtils.js';

const MODULE_NAME = 'adloox';
const MODULE = `${MODULE_NAME}RtdProvider`;
Expand Down
2 changes: 1 addition & 1 deletion modules/admaticBidAdapter.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { getValue, logError, isEmpty, deepAccess, getBidIdParameter, isArray } from '../src/utils.js';
import {getValue, logError, isEmpty, deepAccess, isArray, getBidIdParameter} from '../src/utils.js';
import { registerBidder } from '../src/adapters/bidderFactory.js';
import { config } from '../src/config.js';
import { BANNER, VIDEO } from '../src/mediaTypes.js';
Expand Down
18 changes: 17 additions & 1 deletion modules/adpod.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
*/

import {
compareOn,
deepAccess,
generateUUID,
groupBy,
Expand Down Expand Up @@ -595,6 +594,23 @@ function getAdPodAdUnits(codes) {
.filter((adUnit) => (codes.length > 0) ? codes.indexOf(adUnit.code) != -1 : true);
}

/**
* This function will create compare function to sort on object property
* @param {string} property
* @returns {function} compare function to be used in sorting
*/
function compareOn(property) {
return function compare(a, b) {
if (a[property] < b[property]) {
return 1;
}
if (a[property] > b[property]) {
return -1;
}
return 0;
}
}

/**
* This function removes bids of same category. It will be used when competitive exclusion is enabled.
* @param {Array[Object]} bidsReceived
Expand Down
8 changes: 4 additions & 4 deletions modules/adrelevantisBidAdapter.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
import {Renderer} from '../src/Renderer.js';
import {
chunk,
convertCamelToUnderscore,
convertTypes,
createTrackPixelHtml,
deepAccess,
deepClone,
Expand All @@ -21,7 +18,10 @@ import {BANNER, NATIVE, VIDEO} from '../src/mediaTypes.js';
import {find, includes} from '../src/polyfill.js';
import {INSTREAM, OUTSTREAM} from '../src/video.js';
import { convertOrtbRequestToProprietaryNative } from '../src/native.js';
import {getANKeywordParam, transformBidderParamKeywords} from '../libraries/appnexusKeywords/anKeywords.js';
import {getANKeywordParam, transformBidderParamKeywords} from '../libraries/appnexusUtils/anKeywords.js';
import {convertCamelToUnderscore} from '../libraries/appnexusUtils/anUtils.js';
import {convertTypes} from '../libraries/transformParamsUtils/convertTypes.js';
import {chunk} from '../libraries/chunk/chunk.js';

const BIDDER_CODE = 'adrelevantis';
const URL = 'https://ssp.adrelevantis.com/prebid';
Expand Down
2 changes: 1 addition & 1 deletion modules/adriverBidAdapter.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// ADRIVER BID ADAPTER for Prebid 1.13
import { logInfo, getWindowLocation, getBidIdParameter, _each } from '../src/utils.js';
import {logInfo, getWindowLocation, _each, getBidIdParameter} from '../src/utils.js';
import { registerBidder } from '../src/adapters/bidderFactory.js';
import { getStorageManager } from '../src/storageManager.js';

Expand Down
3 changes: 2 additions & 1 deletion modules/adtargetBidAdapter.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import {_map, chunk, deepAccess, flatten, isArray, logError, parseSizesInput} from '../src/utils.js';
import {_map, deepAccess, flatten, isArray, logError, parseSizesInput} from '../src/utils.js';
import {registerBidder} from '../src/adapters/bidderFactory.js';
import {BANNER, VIDEO} from '../src/mediaTypes.js';
import {config} from '../src/config.js';
import {find} from '../src/polyfill.js';
import {chunk} from '../libraries/chunk/chunk.js';

const ENDPOINT = 'https://ghb.console.adtarget.com.tr/v2/auction/';
const BIDDER_CODE = 'adtarget';
Expand Down
Loading