All files / src/shared/lib/scriptDataTable csv.ts

93.48% Statements 86/92
82.22% Branches 37/45
100% Functions 14/14
94.19% Lines 81/86

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 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 1602x 2x   2x         2x 11x 4x   7x     2x 3x     2x       19x 19x 19x 16x   3x 1x   2x 2x 1x   1x     2x 6x 6x 6x 6x   6x 187x 187x   187x 6x     6x 1x   5x   6x     181x 1x 180x 22x 22x 158x 8x 8x 8x 8x 150x 150x       6x 6x   14x     2x       3x 1x         3x     3x 3x 3x 4x 4x 1x 1x 1x       3x   3x   3x     2x       6x 1x           6x 6x       6x 10x   6x 7x     19x       6x           6x       6x 1x     5x 1x     4x    
import { constantName } from "shared/lib/entities/entitiesHelpers";
import l10n from "shared/lib/lang/l10n";
import { Constant } from "shared/lib/resources/types";
import {
  isScriptDataTable,
  ScriptDataTable,
} from "shared/lib/scriptDataTable/types";
 
const escapeCSVValue = (value: string): string => {
  if (value.includes(",") || value.includes('"') || value.includes("\n")) {
    return `"${value.replace(/"/g, '""')}"`;
  }
  return value;
};
 
const isEngineConstantSymbol = (value: string) => {
  return value.startsWith("engine::");
};
 
const parseCSVCellValue = (
  value: string | undefined,
  reverseConstantsLookup: Record<string, string>,
) => {
  const trimmedValue = (value ?? "").trim();
  const numValue = Number(trimmedValue);
  if (!isNaN(numValue)) {
    return { type: "number" as const, value: numValue };
  }
  if (isEngineConstantSymbol(trimmedValue)) {
    return { type: "constant" as const, value: trimmedValue };
  }
  const constantId = reverseConstantsLookup[trimmedValue];
  if (constantId) {
    return { type: "constant" as const, value: constantId };
  }
  return { type: "number" as const, value: 0 };
};
 
const parseCSV = (csv: string): string[][] => {
  const rows: string[][] = [];
  let row: string[] = [];
  let value = "";
  let inQuotes = false;
 
  for (let i = 0; i < csv.length; i++) {
    const char = csv[i];
    const nextChar = csv[i + 1];
 
    if (inQuotes) {
      Iif (char === '"' && nextChar === '"') {
        value += '"';
        i++;
      } else if (char === '"') {
        inQuotes = false;
      } else {
        value += char;
      }
      continue;
    }
 
    if (char === '"') {
      inQuotes = true;
    } else if (char === ",") {
      row.push(value);
      value = "";
    } else if (char === "\n") {
      row.push(value);
      rows.push(row);
      row = [];
      value = "";
    } else if (char !== "\r") {
      value += char;
    }
  }
 
  row.push(value);
  rows.push(row);
 
  return rows.filter((row) => row.length > 1 || row[0].trim().length > 0);
};
 
export const scriptDataTableToCSV = (
  data: ScriptDataTable,
  constants: Constant[],
): string => {
  const constantsLookup = Object.fromEntries(
    constants.map((constant, constantIndex) => [
      constant.id,
      constantName(constant, constantIndex),
    ]),
  );
  const header = [data.label ?? "", ...data.variables]
    .map(escapeCSVValue)
    .join(",");
  const rows = data.rows.map((row, index) => {
    const label = row.label ?? `Row ${index + 1}`;
    const values = row.values.map((value) => {
      Iif (value === undefined) return "";
      if (value.type === "constant") {
        const constant = constantsLookup[value.value];
        if (constant) {
          return escapeCSVValue(constant);
        }
        return escapeCSVValue(value.value);
      }
      return value.value.toString();
    });
    return [escapeCSVValue(label), ...values].join(",");
  });
  return [header, ...rows].join("\n");
};
 
export const csvToScriptDataTable = (
  csv: string,
  constants: Constant[],
): ScriptDataTable | undefined => {
  const reverseConstantsLookup = Object.fromEntries(
    constants.map((constant, constantIndex) => [
      constantName(constant, constantIndex),
      constant.id,
    ]),
  );
 
  const csvRows = parseCSV(csv);
  Iif (csvRows.length === 0) {
    throw new Error(l10n("ERROR_DATA_TABLE_CSV_NO_ROW_DATA"));
  }
 
  const [header, ...rows] = csvRows;
  const variables = header.slice(1).map((v) => v.trim());
 
  const dataRows = rows.map(([label = "", ...values]) => {
    return {
      label: label.trim(),
      values: variables.map((_, index) =>
        parseCSVCellValue(values[index], reverseConstantsLookup),
      ),
    };
  });
  const dataTable: ScriptDataTable = {
    label: header[0].trim() || undefined,
    variables,
    rows: dataRows,
  };
 
  Iif (!isScriptDataTable(dataTable)) {
    throw new Error(l10n("ERROR_DATA_TABLE_CSV_INVALID"));
  }
 
  if (dataTable.variables.length === 0) {
    throw new Error(l10n("ERROR_DATA_TABLE_CSV_NO_VARIABLES"));
  }
 
  if (dataTable.rows.length === 0) {
    throw new Error(l10n("ERROR_DATA_TABLE_CSV_NO_ROW_DATA"));
  }
 
  return dataTable;
};