All files / utils external.ts

32.14% Statements 9/28
9.09% Branches 1/11
25% Functions 1/4
32.14% Lines 9/28

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 11716x 16x 16x 16x               16x           16x 16x     16x                                                                                                                 16x                                                                            
import { spawn, spawnSync } from "child_process";
import { IS_DEVELOPMENT_OR_CI, TELEMETRY_URL } from "../sdk/utils/constants";
import { serializeValue } from "../sdk/utils/common";
import logger from "./logger";
 
/**
 * Sends a reporting payload to the telemetry server using a child process.
 * This function is intended for use in Node.js environments.
 *
 * @param {any} reportingPayload - The payload to be sent to the telemetry server.
 */
export function sendProcessReq(info: {
  url: string;
  method: string;
  headers: Record<string, string>;
  data: Record<string, unknown>;
}) {
  if (IS_DEVELOPMENT_OR_CI) {
    console.log(
      `Hitting ${info.url}[${info.method}] with ${serializeValue(info.data)}`
    );
    return true;
  }
 
  try {
    // Use node-fetch for making HTTP requests
    const url = new URL(info.url);
    const child = spawn("node", [
      "-e",
      `
        const http = require('${url.protocol === "https:" ? "https" : "http"}');
        const options = {
          hostname: '${url.hostname}',
          path: '${url.pathname}${url.search}',
          port: ${url.port || (url.protocol === "https:" ? 443 : 80)},
          method: '${info.method}',
          headers: ${JSON.stringify(info.headers)}
        };
 
        const req = http.request(options, (res) => {
          let data = '';
          res.on('data', (chunk) => {
            data += chunk;
          });
          
          res.on('end', () => {
            if (res.statusCode >= 200 && res.statusCode < 300) {
              console.log('Request successful');
            } else {
              console.error('Request failed with status:', res.statusCode);
            }
          });
        });
 
        req.on('error', (error) => {
          console.error('Error:', error.message);
          process.exit(1);
        });
 
        req.write(JSON.stringify(${JSON.stringify(info.data)}));
        req.end();
      `,
    ]);
 
    // // Close the stdin stream
    child.stdin.end();
  } catch (error) {
    logger.error("Error sending error to telemetry", error);
    // DO NOTHING
  }
}
 
/**
 * Sends a reporting payload to the telemetry server using XMLHttpRequest.
 * This function is intended for use in browser environments.
 *
 * @param {any} reportingPayload - The payload to be sent to the telemetry server.
 */
export function sendBrowserReq(info: {
  url: string;
  method: string;
  headers: Record<string, string>;
  data: Record<string, unknown>;
}) {
  Iif (IS_DEVELOPMENT_OR_CI) {
    logger.debug(
      `Hitting ${info.url}[${info.method}] with ${serializeValue(info.data)}`
    );
    return true;
  }
  try {
    // Create a new XMLHttpRequest object
    const xhr = new XMLHttpRequest();
    // Open a new POST request to the telemetry server
    xhr.open(info.method, info.url, true);
    // Set the request header to indicate JSON content
    xhr.setRequestHeader("Content-Type", "application/json");
    Object.entries(info.headers || {}).forEach(([key, value]) => {
      xhr.setRequestHeader(key, value);
    });
 
    // Define the onload event handler
    xhr.onload = function () {
      // Log the response if the request was successful
      Iif (xhr.status === 200) {
        logger.debug(xhr.response);
      }
    };
 
    // Send the reporting payload as a JSON string
    xhr.send(JSON.stringify(info.data));
  } catch (error) {
    logger.error("Error sending error to telemetry", error);
    // DO NOTHING
  }
}