An open source design system that's fully customizable and agent ready
TypeScript
lint: flag hardcoded strings passed to announce() (#4387)
Baraa Hamodi72c0956ff9f6
diff --git a/eslint.config.js b/eslint.config.jsindex e3ef67c716..78728543cd 100644--- a/eslint.config.js+++ b/eslint.config.js@@ -180,6 +180,16 @@ export default defineConfig('Carousel/Carousel',],}],+ // announce() live-region messages are user-facing text; the rule checks+ // them as call arguments (callees defaults to ['announce']).+ // TEMPORARY allowlist: these exact strings predate the check and are+ // being replaced with t(...) in the scan #3 i18n sweep PRs+ // (CodeBlock 'Copied'; MultiSelector 'Selection cleared' /+ // 'All selected'). Remove each entry as its fix merges; delete+ // allowedCalleeStrings entirely once the sweep lands.+ '@astryx/no-hardcoded-i18n-string': [isStrictMode ? 'error' : 'warn', {+ allowedCalleeStrings: ['Copied', 'Selection cleared', 'All selected'],+ }],},},// The i18n runtime itself defines the message strings the rest of thediff --git a/internal/eslint-plugin-astryx/no-hardcoded-i18n-string.js b/internal/eslint-plugin-astryx/no-hardcoded-i18n-string.jsindex c4a3c2feb2..f8721a774e 100644--- a/internal/eslint-plugin-astryx/no-hardcoded-i18n-string.js+++ b/internal/eslint-plugin-astryx/no-hardcoded-i18n-string.js@@ -24,6 +24,16 @@* NOT flagged.* 2. Object property assignments of the same names inside .tsx files.* 3. Destructure defaults (`function Foo({label = 'X'})`) of the same names.+ * 4. Call arguments: hardcoded first arguments to configured callees+ * (default: `announce`, the live-region announcer returned by+ * `useAnnounce()`). Matches by CALLEE NAME only — no import/scope+ * tracing — so any local function named `announce` is checked. That is+ * a deliberate simplicity tradeoff: false positives require shadowing+ * the hook's conventional name, which the codebase does not do.+ * Only plain string literals and template literals WITHOUT expressions+ * are flagged; templates with interpolations, identifiers, and t(...)+ * results are allowed (interpolated announcements are caught by the+ * i18n sweep, not this conservative check).** Ignores:* - Test files (*.test.*, __tests__/**)@@ -39,10 +49,22 @@* const label = labelFromProps ?? t('foo.label');* }*+ * Good:+ * announce(t('tokenizer.announce.added', {label}));+ * announce(message);+ ** Bad:* <button aria-label="Close">* {key: 'contains', label: 'contains'}* function Foo({label = 'Cancel'})+ * announce('Copied');+ *+ * Options:+ * callees: string[] — function names whose first argument is a user-facing+ * text sink. Default: ['announce'].+ * allowedCalleeStrings: string[] — exact string values temporarily exempted+ * from the callee check (grandfathered sites tracked for removal).+ * Default: [].*//**@@ -227,13 +249,35 @@ const rule = {'Hardcoded default {{value}} for prop `{{name}}`. ' +'Use the alias-and-resolve pattern: `{{name}}: {{name}}FromProps` in the destructure, then ' +'`const {{name}} = {{name}}FromProps ?? t(\'<namespace>.<component>.<key>\');` inside the body.',+ hardcodedCallArg:+ 'Hardcoded user-facing string {{value}} passed to `{{name}}()`. ' ++ 'Route through `t(\'<namespace>.<component>.<key>\')` via `useTranslator()` so it can be localized.',},- schema: [],+ schema: [+ {+ type: 'object',+ properties: {+ callees: {+ type: 'array',+ items: {type: 'string'},+ },+ allowedCalleeStrings: {+ type: 'array',+ items: {type: 'string'},+ },+ },+ additionalProperties: false,+ },+ ],},create(context) {const filename = context.filename;if (shouldIgnoreFile(filename)) return {};+ const options = context.options[0] || {};+ const callees = new Set(options.callees ?? ['announce']);+ const allowedCalleeStrings = new Set(options.allowedCalleeStrings ?? []);+return {// 1. JSX attribute string literals: <X label="Cancel">JSXAttribute(node) {@@ -322,6 +366,39 @@ const rule = {/*isDefault*/ true,);},++ // 4. Call argument: `announce('Copied')`+ // Matches by callee NAME only (no import/scope tracing) — see the+ // file header for the rationale and limitation. Deliberately+ // conservative about what counts as hardcoded: plain string+ // literals and expression-free template literals. Templates with+ // interpolations, identifiers, and t(...) calls are all allowed.+ CallExpression(node) {+ if (node.callee.type !== 'Identifier') return;+ const name = node.callee.name;+ if (!callees.has(name)) return;+ const arg = node.arguments[0];+ if (arg == null) return;++ let value = null;+ if (arg.type === 'Literal' && typeof arg.value === 'string') {+ value = arg.value;+ } else if (+ arg.type === 'TemplateLiteral' &&+ arg.expressions.length === 0 &&+ arg.quasis.length === 1+ ) {+ value = arg.quasis[0].value?.cooked ?? arg.quasis[0].value?.raw;+ }+ if (typeof value !== 'string') return;+ if (!looksUserFacing(value)) return;+ if (allowedCalleeStrings.has(value)) return;+ context.report({+ node: arg,+ messageId: 'hardcodedCallArg',+ data: {value: JSON.stringify(value), name},+ });+ },};},};diff --git a/internal/eslint-plugin-astryx/no-hardcoded-i18n-string.test.mjs b/internal/eslint-plugin-astryx/no-hardcoded-i18n-string.test.mjsnew file mode 100644index 0000000000..e28f0a92bb--- /dev/null+++ b/internal/eslint-plugin-astryx/no-hardcoded-i18n-string.test.mjs@@ -0,0 +1,97 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file no-hardcoded-i18n-string.test.mjs+ * @description Tests for the no-hardcoded-i18n-string ESLint rule, focused on+ * the call-argument surface (announce() live-region messages) plus a few+ * anchor cases for the pre-existing JSX-attribute surface.+ */++import {RuleTester} from 'eslint';+import tseslint from 'typescript-eslint';+import noHardcodedI18nStringRule from './no-hardcoded-i18n-string.js';++const ruleTester = new RuleTester({+ languageOptions: {+ parser: tseslint.parser,+ parserOptions: {+ ecmaFeatures: {jsx: true},+ },+ },+});++// RuleTester registers its own describe/it blocks internally, so it+// must run at the top level. Vitest 4 forbids calling suite functions+// (describe/it) from inside another it() callback.+ruleTester.run('no-hardcoded-i18n-string', noHardcodedI18nStringRule, {+ valid: [+ // --- Call arguments (announce) ---+ // t(...) result is the pattern we want+ {code: "announce(t('codeblock.announce.copied'));"},+ // Variables are fine — we can't know their provenance+ {code: 'announce(message);'},+ // Template literal WITH expressions is allowed (conservative check; the+ // interpolated-announcement class is handled by the i18n sweep)+ {code: 'announce(`Added ${item.label}`);'},+ // Empty string (used to clear the live region) is not user-facing+ {code: "announce('');"},+ // Identifier-shaped single lowercase word is not user-facing+ {code: "announce('copied');"},+ // No arguments+ {code: 'announce();'},+ // Only the configured callees are checked (default: announce)+ {code: "notify('Something happened');"},+ // Member calls are not matched (callee-name matching only)+ {code: "screenReader.announce('Copied');"},+ // Allowlisted string (grandfathered site awaiting its sweep PR)+ {+ code: "announce('Copied');",+ options: [{allowedCalleeStrings: ['Copied']}],+ },+ // Test files are ignored by the rule itself+ {+ code: "announce('Copied');",+ filename: 'CodeBlock.test.tsx',+ },+ // Stories are ignored by the rule itself+ {+ code: "announce('Copied');",+ filename: 'CodeBlock.stories.tsx',+ },+ // --- Pre-existing surfaces still behave ---+ {code: "<button aria-label={t('dialog.close')}>x</button>"},+ ],+ invalid: [+ // Plain hardcoded string+ {+ code: "announce('Copied');",+ errors: [{messageId: 'hardcodedCallArg'}],+ },+ {+ code: "announce('Selection cleared');",+ errors: [{messageId: 'hardcodedCallArg'}],+ },+ // Expression-free template literal is equivalent to a string literal+ {+ code: 'announce(`All selected`);',+ errors: [{messageId: 'hardcodedCallArg'}],+ },+ // Allowlist is exact-match — other strings still flagged+ {+ code: "announce('Removed item');",+ options: [{allowedCalleeStrings: ['Copied']}],+ errors: [{messageId: 'hardcodedCallArg'}],+ },+ // Custom callees option+ {+ code: "notify('Something happened');",+ options: [{callees: ['notify']}],+ errors: [{messageId: 'hardcodedCallArg'}],+ },+ // --- Pre-existing surfaces still behave ---+ {+ code: '<button aria-label="Close">x</button>',+ errors: [{messageId: 'hardcodedString'}],+ },+ ],+});