src/values.js
// Value helpers shared by steps and templates: numbers, dates, comparisons, safe records.
import { ToolError } from "./errors.js";
const NUM = /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?$/;
const THOUSANDS = /^[-+]?\d{1,3}(?:,\d{3})+(?:\.\d+)?$/;
/** Number from a number or a plain numeric string ("12", "-3.5", "1,234.50", "$1,200"). NaN otherwise. */
export function toNumber(v) {
if (typeof v === "number") return Number.isFinite(v) ? v : NaN;
if (typeof v !== "string") return NaN;
let s = v.trim();
if (!s) return NaN;
s = s.replace(/^([-+]?)[$€£¥]\s?/, "$1");
if (NUM.test(s)) return Number(s);
if (THOUSANDS.test(s)) return Number(s.replace(/,/g, ""));
return NaN;
}
const DATE_ONLY = /^(\d{4})-(\d{2})-(\d{2})$/;
const DATE_TIME = /^(\d{4})-(\d{2})-(\d{2})[T ](\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{1,9}))?)?(Z|[+-]\d{2}:?\d{2})?$/i;
/** Epoch milliseconds from an ISO date / date-time string or an epoch-milliseconds number. NaN otherwise. */
export function toDateMs(v) {
if (typeof v === "number") return Number.isFinite(v) ? v : NaN;
if (typeof v !== "string") return NaN;
const s = v.trim();
let m = DATE_ONLY.exec(s);
if (m) {
const ms = Date.UTC(+m[1], +m[2] - 1, +m[3]);
return new Date(ms).getUTCDate() === +m[3] ? ms : NaN;
}
m = DATE_TIME.exec(s);
if (!m) return NaN;
const frac = m[7] ? Number(`0.${m[7]}`) * 1000 : 0;
let ms = Date.UTC(+m[1], +m[2] - 1, +m[3], +m[4], +m[5], +(m[6] ?? 0), Math.floor(frac));
if (new Date(ms).getUTCDate() !== +m[3] || +m[4] > 23 || +m[5] > 59 || +(m[6] ?? 0) > 59) return NaN;
if (m[8] && m[8].toUpperCase() !== "Z") {
const sign = m[8][0] === "-" ? -1 : 1;
const hh = +m[8].slice(1, 3);
const mm = +m[8].slice(-2);
ms -= sign * (hh * 60 + mm) * 60000;
}
return ms;
}
/** True for dates written without a zone: they are shown as written, not converted. */
export function isFloatingDate(v) {
if (typeof v !== "string") return false;
const s = v.trim();
if (DATE_ONLY.test(s)) return true;
const m = DATE_TIME.exec(s);
return !!m && !m[8];
}
const fmtCache = new Map();
function parts(ms, tz) {
let f = fmtCache.get(tz);
if (!f) {
f = new Intl.DateTimeFormat("en-US", { timeZone: tz, year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", second: "2-digit", hourCycle: "h23" });
fmtCache.set(tz, f);
}
const o = {};
for (const p of f.formatToParts(new Date(ms))) o[p.type] = p.value;
return o;
}
export function validTimezone(tz) {
try {
new Intl.DateTimeFormat("en-US", { timeZone: tz });
return true;
} catch {
return false;
}
}
/** Formats with the tokens YYYY, MM, DD, HH, mm, ss (in the given IANA zone, default UTC). */
export function formatDate(ms, fmt = "YYYY-MM-DD", tz = "UTC") {
const p = parts(ms, validTimezone(tz) ? tz : "UTC");
return String(fmt).replace(/YYYY|MM|DD|HH|mm|ss/g, (t) => ({ YYYY: p.year, MM: p.month, DD: p.day, HH: p.hour, mm: p.minute, ss: p.second })[t]);
}
/** ISO-like local time label "YYYY-MM-DDTHH:mm:ss" plus the zone name. */
export function localStamp(ms, tz) {
return formatDate(ms, "YYYY-MM-DDTHH:mm:ss", tz);
}
// ---------------------------------------------------------------------------------------------
// Records: rows are null-prototype objects, so field names from files ("__proto__", "constructor")
// are ordinary keys and can never reach Object.prototype.
// ---------------------------------------------------------------------------------------------
export function record(entries) {
const o = Object.create(null);
if (entries) for (const [k, v] of entries) o[k] = v;
return o;
}
export function cloneRecord(r) {
const o = Object.create(null);
for (const k of Object.keys(r)) o[k] = r[k];
return o;
}
/** Deep copy of parsed JSON into null-prototype objects (limits depth). */
export function safeJson(v, depth = 0) {
if (depth > 64) throw new ToolError("limit_exceeded", "JSON is nested more than 64 levels deep.");
if (Array.isArray(v)) return v.map((x) => safeJson(x, depth + 1));
if (v !== null && typeof v === "object") {
const o = Object.create(null);
for (const k of Object.keys(v)) o[k] = safeJson(v[k], depth + 1);
return o;
}
return v;
}
export const isRecord = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
export const isRows = (v) => Array.isArray(v) && v.every(isRecord);
/** Field value; dotted names reach into nested objects ("front_matter.status"). */
export function getField(row, name) {
if (!isRecord(row)) return undefined;
if (Object.hasOwn(row, name)) return row[name];
if (!name.includes(".")) return undefined;
let v = row;
for (const p of name.split(".")) {
if (!isRecord(v) || !Object.hasOwn(v, p)) return undefined;
v = v[p];
}
return v;
}
export function isEmpty(v) {
return v === undefined || v === null || (typeof v === "string" && v.trim() === "") || (Array.isArray(v) && v.length === 0);
}
export function textOf(v) {
if (v === undefined || v === null) return "";
if (typeof v === "string") return v;
if (typeof v === "number" || typeof v === "boolean") return String(v);
return JSON.stringify(v);
}
/** Compares two values: "number", "date", "string" or "auto" (numbers if both are numeric, then dates, else text). */
export function compareValues(a, b, type = "auto", ignoreCase = false) {
const ea = isEmpty(a);
const eb = isEmpty(b);
if (ea || eb) return ea && eb ? 0 : ea ? 1 : -1; // empty values sort last
if (type === "number" || type === "auto") {
const x = toNumber(a);
const y = toNumber(b);
if (Number.isFinite(x) && Number.isFinite(y)) return x < y ? -1 : x > y ? 1 : 0;
if (type === "number") return Number.isFinite(x) ? -1 : Number.isFinite(y) ? 1 : 0;
}
if (type === "date" || type === "auto") {
const x = toDateMs(a);
const y = toDateMs(b);
if (Number.isFinite(x) && Number.isFinite(y)) return x < y ? -1 : x > y ? 1 : 0;
if (type === "date") return Number.isFinite(x) ? -1 : Number.isFinite(y) ? 1 : 0;
}
let s = textOf(a);
let t = textOf(b);
if (ignoreCase) {
s = s.toLowerCase();
t = t.toLowerCase();
}
return s < t ? -1 : s > t ? 1 : 0;
}
/** Rounds away binary noise (0.1 + 0.2) without hiding real precision. */
export const tidy = (x) => (Number.isFinite(x) ? Math.round(x * 1e10) / 1e10 : x);