src/data.js
// Loads user-supplied CSV exports into one normalised, time-sorted event list. Rows that cannot be
// read are counted per reason and reported; nothing is guessed or filled in.
import { ToolError } from "./errors.js";
import { parseCsv } from "./csv.js";
const ALIASES = {
user_id: ["user_id", "userid", "user", "client_id", "anonymous_id", "visitor_id", "distinct_id", "customer_id"],
timestamp: ["timestamp", "time", "datetime", "date", "event_time", "event_timestamp", "created_at", "occurred_at"],
event: ["event", "event_name", "event_type", "action"],
utm_source: ["utm_source", "source", "session_source"],
utm_medium: ["utm_medium", "medium", "session_medium"],
utm_campaign: ["utm_campaign", "campaign", "session_campaign", "campaign_name"],
session_id: ["session_id", "sessionid", "session", "ga_session_id"],
};
const DIRECT_SOURCES = new Set(["(direct)", "direct"]);
const NONE_MEDIUMS = new Set(["", "(none)", "none", "(not set)"]);
function resolveColumns(header, overrides, ds) {
const lower = header.map((h) => h.toLowerCase());
const cols = {};
for (const [key, aliases] of Object.entries(ALIASES)) {
const wanted = overrides?.[key];
if (wanted !== undefined) {
const idx = lower.indexOf(wanted.trim().toLowerCase());
// A named column must exist in at least the files that need it; UTM/session columns are optional per file.
if (idx < 0 && (key === "user_id" || key === "timestamp" || (key === "event" && ds.default_event === undefined))) {
throw new ToolError("invalid_input", `${ds.name}: column "${wanted}" not found (headers: ${header.slice(0, 30).join(", ").slice(0, 400)})`);
}
if (idx >= 0) cols[key] = idx;
continue;
}
const idx = aliases.map((a) => lower.indexOf(a)).find((i) => i >= 0);
if (idx !== undefined) cols[key] = idx;
}
if (cols.user_id === undefined) throw new ToolError("invalid_input", `${ds.name}: no user id column (tried ${ALIASES.user_id.join(", ")}); set columns.user_id.`);
if (cols.timestamp === undefined) throw new ToolError("invalid_input", `${ds.name}: no timestamp column (tried ${ALIASES.timestamp.join(", ")}); set columns.timestamp.`);
if (cols.event === undefined && ds.default_event === undefined) throw new ToolError("invalid_input", `${ds.name}: no event column; set columns.event or give this file a default_event (e.g. "signup").`);
return cols;
}
/** Epoch ms and whether the value lacked a time zone, or null when the value is not an unambiguous timestamp. */
export function parseTimestamp(raw) {
const s = String(raw).trim();
if (/^\d{10}$/.test(s)) return { ms: Number(s) * 1000, naive: false };
if (/^\d{13}$/.test(s)) return { ms: Number(s), naive: false };
let iso;
let naive = false;
let m;
if (/^\d{4}-\d{2}-\d{2}$/.test(s)) {
iso = `${s}T00:00:00Z`;
naive = true;
} else if ((m = /^(\d{4}-\d{2}-\d{2})[T ](\d{2}:\d{2}(?::\d{2}(?:\.\d{1,9})?)?)$/.exec(s))) {
iso = `${m[1]}T${m[2]}Z`;
naive = true;
} else if ((m = /^(\d{4}-\d{2}-\d{2})[T ](\d{2}:\d{2}(?::\d{2}(?:\.\d{1,9})?)?)\s?(Z|UTC|[+-]\d{2}:?\d{2})$/i.exec(s))) {
const z = m[3].toUpperCase() === "UTC" ? "Z" : m[3].length === 5 ? `${m[3].slice(0, 3)}:${m[3].slice(3)}` : m[3].toUpperCase();
iso = `${m[1]}T${m[2]}${z}`;
} else return null;
const ms = Date.parse(iso);
if (Number.isNaN(ms)) return null;
// Reject impossible calendar dates such as 2026-02-30 (checked on the written date, before any offset).
const [y, mo, d] = iso.slice(0, 10).split("-").map(Number);
const check = new Date(Date.UTC(y, mo - 1, d));
if (check.getUTCFullYear() !== y || check.getUTCMonth() !== mo - 1 || check.getUTCDate() !== d) return null;
return { ms, naive };
}
export function loadData(input) {
const caseSensitive = input.case_sensitive_utm === true;
const touchEvents = input.touch_events ? new Set(input.touch_events) : null;
const utm = (v) => {
const t = String(v ?? "").replace(/[\u0000-\u001f\u007f]/g, "").trim().slice(0, 200);
return caseSensitive ? t : t.toLowerCase();
};
const names = new Set();
const events = [];
const datasets = [];
const warnings = [];
let order = 0;
let naiveCount = 0;
let totalRows = 0;
for (const ds of input.data) {
if (names.has(ds.name)) throw new ToolError("invalid_input", `Duplicate data name: ${ds.name}`);
names.add(ds.name);
const { header, rows, ragged } = parseCsv(ds.csv, { label: ds.name, maxRows: 200000 - totalRows });
totalRows += rows.length;
const cols = resolveColumns(header, input.columns, ds);
const skipped = { missing_user: 0, bad_timestamp: 0, missing_event: 0 };
let used = 0;
for (const r of rows) {
const u = String(r[cols.user_id] ?? "").trim();
if (!u) {
skipped.missing_user++;
continue;
}
const ts = parseTimestamp(r[cols.timestamp] ?? "");
if (!ts) {
skipped.bad_timestamp++;
continue;
}
const e = (cols.event !== undefined ? String(r[cols.event] ?? "").trim() : "") || ds.default_event || "";
if (!e) {
skipped.missing_event++;
continue;
}
if (ts.naive) naiveCount++;
const src = cols.utm_source !== undefined ? utm(r[cols.utm_source]) : "";
const med = cols.utm_medium !== undefined ? utm(r[cols.utm_medium]) : "";
const camp = cols.utm_campaign !== undefined ? utm(r[cols.utm_campaign]) : "";
const sid = cols.session_id !== undefined ? String(r[cols.session_id] ?? "").trim() : "";
const direct = DIRECT_SOURCES.has(src.toLowerCase()) && NONE_MEDIUMS.has(med.toLowerCase()) && !camp;
const hasUtm = Boolean(src || med || camp) && !direct;
const touch = hasUtm && (touchEvents ? touchEvents.has(e) : true);
events.push({ u, t: ts.ms, e, src, med, camp, sid, touch, order: order++ });
used++;
}
const columnsUsed = Object.fromEntries(Object.entries(cols).map(([k, i]) => [k, header[i]]));
datasets.push({ name: ds.name, rows: rows.length, used, skipped, columns: columnsUsed, ...(ds.default_event ? { default_event: ds.default_event } : {}) });
const bad = skipped.missing_user + skipped.bad_timestamp + skipped.missing_event;
if (bad) warnings.push(`${ds.name}: skipped ${bad} of ${rows.length} rows (missing user ${skipped.missing_user}, unreadable timestamp ${skipped.bad_timestamp}, missing event ${skipped.missing_event}).`);
if (ragged) warnings.push(`${ds.name}: ${ragged} row(s) had a different number of fields than the header; missing fields were read as empty.`);
}
if (naiveCount) warnings.push(`${naiveCount} timestamp(s) had no time zone and were read as UTC.`);
events.sort((a, b) => a.t - b.t || a.order - b.order);
const users = new Set(events.map((e) => e.u)).size;
const dq = {
datasets,
rows_used: events.length,
users,
date_range: events.length ? { start: new Date(events[0].t).toISOString(), end: new Date(events[events.length - 1].t).toISOString() } : null,
};
if (!events.length) warnings.push("No usable rows: every row was skipped. Check the column names and timestamp format (ISO 8601 or epoch).");
return { events, dq, warnings };
}