All files / src/vite proxy.ts

100% Statements 15/15
100% Branches 8/8
100% Functions 3/3
100% Lines 15/15

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        1x                   1x       6x   6x         2x     4x 4x   4x 28x           2x 2x 4x     2x 2x         4x    
import type { ClientRequest } from "http";
import type { ProxyOptions } from "vite";
import type { Credential } from "../servicenow/types";
 
export const DEFAULT_PROXY_PATHS = [
  "/api",
  "/amb",
  "/scripts/",
  "/images/@servicenow/",
  "/uxasset/externals",
  "/$uxappimmutables.do",
  "/uxta",
];
 
export async function createViteProxy(
  credential: Credential | undefined,
  proxyPaths: string[] = DEFAULT_PROXY_PATHS,
): Promise<Record<string, ProxyOptions>> {
  const proxy: Record<string, ProxyOptions> = {};
 
  if (
    !credential ||
    typeof credential.getUrl !== "function" ||
    typeof credential.getHeaders !== "function"
  ) {
    return proxy;
  }
 
  const authHeaders = await credential.getHeaders();
  const proxyTarget = credential.getUrl().href.replace(/\/$/, "");
 
  for (const proxyPath of proxyPaths) {
    proxy[proxyPath] = {
      target: proxyTarget,
      changeOrigin: true,
      // `changeOrigin` only rewrites the HTTP Host header
      ...(proxyPath === "/amb" ? { ws: true, rewriteWsOrigin: true } : {}),
      configure: (proxyServer) => {
        const setAuthHeaders = (proxyReq: ClientRequest) => {
          for (const [key, value] of Object.entries(authHeaders)) {
            proxyReq.setHeader(key, value);
          }
        };
        proxyServer.on("proxyReq", setAuthHeaders);
        proxyServer.on("proxyReqWs", setAuthHeaders);
      },
    };
  }
 
  return proxy;
}