import { Ok, Err, type Result } from "@tsus/runtime";export type CsvError = | { kind: "missing_header" } | { kind: "missing_column"; column: string } | { kind: "column_count"; line: number } | { kind: "unterminated_quote"; line: number };type Row = { line: number; fields: string[]; unterminated: boolean };const isBreak = (text: string, i: number): boolean => text.charAt(i) === "\n" || text.startsWith("\r\n", i);const breakLen = (text: string, i: number): number => (text.charAt(i) === "\n" ? 1 : 2);const readRows = (text: string): Row[] => { const rows: Row[] = []; const n = text.length; let i = 0; let line = 1; while (i < n) { if (isBreak(text, i)) { i += breakLen(text, i); line += 1; continue; } const startLine = line; const fields: string[] = []; let rowDone = false; while (!rowDone) { let value = ""; if (text.charAt(i) === '"') { i += 1; let closed = false; while (i < n && !closed) { const c = text.charAt(i); if (c === '"' && text.charAt(i + 1) === '"') { value += '"'; i += 2; } else if (c === '"') { i += 1; closed = true; } else { line += c === "\n" ? 1 : 0; value += c; i += 1; } } if (!closed) { rows.push({ line: startLine, fields: [], unterminated: true }); return rows; } } while (i < n && text.charAt(i) !== "," && !isBreak(text, i)) { value += text.charAt(i); i += 1; } fields.push(value); if (i < n && text.charAt(i) === ",") { i += 1; } else { if (i < n) { i += breakLen(text, i); line += 1; } rowDone = true; } } rows.push({ line: startLine, fields, unterminated: false }); } return rows;};const toRecord = (header: string[], fields: string[]): Record<string, string> => { const record: Record<string, string> = {}; header.forEach((name, k) => { record[name] = fields[k]; }); return record;};const buildRecords = (header: string[], rows: Row[]): Result<Record<string, string>[], CsvError> => { const out: Record<string, string>[] = []; for (const row of rows) { if (row.unterminated) { return Err({ kind: "unterminated_quote", line: row.line }); } if (row.fields.length !== header.length) { return Err({ kind: "column_count", line: row.line }); } out.push(toRecord(header, row.fields)); } return Ok(out);};export const parseCsv = (text: string, requiredColumns: string[]): Result<Record<string, string>[], CsvError> => { const rows = readRows(text); if (rows.length === 0) { return Err({ kind: "missing_header" }); } const head = rows[0]; if (head.unterminated) { return Err({ kind: "unterminated_quote", line: head.line }); } const missing = requiredColumns.filter((c) => !head.fields.includes(c)); if (missing.length > 0) { return Err({ kind: "missing_column", column: missing[0] }); } return buildRecords(head.fields, rows.slice(1));};