Marketing Analytics v0.2.1 · generic
Archive SHA-256 8e33c2b8ecf72e82b9edc3bf24453b7c7f30311d425df18c285750c66a34b408 · 48.8 KB · built Nov 27, 2026
src/csv.js
// RFC 4180-style CSV parsing (quoted fields, escaped quotes, CRLF/LF/CR, embedded newlines, BOM)
// with delimiter detection (comma, semicolon, tab) and hard limits. Input is untrusted text.
import { ToolError } from "./errors.js";
function detectDelimiter(text) {
const counts = { ",": 0, ";": 0, "\t": 0 };
let inQ = false;
for (let i = 0; i < text.length && i < 20000; i++) {
const c = text[i];
if (c === '"') inQ = !inQ;
else if (!inQ && (c === "\n" || c === "\r")) break;
else if (!inQ && c in counts) counts[c]++;
}
const best = Object.entries(counts).sort((a, b) => b[1] - a[1])[0];
return best[1] > 0 ? best[0] : ",";
}
/** Returns { header, rows, delimiter, ragged } where rows are arrays of strings. */
export function parseCsv(text, { maxRows = 200000, label = "csv" } = {}) {
let s = String(text);
if (s.charCodeAt(0) === 0xfeff) s = s.slice(1);
const delimiter = detectDelimiter(s);
const records = [];
let field = "";
let record = [];
let inQ = false;
let i = 0;
const pushRecord = () => {
record.push(field);
field = "";
if (!(record.length === 1 && record[0] === "")) records.push(record);
record = [];
if (records.length > maxRows + 1) throw new ToolError("invalid_input", `${label}: more than ${maxRows} rows; split the export or filter it first.`);
};
while (i < s.length) {
const c = s[i];
if (inQ) {
if (c === '"') {
if (s[i + 1] === '"') {
field += '"';
i += 2;
continue;
}
inQ = false;
i++;
continue;
}
field += c;
i++;
continue;
}
if (c === '"' && field === "") {
inQ = true;
i++;
} else if (c === delimiter) {
record.push(field);
field = "";
i++;
} else if (c === "\r" || c === "\n") {
pushRecord();
i += c === "\r" && s[i + 1] === "\n" ? 2 : 1;
} else {
field += c;
i++;
}
}
if (inQ) throw new ToolError("invalid_input", `${label}: unterminated quoted field.`);
if (field !== "" || record.length) pushRecord();
if (!records.length) throw new ToolError("invalid_input", `${label}: no header row.`);
const header = records[0].map((h) => h.trim());
let ragged = 0;
const rows = records.slice(1).map((r) => {
if (r.length !== header.length) ragged++;
return header.map((_, k) => r[k] ?? "");
});
return { header, rows, delimiter, ragged };
}