Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 69 additions & 0 deletions scripts/i18n.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,75 @@ test('rich-text validation preserves attributed and self-closing tags', () => {
)
})

test('rich-text validation catches renumbered numbered tags, broken nesting, and stricter HTML/comment tags', () => {
// Valid numbered tags and valid sibling reorder pass.
expect(validateTranslation('<0>Open</0> <1>docs</1>', '<1>docs</1> <0>Ouvrir</0>', 'fr')).toEqual(
[],
)
// Math comparison with space is not mistaken for a tag.
expect(validateTranslation('Width < 5 m', 'Largeur < 5 m', 'fr')).toEqual([])

// Renumbered tags fail.
expect(validateTranslation('<0>Open</0>', '<1>Ouvrir</1>', 'fr')).toContain(
'rich-text tags differ from English',
)

// Broken nesting fails even when the sorted tag set matches English.
expect(validateTranslation('<0><1>Open</1></0>', '<0><1>Ouvrir</0></1>', 'fr')).toContain(
'broken rich-text tag nesting',
)
expect(validateTranslation('<0>Open</0>', '</0>Ouvrir<0>', 'fr')).toContain(
'broken rich-text tag nesting',
)
expect(
validateTranslation(
'<a href="/docs"><b>Open</b></a>',
'<a href="/docs"><b>Ouvrir</a></b>',
'fr',
),
).toContain('broken rich-text tag nesting')

// Stricter tag check catches slash-separated HTML tags, comments, and unclosed tags.
for (const injected of [
'Ouvrir <img/src=x onerror=alert(1)>',
'Ouvrir <svg/onload=alert(1)>',
'Ouvrir <!-- injected -->',
'Ouvrir <img/src=x',
]) {
expect(validateTranslation('Open', injected, 'fr')).toContain(
'rich-text tags differ from English',
)
}
})

test('ICU select validation catches removed branches and missing other branches', () => {
const english = '{gender, select, male {He} female {She} other {They}}'

expect(
validateTranslation(english, '{gender, select, male {Il} female {Elle} other {Ils}}', 'fr'),
).toEqual([])
expect(validateTranslation(english, '{gender, select, male {Il} other {Ils}}', 'fr')).toContain(
'select selector "gender" is missing branch "female"',
)
expect(validateTranslation(english, '{gender, select, male {Il} female {Elle}}', 'fr')).toContain(
'select selector "gender" is missing branch "other"',
)
expect(
validateTranslation(
'{gender, select, male {He} female {She}}',
'{gender, select, male {Il} female {Elle}}',
'fr',
),
).toContain('select selector "gender" is missing "other"')
expect(
validateTranslation(
'{count, plural, one {# item} other {# items}}',
'{count, plural, one {# élément}}',
'fr',
),
).toContain('plural selector "count" is missing "other"')
})

test('source drift fails checking, then extraction updates English and flags translations', () => {
const root = catalogProject()
const sample = join(root, 'packages/editor/src/sample.tsx')
Expand Down
107 changes: 101 additions & 6 deletions scripts/i18n.ts
Original file line number Diff line number Diff line change
Expand Up @@ -193,9 +193,17 @@ function variableNames(tokens: CompiledToken[]): string[] {
return [...names].sort()
}

function tags(message: string): string[] {
function extractTags(message: string): string[] {
const found: string[] = []
for (let start = message.indexOf('<'); start >= 0; start = message.indexOf('<', start + 1)) {
const next = message[start + 1]
if (!next) continue
// Treat any `<` followed by a letter, `!`, or `/` as a tag (catches `<img/src=...>`,
// `<svg/onload=...>`, `<!-- -->`, and closing tags), plus Lingui numbered tags (`<0>`, `<0/>`).
const isStrictTagStart = /[A-Za-z!/]/.test(next)
const isNumericTagStart = /\d/.test(next)
if (!(isStrictTagStart || isNumericTagStart)) continue

let quote: '"' | "'" | undefined
let end = start + 1
for (; end < message.length; end += 1) {
Expand All @@ -208,11 +216,44 @@ function tags(message: string): string[] {
break
}
}
if (end >= message.length) continue
if (end >= message.length) {
if (isStrictTagStart) found.push(message.slice(start))
continue
}
const token = message.slice(start, end + 1)
if (/^<\s*\/?\s*[A-Za-z][\w-]*(?:\s|\/?>)/.test(token)) found.push(token)
if (isStrictTagStart || /^<\d+\s*\/?>$/.test(token)) {
found.push(token)
}
}
return found.sort()
return found
}

function tags(message: string): string[] {
return extractTags(message).sort()
}

function tagNestingErrors(orderedTags: readonly string[]): string[] {
const stack: string[] = []
for (const token of orderedTags) {
if (!token.endsWith('>')) return ['malformed rich-text tag']
if (token.startsWith('<!')) continue
if (token.endsWith('/>')) continue
const closeMatch = /^<\/\s*([A-Za-z0-9][\w-]*)\s*>$/.exec(token)
if (closeMatch) {
const name = closeMatch[1]!
if (stack.length === 0 || stack[stack.length - 1] !== name) {
return ['broken rich-text tag nesting']
}
stack.pop()
continue
}
const openMatch = /^<\s*([A-Za-z0-9][\w-]*)(?:[\s/>]|$)/.exec(token)
if (openMatch) {
stack.push(openMatch[1]!)
}
}
if (stack.length > 0) return ['broken rich-text tag nesting']
return []
}

function plurals(tokens: CompiledToken[]): Map<string, { type: string; categories: Set<string> }> {
Expand Down Expand Up @@ -242,6 +283,26 @@ function plurals(tokens: CompiledToken[]): Map<string, { type: string; categorie
return found
}

function selects(tokens: CompiledToken[]): Map<string, Set<string>> {
const found = new Map<string, Set<string>>()
const visit = (entries: CompiledToken[]) => {
for (const token of entries) {
if (typeof token === 'string') continue
const type = token[1]
const choices = token[2]
if (type === 'select' && choices && typeof choices === 'object') {
found.set(token[0], new Set(Object.keys(choices)))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Select parser overwrites duplicate selectors

Low Severity

selects stores each selector name with Map.set, so a later select with the same name replaces the earlier branch set. Validation then only checks that last occurrence. A translation can drop branches from an earlier or nested select of the same name and still pass, including the new missing-branch checks.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 32ec36e. Configure here.

}
if (!(choices && typeof choices === 'object')) continue
for (const branch of Object.values(choices)) {
if (Array.isArray(branch)) visit(branch as CompiledToken[])
}
}
}
visit(tokens)
return found
}

function requiredPluralCategories(locale: string, type: string): Intl.LDMLPluralRule[] {
return new Intl.PluralRules(locale, {
type: type === 'selectordinal' ? 'ordinal' : 'cardinal',
Expand Down Expand Up @@ -300,9 +361,11 @@ export function validateTranslation(
) {
errors.push('placeholder names differ from English')
}
if (JSON.stringify(tags(source)) !== JSON.stringify(tags(translation))) {
const translatedOrderedTags = extractTags(translation)
if (JSON.stringify(tags(source)) !== JSON.stringify([...translatedOrderedTags].sort())) {
errors.push('rich-text tags differ from English')
}
errors.push(...tagNestingErrors(translatedOrderedTags))

const sourcePlurals = plurals(sourceTokens)
const translatedPlurals = plurals(translatedTokens)
Expand All @@ -312,12 +375,44 @@ export function validateTranslation(
errors.push(`plural selector "${name}" is missing or changed`)
continue
}
for (const category of requiredPluralCategories(locale, sourcePlural.type)) {
const required = new Set<string>([
...requiredPluralCategories(locale, sourcePlural.type),
'other',
])
for (const category of required) {
if (!translatedPlural.categories.has(category)) {
errors.push(`plural selector "${name}" is missing "${category}"`)
}
}
}
for (const [name, translatedPlural] of translatedPlurals) {
if (!sourcePlurals.has(name) && !translatedPlural.categories.has('other')) {
errors.push(`plural selector "${name}" is missing "other"`)
}
}

const sourceSelects = selects(sourceTokens)
const translatedSelects = selects(translatedTokens)
for (const [name, sourceBranches] of sourceSelects) {
const translatedBranches = translatedSelects.get(name)
if (!translatedBranches) {
errors.push(`select selector "${name}" is missing or changed`)
continue
}
for (const branch of sourceBranches) {
if (!translatedBranches.has(branch)) {
errors.push(`select selector "${name}" is missing branch "${branch}"`)
}
}
if (!translatedBranches.has('other')) {
errors.push(`select selector "${name}" is missing "other"`)
}
}
for (const [name, translatedBranches] of translatedSelects) {
if (!sourceSelects.has(name) && !translatedBranches.has('other')) {
errors.push(`select selector "${name}" is missing "other"`)
}
}
errors.push(...validateGlossary(source, translation, locale, glossary))
return errors
}
Expand Down