/** In-memory interpretation of the public bounded collection filter contract. */ export function matchesRecordWhere(data: Record, where: unknown): boolean { if (!where || typeof where !== "object") return true; return Object.entries(where).every(([key, condition]) => { const value = data[key]; if (condition === null || typeof condition !== "object") return value === condition; return Object.entries(condition).every(([operator, expected]) => { if (operator === "eq") return value === expected; if (operator === "contains") return ( typeof value === "string" && typeof expected === "string" && value.toLowerCase().includes(expected.toLowerCase()) ); if ( typeof value !== typeof expected || (typeof value !== "string" && typeof value !== "number") ) return false; const comparison = typeof value === "number" ? value - Number(expected) : value.localeCompare(String(expected)); if (operator === "gt") return comparison > 0; if (operator === "gte") return comparison >= 0; if (operator === "lt") return comparison < 0; if (operator === "lte") return comparison <= 0; return false; }); }); } /** Numeric fields sort by value; mixed scalar types keep numbers together. */ export function compareRecordValues(a: unknown, b: unknown): number { if (typeof a === "number" && typeof b === "number") return a - b; if (typeof a === "number") return -1; if (typeof b === "number") return 1; const left = String(a ?? ""), right = String(b ?? ""); // PostgreSQL's C collation follows Unicode code points for valid UTF-8. // JavaScript's default comparison instead sorts surrogate code units. let i = 0, j = 0; while (i < left.length && j < right.length) { const leftPoint = left.codePointAt(i)!, rightPoint = right.codePointAt(j)!; if (leftPoint !== rightPoint) return leftPoint - rightPoint; i += leftPoint > 0xffff ? 2 : 1; j += rightPoint > 0xffff ? 2 : 1; } return left.length - right.length; }