Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : Vrai-Prix8 * File : src/lib/cost/ai/schema.ts9 * Module : lib10 * Repository : https://git.spboucher.ai/vrai-prix11 * Created : 2026-09-0812 * Last Modified : 2026-09-0813 *14 * Author : Simon-Pierre Boucher15 * Position : Professor of Finance16 * Institution : Université du Québec en Outaouais (UQO)17 * Organization : SP Boucher18 * Website : https://spboucher.ai19 * Git : https://git.spboucher.ai20 *21 * Preferred Contact: contact@spboucher.ai22 * Development : dev@spboucher.ai23 * Support : support@spboucher.ai24 * Security/Admin : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142/**43 * Property Technical JSON (§95-118) : types TypeScript, JSON Schema STRICT44 * (outil Claude, additionalProperties:false, required complet) et validateur /45 * réparateur déterministe maison (aucune dépendance). Module PUR.46 *47 * Le modèle ne produit que la partie TECHNIQUE (`ModelOutput`) ; le code48 * ajoute `metadata` et `listing` (données connues), la géométrie dérivée et49 * les quantités calculables par formule (§193).50 */51import { MATERIALS } from "../taxonomy";5253export const SCHEMA_VERSION = "1.0";54export const PROMPT_VERSION = "v1";5556/* ------------------------------------------------------------------ types */5758export type EvidenceSource = "listing" | "MAMH" | "photo" | "derived" | "ai_estimated" | "assumed" | "unknown";59export type MechStatus = "observed" | "listing" | "inferred" | "unknown";60export type QualityLevel = "economy" | "standard" | "superior" | "prestige" | "custom_luxury";61export type ConditionLevel = "poor" | "below_average" | "average" | "good" | "very_good" | "excellent" | "renovated" | "new";6263export interface StrAttr { value: string | null; confidence: number; source: EvidenceSource; evidence: string[] }64export interface NumAttr { value: number | null; confidence: number; source: EvidenceSource; evidence: string[] }65export interface BoolAttr { value: boolean | null; confidence: number; source: EvidenceSource; evidence: string[] }66export interface Qty { value: number | null; unit: string; confidence: number; source: EvidenceSource; method: string | null; evidence: string[] }67export interface MechAttr { value: string | null; status: MechStatus; confidence: number; evidence: string[] }6869export interface KitchenAnalysis { location: string | null; quality: QualityLevel | null; cabinet_type: string | null; countertop: string | null; island: boolean | null; estimated_cabinet_linear_ft: number | null; estimated_countertop_sqft: number | null; estimated_backsplash_sqft: number | null; condition: ConditionLevel | null; confidence: number; evidence: string[] }70export interface BathroomAnalysis { type: "full" | "powder" | "ensuite" | "unknown"; quality: QualityLevel | null; tub: string | null; shower: string | null; double_vanity: boolean | null; tile_extent: string | null; fixtures_quality: QualityLevel | null; estimated_area_sqft: number | null; estimated_tile_sqft: number | null; condition: ConditionLevel | null; confidence: number; evidence: string[] }71export interface RenovationHint { component: string; renovation_likelihood: number; estimated_renovation_age_range: number[]; evidence: string[] }72export interface AssemblyHint { assembly_code: string; quantity: number | null; unit: string; confidence: number; evidence: string[] }7374export interface ModelOutput {75 property: {76 building_type: StrAttr; year_built: NumAttr; stories: NumAttr; gross_floor_area_sqft: NumAttr; bedrooms: NumAttr; bathrooms: NumAttr; powder_rooms: NumAttr; dwelling_units: NumAttr;77 };78 geometry: { footprint_sqft: NumAttr; roof_area_sqft: NumAttr; exterior_wall_area_sqft: NumAttr; perimeter_ft: NumAttr; roof_pitch_rise_per_12: NumAttr };79 construction: { foundation: StrAttr; structural_system: StrAttr; floor_system: StrAttr; wall_system: StrAttr; roof_system_type: StrAttr; roof_geometry: StrAttr; insulation_level: StrAttr; building_envelope: StrAttr };80 exterior: {81 primary_siding: StrAttr; secondary_siding: StrAttr; siding_shares: { brick_pct: number; vinyl_pct: number; fiber_cement_pct: number; wood_pct: number; stone_pct: number; stucco_pct: number; metal_pct: number; other_pct: number };82 windows_type: StrAttr; window_count_estimate: Qty; exterior_doors_count: Qty; roof_covering: StrAttr; gutters: BoolAttr; balconies_count: Qty; decks_count: Qty; exterior_stairs: StrAttr;83 };84 interior: { flooring_types: { material: string; share_pct: number; evidence: string[] }[]; wall_finish: StrAttr; ceiling_finish: StrAttr; trim_quality: StrAttr; door_quality: StrAttr; stair_quality: StrAttr; fireplace: StrAttr; built_ins: BoolAttr; ceiling_height_ft: NumAttr };85 kitchens: KitchenAnalysis[];86 bathrooms: BathroomAnalysis[];87 mechanical: { heat_source: MechAttr; heat_distribution: MechAttr; heat_pump: MechAttr; air_conditioning: MechAttr; air_exchanger: MechAttr; water_heater: MechAttr; fireplace: MechAttr; boiler: MechAttr; furnace: MechAttr };88 electrical: { panel_type: MechAttr; panel_capacity_amps: NumAttr; service_type: MechAttr; visible_age: MechAttr; ev_charger: MechAttr; generator: MechAttr; lighting_quality: MechAttr; smart_home: MechAttr };89 plumbing: { water_supply: MechAttr; waste_system: MechAttr; visible_pipe_type: MechAttr; fixtures_quality: MechAttr; laundry: MechAttr };90 basement: { state: StrAttr; estimated_finished_pct: NumAttr; quality: StrAttr; ceiling_type: StrAttr; flooring: StrAttr; bathroom: BoolAttr; bedrooms: NumAttr };91 garage: { type: StrAttr; spaces: NumAttr; area_estimate_sqft: NumAttr; finished: BoolAttr; heated: BoolAttr; door_count: NumAttr };92 exterior_improvements: { deck_sqft: Qty; patio_sqft: Qty; pool: StrAttr; spa: BoolAttr; shed: BoolAttr; fence_linear_ft: Qty; driveway_type: StrAttr; driveway_sqft: Qty; landscaping_quality: StrAttr; retaining_wall: BoolAttr; outdoor_kitchen: BoolAttr };93 quality: { exterior_quality: QualityLevel | null; interior_quality: QualityLevel | null; kitchen_quality: QualityLevel | null; bathroom_quality: QualityLevel | null; mechanical_quality: QualityLevel | null; overall_quality: QualityLevel | null; confidence: number };94 condition: { roof: ConditionLevel | null; windows: ConditionLevel | null; exterior: ConditionLevel | null; interior: ConditionLevel | null; kitchen: ConditionLevel | null; bathrooms: ConditionLevel | null; basement: ConditionLevel | null; mechanical: ConditionLevel | null; electrical: ConditionLevel | null; structure: ConditionLevel | null; site: ConditionLevel | null; confidence: number };95 estimated_effective_age: { chronological_age: number | null; effective_age: number | null; economic_life: number | null; confidence: number; reasoning_summary: string[] };96 renovations: RenovationHint[];97 estimated_quantities: { window_count: Qty; kitchen_cabinets_linear_ft: Qty; countertop_sqft: Qty; backsplash_sqft: Qty; bathroom_tile_sqft: Qty; deck_sqft: Qty; driveway_sqft: Qty; fence_linear_ft: Qty; garage_area_sqft: Qty; finished_basement_pct: Qty; interior_door_count: Qty };98 assemblies: AssemblyHint[];99 uncertainties: string[];100 privacy: { people_visible: boolean; documents_visible: boolean; licence_plates_visible: boolean };101 confidence: { overall: number; construction: number; exterior: number; interior: number; mechanical: number; quantities: number };102}103104export interface AnalysisMetadata { analysis_id: string; listing_id: string; listing_source: string; model: string; prompt_version: string; schema_version: string; analysis_timestamp: string; image_count: number; input_hash: string; input_token_estimate: number | null; output_tokens: number | null; latency_ms: number | null }105export interface AnalysisListing { address: string | null; municipality: string | null; region: string | null; asking_price: number; listing_date: string | null; description_excerpt: string | null; bedrooms: number | null; bathrooms: number | null; powder_rooms: number | null; lot_area_sqft: number | null; living_area_sqft: number | null; year_built: number | null; property_type: string | null; url: string | null; unit_id: string | null }106export interface ImageManifestEntry { id: string; position: number; room_hint: string; source_url: string; hash: string; width: number | null; height: number | null }107108export interface PropertyTechnicalAnalysis extends ModelOutput {109 metadata: AnalysisMetadata;110 listing: AnalysisListing;111 images: ImageManifestEntry[];112 /** géométrie recalculée par le code (source derived) — remplace les valeurs IA quand une formule existe */113 derived_geometry: { footprint_sqft: number; perimeter_ft: number; exposed_perimeter_ft: number; gross_wall_sqft: number; net_wall_sqft: number; roof_sqft: number; window_count: number; basement_floor_sqft: number; basement_finished_sqft: number; garage_sqft: number; formulas: Record<string, string> };114}115116/* ----------------------------------------------------------- JSON Schema */117118type JS = Record<string, unknown>;119const NUM_NULL: JS = { type: ["number", "null"] };120const STR_NULL: JS = { type: ["string", "null"] };121const BOOL_NULL: JS = { type: ["boolean", "null"] };122const CONF: JS = { type: "number", minimum: 0, maximum: 1, description: "0.0 to 1.0" };123const EVID: JS = { type: "array", items: { type: "string" } };124const SRC: JS = { type: "string", enum: ["listing", "MAMH", "photo", "derived", "ai_estimated", "assumed", "unknown"] };125const MECH_STATUS: JS = { type: "string", enum: ["observed", "listing", "inferred", "unknown"] };126export const QUALITY_ENUM = ["economy", "standard", "superior", "prestige", "custom_luxury"] as const;127export const CONDITION_ENUM = ["poor", "below_average", "average", "good", "very_good", "excellent", "renovated", "new"] as const;128const QUAL_NULL: JS = nullableEnum(QUALITY_ENUM);129const COND_NULL: JS = nullableEnum(CONDITION_ENUM);130131/** Énumération nullable en mode strict : `anyOf` (un `enum` mixte string/null est refusé par l'API). */132function nullableEnum(values: readonly string[], desc?: string): JS {133 return { anyOf: [{ type: "string", enum: [...values] }, { type: "null" }], ...(desc ? { description: desc } : {}) };134}135function obj(props: Record<string, JS>): JS {136 return { type: "object", properties: props, required: Object.keys(props), additionalProperties: false };137}138const strAttr = (values?: readonly string[], desc?: string): JS => obj({ value: values ? nullableEnum(values, desc) : { ...STR_NULL, ...(desc ? { description: desc } : {}) }, confidence: CONF, source: SRC, evidence: EVID });139const numAttr = (desc?: string): JS => obj({ value: { ...NUM_NULL, ...(desc ? { description: desc } : {}) }, confidence: CONF, source: SRC, evidence: EVID });140const boolAttr = (desc?: string): JS => obj({ value: { ...BOOL_NULL, ...(desc ? { description: desc } : {}) }, confidence: CONF, source: SRC, evidence: EVID });141const qty = (unit: string, desc: string): JS => obj({ value: { ...NUM_NULL, description: desc }, unit: { type: "string", enum: [unit] }, confidence: CONF, source: SRC, method: STR_NULL, evidence: EVID });142const mech = (values?: readonly string[]): JS => obj({ value: values ? nullableEnum(values) : STR_NULL, status: MECH_STATUS, confidence: CONF, evidence: EVID });143144export const BUILDING_TYPE_ENUM = ["detached", "semi_detached", "row", "plex", "condo", "chalet", "mobile", "other"] as const;145export const FOUNDATION_ENUM = ["poured_concrete", "concrete_block", "slab_on_grade", "piers", "stone", "unknown"] as const;146export const STRUCTURE_ENUM = ["wood_frame", "steel", "concrete", "log", "masonry", "unknown"] as const;147export const ROOF_TYPE_ENUM = ["asphalt_shingle", "metal", "membrane", "cedar", "slate_tile", "unknown"] as const;148export const ROOF_GEOM_ENUM = ["gable", "hip", "flat", "mansard", "complex", "unknown"] as const;149export const SIDING_ENUM = ["vinyl", "brick", "fiber_cement", "wood", "stone", "stucco", "aluminum", "steel", "unknown"] as const;150export const WINDOW_ENUM = ["pvc", "hybrid", "aluminum", "wood", "unknown"] as const;151export const BASEMENT_ENUM = ["none", "crawl", "unfinished", "partially_finished", "finished", "walkout", "unknown"] as const;152export const GARAGE_ENUM = ["none", "attached", "detached", "integrated", "carport", "unknown"] as const;153export const HEAT_SOURCE_ENUM = ["electricity", "natural_gas", "propane", "oil", "wood", "geothermal", "dual_energy", "unknown"] as const;154export const HEAT_DIST_ENUM = ["baseboards", "forced_air", "radiant_floor", "hydronic_radiators", "heat_pump_wall", "convectors", "unknown"] as const;155export const POOL_ENUM = ["none", "above_ground", "inground", "unknown"] as const;156export const DRIVEWAY_ENUM = ["asphalt", "pavers", "gravel", "concrete", "none", "unknown"] as const;157const FLOOR_MATERIALS = ["hardwood", "engineered_wood", "vinyl_plank", "laminate_floor", "ceramic_tile", "porcelain_tile", "carpet", "concrete_floor", "unknown"] as const;158159export function buildModelSchema(assemblyCodes: string[]): JS {160 return obj({161 property: obj({162 building_type: strAttr(BUILDING_TYPE_ENUM, "Type de bâtiment"), year_built: numAttr("Année de construction"), stories: numAttr("Nombre d'étages hors sous-sol"), gross_floor_area_sqft: numAttr("Aire d'étages hors sous-sol (pi²)"),163 bedrooms: numAttr(), bathrooms: numAttr("Salles de bain complètes"), powder_rooms: numAttr("Salles d'eau"), dwelling_units: numAttr("Nombre de logements"),164 }),165 geometry: obj({ footprint_sqft: numAttr("Empreinte au sol (pi²) — seulement si observable"), roof_area_sqft: numAttr(), exterior_wall_area_sqft: numAttr(), perimeter_ft: numAttr(), roof_pitch_rise_per_12: numAttr("Pente du toit (élévation sur 12)") }),166 construction: obj({167 foundation: strAttr(FOUNDATION_ENUM), structural_system: strAttr(STRUCTURE_ENUM), floor_system: strAttr(), wall_system: strAttr(), roof_system_type: strAttr(ROOF_TYPE_ENUM, "Type de couverture"), roof_geometry: strAttr(ROOF_GEOM_ENUM), insulation_level: strAttr(), building_envelope: strAttr(),168 }),169 exterior: obj({170 primary_siding: strAttr(SIDING_ENUM), secondary_siding: strAttr(SIDING_ENUM),171 siding_shares: obj({ brick_pct: { type: "number" }, vinyl_pct: { type: "number" }, fiber_cement_pct: { type: "number" }, wood_pct: { type: "number" }, stone_pct: { type: "number" }, stucco_pct: { type: "number" }, metal_pct: { type: "number" }, other_pct: { type: "number" } }),172 windows_type: strAttr(WINDOW_ENUM), window_count_estimate: qty("unit", "Nombre total de fenêtres estimé"), exterior_doors_count: qty("unit", "Portes extérieures (hors porte-patio et garage)"), roof_covering: strAttr(ROOF_TYPE_ENUM), gutters: boolAttr(), balconies_count: qty("unit", "Balcons"), decks_count: qty("unit", "Terrasses"), exterior_stairs: strAttr(),173 }),174 interior: obj({175 flooring_types: { type: "array", items: obj({ material: { type: "string", enum: [...FLOOR_MATERIALS] }, share_pct: { type: "number" }, evidence: EVID }) },176 wall_finish: strAttr(), ceiling_finish: strAttr(), trim_quality: strAttr(), door_quality: strAttr(), stair_quality: strAttr(), fireplace: strAttr(), built_ins: boolAttr(), ceiling_height_ft: numAttr(),177 }),178 kitchens: { type: "array", items: obj({ location: STR_NULL, quality: QUAL_NULL, cabinet_type: nullableEnum(["melamine", "thermofoil", "painted_mdf", "wood_veneer", "solid_wood", "laminate", "unknown"]), countertop: nullableEnum(["quartz", "granite", "laminate", "butcher_block", "solid_surface", "marble", "unknown"]), island: BOOL_NULL, estimated_cabinet_linear_ft: NUM_NULL, estimated_countertop_sqft: NUM_NULL, estimated_backsplash_sqft: NUM_NULL, condition: COND_NULL, confidence: CONF, evidence: EVID }) },179 bathrooms: { type: "array", items: obj({ type: { type: "string", enum: ["full", "powder", "ensuite", "unknown"] }, quality: QUAL_NULL, tub: STR_NULL, shower: STR_NULL, double_vanity: BOOL_NULL, tile_extent: STR_NULL, fixtures_quality: QUAL_NULL, estimated_area_sqft: NUM_NULL, estimated_tile_sqft: NUM_NULL, condition: COND_NULL, confidence: CONF, evidence: EVID }) },180 mechanical: obj({ heat_source: mech(HEAT_SOURCE_ENUM), heat_distribution: mech(HEAT_DIST_ENUM), heat_pump: mech(["central", "wall_mounted", "none", "unknown"]), air_conditioning: mech(["central", "wall_unit", "none", "unknown"]), air_exchanger: mech(["present", "absent", "unknown"]), water_heater: mech(), fireplace: mech(), boiler: mech(), furnace: mech() }),181 electrical: obj({ panel_type: mech(), panel_capacity_amps: numAttr(), service_type: mech(), visible_age: mech(), ev_charger: mech(["present", "absent", "unknown"]), generator: mech(["present", "absent", "unknown"]), lighting_quality: mech(), smart_home: mech() }),182 plumbing: obj({ water_supply: mech(["municipal", "well", "unknown"]), waste_system: mech(["municipal", "septic", "unknown"]), visible_pipe_type: mech(), fixtures_quality: mech(), laundry: mech() }),183 basement: obj({ state: strAttr(BASEMENT_ENUM), estimated_finished_pct: numAttr("0-100"), quality: strAttr(QUALITY_ENUM), ceiling_type: strAttr(), flooring: strAttr(), bathroom: boolAttr(), bedrooms: numAttr() }),184 garage: obj({ type: strAttr(GARAGE_ENUM), spaces: numAttr(), area_estimate_sqft: numAttr(), finished: boolAttr(), heated: boolAttr(), door_count: numAttr() }),185 exterior_improvements: obj({ deck_sqft: qty("pi2", "Terrasse(s), surface totale"), patio_sqft: qty("pi2", "Patio/dalle"), pool: strAttr(POOL_ENUM), spa: boolAttr(), shed: boolAttr(), fence_linear_ft: qty("pi_lin", "Clôture"), driveway_type: strAttr(DRIVEWAY_ENUM), driveway_sqft: qty("pi2", "Entrée"), landscaping_quality: strAttr(QUALITY_ENUM), retaining_wall: boolAttr(), outdoor_kitchen: boolAttr() }),186 quality: obj({ exterior_quality: QUAL_NULL, interior_quality: QUAL_NULL, kitchen_quality: QUAL_NULL, bathroom_quality: QUAL_NULL, mechanical_quality: QUAL_NULL, overall_quality: QUAL_NULL, confidence: CONF }),187 condition: obj({ roof: COND_NULL, windows: COND_NULL, exterior: COND_NULL, interior: COND_NULL, kitchen: COND_NULL, bathrooms: COND_NULL, basement: COND_NULL, mechanical: COND_NULL, electrical: COND_NULL, structure: COND_NULL, site: COND_NULL, confidence: CONF }),188 estimated_effective_age: obj({ chronological_age: NUM_NULL, effective_age: NUM_NULL, economic_life: NUM_NULL, confidence: CONF, reasoning_summary: { type: "array", items: { type: "string" }, description: "Faits observés, factuels et courts (pas de raisonnement interne)" } }),189 renovations: { type: "array", items: obj({ component: { type: "string" }, renovation_likelihood: CONF, estimated_renovation_age_range: { type: "array", items: { type: "number" } }, evidence: EVID }) },190 estimated_quantities: obj({191 window_count: qty("unit", "Fenêtres"), kitchen_cabinets_linear_ft: qty("pi_lin", "Armoires de cuisine (base + haut)"), countertop_sqft: qty("pi2", "Comptoirs"), backsplash_sqft: qty("pi2", "Dosseret"), bathroom_tile_sqft: qty("pi2", "Carrelage des salles de bain"),192 deck_sqft: qty("pi2", "Terrasse"), driveway_sqft: qty("pi2", "Entrée"), fence_linear_ft: qty("pi_lin", "Clôture"), garage_area_sqft: qty("pi2", "Garage"), finished_basement_pct: qty("pct", "Part du sous-sol finie"), interior_door_count: qty("unit", "Portes intérieures"),193 }),194 assemblies: { type: "array", items: obj({ assembly_code: { type: "string", enum: assemblyCodes }, quantity: NUM_NULL, unit: { type: "string" }, confidence: CONF, evidence: EVID }) },195 uncertainties: { type: "array", items: { type: "string" } },196 privacy: obj({ people_visible: { type: "boolean" }, documents_visible: { type: "boolean" }, licence_plates_visible: { type: "boolean" } }),197 confidence: obj({ overall: CONF, construction: CONF, exterior: CONF, interior: CONF, mechanical: CONF, quantities: CONF }),198 });199}200201/* ------------------------------------------------- validation / réparation */202203export interface ValidationIssue { path: string; message: string; repaired: boolean }204205/**206 * Valide `data` contre un schéma (sous-ensemble JSON Schema : type, enum,207 * properties/required/additionalProperties, items, minimum/maximum) et208 * répare de façon déterministe : champ manquant → null / défaut, chaîne209 * numérique → nombre, énumération inconnue → null, confiance hors [0,1] →210 * bornée, clé inconnue → supprimée. Retourne l'objet réparé et les anomalies.211 */212export function validateAndRepair(data: unknown, schema: JS, path = "$"): { value: unknown; issues: ValidationIssue[] } {213 const issues: ValidationIssue[] = [];214 const value = walk(data, schema, path, issues);215 return { value, issues };216}217218/**219 * Sections de premier niveau absentes de la sortie du modèle (`$.property`,220 * `$.exterior`…). Le réparateur les remplit de nulls, mais une sortie où221 * plusieurs sections manquent n'est PAS une analyse : c'est typiquement un appel222 * d'outil « placeholder » (`{"property_analysis":{"placeholder":true}}`, observé223 * avec Sonnet 5 en tool_choice forcé, 2026-09-08). À traiter comme un échec224 * dur → relance, jamais comme une analyse complète.225 */226export function missingTopLevelSections(issues: ValidationIssue[]): string[] {227 return issues.filter((i) => i.repaired && i.message === "champ manquant" && /^\$\.[a-z_]+$/.test(i.path)).map((i) => i.path.slice(2));228}229230/** Seuil au-delà duquel une sortie est jugée vide (placeholder) : ≥ 3 sections manquantes. */231export const MAX_MISSING_SECTIONS = 2;232233function typeList(schema: JS): string[] {234 const t = schema.type;235 return Array.isArray(t) ? (t as string[]) : typeof t === "string" ? [t] : [];236}237238function defaultFor(schema: JS): unknown {239 const types = typeList(schema);240 if (types.includes("null")) return null;241 if (types.includes("object")) return walk({}, schema, "$", []);242 if (types.includes("array")) return [];243 if (types.includes("number") || types.includes("integer")) return typeof schema.minimum === "number" ? schema.minimum : 0;244 if (types.includes("boolean")) return false;245 if (Array.isArray(schema.enum) && schema.enum.length) return schema.enum[0];246 return "";247}248249function walk(v: unknown, schema: JS, path: string, issues: ValidationIssue[]): unknown {250 if (Array.isArray(schema.anyOf)) {251 const branches = schema.anyOf as JS[];252 const nullBranch = branches.find((b) => typeList(b).includes("null"));253 const main = branches.find((b) => !typeList(b).includes("null")) ?? branches[0];254 if (v == null) { if (nullBranch) return null; issues.push({ path, message: "champ manquant", repaired: true }); return defaultFor(main); }255 const before = issues.length;256 const out = walk(v, main, path, issues);257 if (issues.length > before && nullBranch && Array.isArray(main.enum) && !main.enum.includes(v)) return null;258 return out;259 }260 const types = typeList(schema);261 const nullable = types.includes("null");262 if (v === undefined) {263 issues.push({ path, message: "champ manquant", repaired: true });264 return defaultFor(schema);265 }266 if (v === null) {267 if (nullable) return null;268 issues.push({ path, message: "null non permis", repaired: true });269 return defaultFor(schema);270 }271 if (types.includes("object")) {272 if (typeof v !== "object" || Array.isArray(v)) { issues.push({ path, message: "objet attendu", repaired: true }); return walk({}, schema, path, issues); }273 const props = (schema.properties ?? {}) as Record<string, JS>;274 const out: Record<string, unknown> = {};275 const src = v as Record<string, unknown>;276 for (const [k, ps] of Object.entries(props)) out[k] = walk(src[k], ps, `${path}.${k}`, issues);277 for (const k of Object.keys(src)) if (!(k in props)) issues.push({ path: `${path}.${k}`, message: "clé inconnue supprimée", repaired: true });278 return out;279 }280 if (types.includes("array")) {281 if (!Array.isArray(v)) { issues.push({ path, message: "tableau attendu", repaired: true }); return []; }282 const it = schema.items as JS | undefined;283 return it ? v.map((x, i) => walk(x, it, `${path}[${i}]`, issues)).filter((x) => x !== undefined) : v;284 }285 if (types.includes("number") || types.includes("integer")) {286 let n = typeof v === "number" ? v : typeof v === "string" && v.trim() !== "" && Number.isFinite(Number(v.replace(",", "."))) ? Number(v.replace(",", ".")) : NaN;287 if (typeof v === "string" && Number.isFinite(n)) issues.push({ path, message: `nombre en texte « ${v} » converti`, repaired: true });288 if (!Number.isFinite(n)) {289 if (nullable) { issues.push({ path, message: `nombre attendu (${JSON.stringify(v)})`, repaired: true }); return null; }290 issues.push({ path, message: `nombre attendu (${JSON.stringify(v)}) → 0`, repaired: true });291 n = 0;292 }293 if (typeof schema.minimum === "number" && n < schema.minimum) { issues.push({ path, message: `borne min ${schema.minimum}`, repaired: true }); n = schema.minimum; }294 if (typeof schema.maximum === "number" && n > schema.maximum) { issues.push({ path, message: `borne max ${schema.maximum}`, repaired: true }); n = schema.maximum; }295 if (types.includes("integer")) n = Math.round(n);296 return n;297 }298 if (types.includes("boolean")) {299 if (typeof v === "boolean") return v;300 if (v === "true" || v === "false") { issues.push({ path, message: "booléen texte", repaired: true }); return v === "true"; }301 issues.push({ path, message: "booléen attendu", repaired: true });302 return nullable ? null : false;303 }304 if (types.includes("string")) {305 const s = typeof v === "string" ? v : String(v);306 if (typeof v !== "string") issues.push({ path, message: "chaîne attendue (converti)", repaired: true });307 if (Array.isArray(schema.enum) && !schema.enum.includes(s)) {308 issues.push({ path, message: `valeur hors énumération « ${s} »`, repaired: true });309 return nullable ? null : (schema.enum.find((e) => e === "unknown") ?? schema.enum[0]);310 }311 return s;312 }313 return v;314}315316/**317 * Version du schéma acceptée par l'API en mode strict : `minimum`/`maximum`318 * ne sont pas supportés pour les nombres → retirés (le validateur local, lui,319 * les applique pour borner les confiances).320 */321export function schemaForApi(schema: JS): JS {322 const strip = (x: unknown): unknown => {323 if (Array.isArray(x)) return x.map(strip);324 if (x && typeof x === "object") {325 const out: Record<string, unknown> = {};326 for (const [k, v] of Object.entries(x as Record<string, unknown>)) {327 if (k === "minimum" || k === "maximum") continue;328 out[k] = strip(v);329 }330 return out;331 }332 return x;333 };334 return strip(schema) as JS;335}336337/** Vrai si `data` respecte strictement le schéma (aucune réparation nécessaire). */338export function isValid(data: unknown, schema: JS): boolean {339 return validateAndRepair(data, schema).issues.length === 0;340}341342export const KNOWN_MATERIALS: readonly string[] = MATERIALS;343