import { describe, expect, test } from 'bun:test' import { readdirSync, readFileSync } from 'node:fs' import { join } from 'node:path' import { SUPPORTED_LOCALES } from '@gruperly/shared' import { NAMESPACES } from '../src/i18n/instance' /* es-AR es la fuente. Cada idioma tiene que tener exactamente las mismas claves (salvo las formas de plural, que dependen del idioma), sin textos vacíos y con las mismas variables de interpolación. */ const root = join(import.meta.dir, '../src/i18n/locales') const SOURCE = 'es-AR' const PLURAL_SUFFIX = /_(zero|one|two|few|many|other)$/ type Tree = { [key: string]: string | Tree } function load(locale: string, ns: string): Tree { return JSON.parse(readFileSync(join(root, locale, `${ns}.json`), 'utf8')) as Tree } function flatten(tree: Tree, prefix = ''): Map { const out = new Map() for (const [key, value] of Object.entries(tree)) { const path = prefix ? `${prefix}.${key}` : key if (typeof value === 'string') out.set(path, value) else for (const [k, v] of flatten(value, path)) out.set(k, v) } return out } /** Claves sin el sufijo de plural: `a_one` y `a_other` cuentan como `a`. */ function baseKeys(flat: Map): Set { return new Set([...flat.keys()].map((key) => key.replace(PLURAL_SUFFIX, ''))) } function variables(text: string): string[] { return [...text.matchAll(/\{\{\s*(\w+)\s*\}\}/g)].map((m) => m[1]!).sort() } function variablesByBase(flat: Map): Map { const out = new Map>() for (const [key, text] of flat) { const base = key.replace(PLURAL_SUFFIX, '') const set = out.get(base) ?? new Set() for (const v of variables(text)) set.add(v) out.set(base, set) } return new Map([...out].map(([k, v]) => [k, [...v].sort().join(',')])) } describe('traducciones', () => { test('cada namespace declarado tiene su JSON en todos los idiomas', () => { for (const locale of SUPPORTED_LOCALES) { const files = readdirSync(join(root, locale)).filter((f) => f.endsWith('.json')) expect(files.map((f) => f.slice(0, -5)).sort()).toEqual([...NAMESPACES].sort()) } }) for (const ns of NAMESPACES) { const source = flatten(load(SOURCE, ns)) for (const locale of SUPPORTED_LOCALES.filter((l) => l !== SOURCE)) { test(`${locale}/${ns} tiene las mismas claves y variables que ${SOURCE}`, () => { const target = flatten(load(locale, ns)) expect([...baseKeys(target)].sort()).toEqual([...baseKeys(source)].sort()) expect(Object.fromEntries(variablesByBase(target))).toEqual(Object.fromEntries(variablesByBase(source))) for (const [key, text] of target) expect({ key, empty: text.trim() === '' }).toEqual({ key, empty: false }) }) } } })