src/csv.js
// CSV reading (RFC 4180: quoted fields, "" escapes, embedded line breaks, CRLF, UTF-8 BOM) and writing
// (quoted where needed; cells that a spreadsheet would run as a formula are prefixed with ').
import { ToolError } from "./errors.js";
import { record, textOf } from "./values.js";
export const DELIMITERS = { ",": ",", ";": ";", tab: "\t", "\t": "\t", "|": "|" };
/** Picks the delimiter that appears most often (outside quotes) in the first line. */
export function sniffDelimiter(text) {
const counts = { ",": 0, ";": 0, "\t": 0, "|": 0 };
let q = false;
for (let i = 0; i < text.length && i < 20000; i++) {
const c = text[i];
if (c === '"') q = !q;
else if (!q && (c === "\n" || c === "\r")) break;
else if (!q && c in counts) counts[c]++;
}
let best = ",";
for (const d of [",", ";", "\t", "|"]) if (counts[d] > counts[best]) best = d;
return best;
}
/** Splits CSV text into arrays of fields. */
export function parseCsvRecords(text, delimiter, { maxRows = Infinity, maxRowsLabel = maxRows, field = "csv", tick } = {}) {
const rows = [];
let row = [];
let cell = "";
let q = false;
let i = text.charCodeAt(0) === 0xfeff ? 1 : 0;
let quotedCell = false;
const endCell = () => {
row.push(cell);
cell = "";
quotedCell = false;
};
const endRow = () => {
endCell();
if (!(row.length === 1 && row[0] === "" )) rows.push(row);
row = [];
if (rows.length > maxRows) throw new ToolError("limit_exceeded", `${field}: more than ${maxRowsLabel} rows (limits.max_rows).`);
if (rows.length % 5000 === 0) tick?.();
};
for (; i < text.length; i++) {
const c = text[i];
if (q) {
if (c === '"') {
if (text[i + 1] === '"') {
cell += '"';
i++;
} else q = false;
} else cell += c;
} else if (c === '"' && cell === "" && !quotedCell) {
q = true;
quotedCell = true;
} else if (c === delimiter) endCell();
else if (c === "\n") endRow();
else if (c === "\r") {
if (text[i + 1] === "\n") i++;
endRow();
} else cell += c;
}
if (q) throw new ToolError("invalid_input", `${field}: a quoted field is not closed.`);
if (cell !== "" || row.length) endRow();
return rows;
}
/**
* Parses CSV text into rows (null-prototype records). With header: true the first record names the
* columns (blank names become column_N, repeated names get _2, _3). Returns { rows, columns, warnings }.
*/
export function parseCsv(text, { delimiter = "auto", header = true, maxRows, field = "csv", tick } = {}) {
const d = delimiter === "auto" ? sniffDelimiter(text) : DELIMITERS[delimiter];
if (!d) throw new ToolError("invalid_recipe", `${field}: unknown delimiter ${delimiter}.`);
const recs = parseCsvRecords(text, d, { maxRows: maxRows === undefined ? undefined : maxRows + (header ? 1 : 0), maxRowsLabel: maxRows, field, tick });
const warnings = [];
if (!recs.length) return { rows: [], columns: [], warnings, delimiter: d };
let columns;
let body = recs;
if (header) {
const seen = new Map();
columns = recs[0].map((h, i) => {
let name = h.trim() || `column_${i + 1}`;
const n = (seen.get(name.toLowerCase()) ?? 0) + 1;
seen.set(name.toLowerCase(), n);
if (n > 1) name = `${name}_${n}`;
return name;
});
body = recs.slice(1);
} else {
const width = Math.max(...recs.map((r) => r.length));
columns = Array.from({ length: width }, (_, i) => `column_${i + 1}`);
}
let extra = 0;
let short = 0;
const rows = body.map((r) => {
if (r.length > columns.length) extra++;
if (r.length < columns.length) short++;
return record(columns.map((c, i) => [c, r[i] ?? ""]));
});
if (extra) warnings.push(`${field}: ${extra} row(s) had more fields than the header; the extra fields were ignored.`);
if (short) warnings.push(`${field}: ${short} row(s) had fewer fields than the header; missing fields are empty.`);
return { rows, columns, warnings, delimiter: d };
}
const PLAIN_NUMBER = /^[-+]?(?:\d+(?:\.\d+)?|\.\d+)(?:[eE][-+]?\d+)?$/;
/** One CSV cell. protect: prefix ' to text starting with = + - @ tab or CR (spreadsheet formula injection). */
export function csvCell(v, delimiter = ",", protect = true) {
let s = textOf(v);
if (protect && /^[=+\-@\t\r]/.test(s) && !PLAIN_NUMBER.test(s)) s = "'" + s;
if (s.includes(delimiter) || /["\r\n]/.test(s) || /^\s|\s$/.test(s)) s = `"${s.replace(/"/g, '""')}"`;
return s;
}
export function toCsv(rows, columns, { delimiter = ",", protect = true, header = true } = {}) {
const lines = [];
if (header) lines.push(columns.map((c) => csvCell(c, delimiter, protect)).join(delimiter));
for (const r of rows) lines.push(columns.map((c) => csvCell(r[c], delimiter, protect)).join(delimiter));
return lines.join("\r\n") + (lines.length ? "\r\n" : "");
}
/** Column names in order of first appearance across rows. */
export function columnsOf(rows) {
const seen = new Set();
for (const r of rows) for (const k of Object.keys(r)) seen.add(k);
return [...seen];
}