SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.
TypeScript apmapplication-monitoringdistributed-tracinggogood-first-issuejaegerloglogsmetricsmonitoringnextjsobservabilityopen-sourceopentelemetryprometheusreactreactjsself-hostedtracingtypescript
fix(translate): do not crash on use google translate (#12466)
Vinicius Lourenço013e631c6802
diff --git a/frontend/.oxlintrc.json b/frontend/.oxlintrc.jsonindex b7bc78ace9..6a5facf29e 100644--- a/frontend/.oxlintrc.json+++ b/frontend/.oxlintrc.json@@ -487,8 +487,11 @@// Simplifies boolean returns"sonarjs/prefer-while": "error",// Suggests while loops over for loops- "sonarjs/elseif-without-else": "off"+ "sonarjs/elseif-without-else": "off",// Requires final else in if-else-if chains (was disabled)+ "signoz/no-conditional-text-nodes-with-siblings": "warn",+ // Vendored from eslint-plugin-react-google-translate+ "signoz/no-return-text-nodes": "warn"},"ignorePatterns": ["src/parser/*.ts",diff --git a/frontend/package.json b/frontend/package.jsonindex 05a7c6e742..989cd90df9 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -16,6 +16,7 @@"lint:generated": "oxlint ./src/api/generated --fix","lint:fix": "oxlint ./src --fix","lint:styles": "stylelint \"src/**/*.scss\"",+ "test:plugins": "node --test \"plugins/__tests__/*.test.mjs\"","jest": "jest","jest:coverage": "jest --coverage","jest:watch": "jest --watch",@@ -125,6 +126,7 @@"rrule": "2.8.1","styled-components": "^5.3.11","timestamp-nano": "^1.0.0",+ "translation-resilience": "^0.2.0","typescript": "5.9.3","uplot": "1.6.31","uuid": "14.0.1",diff --git a/frontend/plugins/__tests__/README.md b/frontend/plugins/__tests__/README.mdnew file mode 100644index 0000000000..21a20ae65a--- /dev/null+++ b/frontend/plugins/__tests__/README.md@@ -0,0 +1,130 @@+# Plugin rule tests++Tests for the custom oxlint rules in `plugins/rules/`.++```bash+pnpm test:plugins+```++Runs on `node --test` rather than jest. The jest config is built for application+code — jsdom, ts-jest ESM transforms, a large `transformIgnorePatterns` wall —+and none of it applies to a suite whose only job is to shell out to the linter.++## Why it drives the real binary++Each case is written to a temp file and linted by the actual `oxlint` binary,+with every builtin category switched off so the only diagnostics that can appear+belong to the rule under test. Assertions therefore describe what CI enforces.++The alternative — walking the AST in-process — would need a stand-in for+oxlint's JS plugin AST. That AST is ESTree-shaped but not ESTree, and it carries+no type information, so a stand-in would drift from the runtime it claims to+model and the tests would certify behaviour that never happens.++All cases in a suite share one `oxlint` invocation and are mapped back by+filename. Per-case spawning costs roughly 80ms each; batching keeps both suites+together at around 250ms.++## Adding a suite++```js+import { ruleTester } from './rule-tester.mjs';++await ruleTester({+ rule: 'no-navigator-clipboard',+ valid: ['const x = 1;'],+ invalid: [+ {+ code: 'navigator.clipboard.writeText("x");',+ errors: [{ message: 'useCopyToClipboard', line: 1, column: 1 }],+ },+ ],+});+```++`ruleTester` must be awaited at the top level — it loads the plugin and runs+`oxlint` before declaring the tests.++- `rule` — the key the plugin exports it under. `plugin` defaults to+ `plugins/signoz.mjs`; pass a path relative to `frontend/` for another plugin.+- Cases are `.tsx` unless a `filename` gives another extension.+- `errors` takes a count or an array. Each entry may assert `message` (substring+ or `RegExp`), `line` and `column`; omitted fields are not checked.+- `name` labels the case in the output and defaults to its first line of code.+- `output` asserts the source after suggestions are applied — see below.+- `todo` marks a case as a known defect — see below.++## Suggestions++Both Google Translate rules attach their wrap as a *suggestion*, not a fix, so+`--fix` leaves the code alone and `--fix-suggestions` applies it. The wrap is+`<span className="translate-safe">`, and `.translate-safe` is `display: contents`+in `src/styles.scss`: React owns an element that absorbs Translate's `<font>`+swap, while the box tree stays as it was, so a flex or grid parent still sees one+contiguous text run rather than a new item with its own `gap`.++It stays a suggestion because the element is still a DOM child even with no box:+`> *`, `:nth-child` and sibling selectors still count it, and a component that+inspects its children — `React.Children.map`, antd `Tooltip`, `Space` — sees an+element where a string used to be. That is what oxlint means by "May change+program behavior" in `--fix-suggestions --help`.++An invalid case carrying `output` is linted twice: once for diagnostics, and+once with `--fix-suggestions` over an untouched copy of the same files. The+second run costs one extra `oxlint` spawn per suite and only happens when at+least one case asks for it.++```js+{+ code: "export const A = () => <div>{f ? 'a' : 'b'}<b/></div>;",+ errors: 2,+ output:+ 'export const A = () => <div>{f ? <span className="translate-safe">a</span> : <span className="translate-safe">b</span>}<b/></div>;',+}+```++Suggestions do not reformat, so a real run is `oxlint --fix-suggestions` then+`oxfmt`.++## Known defects++A case carrying `todo` asserts what the rule *should* do. It still runs, but a+failure is reported as a todo rather than failing the suite, so a bug can be+pinned as an executable spec instead of prose. Fixing the rule turns the todo+green; deleting the flag then makes it a regression guard.++Cases are prefixed `FP:` where the rule reports something it should not, `GAP:`+where it misses something it should catch, and `TYPE-AWARE:` where the miss is+only fixable once the linter can resolve types. Everything without a flag is a+characterisation test recording current behaviour.++The current todos:++**Gaps — constructs the rules never visit.** `isProblematicConditional` requires+a `JSXElement` parent, so a conditional inside a fragment is never inspected even+though the failure does not care about the parent's kind. `no-return-text-nodes`+listens only for `FunctionDeclaration` and reads the name off `node.id`, so+arrow-function components and anonymous default exports are invisible — this+codebase writes components as arrow functions, which is why that rule reports+nothing across `src`.++Class components are left out deliberately rather than pinned as a gap: there+are none in `src`.++**Type-aware gaps.** Upstream resolves branch types through+`@typescript-eslint/utils` and reports anything typed `string` or `number`.+oxlint's JS plugin runtime exposes no type information — `sourceCode.parserServices`+is always `{}` — so those code paths were removed rather than left dormant. The+`TYPE-AWARE:` todos record what they used to catch, and become the acceptance+criteria if oxlint ever hands types to JS plugins.++## Not a defect++Without types, `no-conditional-text-nodes-with-siblings` falls back to a callee+allowlist (`t`, `formatMessage`, `toString`, `toLocaleString`). Cases around+that allowlist pin its edges; widening it is the supported way to catch more+call expressions.++Both branches of a ternary are reported separately, so one fix can clear two+diagnostics. That inflates the count but every reported node is genuinely a text+node, so the cases assert both.diff --git a/frontend/plugins/__tests__/no-conditional-text-nodes-with-siblings.test.mjs b/frontend/plugins/__tests__/no-conditional-text-nodes-with-siblings.test.mjsnew file mode 100644index 0000000000..8069d65bfc--- /dev/null+++ b/frontend/plugins/__tests__/no-conditional-text-nodes-with-siblings.test.mjs@@ -0,0 +1,302 @@+import { ruleTester } from './rule-tester.mjs';++const CONDITIONAL = 'Conditionally rendered text nodes with siblings';+const PRECEDED = 'Text nodes which are preceded by a conditional expression';++await ruleTester({+ rule: 'no-conditional-text-nodes-with-siblings',+ valid: [+ {+ name: 'conditional text node without siblings',+ code:+ "export const A = () => (\n\t<div>\n\t\t{flag ? 'yes' : 'no'}\n\t</div>\n);",+ },+ {+ name: 'boolean branches are not text',+ code:+ 'export const A = () => (\n\t<div>\n\t\t{flag ? true : false}\n\t\t<span>x</span>\n\t</div>\n);',+ },+ {+ name: 'null branches are not text',+ code:+ 'export const A = () => (\n\t<div>\n\t\t{flag ? null : null}\n\t\t<span>x</span>\n\t</div>\n);',+ },+ {+ name: 'element branches are already wrapped',+ code:+ 'export const A = () => (\n\t<div>\n\t\t{flag ? <b>y</b> : <i>n</i>}\n\t\t<span>x</span>\n\t</div>\n);',+ },+ {+ name: 'text node before the conditional is safe',+ code:+ 'export const A = () => (\n\t<div>\n\t\tleading text\n\t\t{flag && <b>y</b>}\n\t</div>\n);',+ },+ {+ name: 'member expression on the condition side is not rendered',+ code:+ 'export const A = () => (\n\t<div>\n\t\t{obj.name && <b>y</b>}\n\t\t<span>x</span>\n\t</div>\n);',+ },+ {+ name: 'binary comparison on the condition side is not rendered',+ code:+ "export const A = () => (\n\t<div>\n\t\t{obj.name === 'x' && <b>y</b>}\n\t\t<span>x</span>\n\t</div>\n);",+ },+ // An empty string renders no text node at all, so there is nothing for+ // Google Translate to wrap and nothing for React to lose. Reporting it used+ // to be the rule's most common false positive.+ {+ name: 'element branch with an empty-string fallback',+ code:+ "export const A = () => (\n\t<div>\n\t\t{flag ? <b>Free Trial</b> : ''}\n\t\t<span>s</span>\n\t</div>\n);",+ },+ {+ name: 'both branches empty',+ code:+ "export const A = () => (\n\t<div>\n\t\t{flag ? '' : ''}\n\t\t<span>s</span>\n\t</div>\n);",+ },+ {+ name: 'logical and with an empty-string right-hand side',+ code:+ "export const A = () => (\n\t<div>\n\t\t{flag && ''}\n\t\t<span>s</span>\n\t</div>\n);",+ },++ // A template literal is checked the same way as the quoted form, so `{' '}`+ // and ``{` `}`` agree.+ {+ name: 'empty template literal branch',+ code:+ "export const A = () => (\n\t<div>\n\t\t{flag ? `` : ''}\n\t\t<span>s</span>\n\t</div>\n);",+ },+ {+ name: 'whitespace-only template literal branch is skipped',+ code:+ 'export const A = () => (\n\t<div>\n\t\t{flag ? ` ` : <b>x</b>}\n\t\t<span>s</span>\n\t</div>\n);',+ },+ ],+ invalid: [+ {+ name: 'string literal branches with an element sibling',+ code:+ "export const A = () => (\n\t<div>\n\t\t{flag ? 'yes' : 'no'}\n\t\t<span>x</span>\n\t</div>\n);",+ errors: [+ { message: CONDITIONAL, line: 3, column: 11 },+ { message: CONDITIONAL, line: 3, column: 19 },+ ],+ output:+ 'export const A = () => (\n\t<div>\n\t\t{flag ? <span className="translate-safe">yes</span> : <span className="translate-safe">no</span>}\n\t\t<span>x</span>\n\t</div>\n);',+ },+ {+ name: 'logical and with a string right-hand side',+ code:+ "export const A = () => (\n\t<div>\n\t\t{flag && 'yes'}\n\t\t<span>x</span>\n\t</div>\n);",+ errors: [{ message: CONDITIONAL, line: 3, column: 12 }],+ },+ {+ name: 'numeric literals render as text',+ code:+ 'export const A = () => (\n\t<div>\n\t\t{flag ? 1 : 2}\n\t\t<span>x</span>\n\t</div>\n);',+ errors: [+ { message: CONDITIONAL, line: 3, column: 11 },+ { message: CONDITIONAL, line: 3, column: 15 },+ ],+ output:+ 'export const A = () => (\n\t<div>\n\t\t{flag ? <span className="translate-safe">{1}</span> : <span className="translate-safe">{2}</span>}\n\t\t<span>x</span>\n\t</div>\n);',+ },+ {+ name: 'template literal branch',+ code:+ "export const A = () => (\n\t<div>\n\t\t{flag ? `yes ${n}` : 'no'}\n\t\t<span>x</span>\n\t</div>\n);",+ errors: [+ { message: CONDITIONAL, line: 3, column: 11 },+ { message: CONDITIONAL, line: 3, column: 24 },+ ],+ output:+ 'export const A = () => (\n\t<div>\n\t\t{flag ? <span className="translate-safe">{`yes ${n}`}</span> : <span className="translate-safe">no</span>}\n\t\t<span>x</span>\n\t</div>\n);',+ },+ {+ name: 'member expression branch',+ code:+ "export const A = () => (\n\t<div>\n\t\t{flag ? obj.name : 'no'}\n\t\t<span>x</span>\n\t</div>\n);",+ errors: [+ { message: CONDITIONAL, line: 3, column: 11 },+ { message: CONDITIONAL, line: 3, column: 22 },+ ],+ output:+ 'export const A = () => (\n\t<div>\n\t\t{flag ? <span className="translate-safe">{obj.name}</span> : <span className="translate-safe">no</span>}\n\t\t<span>x</span>\n\t</div>\n);',+ },+ {+ name: 'a string needing escapes stays inside braces',+ code:+ 'export const A = () => (\n\t<div>\n\t\t{flag ? "it\'s" : <b>x</b>}\n\t\t<span>s</span>\n\t</div>\n);',+ errors: [{ message: CONDITIONAL, line: 3, column: 11 }],+ output:+ 'export const A = () => (\n\t<div>\n\t\t{flag ? <span className="translate-safe">{"it\'s"}</span> : <b>x</b>}\n\t\t<span>s</span>\n\t</div>\n);',+ },+ {+ name: 'optional chaining branch',+ code:+ "export const A = () => (\n\t<div>\n\t\t{flag ? obj?.deep?.name : 'no'}\n\t\t<span>x</span>\n\t</div>\n);",+ errors: [+ { message: CONDITIONAL, line: 3, column: 11 },+ { message: CONDITIONAL, line: 3, column: 29 },+ ],+ },+ {+ name: 'nested ternary reports every text branch',+ code:+ "export const A = () => (\n\t<div>\n\t\t{a ? (b ? 'x' : 'y') : 'z'}\n\t\t<span>s</span>\n\t</div>\n);",+ errors: [+ { message: CONDITIONAL, line: 3, column: 13 },+ { message: CONDITIONAL, line: 3, column: 19 },+ { message: CONDITIONAL, line: 3, column: 26 },+ ],+ },+ {+ name: 'static text following a conditional',+ code:+ 'export const A = () => (\n\t<div>\n\t\t{flag && <b>y</b>}\n\t\ttrailing text\n\t</div>\n);',+ errors: [{ message: PRECEDED, line: 3, column: 21 }],+ // Only the visible run is wrapped; the surrounding newlines and tabs are+ // formatting and must stay outside the element.+ output:+ 'export const A = () => (\n\t<div>\n\t\t{flag && <b>y</b>}\n\t\t<span className="translate-safe">trailing text</span>\n\t</div>\n);',+ },+ {+ name: 'conditional text plus trailing static text reports both kinds',+ code:+ "export const A = () => (\n\t<div>\n\t\t{flag ? 'a' : 'b'}\n\t\tliteral tail\n\t</div>\n);",+ errors: [+ { message: CONDITIONAL, line: 3, column: 11 },+ { message: CONDITIONAL, line: 3, column: 17 },+ { message: PRECEDED, line: 3, column: 21 },+ ],+ },++ // The callee allowlist below is the untyped fallback. Without type+ // information the rule can only recognise known string-returning helpers,+ // so `t()` and `formatMessage()` are reported while an arbitrary call is+ // not. These cases pin that boundary.+ {+ name: 't() branch is reported via the callee allowlist',+ code:+ "export const A = () => (\n\t<div>\n\t\t{flag ? t('key') : 'no'}\n\t\t<span>x</span>\n\t</div>\n);",+ errors: [+ { message: CONDITIONAL, line: 3, column: 11 },+ { message: CONDITIONAL, line: 3, column: 22 },+ ],+ },+ {+ name: 'formatMessage() branch is reported via the callee allowlist',+ code:+ "export const A = () => (\n\t<div>\n\t\t{flag ? formatMessage({id:'k'}) : 'no'}\n\t\t<span>x</span>\n\t</div>\n);",+ errors: [+ { message: CONDITIONAL, line: 3, column: 11 },+ { message: CONDITIONAL, line: 3, column: 37 },+ ],+ },+ {+ name: 'arbitrary call is not recognised, only the literal branch reports',+ code:+ "export const A = () => (\n\t<div>\n\t\t{flag ? getString() : 'no'}\n\t\t<span>x</span>\n\t</div>\n);",+ errors: [{ message: CONDITIONAL, line: 3, column: 25 }],+ },+ {+ name: 'bare identifier is not recognised, only the literal branch reports',+ code:+ "export const A = () => (\n\t<div>\n\t\t{flag ? name : 'no'}\n\t\t<span>x</span>\n\t</div>\n);",+ errors: [{ message: CONDITIONAL, line: 3, column: 18 }],+ },+ {+ name: 'toString() branch is reported',+ code:+ "export const A = () => (\n\t<div>\n\t\t{flag ? val.toString() : 'no'}\n\t\t<span>x</span>\n\t</div>\n);",+ errors: [+ { message: CONDITIONAL, line: 3, column: 11 },+ { message: CONDITIONAL, line: 3, column: 28 },+ ],+ },+ {+ name: 'toLocaleString() branch is reported',+ code:+ "export const A = () => (\n\t<div>\n\t\t{flag ? val.toLocaleString() : 'no'}\n\t\t<span>x</span>\n\t</div>\n);",+ errors: [+ { message: CONDITIONAL, line: 3, column: 11 },+ { message: CONDITIONAL, line: 3, column: 34 },+ ],+ },+ {+ name: 't() in its own container following a conditional',+ code:+ "export const A = () => (\n\t<div>\n\t\t{flag && <b>y</b>}\n\t\t{t('key')}\n\t</div>\n);",+ errors: [{ message: PRECEDED, line: 4, column: 4 }],+ },+ {+ name: 'toString() in its own container following a conditional',+ code:+ 'export const A = () => (\n\t<div>\n\t\t{flag && <b>y</b>}\n\t\t{val.toString()}\n\t</div>\n);',+ errors: [{ message: PRECEDED, line: 4, column: 4 }],+ // The whole container is replaced, so the result is not `{<span>{…}</span>}`.+ output:+ 'export const A = () => (\n\t<div>\n\t\t{flag && <b>y</b>}\n\t\t<span className="translate-safe">{val.toString()}</span>\n\t</div>\n);',+ },+ {+ name: 'whitespace-only string branch is skipped, the other branch reports',+ code:+ "export const A = () => (\n\t<div>\n\t\t{flag ? ' ' : 'x'}\n\t\t<span>s</span>\n\t</div>\n);",+ errors: [{ message: CONDITIONAL, line: 3, column: 17 }],+ },+ {+ name: 'template literal holding an expression is not blank',+ code:+ 'export const A = () => (\n\t<div>\n\t\t{flag ? `${n}` : <b>x</b>}\n\t\t<span>s</span>\n\t</div>\n);',+ errors: [{ message: CONDITIONAL, line: 3, column: 11 }],+ },++ // Upstream resolves branch types through `@typescript-eslint/utils` and+ // reports anything typed `string` or `number`. oxlint's JS plugin runtime+ // exposes no type information, so those paths were dropped and only the+ // callee allowlist remains. Kept as todos: if oxlint ever hands types to JS+ // plugins these become the acceptance criteria.+ {+ todo: 'needs type information to know the call returns a string',+ name: 'TYPE-AWARE: call returning a string',+ code:+ "export const A = () => (\n\t<div>\n\t\t{flag ? getString() : 'no'}\n\t\t<span>x</span>\n\t</div>\n);",+ errors: [+ { message: CONDITIONAL, line: 3, column: 11 },+ { message: CONDITIONAL, line: 3, column: 25 },+ ],+ },+ {+ todo: 'needs type information to know the identifier is a string',+ name: 'TYPE-AWARE: identifier holding a string',+ code:+ "export const A = () => (\n\t<div>\n\t\t{flag ? name : 'no'}\n\t\t<span>x</span>\n\t</div>\n);",+ errors: [+ { message: CONDITIONAL, line: 3, column: 11 },+ { message: CONDITIONAL, line: 3, column: 18 },+ ],+ },+ {+ todo: 'needs type information to know the identifier is a string',+ name: 'TYPE-AWARE: string identifier following a conditional',+ code:+ 'export const A = () => (\n\t<div>\n\t\t{flag && <b>y</b>}\n\t\t{label}\n\t</div>\n);',+ errors: [{ message: PRECEDED, line: 4, column: 4 }],+ },++ // `isChildOfJSXElement` matches only `JSXElement`, so a fragment parent is+ // never inspected. The Google Translate failure does not care whether the+ // parent is an element or a fragment.+ {+ todo: 'fragment parents are never inspected',+ name: 'GAP: conditional text with a sibling inside a fragment',+ code:+ "export const A = () => (\n\t<>\n\t\t{flag ? 'yes' : 'no'}\n\t\t<span>x</span>\n\t</>\n);",+ errors: [+ { message: CONDITIONAL, line: 3, column: 11 },+ { message: CONDITIONAL, line: 3, column: 19 },+ ],+ },+ ],+});diff --git a/frontend/plugins/__tests__/no-return-text-nodes.test.mjs b/frontend/plugins/__tests__/no-return-text-nodes.test.mjsnew file mode 100644index 0000000000..5935de7601--- /dev/null+++ b/frontend/plugins/__tests__/no-return-text-nodes.test.mjs@@ -0,0 +1,162 @@+import { ruleTester } from './rule-tester.mjs';++const RETURNS_TEXT = 'React components should avoid returning text nodes';++await ruleTester({+ rule: 'no-return-text-nodes',+ valid: [+ {+ name: 'lowercase function is not a component',+ code: "export function foo() {\n\treturn 'text';\n}",+ },+ {+ name: 'returning JSX',+ code: 'export function Foo() {\n\treturn <div>hi</div>;\n}',+ },+ {+ name: 'returning null',+ code: 'export function Foo() {\n\treturn null;\n}',+ },+ {+ name: 'returning boolean',+ code: 'export function Foo() {\n\treturn true;\n}',+ },+ { name: 'bare return', code: 'export function Foo() {\n\treturn;\n}' },+ {+ name: 'returning a variable is not a literal',+ code: "export function Foo() {\n\tconst s = 'x';\n\treturn s;\n}",+ },+ {+ name: 'lowercase nested function inside a component',+ code:+ "export function Foo() {\n\tfunction helper() {\n\t\treturn 'x';\n\t}\n\treturn <div/>;\n}",+ },++ {+ // The repo has no class components, so this is out of scope rather than+ // a gap worth closing.+ name: 'class method',+ code: "export class Foo {\n\trender() {\n\t\treturn 'text';\n\t}\n}",+ },+ ],+ invalid: [+ {+ name: 'string literal',+ code: "export function Foo() {\n\treturn 'text';\n}",+ errors: [{ message: RETURNS_TEXT, line: 2, column: 2 }],+ output:+ 'export function Foo() {\n\treturn <span className="translate-safe">{\'text\'}</span>;\n}',+ },+ {+ // JSX does not parse in a `.ts` file, so no suggestion is offered there.+ name: 'string literal in a non-JSX file',+ filename: 'case.ts',+ code: "export function Foo() {\n\treturn 'text';\n}",+ errors: [{ message: RETURNS_TEXT, line: 2, column: 2 }],+ output: "export function Foo() {\n\treturn 'text';\n}",+ },+ {+ name: 'numeric literal',+ code: 'export function Foo() {\n\treturn 42;\n}',+ errors: [{ message: RETURNS_TEXT, line: 2, column: 2 }],+ },+ {+ name: 'template literal',+ code: 'export function Foo() {\n\treturn `text ${x}`;\n}',+ errors: [{ message: RETURNS_TEXT, line: 2, column: 2 }],+ },+ {+ name: 'inside an if consequent',+ code:+ "export function Foo() {\n\tif (a) {\n\t\treturn 'x';\n\t}\n\treturn <div/>;\n}",+ errors: [{ message: RETURNS_TEXT, line: 3, column: 3 }],+ },+ {+ name: 'inside an else block',+ code:+ "export function Foo() {\n\tif (a) {\n\t\treturn <div/>;\n\t} else {\n\t\treturn 'x';\n\t}\n}",+ errors: [{ message: RETURNS_TEXT, line: 5, column: 3 }],+ },+ {+ name: 'inside an else-if chain',+ code:+ "export function Foo() {\n\tif (a) {\n\t\treturn <div/>;\n\t} else if (b) {\n\t\treturn 'x';\n\t}\n\treturn null;\n}",+ errors: [{ message: RETURNS_TEXT, line: 5, column: 3 }],+ },+ {+ name: 'inside a switch case',+ code:+ "export function Foo() {\n\tswitch (a) {\n\t\tcase 1:\n\t\t\treturn 'x';\n\t\tdefault:\n\t\t\treturn <div/>;\n\t}\n}",+ errors: [{ message: RETURNS_TEXT, line: 4, column: 4 }],+ },+ {+ name: 'inside try, catch and finally',+ code:+ "export function Foo() {\n\ttry {\n\t\treturn 'a';\n\t} catch {\n\t\treturn 'b';\n\t} finally {\n\t\treturn 'c';\n\t}\n}",+ errors: [+ { message: RETURNS_TEXT, line: 3, column: 3 },+ { message: RETURNS_TEXT, line: 5, column: 3 },+ { message: RETURNS_TEXT, line: 7, column: 3 },+ ],+ },+ {+ name: 'inside a for loop',+ code:+ "export function Foo() {\n\tfor (let i = 0; i < 3; i++) {\n\t\treturn 'x';\n\t}\n\treturn <div/>;\n}",+ errors: [{ message: RETURNS_TEXT, line: 3, column: 3 }],+ },+ {+ name: 'inside a for-of loop',+ code:+ "export function Foo() {\n\tfor (const i of list) {\n\t\treturn 'x';\n\t}\n\treturn <div/>;\n}",+ errors: [{ message: RETURNS_TEXT, line: 3, column: 3 }],+ },+ {+ name: 'inside a for-in loop',+ code:+ "export function Foo() {\n\tfor (const k in obj) {\n\t\treturn 'x';\n\t}\n\treturn <div/>;\n}",+ errors: [{ message: RETURNS_TEXT, line: 3, column: 3 }],+ },+ {+ name: 'inside a while loop',+ code:+ "export function Foo() {\n\twhile (a) {\n\t\treturn 'x';\n\t}\n\treturn <div/>;\n}",+ errors: [{ message: RETURNS_TEXT, line: 3, column: 3 }],+ },+ {+ name: 'inside a do-while loop',+ code: "export function Foo() {\n\tdo {\n\t\treturn 'x';\n\t} while (a);\n}",+ errors: [{ message: RETURNS_TEXT, line: 3, column: 3 }],+ },+ {+ name: 'capitalised nested function is treated as a component',+ code:+ "export function Foo() {\n\tfunction Helper() {\n\t\treturn 'x';\n\t}\n\treturn <div/>;\n}",+ errors: [{ message: RETURNS_TEXT, line: 3, column: 3 }],+ },++ // The rule listens only for `FunctionDeclaration` and reads the component+ // name off `node.id`. Everything below returns a text node from something+ // React renders as a component, and none of it is reported. This codebase+ // writes components as arrow functions, which is why the rule currently+ // finds nothing in `src`.+ {+ todo: 'arrow function components are never visited',+ name: 'GAP: arrow component with an expression body',+ code: "export const Foo = () => 'text';",+ errors: 1,+ },+ {+ todo: 'arrow function components are never visited',+ name: 'GAP: arrow component with a block body',+ code: "export const Foo = () => {\n\treturn 'text';\n};",+ errors: [{ message: RETURNS_TEXT, line: 2, column: 2 }],+ },+ {+ todo: 'anonymous declarations have no node.id to read a name from',+ name: 'GAP: anonymous default-exported component',+ code: "export default function () {\n\treturn 'text';\n}",+ errors: [{ message: RETURNS_TEXT, line: 2, column: 2 }],+ },+ ],+});diff --git a/frontend/plugins/__tests__/rule-tester.mjs b/frontend/plugins/__tests__/rule-tester.mjsnew file mode 100644index 0000000000..d11ae4561f--- /dev/null+++ b/frontend/plugins/__tests__/rule-tester.mjs@@ -0,0 +1,257 @@+/**+ * Test harness for oxlint JS plugins.+ *+ * Rules are exercised through the real `oxlint` binary rather than a hand-rolled+ * AST walker, so what the tests assert is exactly what CI enforces. oxlint's JS+ * plugin AST is close to ESTree but not identical, and it exposes no type+ * information, so any in-process fake would drift from the real runtime.+ *+ * All cases in a suite are written to one temp directory and linted in a single+ * oxlint invocation, then mapped back by filename. Spawning per case costs ~80ms+ * each; batching keeps a full suite under a second.+ */++import assert from 'node:assert/strict';+import { execFileSync } from 'node:child_process';+import {+ mkdirSync,+ mkdtempSync,+ readFileSync,+ rmSync,+ writeFileSync,+} from 'node:fs';+import { tmpdir } from 'node:os';+import path from 'node:path';+import test from 'node:test';+import { fileURLToPath, pathToFileURL } from 'node:url';++const FRONTEND_DIR = path.resolve(fileURLToPath(import.meta.url), '../../..');+const OXLINT_BIN = path.join(FRONTEND_DIR, 'node_modules/.bin/oxlint');++// oxlint enables its default categories unless every one is switched off, and a+// stray builtin diagnostic would be indistinguishable from the rule under test.+const CATEGORIES_OFF = {+ correctness: 'off',+ suspicious: 'off',+ pedantic: 'off',+ perf: 'off',+ style: 'off',+ restriction: 'off',+ nursery: 'off',+};++function normaliseCase(entry, index) {+ const testCase = typeof entry === 'string' ? { code: entry } : entry;+ const extension = testCase.filename+ ? path.extname(testCase.filename).slice(1)+ : 'tsx';+ return {+ ...testCase,+ index,+ basename: `case-${String(index).padStart(3, '0')}.${extension}`,+ };+}++function diagnosticFilename(diagnostic) {+ const raw = diagnostic.filename ?? '';+ const asPath = raw.startsWith('file://') ? fileURLToPath(raw) : raw;+ return path.basename(asPath);+}++function toError(diagnostic) {+ const span = diagnostic.labels?.[0]?.span;+ return {+ message: diagnostic.message,+ line: span?.line,+ column: span?.column,+ };+}++function runOxlint(dir, configPath, extraArgs = []) {+ const args = ['--config', configPath, '--format', 'json', ...extraArgs, '.'];+ try {+ return execFileSync(OXLINT_BIN, args, {+ cwd: dir,+ encoding: 'utf8',+ // A rule that reports on every case can produce a lot of output.+ maxBuffer: 64 * 1024 * 1024,+ });+ } catch (error) {+ // oxlint exits non-zero whenever it reports a diagnostic, which is the+ // expected outcome for every `invalid` case.+ if (typeof error.stdout === 'string' && error.stdout.trim() !== '') {+ return error.stdout;+ }+ throw new Error(`oxlint failed to run:\n${error.stderr || error.message}`, {+ cause: error,+ });+ }+}++function writeSuite(dir, cases, { pluginPath, ruleId }) {+ for (const testCase of cases) {+ const target = path.join(dir, testCase.basename);+ mkdirSync(path.dirname(target), { recursive: true });+ writeFileSync(target, testCase.code);+ }++ const configPath = path.join(dir, '.oxlintrc.json');+ writeFileSync(+ configPath,+ JSON.stringify({+ jsPlugins: [pluginPath],+ categories: CATEGORIES_OFF,+ rules: { [ruleId]: 'error' },+ }),+ );+ return configPath;+}++/**+ * Lints every case in one pass, and applies suggestions in a second pass over an+ * untouched copy when any case declares `output`.+ *+ * @returns {{errors: Map<string, object[]>, outputs: Map<string, string>}}+ */+function lintCases(cases, options) {+ const root = mkdtempSync(path.join(tmpdir(), 'oxlint-rule-tester-'));+ try {+ const lintDir = path.join(root, 'lint');+ mkdirSync(lintDir);+ const report = JSON.parse(+ runOxlint(lintDir, writeSuite(lintDir, cases, options)),+ );++ const errors = new Map(cases.map((testCase) => [testCase.basename, []]));+ for (const diagnostic of report.diagnostics ?? []) {+ const bucket = errors.get(diagnosticFilename(diagnostic));+ // oxlint reports config-level problems without a filename; surfacing+ // them as a suite failure beats silently testing nothing.+ if (!bucket) {+ throw new Error(`Unexpected diagnostic: ${diagnostic.message}`);+ }+ bucket.push(toError(diagnostic));+ }++ const outputs = new Map();+ if (cases.some((testCase) => testCase.output !== undefined)) {+ const fixDir = path.join(root, 'fix');+ mkdirSync(fixDir);+ runOxlint(fixDir, writeSuite(fixDir, cases, options), ['--fix-suggestions']);+ for (const testCase of cases) {+ outputs.set(+ testCase.basename,+ readFileSync(path.join(fixDir, testCase.basename), 'utf8'),+ );+ }+ }++ return { errors, outputs };+ } finally {+ rmSync(root, { recursive: true, force: true });+ }+}++function assertMessage(actual, expected, label) {+ if (expected instanceof RegExp) {+ assert.match(actual, expected, label);+ } else {+ assert.ok(+ actual.includes(expected),+ `${label}\n expected message to contain: ${expected}\n actual: ${actual}`,+ );+ }+}++function assertErrors(actual, expected, code) {+ const context = `\n--- code ---\n${code}\n--- reported ---\n${JSON.stringify(actual, null, 2)}`;++ if (typeof expected === 'number') {+ assert.equal(actual.length, expected, `error count${context}`);+ return;+ }++ assert.equal(actual.length, expected.length, `error count${context}`);+ expected.forEach((want, i) => {+ const got = actual[i];+ if (want.message !== undefined) {+ assertMessage(got.message, want.message, `error[${i}] message${context}`);+ }+ if (want.line !== undefined) {+ assert.equal(got.line, want.line, `error[${i}] line${context}`);+ }+ if (want.column !== undefined) {+ assert.equal(got.column, want.column, `error[${i}] column${context}`);+ }+ });+}++/**+ * Declares a suite for one rule.+ *+ * A case carrying `todo` asserts the behaviour the rule *should* have. It still+ * runs, but a failure is reported as a todo instead of failing the suite, so a+ * known bug can be pinned as an executable spec. Delete the flag once the rule+ * is fixed and the case starts guarding the fix.+ *+ * An invalid case carrying `output` also asserts the source after+ * `--fix-suggestions` has been applied.+ *+ * @param {object} options+ * @param {string} options.rule - rule name as exported by the plugin+ * @param {string} [options.plugin] - path to the plugin, relative to `frontend/`+ * @param {Array<string | {code: string, name?: string, filename?: string, todo?: string}>} options.valid+ * @param {Array<{code: string, name?: string, filename?: string, todo?: string, output?: string, errors: number | Array<{message?: string | RegExp, line?: number, column?: number}>}>} options.invalid+ */+export async function ruleTester({+ rule,+ plugin = 'plugins/signoz.mjs',+ valid = [],+ invalid = [],+}) {+ const pluginPath = path.join(FRONTEND_DIR, plugin);+ const { default: pluginModule } = await import(pathToFileURL(pluginPath));++ assert.ok(+ pluginModule.rules?.[rule],+ `plugin ${plugin} does not export a rule named "${rule}"`,+ );++ const ruleId = `${pluginModule.meta.name}/${rule}`;+ const validCases = valid.map(normaliseCase);+ const invalidCases = invalid.map((entry, i) =>+ normaliseCase(entry, valid.length + i),+ );+ const { errors, outputs } = lintCases([...validCases, ...invalidCases], {+ pluginPath,+ ruleId,+ });++ const declare = (t, testCase, expected) => {+ const label = testCase.name ?? testCase.code.trim().split('\n')[0];+ return t.test(label, { todo: testCase.todo }, () => {+ assertErrors(errors.get(testCase.basename), expected, testCase.code);+ if (testCase.output !== undefined) {+ assert.equal(+ outputs.get(testCase.basename),+ testCase.output,+ `suggestion output\n--- code ---\n${testCase.code}`,+ );+ }+ });+ };++ test(ruleId, async (t) => {+ await t.test('valid', async (t) => {+ for (const testCase of validCases) {+ await declare(t, testCase, 0);+ }+ });++ await t.test('invalid', async (t) => {+ for (const testCase of invalidCases) {+ await declare(t, testCase, testCase.errors);+ }+ });+ });+}diff --git a/frontend/plugins/rules/no-conditional-text-nodes-with-siblings.mjs b/frontend/plugins/rules/no-conditional-text-nodes-with-siblings.mjsnew file mode 100644index 0000000000..2feb43fce8--- /dev/null+++ b/frontend/plugins/rules/no-conditional-text-nodes-with-siblings.mjs@@ -0,0 +1,313 @@+/**+ * Rule: no-conditional-text-nodes-with-siblings+ *+ * Conditionally rendered text nodes with siblings should be wrapped in an+ * element (for example a `<span>`), otherwise Google Translate causes a browser+ * error. Translate replaces the text node with a `<font>` wrapper, React still+ * holds a reference to the original node, and the next render throws on+ * `removeChild`.+ *+ * Adapted from https://github.com/getcouped/eslint-plugin-react-google-translate+ * (v1.0.4). The upstream rule resolves branch types through+ * `@typescript-eslint/utils`; oxlint's JS plugin runtime exposes no type+ * information, so those paths are dropped and call expressions are matched+ * against the allowlist below instead.+ */++// Calls known to render as text. Without types this is the only way to+// recognise a string-returning call; widen it to catch more helpers.+const TEXT_RETURNING_CALLEES = new Set(['formatMessage', 't']);+const STRINGIFY_METHODS = new Set(['toString', 'toLocaleString']);++function calleeName(node) {+ return node.type === 'Identifier' ? node.name : null;+}++function isTextReturningCall(node) {+ const { callee } = node;++ if (TEXT_RETURNING_CALLEES.has(calleeName(callee))) {+ return node.arguments.length > 0;+ }++ if (callee.type === 'MemberExpression' && !callee.computed) {+ return STRINGIFY_METHODS.has(calleeName(callee.property));+ }++ return STRINGIFY_METHODS.has(calleeName(callee));+}++/**+ * True when the node renders no visible text. An empty or whitespace-only value+ * produces no DOM text node, so Google Translate has nothing to wrap and React+ * nothing to lose.+ */+function isBlankText(node) {+ if (node.type === 'Literal' || node.type === 'JSXText') {+ return typeof node.value === 'string' && node.value.trim() === '';+ }+ if (node.type === 'TemplateLiteral') {+ return (+ node.expressions.length === 0 &&+ node.quasis.every((quasi) => (quasi.value.cooked ?? '').trim() === '')+ );+ }+ return false;+}++function isConditionallyRendered(node) {+ const parent = node.parent;+ return (+ parent?.type === 'ConditionalExpression' ||+ parent?.type === 'LogicalExpression'+ );+}++function isRenderedConditional(node) {+ return (+ node.type === 'JSXExpressionContainer' &&+ (node.expression?.type === 'ConditionalExpression' ||+ node.expression?.type === 'LogicalExpression')+ );+}++/** Children that produce output, i.e. everything but formatting whitespace. */+function renderedChildren(node) {+ const children = node?.children;+ if (!children) {+ return null;+ }+ return children.filter((child) => !isBlankText(child));+}++/** True when `node` is a JSX child rendered alongside at least one other child. */+function hasSiblings(node) {+ if (!(node?.parent?.children?.length > 1)) {+ return false;+ }+ return renderedChildren(node.parent).some((child) => child !== node);+}++function isPrecededByConditional(node) {+ const children = renderedChildren(node?.parent);+ if (!children) {+ return false;+ }+ return children.some(+ (child) => child.start < node.start && isRenderedConditional(child),+ );+}++/** Walk out of nested conditionals so nested branches report against the outer container. */+function getOutermostConditional(node) {+ let current = node;+ while (isConditionallyRendered(current)) {+ current = current.parent;+ }+ return current;+}++/** True when `node` is a conditional branch rendered directly beside other JSX children. */+function isProblematicConditional(node) {+ if (!isConditionallyRendered(node)) {+ return false;+ }++ const container = getOutermostConditional(node);+ return (+ container.parent?.type === 'JSXExpressionContainer' &&+ container.parent.parent?.type === 'JSXElement' &&+ hasSiblings(container.parent)+ );+}++/** True when `node` renders after a sibling conditional, i.e. the DOM order Translate breaks. */+function followsConditionalSibling(node) {+ return (+ node.parent?.parent?.type === 'JSXElement' &&+ hasSiblings(node.parent) &&+ isPrecededByConditional(node.parent)+ );+}++/**+ * `A && B` and the test of a ternary are conditions, not rendered output.+ */+function isCondition(node) {+ let current = node;+ while (current.parent?.type === 'LogicalExpression') {+ if (current.parent.left === current) {+ return true;+ }+ current = current.parent;+ }+ if (current.parent?.type === 'ConditionalExpression') {+ return current.parent.test === current;+ }+ return false;+}++function isConditionOperand(node) {+ if (node.parent?.type === 'BinaryExpression') {+ return isCondition(node.parent);+ }+ return isCondition(node);+}++// A string may only be inlined as JSX text when it needs no escaping and no+// whitespace of its own: JSX collapses leading and trailing whitespace, and+// these characters would either close the element or start an entity.+const NEEDS_BRACES = /['"{}<>&\r\n]/;++// `display: contents`, declared in src/styles.scss. React owns the element so+// Translate's `<font>` swap is absorbed, while the box tree stays as it was and+// a flex or grid parent still sees one contiguous text run.+const OPEN = '<span className="translate-safe">';+const CLOSE = '</span>';++/** Wraps the reported expression so React owns an element Translate cannot replace. */+function wrapExpression(fixer, sourceCode, node) {+ // A call reported on its own already sits in a container. Replacing the+ // container yields `<span …>{expr}</span>` rather than `{<span …>{expr}</span>}`.+ const target =+ node.parent?.type === 'JSXExpressionContainer' ? node.parent : node;++ if (+ node.type === 'Literal' &&+ typeof node.value === 'string' &&+ !NEEDS_BRACES.test(node.value) &&+ node.value.trim() === node.value+ ) {+ return fixer.replaceText(target, `${OPEN}${node.value}${CLOSE}`);+ }++ return fixer.replaceText(+ target,+ `${OPEN}{${sourceCode.getText(node)}}${CLOSE}`,+ );+}++/**+ * Wraps static JSX text. Only the visible run is wrapped: the node also spans+ * the formatting whitespace around it, which has to stay outside the element.+ */+function wrapJsxText(fixer, node) {+ const raw = node.value;+ const leading = raw.length - raw.trimStart().length;+ const trailing = raw.length - raw.trimEnd().length;+ return fixer.replaceTextRange(+ [node.start + leading, node.end - trailing],+ `${OPEN}${raw.trim()}${CLOSE}`,+ );+}++export default {+ meta: {+ type: 'problem',+ docs: {+ description:+ 'Conditionally rendered text nodes should be wrapped in an element (for example a `<span>`), otherwise Google Translate can cause a browser error.',+ url: 'https://github.com/getcouped/eslint-plugin-react-google-translate#eslint-plugin-react-google-translate',+ },+ schema: [],+ // Wrapping adds a DOM element, which can turn into a flex/grid item or+ // break `> *` and `:nth-child` selectors, so it is offered as a suggestion+ // (`--fix-suggestions`) rather than applied by a bare `--fix`.+ hasSuggestions: true,+ messages: {+ 'conditional-text-node':+ 'Conditionally rendered text nodes with siblings, rendered as a direct child of a JSX element, must be wrapped so Google Translate cannot break React\'s DOM: `<span className="translate-safe">{value}</span>`. Translate replaces the bare text node with a `<font>` element and React then throws on `removeChild`. This also applies to values returned from functions, so `getString()` becomes `<span className="translate-safe">{getString()}</span>`.',+ 'text-node-preceded-by-conditional':+ 'Text nodes which are preceded by a conditional expression, rendered as a direct child of a JSX element, must be wrapped so Google Translate cannot break React\'s DOM: `<span className="translate-safe">text</span>`. Translate replaces the bare text node with a `<font>` element and React then throws on `removeChild`.',+ },+ },++ createOnce(context) {+ const suggestWrap = (build) => [{ desc: 'Wrap in a <span>', fix: build }];++ const wrap = (fixer, node) => wrapExpression(fixer, context.sourceCode, node);++ const reportConditional = (node) => {+ context.report({+ node,+ messageId: 'conditional-text-node',+ suggest: suggestWrap((fixer) => wrap(fixer, node)),+ });+ };++ const reportPreceded = (node, build) => {+ context.report({+ node,+ messageId: 'text-node-preceded-by-conditional',+ suggest: suggestWrap(build),+ });+ };++ return {+ // String and numeric branches: `{flag ? 'yes' : 'no'}`+ Literal(node) {+ if (node.value === null || typeof node.value === 'boolean') {+ return;+ }+ if (isBlankText(node)) {+ return;+ }+ if (isProblematicConditional(node)) {+ reportConditional(node);+ }+ },++ TemplateLiteral(node) {+ if (isBlankText(node)) {+ return;+ }+ if (isProblematicConditional(node)) {+ reportConditional(node);+ }+ },++ // Static text rendered after a conditional: `{flag && <b/>}trailing`+ JSXText(node) {+ if (isBlankText(node)) {+ return;+ }+ if (hasSiblings(node) && isPrecededByConditional(node)) {+ reportPreceded(node, (fixer) => wrapJsxText(fixer, node));+ }+ },++ CallExpression(node) {+ if (isCondition(node) || !isTextReturningCall(node)) {+ return;+ }++ if (isProblematicConditional(node)) {+ reportConditional(node);+ }+ if (followsConditionalSibling(node)) {+ reportPreceded(node, (fixer) => wrap(fixer, node));+ }+ },++ // Values read off an object: `{flag ? user.name : 'anonymous'}`+ MemberExpression(node) {+ if (isConditionOperand(node)) {+ return;+ }+ if (isProblematicConditional(node)) {+ reportConditional(node);+ }+ },++ // Optional chaining wraps the member expression: `{flag ? a?.b?.c : 'x'}`+ ChainExpression(node) {+ if (isConditionOperand(node)) {+ return;+ }+ if (isProblematicConditional(node)) {+ reportConditional(node);+ }+ },+ };+ },+};diff --git a/frontend/plugins/rules/no-return-text-nodes.mjs b/frontend/plugins/rules/no-return-text-nodes.mjsnew file mode 100644index 0000000000..6980147b73--- /dev/null+++ b/frontend/plugins/rules/no-return-text-nodes.mjs@@ -0,0 +1,115 @@+/**+ * Rule: no-return-text-nodes+ *+ * React components should not return a bare text node. Google Translate keeps+ * displaying the stale translated text after a state change and nothing throws,+ * which makes the bug very hard to track down. Numbers count too: JSX renders+ * them as text.+ *+ * Adapted from https://github.com/getcouped/eslint-plugin-react-google-translate+ * (v1.0.4). Upstream walks the function body statement by statement; this+ * version visits `ReturnStatement` directly and walks up to the enclosing+ * function, which covers the same constructs without enumerating them.+ */++const FUNCTION_TYPES = new Set([+ 'FunctionDeclaration',+ 'FunctionExpression',+ 'ArrowFunctionExpression',+]);++function isTextNode(node) {+ if (!node) {+ return false;+ }+ if (node.type === 'TemplateLiteral') {+ return true;+ }+ return (+ node.type === 'Literal' &&+ (typeof node.value === 'string' || typeof node.value === 'number')+ );+}++function getEnclosingFunction(node) {+ let current = node.parent;+ while (current) {+ if (FUNCTION_TYPES.has(current.type)) {+ return current;+ }+ current = current.parent;+ }+ return null;+}++function isComponentName(name) {+ return (+ typeof name === 'string' && name !== '' && name[0] === name[0].toUpperCase()+ );+}++// The suggestion introduces JSX, which only parses in a JSX-enabled file.+function allowsJsx(filename) {+ return filename.endsWith('.tsx') || filename.endsWith('.jsx');+}++export default {+ meta: {+ type: 'problem',+ docs: {+ description:+ 'React components should avoid returning text nodes directly (or numerical values which will be rendered as text). When a React component returns values other than JSX / null, Google Translate can continue to display stale values after state changes, without any error being thrown. Since this is very hard to debug it is better to avoid it altogether.',+ url: 'https://github.com/getcouped/eslint-plugin-react-google-translate#eslint-plugin-react-google-translate',+ },+ schema: [],+ // Wrapping changes what the component renders, so it is offered as a+ // suggestion (`--fix-suggestions`) rather than applied by a bare `--fix`.+ hasSuggestions: true,+ messages: {+ 'return-value-is-text-node':+ 'React components should avoid returning text nodes directly (or numerical values which will be rendered as text). When a React component returns values other than JSX / null, Google Translate can continue to display stale values after state changes, without any error being thrown. Since this is very hard to debug it is better to avoid it altogether.',+ },+ },++ createOnce(context) {+ const buildSuggestion = (node) => {+ if (!allowsJsx(context.filename)) {+ return undefined;+ }+ return [+ {+ desc: 'Wrap in a <span>',+ fix: (fixer) =>+ fixer.replaceText(+ node.argument,+ `<span className="translate-safe">{${context.sourceCode.getText(node.argument)}}</span>`,+ ),+ },+ ];+ };++ return {+ ReturnStatement(node) {+ if (!isTextNode(node.argument)) {+ return;+ }++ // Only named function declarations are recognised as components, so a+ // text return from a nested helper or a class method is left alone.+ const fn = getEnclosingFunction(node);+ if (fn?.type !== 'FunctionDeclaration') {+ return;+ }+ if (!isComponentName(fn.id?.name)) {+ return;+ }++ context.report({+ node,+ messageId: 'return-value-is-text-node',+ suggest: buildSuggestion(node),+ });+ },+ };+ },+};diff --git a/frontend/plugins/signoz.mjs b/frontend/plugins/signoz.mjsindex e237fa8324..c17a0c3632 100644--- a/frontend/plugins/signoz.mjs+++ b/frontend/plugins/signoz.mjs@@ -13,6 +13,8 @@ import noAntdComponents from './rules/no-antd-components.mjs';import noSignozhqUiBarrel from './rules/no-signozhq-ui-barrel.mjs';import noCssModuleBracketAccess from './rules/no-css-module-bracket-access.mjs';import noDashboardFetchOutsideRoot from './rules/no-dashboard-fetch-outside-root.mjs';+import noConditionalTextNodesWithSiblings from './rules/no-conditional-text-nodes-with-siblings.mjs';+import noReturnTextNodes from './rules/no-return-text-nodes.mjs';export default {meta: {@@ -27,5 +29,7 @@ export default {'no-signozhq-ui-barrel': noSignozhqUiBarrel,'no-css-module-bracket-access': noCssModuleBracketAccess,'no-dashboard-fetch-outside-root': noDashboardFetchOutsideRoot,+ 'no-conditional-text-nodes-with-siblings': noConditionalTextNodesWithSiblings,+ 'no-return-text-nodes': noReturnTextNodes,},};diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yamlindex d0f445bc94..0fe84fa387 100644--- a/frontend/pnpm-lock.yaml+++ b/frontend/pnpm-lock.yaml@@ -294,6 +294,9 @@ importers:timestamp-nano:specifier: ^1.0.0version: 1.0.1+ translation-resilience:+ specifier: ^0.2.0+ version: 0.2.0typescript:specifier: 5.9.3version: 5.9.3@@ -8475,6 +8478,9 @@ packages:resolution: {integrity: sha512-l7FvfAHlcmulp8kr+flpQZmVwtu7nfRV7NZujtN0OqES8EL4O4e0qqzL0DC5gAvx/ZC/9lk6rhcUwYvkBnBnYA==}engines: {node: '>=12'}+ resolution: {integrity: sha512-IxTjhpHGp1SJxVEEPBu/YbBaHnymMRJdYxUY1i5qtYADuz9b8fdWhZSE/EeRS2aVIiuQjRqtYDk69ruS/3fzTg==}+resolution: {integrity: sha512-kRj8B+YHZCc9kQYdWfJB2/oUl9rA99qbowYYBtr4ui4mZyAQ2JpvVBd/6U2YloATfqBhBTSMhTpgBHtU0Mf3Rg==}@@ -18232,6 +18238,8 @@ snapshots:dependencies:punycode: 2.3.1+ [email protected]: {}+diff --git a/frontend/src/index.tsx b/frontend/src/index.tsxindex d705576b2a..1ed54da112 100644--- a/frontend/src/index.tsx+++ b/frontend/src/index.tsx@@ -13,11 +13,13 @@ import { AppProvider } from 'providers/App/App';import TimezoneProvider from 'providers/Timezone';import store from 'store';import APIError from 'types/api/error';+import { installTranslationResilience } from 'translation-resilience';import './ReactI18';import 'styles.scss';+installTranslationResilience();configureOverlayScrollbars();const queryClient = new QueryClient({diff --git a/frontend/src/styles.scss b/frontend/src/styles.scssindex 3736143259..db679bbab9 100644--- a/frontend/src/styles.scss+++ b/frontend/src/styles.scss@@ -30,6 +30,10 @@ body {box-sizing: border-box;}+.translate-safe {+ display: contents;+}+// Respect user's reduced motion preference@media (prefers-reduced-motion: reduce) {* {