/**
Copyright: 2024 Contrast Security, Inc
  Contact: support@contrastsecurity.com
  License: Commercial

  NOTICE: This Software and the patented inventions embodied within may only be
  used as part of Contrast Security’s commercial offerings. Even though it is
  made available through public repositories, use of this Software is subject to
  the applicable End User Licensing Agreement found at
  https://www.contrastsecurity.com/enduser-terms-0317a or as otherwise agreed
  between Contrast Security and the End User. The Software may not be reverse
  engineered, modified, repackaged, sold, redistributed or otherwise used in a
  way not consistent with the End User License Agreement.
*/
'use strict';

const { dtm } = require('@contrast/protobuf-api');

/*
message ObservedRoute {
    // Language specific signature of the controller method.
    // For instance, Users#show
    string signature = 1;
    // The concrete, normalized URL of the request that matches this route.
    // For instance, /users/{n}/show
    string url = 2;
    // The HTTP verb of this request.
    // For instance, GET
    string verb = 3;
    // The ID of the current application run, as returned by the application
    // settings endpoint or set by application.session_id.
    string session_id = 4;
    // The observed event sources for this route. Those that were created from
    // untrusted inputs accessed through the Request object which corresponds
    // to this request.
    // For instance, type: PARAMETER, name: foo
    repeated contrast.api.dtm.TraceEventSource sources = 5;
}

message TraceEventSource {
    string type = 1;
    string name = 2;
}
*/

/**
 * Generate an array of protobuf TraceEventSources from an array of sources
 *
 * @param {Object[]} sources array of source objects
 */
function toTraceEventSourceDtm(sources) {
  if (!Array.isArray(sources)) {
    return [];
  }

  // previously called dtm.TraceEventSource() and used .array - an
  // expensive way to get the following.
  return sources.map((tes) => [tes.type, tes.name]);
}

/**
 * Create an ObservedRoute protobuf object
 *
 * @param {Object} route observation event
 */
module.exports = function ObservedRoute({ signature, verb, url, sources }) {
  return new dtm.ObservedRoute({
    0: signature, // 1 signature
    1: url, // 2 url
    2: verb, // 3 verb
    4: toTraceEventSourceDtm(sources) // 4 sources
  });
};
