An open source design system that's fully customizable and agent ready
TypeScript
fix(i18n): validate ICU catalog contracts (#5188)
nynexman4464ac68796353a1
diff --git a/package.json b/package.jsonindex 9c5436a6eb..c9e46f3aee 100644--- a/package.json+++ b/package.json@@ -67,6 +67,7 @@"@eslint-react/eslint-plugin": "^5.10.4","@eslint/compat": "^2.1.0","@eslint/js": "^10.0.1",+ "@formatjs/icu-messageformat-parser": "^3.5.12","@playwright/test": "^1.61.1","@testing-library/user-event": "^14.5.0","@types/node": "^25.9.3",diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 44f22d2309..4c9f8e6b79 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -49,6 +49,9 @@ importers:'@eslint/js':specifier: ^10.0.1version: 10.0.1([email protected]([email protected]))+ '@formatjs/icu-messageformat-parser':+ specifier: ^3.5.12+ version: 3.5.12'@playwright/test':specifier: ^1.61.1version: 1.61.1diff --git a/scripts/check-i18n-catalog.mjs b/scripts/check-i18n-catalog.mjsindex 58d11d3434..5b526c3dd3 100644--- a/scripts/check-i18n-catalog.mjs+++ b/scripts/check-i18n-catalog.mjs@@ -9,10 +9,16 @@** 1. Source ⊆ catalog. Every `@astryx.*` key referenced in packages/core/src* and packages/lab/src exists in en.json.- * 2. Locale parity. Every shipped locale file has en.json's key set — extra- * keys fail (see LOCALE_MISSING_KEYS_ARE_FATAL for the missing direction).+ * 2. Locale parity. Translated catalogs may omit keys and fall back to en,+ * but extra keys are stale and fail.* 3. Every en.json entry carries a non-empty `description` — the only* context a Crowdin translator gets.+ * 4. Every source and translated message parses as ICU.+ * 5. Each translated message consumes the same argument and rich-text+ * contract as its source, ignoring literal text, argument order, and+ * locale-specific plural/selectordinal categories.+ * 6. Every named plural branch is reachable under that catalog's cardinal+ * or ordinal rules. Source findings fail; translation findings are notes.** Deliberately NOT checked: catalog keys with no call site. A shipped key is* public surface (consumers override any key through `overrides`), so an@@ -31,6 +37,7 @@ import fs from 'node:fs';import path from 'node:path';import {fileURLToPath} from 'node:url';import {createRequire} from 'node:module';+import {parse, TYPE} from '@formatjs/icu-messageformat-parser';const require = createRequire(import.meta.url);const ts = require('typescript');@@ -45,9 +52,9 @@ const LOCALES_DIR = 'packages/core/locales';* False, because a partial locale is the intended steady state, not a defect:* crowdin.yml sets `skip_untranslated_strings: true`, so Crowdin strips* untranslated keys out of every download, and `resolve.ts` falls back to en- * for them without warning. Making this fatal would fail `main` today (fr-FR- * carries 3 of 251 keys) and would red every translations PR. The other- * direction — a key a locale has and en does not — is always an error: en is+ * for them without warning. Making this fatal would reject every partially+ * translated catalog. The other direction — a key a locale has and en does+ * not — is always an error: en is* the source of truth, so an extra key is stale and will never be read.*/const LOCALE_MISSING_KEYS_ARE_FATAL = false;@@ -61,6 +68,342 @@ const TRANSLATOR_CALL_NAMES = new Set(['t', 'translator', 'translate']);const KEY_PREFIX = '@astryx.';+const ICU_ARGUMENT_KINDS = new Map([+ [TYPE.argument, 'argument'],+ [TYPE.number, 'number'],+ [TYPE.date, 'date'],+ [TYPE.time, 'time'],+]);++/** Parse one message with locations so syntax failures have stable diagnostics. */+function parseIcuMessage(message) {+ return parse(message, {captureLocation: true});+}++function formatIcuSyntaxError(error) {+ const start = error?.location?.start;+ const location = start+ ? ` at line ${start.line}, column ${start.column}`+ : '';+ const reason =+ error instanceof Error && error.message ? error.message : 'INVALID_MESSAGE';+ return `malformed ICU message${location}: ${reason}`;+}++function addUsage(group, name, kind, context, detail = '') {+ let usages = group.get(name);+ if (!usages) {+ usages = new Map();+ group.set(name, usages);+ }+ const usage = {kind, detail, context};+ usages.set(JSON.stringify([kind, detail, context]), usage);+}++/**+ * Reduce an ICU AST to the runtime value contract it consumes. Literal text and+ * sibling order are deliberately absent. Select option names remain part of+ * the contract, while plural categories do not: their valid sets are locale+ * dependent. Parent contexts retain nesting, including rich-text tags.+ */+function collectMessageContract(ast) {+ const contract = {+ arguments: new Map(),+ tags: new Map(),+ pounds: new Map(),+ };++ const walk = (elements, context = []) => {+ for (const element of elements) {+ if (element.type === TYPE.literal) continue;++ const simpleKind = ICU_ARGUMENT_KINDS.get(element.type);+ if (simpleKind) {+ addUsage(contract.arguments, element.value, simpleKind, context);+ continue;+ }++ if (element.type === TYPE.select) {+ const selectors = Object.keys(element.options).sort();+ addUsage(+ contract.arguments,+ element.value,+ 'select',+ context,+ `options=[${selectors.join(', ')}]`,+ );+ for (const selector of selectors) {+ walk(element.options[selector].value, [+ ...context,+ `select "${element.value}" option "${selector}"`,+ ]);+ }+ continue;+ }++ if (element.type === TYPE.plural) {+ const kind =+ element.pluralType === 'ordinal' ? 'selectordinal' : 'plural';+ const exactSelectors = Object.keys(element.options)+ .filter(selector => selector.startsWith('='))+ .sort();+ addUsage(+ contract.arguments,+ element.value,+ kind,+ context,+ `offset=${element.offset}; exact=[${exactSelectors.join(', ')}]`,+ );+ // Named categories and their counts vary by locale, so merge their+ // child contracts. Walk the mandatory `other` branch a second time with+ // its own context so a translation cannot move a required value, tag,+ // or pound placeholder into a locale-specific branch. Exact-value+ // selectors remain locale-independent runtime branches.+ for (const [selector, option] of Object.entries(element.options)) {+ const pluralContext = `${kind} "${element.value}"`;+ if (selector.startsWith('=')) {+ walk(option.value, [+ ...context,+ `${pluralContext} exact "${selector}"`,+ ]);+ continue;+ }++ walk(option.value, [...context, pluralContext]);+ if (selector === 'other') {+ walk(option.value, [...context, `${pluralContext} option "other"`]);+ }+ }+ continue;+ }++ if (element.type === TYPE.tag) {+ addUsage(contract.tags, element.value, 'tag', context);+ walk(element.children, [...context, `tag <${element.value}>`]);+ continue;+ }++ if (element.type === TYPE.pound) {+ addUsage(contract.pounds, '#', 'pound', context);+ }+ }+ };++ walk(ast);+ return contract;+}++function usageLabel({kind, detail, context}) {+ const suffix = detail ? ` (${detail})` : '';+ const location =+ context.length > 0 ? ` inside ${context.join(' > ')}` : ' at message root';+ return `${kind}${suffix}${location}`;+}++function compareUsageGroup(label, source, translation) {+ const problems = [];+ const sourceNames = [...source.keys()].sort();+ const translationNames = [...translation.keys()].sort();+ const missing = sourceNames.filter(name => !translation.has(name));+ const extra = translationNames.filter(name => !source.has(name));++ if (missing.length > 0) {+ problems.push(`missing ${label}(s): ${missing.join(', ')}`);+ }+ if (extra.length > 0) {+ problems.push(`extra ${label}(s): ${extra.join(', ')}`);+ }++ for (const name of sourceNames) {+ const sourceUsages = source.get(name);+ const translationUsages = translation.get(name);+ if (!translationUsages) continue;++ const sourceSignatures = [...sourceUsages.keys()].sort();+ const translationSignatures = [...translationUsages.keys()].sort();+ if (+ sourceSignatures.length === translationSignatures.length &&+ sourceSignatures.every(+ (signature, index) => signature === translationSignatures[index],+ )+ ) {+ continue;+ }++ const sourceKinds = [+ ...new Set([...sourceUsages.values()].map(usage => usage.kind)),+ ].sort();+ const translationKinds = [+ ...new Set([...translationUsages.values()].map(usage => usage.kind)),+ ].sort();+ const sameKinds =+ sourceKinds.length === translationKinds.length &&+ sourceKinds.every((kind, index) => kind === translationKinds[index]);++ if (!sameKinds) {+ problems.push(+ `${label} "${name}" has incompatible kind: expected ${sourceKinds.join(+ ' + ',+ )}; found ${translationKinds.join(' + ')}`,+ );+ continue;+ }++ const expected = [...sourceUsages.values()]+ .map(usageLabel)+ .sort()+ .join(' | ');+ const found = [...translationUsages.values()]+ .map(usageLabel)+ .sort()+ .join(' | ');+ problems.push(+ `${label} "${name}" has incompatible structure: expected ${expected}; found ${found}`,+ );+ }++ return problems;+}++/** Compare parsed messages without comparing literal text or sibling order. */+function compareMessageContracts(sourceAst, translationAst) {+ const source = collectMessageContract(sourceAst);+ const translation = collectMessageContract(translationAst);+ return [+ ...compareUsageGroup('argument', source.arguments, translation.arguments),+ ...compareUsageGroup('rich-text tag', source.tags, translation.tags),+ ...compareUsageGroup(+ 'pound placeholder',+ source.pounds,+ translation.pounds,+ ),+ ];+}++/**+ * Resolve the cardinal and ordinal category sets supplied by this Node runtime.+ * Locale identifiers rejected by `Intl.Locale` and valid-but-unsupported+ * identifiers stay distinct so the caller can explain why category validation+ * was skipped.+ */+function pluralRulesFor(locale) {+ let canonicalLocale;+ try {+ canonicalLocale = new Intl.Locale(locale).toString();+ } catch {+ return {+ status: 'invalid',+ reason: `locale identifier "${locale}" is not accepted by Intl.Locale`,+ };+ }++ if (Intl.PluralRules.supportedLocalesOf([canonicalLocale]).length === 0) {+ return {+ status: 'unsupported',+ reason: `this Node runtime has no plural-rule data for "${locale}"`,+ };+ }++ const cardinal = new Intl.PluralRules(canonicalLocale, {type: 'cardinal'});+ const ordinal = new Intl.PluralRules(canonicalLocale, {type: 'ordinal'});+ return {+ status: 'supported',+ cardinal: new Set([...cardinal.resolvedOptions().pluralCategories].sort()),+ ordinal: new Set([...ordinal.resolvedOptions().pluralCategories].sort()),+ };+}++function classifyLocalePluralRules(file) {+ const locale = path.basename(file, '.json');+ const pluralRules = pluralRulesFor(locale);+ if (pluralRules.status === 'supported') return {pluralRules};++ if (pluralRules.status === 'invalid') {+ return {+ pluralRules,+ error: {+ title: `${file}: invalid locale filename`,+ lines: [pluralRules.reason],+ hint: 'Rename the catalog to a locale identifier accepted by Intl.Locale.',+ },+ };+ }++ return {+ pluralRules,+ note:+ `${file}: plural categories unchecked — ${pluralRules.reason}; ` ++ 'ICU syntax and source contracts were still validated',+ };+}++/** Find unreachable named categories throughout a parsed ICU message. */+function collectPluralCategoryProblems(ast, pluralRules) {+ if (pluralRules?.status !== 'supported') return [];++ const problems = [];+ const walk = elements => {+ for (const element of elements) {+ if (element.type === TYPE.plural) {+ const ordinal = element.pluralType === 'ordinal';+ const syntax = ordinal ? 'selectordinal' : 'plural';+ const ruleType = ordinal ? 'ordinal' : 'cardinal';+ const valid = ordinal ? pluralRules.ordinal : pluralRules.cardinal;+ for (const selector of Object.keys(element.options).sort()) {+ if (!selector.startsWith('=') && !valid.has(selector)) {+ problems.push(+ `${syntax} argument "${element.value}" uses unreachable ${ruleType} category "${selector}" ` ++ `(valid: ${[...valid].join(', ')})`,+ );+ }+ }+ }++ if (element.options) {+ for (const selector of Object.keys(element.options).sort()) {+ walk(element.options[selector].value);+ }+ }+ if (element.children) walk(element.children);+ }+ };++ walk(ast);+ return problems;+}++/**+ * Parse once, then share that AST between contract and plural validation.+ * Unsupported locale data suppresses only plural findings: syntax and source+ * contract checks still run.+ */+function analyzeIcuMessage(+ message,+ {sourceAst = null, pluralRules = null, isSource = false} = {},+) {+ let ast;+ try {+ ast = parseIcuMessage(message);+ } catch (error) {+ return {+ ast: null,+ syntaxError: formatIcuSyntaxError(error),+ contractProblems: [],+ pluralErrors: [],+ pluralNotes: [],+ };+ }++ const pluralProblems = collectPluralCategoryProblems(ast, pluralRules);+ return {+ ast,+ syntaxError: null,+ contractProblems: sourceAst ? compareMessageContracts(sourceAst, ast) : [],+ pluralErrors: isSource ? pluralProblems : [],+ pluralNotes: isSource ? [] : pluralProblems,+ };+}+/** Mirrors scripts/check-use-client.mjs — source files only, no tests,* stories, docs, or perf fixtures (those legitimately name absent keys). */function walk(dir) {@@ -286,6 +629,60 @@ function main() {// 1. Source ⊆ catalogconst catalog = readJson(path.join(ROOT, LOCALES_DIR, 'en.json'));const enKeys = new Set(Object.keys(catalog));+ const sourceAsts = new Map();++ const catalogProblems = validateSourceCatalog(catalog);+ if (catalogProblems.length > 0) {+ errors.push({+ title: `${catalogProblems.length} en.json entry problem(s)`,+ lines: catalogProblems,+ hint: 'A description is the only context a Crowdin translator gets.',+ });+ }++ const sourceIcuProblems = [];+ const sourcePluralProblems = [];+ const enPluralRules = pluralRulesFor('en');+ for (const key of [...enKeys].sort()) {+ const message = catalog[key]?.defaultMessage;+ if (typeof message !== 'string' || message === '') continue;++ const analysis = analyzeIcuMessage(message, {+ pluralRules: enPluralRules,+ isSource: true,+ });+ if (analysis.syntaxError) {+ sourceIcuProblems.push(`${key}: ${analysis.syntaxError}`);+ continue;+ }++ sourceAsts.set(key, analysis.ast);+ for (const problem of analysis.pluralErrors) {+ sourcePluralProblems.push(`${key}: ${problem}`);+ }+ }+ if (sourceIcuProblems.length > 0) {+ errors.push({+ title: `en.json: ${sourceIcuProblems.length} invalid ICU message(s)`,+ lines: sourceIcuProblems,+ hint: 'Fix ICU syntax before translations are compared.',+ });+ }+ if (enPluralRules.status !== 'supported') {+ errors.push({+ title: 'en.json: plural categories could not be checked',+ lines: [enPluralRules.reason],+ hint: 'Use the repository-pinned Node version with full ICU data.',+ });+ }+ if (sourcePluralProblems.length > 0) {+ errors.push({+ title: `en.json: ${sourcePluralProblems.length} unreachable plural category finding(s)`,+ lines: sourcePluralProblems,+ hint: 'Intl.PluralRules never selects these branches for English.',+ });+ }+const missingRefs = [];const unverifiable = [];let refCount = 0;@@ -325,6 +722,7 @@ function main() {.filter(f => f.endsWith('.json') && !NOT_A_SHIPPED_LOCALE.has(f)).sort();+ let translatedMessageCount = 0;for (const file of localeFiles) {const localeCatalog = readJson(path.join(ROOT, LOCALES_DIR, file));const {missing, extra} = compareLocale(enKeys, Object.keys(localeCatalog));@@ -343,16 +741,52 @@ function main() {notes.push(summary);}}- }- // 3. Translator context- const catalogProblems = validateSourceCatalog(catalog);- if (catalogProblems.length > 0) {- errors.push({- title: `${catalogProblems.length} en.json entry problem(s)`,- lines: catalogProblems,- hint: 'A description is the only context a Crowdin translator gets.',- });+ const localeIcuProblems = [];+ const localePluralNotes = [];+ const {+ pluralRules: localePluralRules,+ error: localeRuleError,+ note: localeRuleNote,+ } = classifyLocalePluralRules(file);+ if (localeRuleError) errors.push(localeRuleError);+ if (localeRuleNote) notes.push(localeRuleNote);++ for (const key of Object.keys(localeCatalog).sort()) {+ const message = localeCatalog[key]?.defaultMessage;+ if (typeof message !== 'string' || message === '') {+ localeIcuProblems.push(`${key}: missing or empty "defaultMessage"`);+ continue;+ }++ translatedMessageCount += 1;+ const analysis = analyzeIcuMessage(message, {+ sourceAst: sourceAsts.get(key),+ pluralRules: localePluralRules,+ });+ if (analysis.syntaxError) {+ localeIcuProblems.push(`${key}: ${analysis.syntaxError}`);+ continue;+ }++ for (const problem of analysis.contractProblems) {+ localeIcuProblems.push(`${key}: ${problem}`);+ }+ for (const problem of analysis.pluralNotes) {+ localePluralNotes.push(`${key}: ${problem}`);+ }+ }++ if (localeIcuProblems.length > 0) {+ errors.push({+ title: `${file}: ${localeIcuProblems.length} ICU message problem(s)`,+ lines: localeIcuProblems,+ hint: 'Keep the translated message syntax valid and its runtime value contract aligned with en.json.',+ });+ }+ for (const problem of localePluralNotes) {+ notes.push(`${file}: ${problem}`);+ }}if (unverifiable.length > 0) {@@ -376,7 +810,9 @@ function main() {console.log(`✓ check:i18n-catalog — ${seen.size} key(s) over ${refCount} reference(s) resolve; ` +- `${enKeys.size} en entries described; ${localeFiles.length} locale(s) consistent`,+ `${enKeys.size} en and ${translatedMessageCount} translated message(s) parsed and contract-checked; ` ++ `plural categories evaluated with runtime CLDR ${process.versions.cldr}; ` ++ `${localeFiles.length} locale(s) consistent`,);for (const note of notes) console.log(` · ${note}`);}@@ -386,4 +822,15 @@ if (process.argv[1] === fileURLToPath(import.meta.url)) {main();}-export {extractKeyRefs, validateSourceCatalog, compareLocale};+export {+ extractKeyRefs,+ validateSourceCatalog,+ compareLocale,+ parseIcuMessage,+ formatIcuSyntaxError,+ collectMessageContract,+ compareMessageContracts,+ pluralRulesFor,+ classifyLocalePluralRules,+ analyzeIcuMessage,+};diff --git a/scripts/check-i18n-catalog.test.mjs b/scripts/check-i18n-catalog.test.mjsindex 3f69030ae6..b3495d2d81 100644--- a/scripts/check-i18n-catalog.test.mjs+++ b/scripts/check-i18n-catalog.test.mjs@@ -6,7 +6,8 @@* counts as a key reference: the AST walk has to see the keys a regex would* miss (a key behind a module constant) and ignore the ones a regex would* invent (a key in a comment or an unrelated string), and it has to declare a- * key it cannot resolve rather than pass it.+ * key it cannot resolve rather than pass it. It also pins ICU syntax,+ * message-contract, locale-severity, and plural-category behavior.*/import {describe, it, expect} from 'vitest';@@ -14,6 +15,11 @@ import {extractKeyRefs,validateSourceCatalog,compareLocale,+ parseIcuMessage,+ compareMessageContracts,+ pluralRulesFor,+ classifyLocalePluralRules,+ analyzeIcuMessage,} from './check-i18n-catalog.mjs';const keys = source => extractKeyRefs(source, 'Test.tsx').refs.map(r => r.key);@@ -191,3 +197,287 @@ describe('compareLocale', () => {});});});++const contractProblems = (source, translation) =>+ compareMessageContracts(+ parseIcuMessage(source),+ parseIcuMessage(translation),+ );++describe('ICU message contracts', () => {+ it('allows arguments to be reordered without comparing literal text', () => {+ expect(+ contractProblems(+ 'Hello {first} {last}, balance {balance, number}',+ 'Solde {balance, number} — {last}, {first}',+ ),+ ).toEqual([]);+ });++ it('allows locale-specific cardinal and ordinal categories', () => {+ expect(+ contractProblems(+ '{count, plural, one {{owner} has one item} other {{owner} has # items}} ' ++ '{rank, selectordinal, one {#st} other {#th}}',+ '{rank, selectordinal, few {#e} many {#e} other {#e}} — ' ++ '{count, plural, one {{owner} a un élément} few {{owner} a # éléments} many {{owner} a # éléments} other {{owner} a # éléments}}',+ ),+ ).toEqual([]);+ });++ it.each([+ ['source', 'Hello {name'],+ ['translation', '{count, plural, one {Un}}'],+ ])('reports malformed %s ICU deterministically', (catalog, message) => {+ const {syntaxError} = analyzeIcuMessage(message);+ expect(`${catalog}: ${syntaxError}`).toMatch(+ new RegExp(+ `^${catalog}: malformed ICU message at line 1, column \\d+: [A-Z_]+$`,+ ),+ );+ });++ it('reports missing and extra arguments', () => {+ expect(contractProblems('Hello {name}', 'Hello {account}')).toEqual([+ 'missing argument(s): name',+ 'extra argument(s): account',+ ]);+ });++ it('reports an incompatible argument kind', () => {+ expect(+ contractProblems('Total: {value, number}', 'Date: {value, date}'),+ ).toEqual([+ 'argument "value" has incompatible kind: expected number; found date',+ ]);+ });++ it('preserves nested select, plural, and rich-text structure', () => {+ const source =+ '{count, plural, one {<strong>{owner}</strong> has one item} ' ++ 'other {<strong>{owner}</strong> has # items for {audience, select, public {everyone} other {{viewer}}}}}';+ const reorderedTranslation =+ '{count, plural, few {{audience, select, public {tous} other {{viewer}}}: <strong>{owner}</strong> a # éléments} ' ++ 'other {{audience, select, public {tous} other {{viewer}}}: <strong>{owner}</strong> a # éléments}}';+ expect(contractProblems(source, reorderedTranslation)).toEqual([]);++ const movedOutOfTag =+ '{count, plural, one {{owner} <strong>a un élément</strong>} ' ++ 'other {{owner} <strong>a # éléments</strong> pour {audience, select, public {tous} other {{viewer}}}}}';+ expect(contractProblems(source, movedOutOfTag)).toContain(+ 'argument "owner" has incompatible structure: expected argument inside plural "count" > tag <strong> | argument inside plural "count" option "other" > tag <strong>; found argument inside plural "count" | argument inside plural "count" option "other"',+ );+ });++ it.each([+ ['argument', '{owner}', 'fallback'],+ ['rich-text tag', '<strong>value</strong>', 'fallback'],+ ['pound placeholder', '# items', 'items'],+ ])(+ 'requires the plural other branch to retain its %s contract',+ (_kind, sourceValue, translationValue) => {+ const problems = contractProblems(+ `{count, plural, one {${sourceValue}} other {${sourceValue}}}`,+ `{count, plural, one {${sourceValue}} other {${translationValue}}}`,+ );+ expect(problems).toHaveLength(1);+ expect(problems[0]).toContain('option "other"');+ },+ );++ it('requires nested plural other branches to retain their contracts', () => {+ const source =+ '{choice, select, nested {{count, plural, one {{owner}} other {{owner}}}} other {fallback}}';+ const translation =+ '{choice, select, nested {{count, plural, one {{owner}} other {fallback}}} other {fallback}}';+ const problems = contractProblems(source, translation);++ expect(problems).toHaveLength(1);+ expect(problems[0]).toContain(+ 'select "choice" option "nested" > plural "count" option "other"',+ );+ });++ it('keeps pound placeholders in the nested contract', () => {+ expect(+ contractProblems(+ '{count, plural, one {One} other {# items}}',+ '{count, plural, one {Un} other {éléments}}',+ ),+ ).toEqual(['missing pound placeholder(s): #']);+ });++ it('distinguishes cardinal plurals from selectordinal', () => {+ expect(+ contractProblems(+ '{count, plural, one {One} other {Items}}',+ '{count, selectordinal, one {First} other {Later}}',+ ),+ ).toEqual([+ 'argument "count" has incompatible kind: expected plural; found selectordinal',+ ]);+ });++ it('keeps exact plural selectors in the contract', () => {+ expect(+ contractProblems(+ '{count, plural, =0 {None} other {# items}}',+ '{count, plural, =1 {Un} other {# éléments}}',+ ),+ ).toEqual([+ 'argument "count" has incompatible structure: expected plural (offset=0; exact=[=0]) at message root; found plural (offset=0; exact=[=1]) at message root',+ ]);+ });++ it('keeps select option names in the contract', () => {+ expect(+ contractProblems(+ '{tone, select, formal {Welcome} other {Hi}}',+ '{tone, select, casual {Salut} other {Bonjour}}',+ ),+ ).toEqual([+ 'argument "tone" has incompatible structure: expected select (options=[formal, other]) at message root; found select (options=[casual, other]) at message root',+ ]);+ });+});++describe('ICU plural categories', () => {+ const rulesFor = locale => {+ const rules = pluralRulesFor(locale);+ expect(rules.status).toBe('supported');+ return rules;+ };++ const messageWith = (syntax, selector) =>+ `{count, ${syntax}, ${selector} {named} other {fallback}}`;++ it.each([+ ['en', 'plural', 'few', false],+ ['en', 'selectordinal', 'two', true],+ ['ar', 'plural', 'zero', true],+ ['ar', 'selectordinal', 'zero', false],+ ])(+ '%s %s category %s has the expected reachability',+ (locale, syntax, selector, reachable) => {+ const result = analyzeIcuMessage(messageWith(syntax, selector), {+ pluralRules: rulesFor(locale),+ isSource: true,+ });+ expect(result.pluralErrors).toHaveLength(reachable ? 0 : 1);+ },+ );++ it('accepts every cardinal category reported by Intl.PluralRules', () => {+ const rules = rulesFor('en');+ const options = [...rules.cardinal]+ .map(category => `${category} {${category}}`)+ .join(' ');+ const result = analyzeIcuMessage(`{count, plural, ${options}}`, {+ pluralRules: rules,+ isSource: true,+ });+ expect(result.pluralErrors).toEqual([]);+ });++ it('distinguishes cardinal categories from ordinal categories', () => {+ const rules = rulesFor('en');+ const ordinalOnly = [...rules.ordinal].find(+ category => !rules.cardinal.has(category),+ );+ expect(ordinalOnly).toBeDefined();++ const cardinal = analyzeIcuMessage(messageWith('plural', ordinalOnly), {+ pluralRules: rules,+ isSource: true,+ });+ const ordinal = analyzeIcuMessage(+ messageWith('selectordinal', ordinalOnly),+ {pluralRules: rules, isSource: true},+ );+ expect(cardinal.pluralErrors).toHaveLength(1);+ expect(cardinal.pluralErrors[0]).toContain(+ `unreachable cardinal category "${ordinalOnly}"`,+ );+ expect(ordinal.pluralErrors).toEqual([]);+ });++ it('descends into plurals nested under other ICU nodes', () => {+ const rules = rulesFor('en');+ const message =+ '{choice, select, nested {' ++ messageWith('plural', 'unreachable') ++ '} other {fallback}}';+ const result = analyzeIcuMessage(message, {+ pluralRules: rules,+ isSource: true,+ });+ expect(result.pluralErrors).toHaveLength(1);+ expect(result.pluralErrors[0]).toContain('"unreachable"');+ });++ it('exempts exact selectors', () => {+ const result = analyzeIcuMessage(+ '{count, plural, =99 {exact} other {fallback}}',+ {pluralRules: rulesFor('en'), isSource: true},+ );+ expect(result.pluralErrors).toEqual([]);+ });++ it('does not treat a select option named many as a plural category', () => {+ const result = analyzeIcuMessage(+ '{choice, select, many {several} other {fallback}}',+ {pluralRules: rulesFor('en'), isSource: true},+ );+ expect(result.pluralErrors).toEqual([]);+ });++ it('makes source findings fatal and translation findings notes', () => {+ const message = messageWith('plural', 'unreachable');+ const pluralRules = rulesFor('en');+ const source = analyzeIcuMessage(message, {+ pluralRules,+ isSource: true,+ });+ const translation = analyzeIcuMessage(message, {pluralRules});++ expect(source.pluralErrors).toHaveLength(1);+ expect(source.pluralNotes).toEqual([]);+ expect(translation.pluralErrors).toEqual([]);+ expect(translation.pluralNotes).toHaveLength(1);+ });++ it('keeps unsupported locale data nonfatal but rejects malformed filenames', () => {+ const unsupported = classifyLocalePluralRules('xx-YY.json');+ expect(unsupported).toMatchObject({+ pluralRules: {status: 'unsupported'},+ note: expect.stringContaining('plural categories unchecked'),+ });+ expect(unsupported.error).toBeUndefined();++ const invalid = classifyLocalePluralRules('x-private.json');+ expect(invalid).toMatchObject({+ pluralRules: {status: 'invalid'},+ error: {+ title: 'x-private.json: invalid locale filename',+ lines: ['locale identifier "x-private" is not accepted by Intl.Locale'],+ },+ });+ expect(invalid.note).toBeUndefined();+ });++ it('does not let an unsupported locale mask syntax or contract errors', () => {+ const pluralRules = pluralRulesFor('xx-YY');+ expect(pluralRules.status).toBe('unsupported');++ const syntax = analyzeIcuMessage('Hello {name', {pluralRules});+ expect(syntax.syntaxError).toMatch(/^malformed ICU message/);++ const contract = analyzeIcuMessage('{value, date}', {+ sourceAst: parseIcuMessage('{value, number}'),+ pluralRules,+ });+ expect(contract.contractProblems).toEqual([+ 'argument "value" has incompatible kind: expected number; found date',+ ]);+ });+});