Skip to content

Commit 8609c1a

Browse files
committed
chore(i18n): add i18n key lint rule and interpolation check
1 parent b1ea428 commit 8609c1a

8 files changed

Lines changed: 223 additions & 35 deletions

File tree

‎.github/workflows/code-qa.yml‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,8 @@ jobs:
6868
uses: ./.github/actions/setup-node-pnpm
6969
- name: Verify all translations are complete
7070
run: node scripts/find-missing-translations.js
71+
- name: Verify t() calls pass every interpolation variable
72+
run: node scripts/check-i18n-interpolation.js
7173

7274
knip:
7375
runs-on: ubuntu-latest
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
// i18next splits a namespace from a key on ":" only. t("chat.foo") has no namespace, so it looks in the
2+
// default namespace, misses, and shows the raw key to the user. Built-in no-restricted-syntax only.
3+
import { readdirSync } from "node:fs"
4+
import { basename } from "node:path"
5+
6+
/**
7+
* @param {URL | string} enLocalesDir The `en` locale directory. Each JSON file name is a namespace.
8+
*/
9+
export function createI18nDotKeyConfig(enLocalesDir) {
10+
const namespaces = readdirSync(enLocalesDir)
11+
.filter((file) => file.endsWith(".json"))
12+
.map((file) => basename(file, ".json"))
13+
const dotKey = `/^(${namespaces.join("|")})\\./`
14+
const message = "Write the key as 'namespace:path'. A dot after the namespace is not a namespace separator."
15+
16+
return {
17+
files: ["**/*.ts", "**/*.tsx"],
18+
ignores: ["**/__tests__/**", "**/*.test.ts", "**/*.test.tsx", "**/*.spec.ts", "**/*.spec.tsx"],
19+
rules: {
20+
"no-restricted-syntax": [
21+
"error",
22+
...i18nDotKeySelectors(dotKey).map((selector) => ({ selector, message })),
23+
],
24+
},
25+
}
26+
}
27+
28+
/** The selectors alone, for a file set that already sets no-restricted-syntax. */
29+
export function getI18nDotKeySelectors(config) {
30+
return config.rules["no-restricted-syntax"].slice(1)
31+
}
32+
33+
function i18nDotKeySelectors(dotKey) {
34+
const call = "CallExpression:matches([callee.name='t'], [callee.property.name='t'])"
35+
return [`${call}[arguments.0.value=${dotKey}]`, `${call}[arguments.0.quasis.0.value.raw=${dotKey}]`]
36+
}
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
import assert from "node:assert/strict"
2+
import { describe, it } from "node:test"
3+
4+
import { Linter } from "eslint"
5+
import typescriptEslint from "typescript-eslint"
6+
7+
import { createI18nDotKeyConfig } from "./i18n-keys.js"
8+
9+
const linter = new Linter({ configType: "flat" })
10+
const config = [
11+
{ files: ["**/*.ts", "**/*.tsx"], languageOptions: { parser: typescriptEslint.parser } },
12+
createI18nDotKeyConfig(new URL("../../webview-ui/src/i18n/locales/en", import.meta.url)),
13+
]
14+
15+
const lint = (code, filename = "components/example.tsx") =>
16+
linter.verify(code, config, { filename }).map((message) => message.message)
17+
18+
describe("i18n dot-form keys", () => {
19+
for (const code of [
20+
't("chat.commandExecution.exitStatus", { exitCode })',
21+
'i18next.t("settings.autoApprove.title")',
22+
"t(`chat.errors.${name}`)",
23+
]) {
24+
it(`flags: ${code}`, () => {
25+
assert.equal(lint(code).length, 1)
26+
})
27+
}
28+
29+
for (const code of [
30+
't("chat:commandExecution.exitStatus", { exitCode })',
31+
't("unknownNamespace.key")',
32+
"t(`chat:errors.${name}`)",
33+
]) {
34+
it(`allows: ${code}`, () => {
35+
assert.deepEqual(lint(code), [])
36+
})
37+
}
38+
39+
it("does not apply to spec files", () => {
40+
assert.deepEqual(lint('t("chat.key")', "components/__tests__/example.spec.tsx"), [])
41+
})
42+
})

‎packages/config-eslint/package.json‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,11 @@
77
"./react": "./react.js",
88
"./next-js": "./next.js",
99
"./provider-identifiers": "./provider-identifiers.js",
10-
"./api-provider-hygiene": "./api-provider-hygiene.js"
10+
"./api-provider-hygiene": "./api-provider-hygiene.js",
11+
"./i18n-keys": "./i18n-keys.js"
1112
},
1213
"scripts": {
13-
"test": "node --test provider-identifiers.test.js api-provider-hygiene.test.js"
14+
"test": "node --test provider-identifiers.test.js api-provider-hygiene.test.js i18n-keys.test.js"
1415
},
1516
"devDependencies": {
1617
"@eslint/js": "9.39.5",
Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
/**
2+
* Finds t("ns:key", { ... }) calls that do not pass a variable the English string needs.
3+
* Example: the string has {{exitCode}} but the call passes { exitStatus }.
4+
*
5+
* Usage: node scripts/check-i18n-interpolation.js
6+
*
7+
* Only calls with a string-literal key and an object-literal second argument are checked.
8+
* A spread in the object skips the call.
9+
*/
10+
11+
const path = require("path")
12+
const fs = require("fs")
13+
const { execFileSync } = require("child_process")
14+
const ts = require("typescript")
15+
16+
const ROOT = path.join(__dirname, "..")
17+
const PACKAGES = ["src", "webview-ui/src"]
18+
19+
const files = execFileSync(
20+
"git",
21+
["ls-files", "-z", "--", ...PACKAGES.map((p) => `${p}/**/*.ts`), ...PACKAGES.map((p) => `${p}/**/*.tsx`)],
22+
{
23+
cwd: ROOT,
24+
encoding: "utf8",
25+
},
26+
)
27+
.split("\0")
28+
.filter((f) => f && !/(\/__tests__\/|\.(spec|test)\.tsx?$)/.test(f))
29+
30+
const resources = {}
31+
function getResource(pkg, ns) {
32+
const id = `${pkg}:${ns}`
33+
if (!(id in resources)) {
34+
const file = path.join(ROOT, pkg === "src" ? "src" : "webview-ui/src", "i18n/locales/en", `${ns}.json`)
35+
resources[id] = fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, "utf8")) : undefined
36+
}
37+
return resources[id]
38+
}
39+
40+
function lookup(resource, keyPath) {
41+
let node = resource
42+
for (const part of keyPath.split(".")) {
43+
if (node === null || typeof node !== "object" || !(part in node)) return undefined
44+
node = node[part]
45+
}
46+
return node
47+
}
48+
49+
// "Exited with {{exitCode}}" and "{{- name}}" and "{{n, number}}" -> exitCode, name, n
50+
function placeholders(value) {
51+
return [...value.matchAll(/\{\{-?\s*([\w$]+)[^}]*\}\}/g)].map((m) => m[1])
52+
}
53+
54+
const problems = []
55+
56+
for (const rel of files) {
57+
const pkg = rel.startsWith("src/") ? "src" : "webview-ui"
58+
const source = fs.readFileSync(path.join(ROOT, rel), "utf8")
59+
const sf = ts.createSourceFile(
60+
rel,
61+
source,
62+
ts.ScriptTarget.Latest,
63+
true,
64+
rel.endsWith("x") ? ts.ScriptKind.TSX : ts.ScriptKind.TS,
65+
)
66+
67+
const visit = (node) => {
68+
if (ts.isCallExpression(node)) {
69+
const callee = node.expression
70+
const isT =
71+
(ts.isIdentifier(callee) && callee.text === "t") ||
72+
(ts.isPropertyAccessExpression(callee) && callee.name.text === "t")
73+
const [keyArg, optionsArg] = node.arguments
74+
if (
75+
isT &&
76+
keyArg &&
77+
ts.isStringLiteralLike(keyArg) &&
78+
keyArg.text.includes(":") &&
79+
optionsArg &&
80+
ts.isObjectLiteralExpression(optionsArg) &&
81+
!optionsArg.properties.some(ts.isSpreadAssignment)
82+
) {
83+
// i18next splits on the first ":" and joins the rest with "."
84+
const [ns, ...rest] = keyArg.text.split(":")
85+
const keyPath = rest.join(".")
86+
const resource = getResource(pkg, ns)
87+
if (resource) {
88+
const passed = new Set(
89+
optionsArg.properties.map(
90+
(p) => p.name && (ts.isIdentifier(p.name) || ts.isStringLiteral(p.name)) && p.name.text,
91+
),
92+
)
93+
// A plural key lives under key_one, key_other, and so on.
94+
const values = [keyPath, `${keyPath}_one`, `${keyPath}_other`]
95+
.map((k) => lookup(resource, k))
96+
.filter((v) => typeof v === "string")
97+
const missing = new Set(values.flatMap(placeholders).filter((name) => !passed.has(name)))
98+
if (missing.size > 0) {
99+
const { line } = sf.getLineAndCharacterOfPosition(node.getStart())
100+
problems.push(
101+
`${rel}:${line + 1} t("${keyArg.text}") does not pass: ${[...missing].join(", ")}`,
102+
)
103+
}
104+
}
105+
}
106+
}
107+
ts.forEachChild(node, visit)
108+
}
109+
visit(sf)
110+
}
111+
112+
if (problems.length > 0) {
113+
console.error(`Found ${problems.length} t() call(s) missing an interpolation variable:\n${problems.join("\n")}`)
114+
process.exit(1)
115+
}
116+
console.log(`OK: checked ${files.length} files, no missing interpolation variables.`)

‎src/eslint.config.mjs‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import {
44
apiProviderTestSelectors,
55
apiSpecTsIgnoreConfig,
66
} from "@roo-code/config-eslint/api-provider-hygiene"
7+
import { createI18nDotKeyConfig, getI18nDotKeySelectors } from "@roo-code/config-eslint/i18n-keys"
78
import { createProviderIdentifierConfig } from "@roo-code/config-eslint/provider-identifiers"
89
import { providerIdentifiers, retiredProviderIdentifiers } from "@roo-code/types/provider-identifiers"
910

@@ -27,11 +28,25 @@ const testPathTraversalSelectors = [
2728
},
2829
]
2930

31+
const i18nDotKeyConfig = createI18nDotKeyConfig(`${import.meta.dirname}/i18n/locales/en`)
32+
3033
/** @type {import("eslint").Linter.Config} */
3134
export default [
3235
...config,
3336
createProviderIdentifierConfig({ providerIdentifiers, retiredProviderIdentifiers }),
37+
i18nDotKeyConfig,
3438
apiProviderHygieneConfig,
39+
{
40+
// A later block replaces no-restricted-syntax for the same files, so repeat the i18n selectors.
41+
...apiProviderHygieneConfig,
42+
rules: {
43+
"no-restricted-syntax": [
44+
"error",
45+
...apiProviderHygieneConfig.rules["no-restricted-syntax"].slice(1),
46+
...getI18nDotKeySelectors(i18nDotKeyConfig),
47+
],
48+
},
49+
},
3550
{
3651
rules: {
3752
"prefer-const": ["error", { destructuring: "all" }],

‎webview-ui/eslint.config.mjs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
11
import { reactConfig } from "@roo-code/config-eslint/react"
22
import { createProviderIdentifierConfig } from "@roo-code/config-eslint/provider-identifiers"
3+
import { createI18nDotKeyConfig } from "@roo-code/config-eslint/i18n-keys"
34
import { providerIdentifiers, retiredProviderIdentifiers } from "@roo-code/types/provider-identifiers"
45

56
/** @type {import("eslint").Linter.Config} */
67
export default [
78
...reactConfig,
89
createProviderIdentifierConfig({ providerIdentifiers, retiredProviderIdentifiers }),
10+
createI18nDotKeyConfig(`${import.meta.dirname}/src/i18n/locales/en`),
911
{
1012
rules: {
1113
"@typescript-eslint/no-unused-vars": [

‎webview-ui/src/components/chat/__tests__/CommandExecution.spec.tsx‎

Lines changed: 7 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -843,51 +843,25 @@ Output:
843843

844844
describe("exit status tooltip", () => {
845845
// The tooltip key must be written in i18next's namespace form ("ns:path").
846-
// A dot-form key ("chat.commandExecution.exitStatus") carries no namespace
847-
// separator, so i18next looks for a "chat.commandExecution.exitStatus" key
848-
// inside the default namespace, misses, and renders the raw key to the user.
849-
it("resolves the exit-status copy instead of rendering the raw key", async () => {
850-
const instance = i18next.createInstance()
851-
await instance.init({
846+
// A dot-form key carries no namespace separator, so i18next misses and renders
847+
// the raw key. This test renders the real exited branch and reads the tooltip
848+
// the user sees, so a wrong key or a dropped exitCode interpolation fails it.
849+
beforeAll(async () => {
850+
await i18next.init({
852851
lng: "en",
853852
fallbackLng: "en",
854853
resources: { en: { chat: enChat } },
855854
interpolation: { escapeValue: false },
856855
})
857-
858-
const resolved = instance.t("chat:commandExecution.exitStatus", { exitCode: 0 })
859-
expect(resolved).toBe("Exited with status 0")
860-
expect(resolved).not.toContain("chat:commandExecution")
861856
})
862857

863-
it("does not resolve the dot form, which is why the namespace separator matters", async () => {
864-
const instance = i18next.createInstance()
865-
await instance.init({
866-
lng: "en",
867-
fallbackLng: "en",
868-
resources: { en: { chat: enChat } },
869-
interpolation: { escapeValue: false },
870-
})
871-
872-
expect(instance.t("chat.commandExecution.exitStatus", { exitCode: 0 })).toBe(
873-
"chat.commandExecution.exitStatus",
874-
)
858+
afterAll(() => {
859+
i18next.removeResourceBundle("en", "chat")
875860
})
876861

877-
// The two tests above only exercise a standalone i18next instance, so they
878-
// would keep passing if CommandExecution used the wrong key or dropped the
879-
// exitCode interpolation. This one renders the real exited branch and reads
880-
// the tooltip the user actually sees.
881862
it("renders the interpolated exit-status tooltip for an exited command", async () => {
882863
const user = userEvent.setup()
883864

884-
await i18next.init({
885-
lng: "en",
886-
fallbackLng: "en",
887-
resources: { en: { chat: enChat } },
888-
interpolation: { escapeValue: false },
889-
})
890-
891865
render(
892866
<TooltipProvider delayDuration={0}>
893867
<ExtensionStateWrapper>

0 commit comments

Comments
 (0)