@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 03:37 UTC

main
ts 452 lines 13.3 KB
Raw
1 import { defineRule, type ESTree } from "@oxlint/plugins";
2 import * as Option from "effect/Option";
3
4 import { getPropertyName, unwrapExpression } from "../utils.ts";
5
6 const MESSAGE =
7 "Untranslated copy. Wrap JSX text in <T>, props in gt(), and strings outside React in m(msg()). See docs/internals/i18n.md.";
8
9 // Props and object keys whose string values users read.
10 const COPY_NAMES = new Set([
11 "alt",
12 "aria-description",
13 "aria-label",
14 "aria-placeholder",
15 "aria-roledescription",
16 "aria-valuetext",
17 "caption",
18 "children",
19 "description",
20 "detail",
21 "emptyState",
22 "error",
23 "heading",
24 "headline",
25 "hint",
26 "label",
27 "message",
28 "notice",
29 "placeholder",
30 "subtitle",
31 "summary",
32 "text",
33 "title",
34 "tooltip",
35 ]);
36 const COPY_NAME_SUFFIX =
37 /(?:Label|Title|Tooltip|Description|Placeholder|Hint|Heading|Message|Reason|Text)$/u;
38 const COPY_ATTRIBUTES = new Set([
39 "alt",
40 "aria-description",
41 "aria-label",
42 "aria-placeholder",
43 "aria-roledescription",
44 "aria-valuetext",
45 "placeholder",
46 "title",
47 ]);
48
49 // Calls whose leading arguments are read or heard by the user: screen reader announcements,
50 // native dialogs.
51 const COPY_CALLS = new Map([
52 ["announce", 1],
53 ["confirm", 1],
54 ["alert", 2],
55 ["prompt", 2],
56 ]);
57 // Setters and reporters whose every string argument ends up on screen.
58 const COPY_CALL_NAME =
59 /^(?:set\w*(?:Error|Message|Notice|Status|Label|Title|Hint)|(?:report|show)\w*(?:Failure|Error|Notice)|on(?:Error|Failure))$/u;
60
61 // Atom command and query options: their `label` names the operation in logs.
62 const LOG_LABEL_CALLS = new Set([
63 "executeAtomQuery",
64 "reportAtomCommandResult",
65 "runAtomCommand",
66 "useAtomCommand",
67 "useAtomQueryRunner",
68 "useOrchestrationCommand",
69 ]);
70 const LOG_LABEL_SIBLINGS = new Set(["reportDefect", "reportFailure", "refresh"]);
71 // Error payloads are data for logs and callers; the screen translates at the call site.
72 const ERROR_CLASS_NAME = /(?:Error|Refusal|Failure|Exception|Defect)$/u;
73
74 // Text inside these renders code, a keybinding, or is already translated.
75 const NON_COPY_ELEMENTS = new Set([
76 "T",
77 "Var",
78 "Num",
79 "Currency",
80 "DateTime",
81 "RelativeTime",
82 "code",
83 "kbd",
84 "pre",
85 "samp",
86 "script",
87 "style",
88 "Kbd",
89 "KbdGroup",
90 ]);
91
92 // Key names that are also common words: exempt only as the whole text.
93 const WHOLE_TEXT_NAMES = new Set([
94 "Delete",
95 "Down",
96 "End",
97 "Enter",
98 "Home",
99 "Left",
100 "Option",
101 "Right",
102 "Space",
103 "Tab",
104 "Up",
105 // navigator.platform values.
106 "Win32",
107 "MacIntel",
108 ]);
109
110 // Names shown as-is in every language. Removed from the text before looking for words.
111 const PROPER_NOUNS = [
112 "T3 Code",
113 "T3 Connect",
114 "T3 Chat",
115 "GitHub",
116 "GitLab",
117 "Bitbucket",
118 "Azure DevOps",
119 "Forgejo",
120 "Codex",
121 "Claude",
122 "Claude Code",
123 "Cursor",
124 "Grok",
125 "Grok Build",
126 "OpenCode",
127 "Antigravity",
128 "Kiro",
129 "Pi",
130 "Muse Code",
131 "OpenAI",
132 "OpenRouter",
133 "Anthropic",
134 "Tailscale",
135 "Simlock",
136 "macOS",
137 "Windows",
138 "Linux",
139 "iOS",
140 "Android",
141 "ChromeOS",
142 "Finder",
143 "CarPlay",
144 "VoiceOver",
145 "Liquid Glass",
146 "One UI",
147 "Material",
148 "Material You",
149 "KDE Plasma",
150 "GNOME",
151 "Niri",
152 "Hyprland",
153 "SF Pro",
154 "SF Mono",
155 "Chrome",
156 "Edge",
157 "Firefox",
158 "Opera",
159 "Safari",
160 "Samsung Internet",
161 // Programming languages and formats.
162 "Bash",
163 "Dart",
164 "Dockerfile",
165 "Elixir",
166 "Go",
167 "GraphQL",
168 "Haskell",
169 "Java",
170 "JavaScript",
171 "Kotlin",
172 "Lua",
173 "Markdown",
174 "Mermaid",
175 "PowerShell",
176 "Python",
177 "Ruby",
178 "Rust",
179 "Scala",
180 "Svelte",
181 "Swift",
182 "TypeScript",
183 "Vue",
184 "Zig",
185 // Modifier keys, never words.
186 "Alt",
187 "Backspace",
188 "Cmd",
189 "Ctrl",
190 "Esc",
191 "Shift",
192 "PageUp",
193 "PageDown",
194 ];
195 const escapeRegExp = (text: string) => text.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
196 const PROPER_NOUN_PATTERN = new RegExp(
197 `(?<![\\p{L}\\d])(?:${PROPER_NOUNS.toSorted((left, right) => right.length - left.length)
198 .map(escapeRegExp)
199 .join("|")})(?![\\p{L}\\d])`,
200 "gu",
201 );
202
203 const HAS_WORD = /\p{L}\p{L}/u;
204 const URL_OR_PATH = /^(?:[a-z][a-z0-9+.-]*:\/\/|mailto:|data:|\/|\.\.?\/|~\/|#)/u;
205 // One lowercase token is an id, key, command, or icon name, not a sentence.
206 const CODE_TOKEN = /^[a-z0-9@$_.:/=-][^\s]*$/u;
207 // One all-caps token is an acronym or format name: HEX, PDF, SSH, JSON.
208 const ACRONYM = /^[\p{Lu}\d][\p{Lu}\d+#.]*$/u;
209 // One token with a capital after a lowercase letter is an identifier or brand: PageUp, OpenAI.
210 const CAMEL_TOKEN = /^[\p{L}\d.]*\p{Ll}\p{Lu}[\p{L}\d.]*$/u;
211 const TEMPLATE_PLACEHOLDER = /\{\{[^}]*\}\}/gu;
212 const CLASS_CHARACTER = /[-:/[\]]/u;
213
214 // A Tailwind class list: lowercase tokens with utility punctuation, as in cva variant maps.
215 const isClassList = (text: string) =>
216 !/\p{Lu}/u.test(text) && text.split(" ").every((token) => CLASS_CHARACTER.test(token));
217
218 const normalize = (raw: string) => raw.replace(/\s+/gu, " ").trim();
219
220 const isCopy = (raw: string) => {
221 const text = normalize(raw);
222 if (!HAS_WORD.test(text) || URL_OR_PATH.test(text) || CODE_TOKEN.test(text)) return false;
223 if (text === "OK") return true;
224 if (WHOLE_TEXT_NAMES.has(text) || ACRONYM.test(text) || CAMEL_TOKEN.test(text)) return false;
225 if (isClassList(text)) return false;
226 return HAS_WORD.test(text.replace(TEMPLATE_PLACEHOLDER, " ").replace(PROPER_NOUN_PATTERN, " "));
227 };
228
229 const leafText = (leaf: ESTree.Node) =>
230 leaf.type === "Literal"
231 ? String(leaf.value)
232 : leaf.type === "TemplateLiteral"
233 ? leaf.quasis.map((quasi) => quasi.value.cooked ?? "").join(" ")
234 : "";
235
236 // Returned strings are often CSS, commands, or class lists; sentences start with a capital.
237 const hasCapitalizedWord = (text: string) => /(?:^|\s)\p{Lu}\p{Ll}/u.test(text.trim());
238
239 // An Error's `get message()` text is for logs, not the screen.
240 const isErrorMessageGetter = (node: ESTree.Node) => {
241 for (let current = node.parent; current; current = current.parent) {
242 if (current.type === "MethodDefinition") {
243 return (
244 current.kind === "get" && Option.getOrUndefined(getPropertyName(current.key)) === "message"
245 );
246 }
247 }
248 return false;
249 };
250
251 const isLiteralUnion = (type: ESTree.TSType): boolean =>
252 type.type === "TSLiteralType" ||
253 (type.type === "TSUnionType" &&
254 type.types.every(
255 (member) =>
256 member.type === "TSLiteralType" ||
257 member.type === "TSNullKeyword" ||
258 member.type === "TSUndefinedKeyword",
259 ));
260
261 const enclosingFunction = (node: ESTree.Node) => {
262 for (let current = node.parent; current; current = current.parent) {
263 if (
264 current.type === "FunctionDeclaration" ||
265 current.type === "FunctionExpression" ||
266 current.type === "ArrowFunctionExpression"
267 ) {
268 return current;
269 }
270 }
271 return undefined;
272 };
273
274 const isCopyName = (name: string) => COPY_NAMES.has(name) || COPY_NAME_SUFFIX.test(name);
275
276 const calleeName = (callee: unknown) => {
277 const node = unwrapExpression(callee);
278 if (Option.isNone(node)) return undefined;
279 if (node.value.type === "Identifier") return node.value.name;
280 if (node.value.type === "MemberExpression") {
281 return Option.getOrUndefined(getPropertyName(node.value.property));
282 }
283 return undefined;
284 };
285
286 const elementName = (node: ESTree.JSXElement): string | undefined => {
287 const name = node.openingElement.name;
288 if (name.type === "JSXIdentifier") return name.name;
289 if (name.type === "JSXMemberExpression") return name.property.name;
290 return undefined;
291 };
292
293 const nonCopyAncestors = (node: ESTree.Node) => {
294 const names = new Set<string>();
295 for (let current = node.parent; current; current = current.parent) {
296 if (current.type === "JSXElement") {
297 const name = elementName(current);
298 if (name !== undefined && NON_COPY_ELEMENTS.has(name)) names.add(name);
299 }
300 }
301 return names;
302 };
303
304 const insideNonCopyElement = (node: ESTree.Node) => nonCopyAncestors(node).size > 0;
305
306 // Inside only <code>, a plain sentence is copy: capitalized words, no code punctuation.
307 const isPlainSentenceInCode = (ancestors: ReadonlySet<string>, raw: string) => {
308 const text = normalize(raw);
309 return (
310 ancestors.size === 1 &&
311 ancestors.has("code") &&
312 /^\p{Lu}[\p{L}\d ,.'!?]*$/u.test(text) &&
313 text.includes(" ") &&
314 isCopy(text)
315 );
316 };
317
318 /** String and template literals an expression can evaluate to, through ternaries and fallbacks. */
319 const literalLeaves = (expression: unknown): ReadonlyArray<ESTree.Node> => {
320 const node = unwrapExpression(expression);
321 if (Option.isNone(node)) return [];
322 const value = node.value;
323 switch (value.type) {
324 case "Literal":
325 return typeof value.value === "string" && isCopy(value.value) ? [value] : [];
326 case "TemplateLiteral":
327 return isCopy(value.quasis.map((quasi) => quasi.value.cooked ?? "").join(" ")) ? [value] : [];
328 case "ConditionalExpression":
329 return [...literalLeaves(value.consequent), ...literalLeaves(value.alternate)];
330 case "LogicalExpression":
331 return value.operator === "&&"
332 ? literalLeaves(value.right)
333 : [...literalLeaves(value.left), ...literalLeaves(value.right)];
334 default:
335 return [];
336 }
337 };
338
339 const isNonCopyProperty = (object: ESTree.ObjectExpression, name: string) => {
340 const owner = object.parent;
341 if (owner?.type === "NewExpression" && object === owner.arguments[0]) {
342 if (ERROR_CLASS_NAME.test(calleeName(owner.callee) ?? "")) return true;
343 }
344 if (name !== "label") return false;
345 if (owner?.type === "CallExpression" && LOG_LABEL_CALLS.has(calleeName(owner.callee) ?? "")) {
346 return true;
347 }
348 return object.properties.some((property) => {
349 if (property.type !== "Property") return false;
350 const key = getPropertyName(property.key);
351 return Option.isSome(key) && LOG_LABEL_SIBLINGS.has(key.value);
352 });
353 };
354
355 export default defineRule({
356 meta: {
357 type: "suggestion",
358 docs: {
359 description:
360 "Flag user-facing English that is not wrapped for translation: JSX text, copy props, and copy keys.",
361 },
362 },
363 create(context) {
364 const report = (node: ESTree.Node) => context.report({ node, message: MESSAGE });
365 const reportLeaves = (expression: unknown) => {
366 for (const leaf of literalLeaves(expression)) report(leaf);
367 };
368 // Type aliases in this file that are unions of literals: returning a member is not copy.
369 const literalUnionAliases = new Set<string>();
370 return {
371 Program(node) {
372 for (const statement of node.body) {
373 const declaration =
374 statement.type === "ExportNamedDeclaration" ? statement.declaration : statement;
375 if (
376 declaration?.type === "TSTypeAliasDeclaration" &&
377 isLiteralUnion(declaration.typeAnnotation)
378 ) {
379 literalUnionAliases.add(declaration.id.name);
380 }
381 }
382 },
383 JSXText(node) {
384 const ancestors = nonCopyAncestors(node);
385 if (
386 ancestors.size === 0 ? isCopy(node.value) : isPlainSentenceInCode(ancestors, node.value)
387 ) {
388 report(node);
389 }
390 },
391 JSXExpressionContainer(node) {
392 const parent = node.parent;
393 if (parent?.type !== "JSXElement" && parent?.type !== "JSXFragment") return;
394 if (insideNonCopyElement(node)) return;
395 reportLeaves(node.expression);
396 },
397 JSXAttribute(node) {
398 if (node.name.type !== "JSXIdentifier" || !isCopyName(node.name.name)) return;
399 const value = node.value;
400 if (value?.type === "Literal") reportLeaves(value);
401 else if (value?.type === "JSXExpressionContainer") reportLeaves(value.expression);
402 },
403 CallExpression(node) {
404 const name = calleeName(node.callee);
405 if (name === undefined) return;
406 if (name === "setAttribute") {
407 const attribute = unwrapExpression(node.arguments[0]);
408 if (
409 Option.isSome(attribute) &&
410 attribute.value.type === "Literal" &&
411 typeof attribute.value.value === "string" &&
412 COPY_ATTRIBUTES.has(attribute.value.value)
413 ) {
414 reportLeaves(node.arguments[1]);
415 }
416 return;
417 }
418 const copyArguments =
419 COPY_CALLS.get(name) ?? (COPY_CALL_NAME.test(name) ? node.arguments.length : 0);
420 for (const argument of node.arguments.slice(0, copyArguments)) reportLeaves(argument);
421 },
422 // Label helpers: a function returning a sentence returns copy.
423 ReturnStatement(node) {
424 if (isErrorMessageGetter(node)) return;
425 const returnType = enclosingFunction(node)?.returnType?.typeAnnotation;
426 if (
427 returnType !== undefined &&
428 (isLiteralUnion(returnType) ||
429 (returnType.type === "TSTypeReference" &&
430 returnType.typeName.type === "Identifier" &&
431 literalUnionAliases.has(returnType.typeName.name)))
432 ) {
433 return;
434 }
435 for (const leaf of literalLeaves(node.argument)) {
436 if (hasCapitalizedWord(leafText(leaf))) report(leaf);
437 }
438 },
439 Property(node) {
440 if (node.parent?.type !== "ObjectExpression" || node.computed) return;
441 const name = getPropertyName(node.key);
442 if (Option.isNone(name) || !isCopyName(name.value)) return;
443 if (isNonCopyProperty(node.parent, name.value)) return;
444 reportLeaves(node.value);
445 },
446 // Defaults such as `emptyLabel = "No results"` are copy.
447 AssignmentPattern(node) {
448 if (node.left.type === "Identifier" && isCopyName(node.left.name)) reportLeaves(node.right);
449 },
450 };
451 },
452 });