/** * Copyright 2026 aphrody-code * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @module bxc/extract/schema * * Schema subset accepted by `bxc extract`, its normalizer, the value coercions * applied to raw DOM strings and a small validator. * * Accepted inputs: * - JSON Schema (draft-07 subset): `{ type: "object", properties, required }` * for a single record, or `{ type: "array", items: { type: "object", ... } }` * for a record list. Property `type` may be `string | number | integer | * boolean | array` (of scalars) or `object` (nested one level), optionally * with `format` (`uri | date | date-time | email`), `description` and the * `x-bxc-selector` hint (`css` or `css@attribute`). * - Shorthand: `{ title: "string", price: "number", url: "uri" }` (fields are * required unless the type ends with `?`; `"string[]"` is an array; a nested * object is a nested shorthand; `[ { ... } ]` is a record list). */ import { createHash } from "node:crypto"; export type ScalarType = "string" | "number" | "integer" | "boolean"; export type FieldType = ScalarType | "array" | "object"; export type FieldFormat = "uri" | "date" | "date-time" | "email"; export interface FieldSpec { name: string; type: FieldType; format?: FieldFormat; description?: string; required: boolean; /** JSON Schema type union includes `"null"`: a required key may hold `null`. */ nullable?: boolean; /** `x-bxc-selector` hint: CSS selector relative to the record. */ selector?: string; /** Attribute read from the hinted selector (`css@attr`). */ selectorAttribute?: string; /** Item type of `array` fields (scalars only). */ items?: { type: ScalarType; format?: FieldFormat }; /** Sub-fields of `object` fields (one nesting level). */ properties?: FieldSpec[]; } export interface NormalizedSchema { /** `list` extracts `records[]`, `object` extracts one `record`. */ kind: "list" | "object"; fields: FieldSpec[]; /** Stable hash of the normalized schema (selector cache key). */ hash: string; } /** A scalar (or scalar array) field addressed by a dotted path. */ export interface LeafField { /** Dotted path, e.g. `author.name`. */ key: string; path: string[]; spec: FieldSpec; parent?: FieldSpec; required: boolean; } export class SchemaError extends Error { constructor(message: string) { super(message); this.name = "SchemaError"; } } const SCALARS: ReadonlySet = new Set(["string", "number", "integer", "boolean"]); const FORMATS: ReadonlySet = new Set(["uri", "date", "date-time", "email"]); const SHORTHAND_TYPES: Record = { string: { type: "string" }, str: { type: "string" }, text: { type: "string" }, number: { type: "number" }, float: { type: "number" }, integer: { type: "integer" }, int: { type: "integer" }, boolean: { type: "boolean" }, bool: { type: "boolean" }, uri: { type: "string", format: "uri" }, url: { type: "string", format: "uri" }, date: { type: "string", format: "date" }, "date-time": { type: "string", format: "date-time" }, datetime: { type: "string", format: "date-time" }, email: { type: "string", format: "email" }, }; function isPlainObject(value: unknown): value is Record { return typeof value === "object" && value !== null && !Array.isArray(value); } function isJsonSchemaLike(value: Record): boolean { return ( typeof value.type === "string" || Array.isArray(value.type) || isPlainObject(value.properties) || typeof value.$schema === "string" ); } /** Normalize a JSON Schema subset or shorthand into a {@link NormalizedSchema}. */ export function normalizeSchema(input: unknown): NormalizedSchema { if (isNormalizedSchema(input)) return input; let raw = input; if (typeof raw === "string") { try { raw = JSON.parse(raw); } catch { throw new SchemaError("schema string is not valid JSON"); } } let kind: "list" | "object"; let fields: FieldSpec[]; if (Array.isArray(raw)) { if (raw.length !== 1 || !isPlainObject(raw[0])) { throw new SchemaError("a shorthand list schema must be [ { ...fields } ]"); } kind = "list"; fields = normalizeObjectBody(raw[0], 0); } else if (isPlainObject(raw)) { if (isJsonSchemaLike(raw)) { const type = primaryType(raw.type); if (type === "array") { if (!isPlainObject(raw.items)) { throw new SchemaError("list schemas need `items` describing an object"); } kind = "list"; fields = normalizeObjectBody(raw.items, 0); } else if (type === "object" || type === undefined) { kind = "object"; fields = normalizeObjectBody(raw, 0); } else { throw new SchemaError(`top-level schema type must be object or array, got ${type}`); } } else { kind = "object"; fields = normalizeObjectBody(raw, 0); } } else { throw new SchemaError("schema must be an object, an array or a JSON string"); } if (fields.length === 0) throw new SchemaError("schema declares no fields"); return { kind, fields, hash: hashFields(kind, fields) }; } function isNormalizedSchema(value: unknown): value is NormalizedSchema { return ( isPlainObject(value) && (value.kind === "list" || value.kind === "object") && Array.isArray(value.fields) && typeof value.hash === "string" ); } function primaryType(type: unknown): string | undefined { if (typeof type === "string") return type; if (Array.isArray(type)) { const nonNull = type.filter((t) => t !== "null"); return typeof nonNull[0] === "string" ? nonNull[0] : undefined; } return undefined; } /** Fields of an object schema (`properties`) or of a shorthand object. */ function normalizeObjectBody(body: Record, depth: number): FieldSpec[] { if (isJsonSchemaLike(body)) { const properties = isPlainObject(body.properties) ? body.properties : {}; const required = new Set( Array.isArray(body.required) ? body.required.filter((r) => typeof r === "string") : [], ); return Object.entries(properties).map(([name, prop]) => normalizeJsonProperty(name, prop, required.has(name), depth), ); } return Object.entries(body).map(([name, value]) => normalizeShorthand(name, value, depth)); } function normalizeJsonProperty( name: string, prop: unknown, required: boolean, depth: number, ): FieldSpec { if (!isPlainObject(prop)) { if (typeof prop === "string") return normalizeShorthand(name, prop, depth); throw new SchemaError(`property ${name} must be an object`); } const type = primaryType(prop.type) ?? (isPlainObject(prop.properties) ? "object" : "string"); const spec: FieldSpec = { name, type: "string", required }; if (Array.isArray(prop.type) && prop.type.includes("null")) spec.nullable = true; if (typeof prop.description === "string") spec.description = prop.description; const format = typeof prop.format === "string" ? normalizeFormat(prop.format) : undefined; const hint = prop["x-bxc-selector"]; if (typeof hint === "string" && hint.trim()) applySelectorHint(spec, hint); if (SCALARS.has(type)) { spec.type = type as ScalarType; if (format) spec.format = format; } else if (type === "array") { const items = isPlainObject(prop.items) ? prop.items : { type: "string" }; const itemType = primaryType(items.type) ?? "string"; if (!SCALARS.has(itemType)) { throw new SchemaError(`array property ${name} must contain scalars (got ${itemType})`); } spec.type = "array"; const itemFormat = typeof items.format === "string" ? normalizeFormat(items.format) : undefined; spec.items = { type: itemType as ScalarType, ...(itemFormat ? { format: itemFormat } : {}) }; } else if (type === "object") { if (depth >= 1) throw new SchemaError(`object property ${name} nests deeper than one level`); spec.type = "object"; spec.properties = normalizeObjectBody(prop, depth + 1); } else { throw new SchemaError(`unsupported type ${type} for property ${name}`); } return spec; } function normalizeShorthand(name: string, value: unknown, depth: number): FieldSpec { if (isPlainObject(value)) { if (isJsonSchemaLike(value)) return normalizeJsonProperty(name, value, true, depth); if (depth >= 1) throw new SchemaError(`object property ${name} nests deeper than one level`); return { name, type: "object", required: true, properties: normalizeObjectBody(value, depth + 1) }; } if (Array.isArray(value)) { if (value.length !== 1 || typeof value[0] !== "string") { throw new SchemaError(`shorthand array property ${name} must be [""]`); } return normalizeShorthand(name, `${value[0]}[]`, depth); } if (typeof value !== "string") throw new SchemaError(`shorthand property ${name} must be a type string`); let text = value.trim().toLowerCase(); let required = true; if (text.endsWith("?")) { required = false; text = text.slice(0, -1); } let isArray = false; if (text.endsWith("[]")) { isArray = true; text = text.slice(0, -2); } const scalar = SHORTHAND_TYPES[text]; if (!scalar) throw new SchemaError(`unknown shorthand type "${value}" for property ${name}`); if (isArray) return { name, type: "array", required, items: { ...scalar } }; return { name, required, ...scalar }; } function normalizeFormat(format: string): FieldFormat | undefined { const f = format.toLowerCase(); if (f === "url" || f === "uri-reference" || f === "iri") return "uri"; return FORMATS.has(f) ? (f as FieldFormat) : undefined; } function applySelectorHint(spec: FieldSpec, hint: string): void { const at = hint.lastIndexOf("@"); // `a[href@x]` style attribute values never contain a bare trailing `@attr`. if (at > 0 && /^[a-z_:][-a-z0-9_:.]*$/i.test(hint.slice(at + 1))) { spec.selector = hint.slice(0, at).trim(); spec.selectorAttribute = hint.slice(at + 1); } else { spec.selector = hint.trim(); } } function canonicalField(field: FieldSpec): unknown { return [ field.name, field.type, field.format ?? null, field.required, field.nullable ?? false, field.selector ?? null, field.selectorAttribute ?? null, field.items ? [field.items.type, field.items.format ?? null] : null, field.properties ? field.properties.map(canonicalField) : null, ]; } function hashFields(kind: string, fields: FieldSpec[]): string { return createHash("sha256") .update(JSON.stringify([kind, fields.map(canonicalField)])) .digest("hex") .slice(0, 16); } /** Scalar leaves of a schema (nested object properties are flattened). */ export function leafFields(schema: NormalizedSchema): LeafField[] { const out: LeafField[] = []; for (const field of schema.fields) { if (field.type === "object" && field.properties) { const childRequired = field.properties.some((p) => p.required); for (const child of field.properties) { out.push({ key: `${field.name}.${child.name}`, path: [field.name, child.name], spec: child, parent: field, required: field.required && (child.required || !childRequired), }); } } else { out.push({ key: field.name, path: [field.name], spec: field, required: field.required }); } } return out; } /** Leaves counted by the fill rate: required leaves, or every leaf when none is required. */ export function requiredLeaves(schema: NormalizedSchema): LeafField[] { const leaves = leafFields(schema); const required = leaves.filter((l) => l.required); return required.length > 0 ? required : leaves; } /** JSON Schema (draft-07) equivalent of a normalized schema, for LLM prompts and docs. */ export function toJsonSchema(schema: NormalizedSchema, only?: ReadonlySet): Record { const objectSchema = (fields: FieldSpec[], prefix: string): Record => { const properties: Record = {}; const required: string[] = []; for (const field of fields) { const key = prefix ? `${prefix}.${field.name}` : field.name; if (only && field.type !== "object" && !only.has(key)) continue; if (field.type === "object" && field.properties) { const nested = objectSchema(field.properties, key); if (only && Object.keys(nested.properties as object).length === 0) continue; properties[field.name] = nested; } else if (field.type === "array") { properties[field.name] = { type: "array", items: { type: field.items?.type ?? "string", ...(field.items?.format ? { format: field.items.format } : {}) }, }; } else { properties[field.name] = { type: [field.type, "null"], ...(field.format ? { format: field.format } : {}), ...(field.description ? { description: field.description } : {}), }; } if (field.required) required.push(field.name); } return { type: "object", properties, ...(required.length ? { required } : {}) }; }; const body = objectSchema(schema.fields, ""); return schema.kind === "list" ? { type: "array", items: body } : body; } // --------------------------------------------------------------------------- // Coercion // --------------------------------------------------------------------------- export interface CoerceContext { /** Page URL used to resolve relative URLs. */ baseUrl?: string; /** Reference time for relative dates ("3 hours ago"). Default `Date.now()`. */ now?: number; /** Treat `05/06/2026` as day-first. Default: `/` is month-first, `.` and `-` are day-first. */ dayFirst?: boolean; } /** Collapse whitespace (including NBSP and thin spaces) and trim. */ export function normalizeText(value: string): string { return value.replace(/[\s   ​]+/g, " ").trim(); } /** `"€1 299,00"` → 1299, `"$12.50"` → 12.5, `"1.2k"` → 1200, `"Sold out"` → null. */ export function coerceNumber(value: unknown): number | null { if (typeof value === "number") return Number.isFinite(value) ? value : null; if (typeof value === "boolean" || value === null || value === undefined) return null; const text = normalizeText(String(value)).replace(/−/g, "-"); const match = /([-+]?)\s?(\d[\d.,'’ ]*)(?:\s?([kmb])(?![a-z]))?/i.exec(text); if (!match) return null; let token = (match[2] ?? "").replace(/[\s'’]/g, "").replace(/[.,]+$/, ""); if (!token) return null; const lastDot = token.lastIndexOf("."); const lastComma = token.lastIndexOf(","); if (lastDot >= 0 && lastComma >= 0) { const decimal = lastDot > lastComma ? "." : ","; const thousands = decimal === "." ? "," : "."; token = token.split(thousands).join("").replace(decimal, "."); } else if (lastComma >= 0) { const parts = token.split(","); const thousandsGrouping = parts.length > 2 || (/^[1-9]\d{0,2}$/.test(parts[0] ?? "") && (parts[1] ?? "").length === 3); token = thousandsGrouping ? parts.join("") : parts.join("."); } else if (token.split(".").length > 2) { token = token.split(".").join(""); } let number = Number(token); if (!Number.isFinite(number)) return null; const suffix = (match[3] ?? "").toLowerCase(); if (suffix === "k") number *= 1e3; else if (suffix === "m") number *= 1e6; else if (suffix === "b") number *= 1e9; if (match[1] === "-") number = -number; return Math.round(number * 1e6) / 1e6; } export function coerceInteger(value: unknown): number | null { const number = coerceNumber(value); return number !== null && Number.isInteger(number) ? number : null; } const FALSE_PATTERNS = [ /\bsold[\s-]?out\b/, /\bout[\s-]?of[\s-]?stock\b/, /\boutofstock\b/, /\bunavailable\b/, /\bnot available\b/, /\bdiscontinued\b/, /épuisé/, /\brupture\b/, /\bindisponible\b/, /^(false|no|n|0|off|non|nein|✗|✘)$/, ]; const TRUE_PATTERNS = [ /\bin[\s-]?stock\b/, /\binstock\b/, /\bavailable\b/, /\ben stock\b/, /\bdisponible\b/, /\blimitedavailability\b/, /\bpreorder\b/, /^(true|yes|y|1|on|oui|ja|✓|✔)$/, ]; export function coerceBoolean(value: unknown): boolean | null { if (typeof value === "boolean") return value; if (typeof value === "number") return value !== 0; if (typeof value !== "string") return null; const text = normalizeText(value).toLowerCase(); if (!text) return null; if (FALSE_PATTERNS.some((re) => re.test(text))) return false; if (TRUE_PATTERNS.some((re) => re.test(text))) return true; return null; } const MONTHS: Record = {}; for (const [index, names] of [ ["jan", "january", "janv", "janvier", "januar", "enero", "ene"], ["feb", "february", "févr", "fevr", "février", "fevrier", "februar", "febrero"], ["mar", "march", "mars", "märz", "marz", "marzo"], ["apr", "april", "avr", "avril", "abril", "abr"], ["may", "mai", "mayo"], ["jun", "june", "juin", "juni", "junio"], ["jul", "july", "juil", "juillet", "juli", "julio"], ["aug", "august", "août", "aout", "agosto", "ago"], ["sep", "sept", "september", "septembre", "septiembre", "set"], ["oct", "october", "octobre", "oktober", "octubre", "okt"], ["nov", "november", "novembre", "noviembre"], ["dec", "december", "déc", "decembre", "décembre", "dezember", "diciembre", "dic", "dez"], ].entries()) { for (const name of names) MONTHS[name] = index + 1; } const RELATIVE_UNITS: Array<[RegExp, number]> = [ [/^(s|sec|secs|second|seconds|seconde|secondes)$/, 1_000], [/^(m|min|mins|minute|minutes)$/, 60_000], [/^(h|hr|hrs|hour|hours|heure|heures)$/, 3_600_000], [/^(d|day|days|jour|jours)$/, 86_400_000], [/^(w|wk|wks|week|weeks|semaine|semaines)$/, 7 * 86_400_000], [/^(mo|month|months|mois)$/, 30 * 86_400_000], [/^(y|yr|yrs|year|years|an|ans|année|années)$/, 365 * 86_400_000], ]; function validYmd(y: number, m: number, d: number): boolean { if (y < 1900 || y > 2200 || m < 1 || m > 12 || d < 1 || d > 31) return false; const date = new Date(Date.UTC(y, m - 1, d)); return date.getUTCMonth() === m - 1 && date.getUTCDate() === d; } function formatDate(ms: number, kind: "date" | "date-time"): string { const iso = new Date(ms).toISOString(); return kind === "date" ? iso.slice(0, 10) : iso.replace(/\.000Z$/, "Z"); } function timeOfDay(text: string): number { const match = /(\d{1,2}):(\d{2})(?::(\d{2}))?\s*([ap]\.?m\.?)?/i.exec(text); if (!match) { const bare = /\b(\d{1,2})\s*([ap])\.?m\b/i.exec(text); if (!bare) return 0; let hour = Number(bare[1]) % 12; if (bare[2]?.toLowerCase() === "p") hour += 12; return hour * 3_600_000; } let hour = Number(match[1]); const minute = Number(match[2]); const second = Number(match[3] ?? 0); const meridiem = match[4]?.toLowerCase().replace(/\./g, ""); if (meridiem === "pm" && hour < 12) hour += 12; if (meridiem === "am" && hour === 12) hour = 0; if (hour > 23 || minute > 59 || second > 59) return 0; return ((hour * 60 + minute) * 60 + second) * 1000; } /** * Parse common date spellings into `YYYY-MM-DD` (`date`) or an ISO-8601 UTC * timestamp (`date-time`). Dates without a zone are interpreted as UTC so * results do not depend on the host timezone. */ export function coerceDate( value: unknown, kind: "date" | "date-time" = "date", ctx: CoerceContext = {}, ): string | null { if (value instanceof Date) return Number.isFinite(value.getTime()) ? formatDate(value.getTime(), kind) : null; if (typeof value === "number") { if (!Number.isFinite(value)) return null; return formatDate(value < 1e11 ? value * 1000 : value, kind); } if (typeof value !== "string") return null; const text = normalizeText(value); if (!text) return null; const now = ctx.now ?? Date.now(); // ISO-8601 (optionally with time and zone). const iso = /^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2})(?::(\d{2})(?:\.\d+)?)?\s*(Z|[+-]\d{2}:?\d{2})?)?/.exec(text); if (iso) { const [y, m, d] = [Number(iso[1]), Number(iso[2]), Number(iso[3])]; if (!validYmd(y, m, d)) return null; if (!iso[4]) return formatDate(Date.UTC(y, m - 1, d), kind); const zone = iso[7] ? (iso[7] === "Z" ? "Z" : iso[7].replace(/^([+-]\d{2})(\d{2})$/, "$1:$2")) : "Z"; const stamp = `${iso[1]}-${iso[2]}-${iso[3]}T${iso[4]}:${iso[5]}:${iso[6] ?? "00"}${zone}`; const ms = Date.parse(stamp); return Number.isFinite(ms) ? formatDate(ms, kind) : null; } // Unix timestamps. if (/^\d{10}$/.test(text)) return formatDate(Number(text) * 1000, kind); if (/^\d{13}$/.test(text)) return formatDate(Number(text), kind); const lower = text.toLowerCase(); // Relative dates. if (/^(just now|now|à l'instant|maintenant)$/.test(lower)) return formatDate(now, kind); if (/^(today|aujourd'hui)\b/.test(lower)) return formatDate(now - (now % 86_400_000) + timeOfDay(lower), kind); if (/^(yesterday|hier)\b/.test(lower)) { return formatDate(now - (now % 86_400_000) - 86_400_000 + timeOfDay(lower), kind); } const relative = /(?:^|\b)(?:il y a\s+)?(an?|one|un|une|\d+)\s*([a-zéè]+)\.?\s*(?:ago)?$/i.exec(lower); if (relative && (/\bago$/.test(lower) || /^il y a\b/.test(lower))) { const amount = /^\d+$/.test(relative[1] ?? "") ? Number(relative[1]) : 1; const unit = RELATIVE_UNITS.find(([re]) => re.test(relative[2] ?? "")); if (unit) return formatDate(now - amount * unit[1], kind); } // Numeric y/m/d and d/m/y (or m/d/y). const ymd = /\b(\d{4})[./-](\d{1,2})[./-](\d{1,2})\b/.exec(text); if (ymd) { const [y, m, d] = [Number(ymd[1]), Number(ymd[2]), Number(ymd[3])]; if (validYmd(y, m, d)) return formatDate(Date.UTC(y, m - 1, d) + timeOfDay(text.slice(ymd.index + ymd[0].length)), kind); } const dmy = /\b(\d{1,2})([./-])(\d{1,2})\2(\d{4}|\d{2})\b/.exec(text); if (dmy) { const a = Number(dmy[1]); const b = Number(dmy[3]); let y = Number(dmy[4]); if (y < 100) y += y >= 70 ? 1900 : 2000; let dayFirst = ctx.dayFirst ?? dmy[2] !== "/"; if (a > 12) dayFirst = true; else if (b > 12) dayFirst = false; const [d, m] = dayFirst ? [a, b] : [b, a]; if (validYmd(y, m, d)) return formatDate(Date.UTC(y, m - 1, d) + timeOfDay(text.slice(dmy.index + dmy[0].length)), kind); } // Month names ("Sep 17, 2026", "17 septembre 2026", "September 17th 2026 10:30 AM"). const words = lower.match(/[a-zàâäçéèêëîïôöûüù]+\.?|\d+(?:st|nd|rd|th|er|e)?/g) ?? []; let month = 0; let day = 0; let year = 0; for (const word of words) { const bare = word.replace(/\.$/, ""); if (!month && MONTHS[bare] !== undefined) { month = MONTHS[bare] ?? 0; continue; } const num = /^(\d+)(?:st|nd|rd|th|er|e)?$/.exec(bare); if (!num) continue; const n = Number(num[1]); if ((num[1] ?? "").length === 4 && n >= 1900 && n <= 2200 && !year) year = n; else if (n >= 1 && n <= 31 && !day && (num[1] ?? "").length <= 2) day = n; } if (month && day) { if (!year) year = new Date(now).getUTCFullYear(); if (validYmd(year, month, day)) { const clock = text.replace(/\b\d{4}\b/, ""); return formatDate(Date.UTC(year, month - 1, day) + timeOfDay(clock), kind); } } if (month && year && !day && kind === "date") { return formatDate(Date.UTC(year, month - 1, 1), kind); } return null; } /** Resolve a URL (or the best `srcset` candidate) against the page URL. */ export function coerceUri(value: unknown, ctx: CoerceContext = {}): string | null { if (typeof value !== "string") return null; let text = value.trim(); if (!text || text === "#" || /^javascript:/i.test(text) || /^data:/i.test(text)) return null; if (/\s\d+(?:\.\d+)?[wx](?:\s*,|\s*$)/.test(text)) text = bestSrcsetCandidate(text) ?? text; if (/\s/.test(text) && !/^https?:\/\//i.test(text)) return null; try { return new URL(text, ctx.baseUrl).href; } catch { return ctx.baseUrl ? null : text; } } function bestSrcsetCandidate(srcset: string): string | null { let best: { url: string; weight: number } | null = null; for (const part of srcset.split(/,\s+/)) { const [url, descriptor] = part.trim().split(/\s+/); if (!url) continue; const weight = descriptor ? Number.parseFloat(descriptor) || 1 : 1; if (!best || weight > best.weight) best = { url, weight }; } return best?.url ?? null; } export function coerceEmail(value: unknown): string | null { if (typeof value !== "string") return null; const text = value.trim().replace(/^mailto:/i, "").split("?")[0] ?? ""; const match = /[^\s@<>()"',;:]+@[^\s@<>()"',;:]+\.[a-z]{2,}/i.exec(text); return match ? match[0] : null; } export function coerceString(value: unknown): string | null { if (value === null || value === undefined) return null; if (typeof value === "object") return null; const text = normalizeText(String(value)); return text ? text : null; } /** Coerce a scalar according to a type/format pair. */ export function coerceScalar( value: unknown, type: ScalarType, format: FieldFormat | undefined, ctx: CoerceContext = {}, ): string | number | boolean | null { switch (type) { case "number": return coerceNumber(value); case "integer": return coerceInteger(value); case "boolean": return coerceBoolean(value); default: switch (format) { case "uri": return coerceUri(value, ctx); case "date": case "date-time": return coerceDate(value, format, ctx); case "email": return coerceEmail(value); default: return coerceString(value); } } } /** Coerce a raw value (scalar, array or nested object) for `field`. */ export function coerceField(value: unknown, field: FieldSpec, ctx: CoerceContext = {}): unknown { if (field.type === "array") { const items = Array.isArray(value) ? value : value === null || value === undefined ? [] : [value]; const itemType = field.items?.type ?? "string"; const out = items .map((item) => coerceScalar(item, itemType, field.items?.format, ctx)) .filter((item) => item !== null); return out; } if (field.type === "object") { const source = isPlainObject(value) ? value : {}; const out: Record = {}; for (const child of field.properties ?? []) out[child.name] = coerceField(source[child.name], child, ctx); return out; } return coerceScalar(value, field.type, field.format, ctx); } /** Coerce every field of a record (unknown keys are dropped, missing ones become `null`). */ export function coerceRecord( record: Record, schema: NormalizedSchema, ctx: CoerceContext = {}, ): Record { const out: Record = {}; for (const field of schema.fields) out[field.name] = coerceField(record[field.name], field, ctx); return out; } // --------------------------------------------------------------------------- // Validation // --------------------------------------------------------------------------- export interface ValidationIssue { path: string; message: string; } export function isFilled(value: unknown): boolean { if (value === null || value === undefined) return false; if (typeof value === "string") return value.length > 0; if (Array.isArray(value)) return value.length > 0; if (isPlainObject(value)) return Object.values(value).some(isFilled); return true; } /** Value at a dotted leaf path of a record. */ export function valueAt(record: Record, path: readonly string[]): unknown { let current: unknown = record; for (const segment of path) { if (!isPlainObject(current)) return undefined; current = current[segment]; } return current; } function checkScalar(value: unknown, type: ScalarType, format: FieldFormat | undefined): string | null { switch (type) { case "number": return typeof value === "number" && Number.isFinite(value) ? null : "expected number"; case "integer": return typeof value === "number" && Number.isInteger(value) ? null : "expected integer"; case "boolean": return typeof value === "boolean" ? null : "expected boolean"; default: if (typeof value !== "string") return "expected string"; if (format === "date" && !/^\d{4}-\d{2}-\d{2}$/.test(value)) return "expected date (YYYY-MM-DD)"; if (format === "date-time" && !Number.isFinite(Date.parse(value))) return "expected date-time"; if (format === "email" && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)) return "expected email"; if (format === "uri" && !/^[a-z][a-z0-9+.-]*:/i.test(value)) return "expected absolute uri"; return null; } } /** Validate a coerced record: required leaves filled and every present value well-typed. */ export function validateRecord(record: Record, schema: NormalizedSchema): ValidationIssue[] { const issues: ValidationIssue[] = []; for (const leaf of leafFields(schema)) { const value = valueAt(record, leaf.path); if (!isFilled(value)) { const allowedNull = value === null && leaf.spec.nullable === true; if (leaf.required && !allowedNull) issues.push({ path: leaf.key, message: "required field is empty" }); continue; } if (leaf.spec.type === "array") { if (!Array.isArray(value)) { issues.push({ path: leaf.key, message: "expected array" }); continue; } for (const item of value) { const problem = checkScalar(item, leaf.spec.items?.type ?? "string", leaf.spec.items?.format); if (problem) issues.push({ path: leaf.key, message: problem }); } continue; } const problem = checkScalar(value, leaf.spec.type as ScalarType, leaf.spec.format); if (problem) issues.push({ path: leaf.key, message: problem }); } return issues; } /** Fraction of required leaves (all leaves when none is required) that are filled. */ export function fillRate(records: ReadonlyArray>, schema: NormalizedSchema): number { if (records.length === 0) return 0; const leaves = requiredLeaves(schema); if (leaves.length === 0) return 1; let filled = 0; for (const record of records) { for (const leaf of leaves) if (isFilled(valueAt(record, leaf.path))) filled++; } return filled / (records.length * leaves.length); }