All files exportCapture.ts

77.46% Statements 55/71
63.46% Branches 33/52
100% Functions 11/11
87.27% Lines 48/55

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 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144                                                                  6x 7x       6x 4x     3x                   1x 1x 1x   1x 1x   1x 2x 2x 1x         1x             1x 1x 1x 1x 1x 1x 1x   1x 1x 2x         2x 2x 2x 2x 1x   2x 2x       1x             2x                   2x 2x 2x 2x 2x       1x 2x       2x 1x 1x 1x 1x 1x 1x              
import type { Har, HarEntry, NEntry } from "../types/har";
import { protectedOccurrences, withResolvedValues } from "./protection";
 
export type ExportFormat = "har" | "ndjson";
export type ExportProtection = "protected" | "resolved";
 
export interface ExportOptions {
  resolvedValues?: ReadonlyMap<string, string>;
}
 
export interface ExportReadiness {
  entries: number;
  protectedValues: number;
  externalBodies: number;
  incompleteBodies: number;
}
 
export interface ResolvedExportSummary {
  resolvedLocations: number;
  uniqueResolvedValues: number;
  encryptedLocations: number;
  tokenizedLocations: number;
  unresolvedLocations: number;
  keyIds: string[];
  areas: Array<{ name: string; count: number }>;
}
 
export function exportCapture(
  har: Har,
  entries: readonly NEntry[],
  format: ExportFormat,
  options: ExportOptions = {},
): string {
  const rawEntries = entries.map((entry) => (
    options.resolvedValues == null
      ? entry.e
      : withResolvedValues(entry.e, options.resolvedValues)
  ));
  if (format === "ndjson") {
    return rawEntries.map((entry) => JSON.stringify(entry)).join("\n") + (rawEntries.length > 0 ? "\n" : "");
  }
 
  return JSON.stringify({
    ...har,
    log: {
      ...har.log,
      entries: rawEntries,
    },
  }, null, 2) + "\n";
}
 
export function exportReadiness(entries: readonly NEntry[]): ExportReadiness {
  let protectedValues = 0;
  let externalBodies = 0;
  let incompleteBodies = 0;
 
  for (const entry of entries) {
    protectedValues += protectedOccurrences(entry.e).length;
 
    for (const body of bodyInfos(entry.e)) {
      if (body.store) externalBodies += 1;
      if (body.truncated || body.closedEarly || !body.complete || body.capturedBytes < body.totalBytes) {
        incompleteBodies += 1;
      }
    }
  }
 
  return { entries: entries.length, protectedValues, externalBodies, incompleteBodies };
}
 
export function resolvedExportSummary(
  entries: readonly NEntry[],
  resolvedValues: ReadonlyMap<string, string>,
): ResolvedExportSummary {
  const unique = new Set<string>();
  const keyIds = new Set<string>();
  const areas = new Map<string, number>();
  let resolvedLocations = 0;
  let encryptedLocations = 0;
  let tokenizedLocations = 0;
  let unresolvedLocations = 0;
 
  for (const entry of entries) {
    for (const occurrence of protectedOccurrences(entry.e)) {
      Iif (!resolvedValues.has(occurrence.token)) {
        unresolvedLocations += 1;
        continue;
      }
 
      resolvedLocations += 1;
      unique.add(occurrence.token);
      keyIds.add(occurrence.keyId);
      if (occurrence.mode === "encrypt") encryptedLocations += 1;
      else tokenizedLocations += 1;
 
      const area = exportArea(occurrence.path);
      areas.set(area, (areas.get(area) ?? 0) + 1);
    }
  }
 
  return {
    resolvedLocations,
    uniqueResolvedValues: unique.size,
    encryptedLocations,
    tokenizedLocations,
    unresolvedLocations,
    keyIds: [...keyIds].sort(),
    areas: [...areas].map(([name, count]) => ({ name, count })).sort((left, right) => left.name.localeCompare(right.name)),
  };
}
 
export function exportFilename(
  sourceName: string,
  format: ExportFormat,
  scope: string,
  protection: ExportProtection = "protected",
): string {
  const leaf = sourceName.split(/[\\/]/).pop() ?? "capture";
  const base = leaf.replace(/\.(?:har|ndjson)$/i, "") || "capture";
  const safeScope = scope.replace(/[^a-z0-9_-]+/gi, "-").replace(/^-+|-+$/g, "").toLowerCase();
  const sensitivity = protection === "resolved" ? ".resolved" : "";
  return `${base}${safeScope ? `-${safeScope}` : ""}${sensitivity}.${format}`;
}
 
function bodyInfos(entry: HarEntry) {
  const extension = entry._recorder;
  return [extension?.requestBody, extension?.responseBody].filter((body) => body != null);
}
 
function exportArea(path: string): string {
  if (path.startsWith("request.url")) return "request URL";
  Iif (path.startsWith("request.headers")) return "request headers";
  Iif (path.startsWith("request.cookies")) return "request cookies";
  Iif (path.startsWith("request.postData")) return "request body";
  Iif (path.startsWith("response.headers")) return "response headers";
  Iif (path.startsWith("response.cookies")) return "response cookies";
  Eif (path.startsWith("response.content")) return "response body";
  if (path.includes("requestTrailers")) return "request trailers";
  if (path.includes("responseTrailers")) return "response trailers";
  if (path.startsWith("_recorder.network")) return "network and proxy";
  if (path.startsWith("_recorder")) return "recorder diagnostics";
  return "other fields";
}