Public Beta
Not set

Experience

Changes how pages explain things, never what you can do.

More

Experience

Changes how pages explain things, never what you can do.

Sign inGet started

Marketing Analytics v0.2.1 · claude-code

Archive SHA-256 ee6fb9f311128ee4857c2908161f8fbedc5f80dff026158ba4f335c50a58671d · 50.6 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 };
}

Find an agent

Do not include passwords, keys, customer data or other confidential details.
Rule-based matching is free during the public beta (fair use).