<commit_before>import Adapter from 'src/adapters/adapter';
import bidfactory from 'src/bidfactory';
import bidmanager from 'src/bidmanager';
import * as utils from 'src/utils';
import { ajax } from 'src/ajax';
import { STATUS } from 'src/constants';

const ENDPOINT = '//ib.adnxs.com/ut/v2/prebid';
const VIDEO_TARGETING = ['id', 'mimes', 'minduration', 'maxduration',
  'startdelay', 'skippable', 'playback_method', 'frameworks'];
const USER_PARAMS = [
  'age', 'external_uid', 'segments', 'gender', 'dnt', 'language'
];

/**
 * Bidder adapter for /ut endpoint. Given the list of all ad unit tag IDs,
 * sends out a bid request. When a bid response is back, registers the bid
 * to Prebid.js. This adapter supports alias bidding.
 */
function AppnexusAstAdapter() {

  let baseAdapter = Adapter.createNew('appnexusAst');
  let bidRequests = {};
  let usersync = false;

  /* Prebid executes this function when the page asks to send out bid requests */
  baseAdapter.callBids = function(bidRequest) {
    const bids = bidRequest.bids || [];
    const tags = bids
      .filter(bid => valid(bid))
      .map(bid => {
        // map request id to bid object to retrieve adUnit code in callback
        bidRequests[bid.bidId] = bid;

        let tag = {};
        tag.sizes = getSizes(bid.sizes);
        tag.primary_size = tag.sizes[0];
        tag.uuid = bid.bidId;
        tag.id = parseInt(bid.params.placementId, 10);
        tag.allow_smaller_sizes = bid.params.allowSmallerSizes || false;
        tag.prebid = true;
        tag.disable_psa = true;
        if (!utils.isEmpty(bid.params.keywords)) {
          tag.keywords = getKeywords(bid.params.keywords);
        }

        if (bid.mediaType === 'video') {tag.require_asset_url = true;}
        if (bid.params.video) {
          tag.video = {};
          // place any valid video params on the tag
          Object.keys(bid.params.video)
            .filter(param => VIDEO_TARGETING.includes(param))
            .forEach(param => tag.video[param] = bid.params.video[param]);
        }

        if (bid.params.user) {
          tag.user = {};
          Object.keys(bid.params.user)
            .filter(param => USER_PARAMS.includes(param))
            .forEach(param => tag.user[param] = bid.params.user[param]);
        }

        return tag;
      });

    if (!utils.isEmpty(tags)) {
      const payload = JSON.stringify({tags: [...tags]});
      ajax(ENDPOINT, handleResponse, payload, {
        contentType: 'text/plain',
        withCredentials : true
      });
    }
  };

  /* Notify Prebid of bid responses so bids can get in the auction */
  function handleResponse(response) {
    let parsed;

    try {
      parsed = JSON.parse(response);
    } catch (error) {
      utils.logError(error);
    }

    if (!parsed || parsed.error) {
      let errorMessage = `in response for ${baseAdapter.getBidderCode()} adapter`;
      if (parsed && parsed.error) {errorMessage += `: ${parsed.error}`;}
      utils.logError(errorMessage);

      // signal this response is complete
      Object.keys(bidRequests)
        .map(bidId => bidRequests[bidId].placementCode)
        .forEach(placementCode => {
          bidmanager.addBidResponse(placementCode, createBid(STATUS.NO_BID));
        });
      return;
    }

    parsed.tags.forEach(tag => {
      const ad = getRtbBid(tag);
      const cpm = ad && ad.cpm;
      const type = ad && ad.ad_type;

      let status;
      if (cpm !== 0 && (type === 'banner' || type === 'video')) {
        status = STATUS.GOOD;
      } else {
        status = STATUS.NO_BID;
      }

      if (type && (type !== 'banner' && type !== 'video')) {
        utils.logError(`${type} ad type not supported`);
      }

      tag.bidId = tag.uuid;  // bidfactory looks for bidId on requested bid
      const bid = createBid(status, tag);
      if (type === 'video') bid.mediaType = 'video';
      const placement = bidRequests[bid.adId].placementCode;
      bidmanager.addBidResponse(placement, bid);
    });

    if (!usersync) {
      const iframe = utils.createInvisibleIframe();
      iframe.src = '//acdn.adnxs.com/ib/static/usersync/v3/async_usersync.html';
      try {
        document.body.appendChild(iframe);
      } catch (error) {
        utils.logError(error);
      }
      usersync = true;
    }
  }

  /* Check that a bid has required paramters */
  function valid(bid) {
    if (bid.params.placementId || bid.params.memberId && bid.params.invCode) {
      return bid;
    } else {
      utils.logError('bid requires placementId or (memberId and invCode) params');
    }
  }

  /* Turn keywords parameter into ut-compatible format */
  function getKeywords(keywords) {
    let arrs = [];<commit_msg>Adding support for all AST parameters (#923)<commit_after>import Adapter from 'src/adapters/adapter';
import bidfactory from 'src/bidfactory';
import bidmanager from 'src/bidmanager';
import * as utils from 'src/utils';
import { ajax } from 'src/ajax';
import { STATUS } from 'src/constants';

const ENDPOINT = '//ib.adnxs.com/ut/v2/prebid';
const VIDEO_TARGETING = ['id', 'mimes', 'minduration', 'maxduration',
  'startdelay', 'skippable', 'playback_method', 'frameworks'];
const USER_PARAMS = [
  'age', 'external_uid', 'segments', 'gender', 'dnt', 'language'
];

/**
 * Bidder adapter for /ut endpoint. Given the list of all ad unit tag IDs,
 * sends out a bid request. When a bid response is back, registers the bid
 * to Prebid.js. This adapter supports alias bidding.
 */
function AppnexusAstAdapter() {

  let baseAdapter = Adapter.createNew('appnexusAst');
  let bidRequests = {};
  let usersync = false;

  /* Prebid executes this function when the page asks to send out bid requests */
  baseAdapter.callBids = function(bidRequest) {
    const bids = bidRequest.bids || [];
    var member = 0;
    const tags = bids
      .filter(bid => valid(bid))
      .map(bid => {
        // map request id to bid object to retrieve adUnit code in callback
        bidRequests[bid.bidId] = bid;

        let tag = {};
        tag.sizes = getSizes(bid.sizes);
        tag.primary_size = tag.sizes[0];
        tag.uuid = bid.bidId;
        if(bid.params.placementId) {
          tag.id = parseInt(bid.params.placementId, 10);
        } else { 
          tag.code = bid.params.invCode;
        }
        tag.allow_smaller_sizes = bid.params.allowSmallerSizes || false;
        tag.prebid = true;
        tag.disable_psa = true;
        member = parseInt(bid.params.member, 10);
        if (bid.params.reserve) {
          tag.reserve = bid.params.reserve;
        }
        if (bid.params.position) {
          tag.position = {'above': 1, 'below': 2}[bid.params.position] || 0;
        }
        if (bid.params.trafficSourceCode) {
          tag.traffic_source_code = bid.params.trafficSourceCode;
        }
        if (bid.params.privateSizes) {
          tag.private_sizes = getSizes(bid.params.privateSizes);
        }
        if (bid.params.supplyType) {
          tag.supply_type = bid.params.supplyType;
        }
        if (bid.params.pubClick) {
          tag.pubclick = bid.params.pubClick;
        }
        if (bid.params.extInvCode) {
          tag.ext_inv_code = bid.params.extInvCode;
        }
        if (bid.params.externalImpId) {
          tag.external_imp_id = bid.params.externalImpId;
        }
        if (!utils.isEmpty(bid.params.keywords)) {
          tag.keywords = getKeywords(bid.params.keywords);
        }

        if (bid.mediaType === 'video') {tag.require_asset_url = true;}
        if (bid.params.video) {
          tag.video = {};
          // place any valid video params on the tag
          Object.keys(bid.params.video)
            .filter(param => VIDEO_TARGETING.includes(param))
            .forEach(param => tag.video[param] = bid.params.video[param]);
        }

        if (bid.params.user) {
          tag.user = {};
          Object.keys(bid.params.user)
            .filter(param => USER_PARAMS.includes(param))
            .forEach(param => tag.user[param] = bid.params.user[param]);
        }

        return tag;
      });

    if (!utils.isEmpty(tags)) {
      const payloadJson = {tags: [...tags]};
      if (member > 0) {
        payloadJson.member_id = member;
      }
      const payload = JSON.stringify(payloadJson);
      ajax(ENDPOINT, handleResponse, payload, {
        contentType: 'text/plain',
        withCredentials : true
      });
    }
  };

  /* Notify Prebid of bid responses so bids can get in the auction */
  function handleResponse(response) {
    let parsed;

    try {
      parsed = JSON.parse(response);
    } catch (error) {
      utils.logError(error);
    }

    if (!parsed || parsed.error) {
      let errorMessage = `in response for ${baseAdapter.getBidderCode()} adapter`;
      if (parsed && parsed.error) {errorMessage += `: ${parsed.error}`;}
      utils.logError(errorMessage);

      // signal this response is complete
      Object.keys(bidRequests)
        .map(bidId => bidRequests[bidId].placementCode)
        .forEach(placementCode => {
          bidmanager.addBidResponse(placementCode, createBid(STATUS.NO_BID));
        });
      return;
    }

    parsed.tags.forEach(tag => {
      const ad = getRtbBid(tag);
      const cpm = ad && ad.cpm;
      const type = ad && ad.ad_type;

      let status;
      if (cpm !== 0 && (type === 'banner' || type === 'video')) {
        status = STATUS.GOOD;
      } else {
        status = STATUS.NO_BID;
      }

      if (type && (type !== 'banner' && type !== 'video')) {
        utils.logError(`${type} ad type not supported`);
      }

      tag.bidId = tag.uuid;  // bidfactory looks for bidId on requested bid
      const bid = createBid(status, tag);
      if (type === 'video') bid.mediaType = 'video';
      const placement = bidRequests[bid.adId].placementCode;
      bidmanager.addBidResponse(placement, bid);
    });

    if (!usersync) {
      const iframe = utils.createInvisibleIframe();
      iframe.src = '//acdn.adnxs.com/ib/static/usersync/v3/async_usersync.html';
      try {
        document.body.appendChild(iframe);
      } catch (error) {
        utils.logError(error);
      }
      usersync = true;
    }
  }

  /* Check that a bid has required paramters */
  function valid(bid) {
    if (bid.params.placementId || bid.params.member && bid.params.invCode) {
      return bid;
    } else {
      utils.logError('bid requires placementId or (member and invCode) params');
    }
  }

  /* Turn keywords parameter into ut-compatible format */
  function getKeywords(keywords) {
    let arrs = [];
{'fraction_non_alphanumeric': 0.13589840788476118, 'fraction_numerical': 0.002084912812736922, 'mean_word_length': 2.409693053311793, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 22, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3683552', 'n_tokens_mistral': 3308, 'n_tokens_neox': 3256, 'n_words': 770}