import { DEFAULT_MESSAGES } from "./defaultMessages"; export type MessageParams = Record; export type Translate = (code: string, params?: MessageParams) => string; /** Replace {key} placeholders; unknown placeholders are left untouched. */ export function interpolate(template: string, params?: MessageParams): string { if (!params) return template; return template.replace(/\{(\w+)\}/g, (match, key) => Object.prototype.hasOwnProperty.call(params, key) ? String(params[key]) : match, ); } // services-system's message.code column is case-insensitive (utf8mb3_general_ci): a legacy row keyed // SIGNIN is the same code as SignIn, and an insert of SignIn is skipped because SIGNIN exists. The // catalog arrives as a case-sensitive JSON map, so a miss on the exact key retries case-insensitively. // The lower-cased view is built once per catalog object. const folded = new WeakMap, Map>(); function lookupIgnoringCase(catalog: Record, code: string): string | undefined { let byLower = folded.get(catalog); if (!byLower) { byLower = new Map(Object.entries(catalog).map(([key, value]) => [key.toLowerCase(), value])); folded.set(catalog, byLower); } return byLower.get(code.toLowerCase()); } /** Resolve a code: active-locale catalog (exact, then any case) -> built-in English default -> raw code. */ export function resolveMessage( catalog: Record, code: string, params?: MessageParams, ): string { const raw = catalog[code] ?? lookupIgnoringCase(catalog, code) ?? DEFAULT_MESSAGES[code] ?? code; return interpolate(raw, params); }