i18next-cli 1.88.1 → 1.90.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +104 -12
- package/dist/cjs/cli.js +25 -6
- package/dist/cjs/config.js +13 -12
- package/dist/cjs/extractor/core/extractor.js +1 -3
- package/dist/cjs/extractor/core/translation-manager.js +9 -2
- package/dist/cjs/heuristic-config.js +51 -6
- package/dist/cjs/index.js +2 -1
- package/dist/cjs/init.js +8 -11
- package/dist/cjs/instrumenter/core/instrumenter.js +1372 -218
- package/dist/cjs/instrumenter/core/key-generator.js +20 -9
- package/dist/cjs/instrumenter/core/next-files.js +104 -0
- package/dist/cjs/instrumenter/core/string-detector.js +106 -29
- package/dist/cjs/instrumenter/core/transformer.js +165 -83
- package/dist/cjs/localize/agent-prompt.js +5 -2
- package/dist/cjs/localize/detect.js +3 -11
- package/dist/cjs/localize/localize.js +27 -5
- package/dist/cjs/utils/file-utils.js +48 -0
- package/dist/cjs/utils/jsx-attributes.js +3 -1
- package/dist/esm/cli.js +25 -6
- package/dist/esm/config.js +13 -12
- package/dist/esm/extractor/core/extractor.js +1 -3
- package/dist/esm/extractor/core/translation-manager.js +9 -2
- package/dist/esm/heuristic-config.js +52 -7
- package/dist/esm/index.js +2 -1
- package/dist/esm/init.js +8 -11
- package/dist/esm/instrumenter/core/instrumenter.js +1376 -222
- package/dist/esm/instrumenter/core/key-generator.js +20 -9
- package/dist/esm/instrumenter/core/next-files.js +101 -0
- package/dist/esm/instrumenter/core/string-detector.js +107 -31
- package/dist/esm/instrumenter/core/transformer.js +165 -83
- package/dist/esm/localize/agent-prompt.js +5 -2
- package/dist/esm/localize/detect.js +4 -12
- package/dist/esm/localize/localize.js +27 -5
- package/dist/esm/utils/file-utils.js +49 -2
- package/dist/esm/utils/jsx-attributes.js +3 -1
- package/package.json +1 -1
- package/types/cli.d.ts.map +1 -1
- package/types/config.d.ts.map +1 -1
- package/types/extractor/core/extractor.d.ts.map +1 -1
- package/types/extractor/core/translation-manager.d.ts.map +1 -1
- package/types/heuristic-config.d.ts.map +1 -1
- package/types/index.d.ts +1 -1
- package/types/index.d.ts.map +1 -1
- package/types/init.d.ts.map +1 -1
- package/types/instrumenter/core/instrumenter.d.ts.map +1 -1
- package/types/instrumenter/core/key-generator.d.ts +2 -0
- package/types/instrumenter/core/key-generator.d.ts.map +1 -1
- package/types/instrumenter/core/next-files.d.ts +25 -0
- package/types/instrumenter/core/next-files.d.ts.map +1 -0
- package/types/instrumenter/core/string-detector.d.ts +5 -1
- package/types/instrumenter/core/string-detector.d.ts.map +1 -1
- package/types/instrumenter/core/transformer.d.ts +16 -1
- package/types/instrumenter/core/transformer.d.ts.map +1 -1
- package/types/instrumenter/index.d.ts +1 -1
- package/types/instrumenter/index.d.ts.map +1 -1
- package/types/localize/agent-prompt.d.ts +1 -1
- package/types/localize/agent-prompt.d.ts.map +1 -1
- package/types/localize/detect.d.ts +2 -0
- package/types/localize/detect.d.ts.map +1 -1
- package/types/localize/localize.d.ts.map +1 -1
- package/types/types.d.ts +87 -1
- package/types/types.d.ts.map +1 -1
- package/types/utils/file-utils.d.ts +7 -0
- package/types/utils/file-utils.d.ts.map +1 -1
- package/types/utils/jsx-attributes.d.ts.map +1 -1
|
@@ -14,24 +14,31 @@
|
|
|
14
14
|
function generateKeyFromContent(content) {
|
|
15
15
|
// Remove punctuation and split by whitespace and word boundaries
|
|
16
16
|
const normalized = content
|
|
17
|
+
// A placeholder's name gives words of its own: `{{unreadNews}}` → unread News
|
|
18
|
+
.replace(/\{\{\s*([^}]*?)\s*\}\}/g, (_, name) => ` ${name.replace(/([a-z0-9])([A-Z])/g, '$1 $2')} `)
|
|
19
|
+
.replace(/_/g, ' ') // `_` separates plural and context suffixes in i18next keys: none in a generated one
|
|
20
|
+
.normalize('NFD').replace(/[\u0300-\u036f]/g, '') // `Français` → Francais, not Franais
|
|
17
21
|
.replace(/[^\w\s\d]/g, '') // Remove punctuation
|
|
18
22
|
.trim();
|
|
19
23
|
if (!normalized) {
|
|
20
24
|
return 'key';
|
|
21
25
|
}
|
|
22
|
-
// Split on whitespace and camelCase
|
|
26
|
+
// Split on whitespace and camelCase; whole words up to MAX_KEY_LENGTH, the first word always
|
|
23
27
|
const words = normalized.split(/\s+/);
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
}
|
|
31
|
-
.join('');
|
|
28
|
+
let camelCased = '';
|
|
29
|
+
for (const [index, word] of words.entries()) {
|
|
30
|
+
const part = index === 0 ? word.toLowerCase() : word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
|
|
31
|
+
if (index > 0 && camelCased.length + part.length > MAX_KEY_LENGTH)
|
|
32
|
+
break;
|
|
33
|
+
camelCased += part;
|
|
34
|
+
}
|
|
32
35
|
// If result is empty, use fallback
|
|
33
36
|
return camelCased.length > 0 ? camelCased : 'key';
|
|
34
37
|
}
|
|
38
|
+
/** A key names its text, it does not repeat it: a long sentence's key keeps its first words. */
|
|
39
|
+
const MAX_KEY_LENGTH = 40;
|
|
40
|
+
/** The content of a key reserved as the parent of nested keys: no text matches it. */
|
|
41
|
+
const PARENT_KEY = '\u0000';
|
|
35
42
|
/**
|
|
36
43
|
* Creates a new key registry with collision detection.
|
|
37
44
|
*/
|
|
@@ -39,6 +46,10 @@ function createKeyRegistry() {
|
|
|
39
46
|
const keys = new Map();
|
|
40
47
|
return {
|
|
41
48
|
keys,
|
|
49
|
+
reserve(key, content) {
|
|
50
|
+
if (!keys.has(key))
|
|
51
|
+
keys.set(key, content ?? PARENT_KEY);
|
|
52
|
+
},
|
|
42
53
|
add(baseKey, content) {
|
|
43
54
|
const existing = keys.get(baseKey);
|
|
44
55
|
// No collision - add the key
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var node_fs = require('node:fs');
|
|
4
|
+
var node_path = require('node:path');
|
|
5
|
+
var config = require('../../config.js');
|
|
6
|
+
|
|
7
|
+
/** A `'use client'` directive: the first statement, after comments only. */
|
|
8
|
+
const USE_CLIENT_RE = /^(?:\s|\/\/[^\n]*\n|\/\*[\s\S]*?\*\/)*(['"])use client\1/;
|
|
9
|
+
/** The module specifiers of a file's static, dynamic and `require` imports and its re-exports. */
|
|
10
|
+
const IMPORT_RE = /\bfrom\s*['"]([^'"\n]+)['"]|\bimport\s*\(?\s*['"]([^'"\n]+)['"]|\brequire\(\s*['"]([^'"\n]+)['"]\s*\)/g;
|
|
11
|
+
const EXTENSIONS = ['', '.tsx', '.ts', '.jsx', '.js', '.mjs', '/index.tsx', '/index.ts', '/index.jsx', '/index.js'];
|
|
12
|
+
/**
|
|
13
|
+
* A file's absolute path with symbolic links resolved (`/var` is `/private/var` on macOS); one that does not exist
|
|
14
|
+
* (yet) resolves under the project root's real path.
|
|
15
|
+
*/
|
|
16
|
+
function real(file, cwd) {
|
|
17
|
+
const abs = node_path.resolve(cwd, file);
|
|
18
|
+
try {
|
|
19
|
+
return node_fs.realpathSync(abs);
|
|
20
|
+
}
|
|
21
|
+
catch { }
|
|
22
|
+
try {
|
|
23
|
+
return abs.startsWith(cwd + node_path.sep) ? node_fs.realpathSync(cwd) + abs.slice(cwd.length) : abs;
|
|
24
|
+
}
|
|
25
|
+
catch {
|
|
26
|
+
return abs;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
/** A file's path in the project, `/`-separated, without a leading `src/`: `app/page.tsx`, `pages/api/hello.js`. */
|
|
30
|
+
function projectPath(file, cwd = process.cwd()) {
|
|
31
|
+
return node_path.relative(real(cwd, cwd), real(file, cwd)).split(node_path.sep).join('/').replace(/^src\//, '');
|
|
32
|
+
}
|
|
33
|
+
/** The directory a file lies in under the project root: `app` or `src/app` (App Router), `pages` or `src/pages`. */
|
|
34
|
+
function routerOf(file, cwd) {
|
|
35
|
+
const top = projectPath(file, cwd).split('/')[0];
|
|
36
|
+
return top === 'app' || top === 'pages' ? top : null;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Classifies the files of a Next.js app by the components that render them, from the import graph: a file under
|
|
40
|
+
* `app/` is a Server Component unless it says `'use client'`; a `'use client'` file and all it imports are Client
|
|
41
|
+
* Components; a file under `pages/` and all it imports render with the Pages Router. Imports resolve relative,
|
|
42
|
+
* through the tsconfig `paths`, from the project root (a `baseUrl` import, `components/Card`) and with the `.js`
|
|
43
|
+
* of an ESM import for a `.ts` file; only the given files count.
|
|
44
|
+
*
|
|
45
|
+
* @param contents - The files' contents by path (relative to `cwd` or absolute)
|
|
46
|
+
* @returns The kind of each file and the files it imports, by the paths they were given with; a file nothing
|
|
47
|
+
* reaches is `unknown` (`pages` in an app without `app/`)
|
|
48
|
+
*/
|
|
49
|
+
async function classifyNextFiles(contents, cwd = process.cwd()) {
|
|
50
|
+
const aliases = Object.entries(await config.getTsConfigAliases());
|
|
51
|
+
// by real path: the tsconfig aliases are real paths, and an absolute input glob may name a link (`/var/…`)
|
|
52
|
+
const byAbs = new Map([...contents.keys()].map(f => [real(f, cwd), f]));
|
|
53
|
+
const root = real(cwd, cwd);
|
|
54
|
+
const resolveImport = (from, spec) => {
|
|
55
|
+
const alias = aliases.find(([key]) => spec === key || spec.startsWith(key + '/'));
|
|
56
|
+
const bases = spec.startsWith('.')
|
|
57
|
+
? [node_path.resolve(node_path.dirname(from), spec)]
|
|
58
|
+
: alias ? [node_path.resolve(alias[1], `.${spec.slice(alias[0].length)}`)] : [node_path.resolve(root, spec), node_path.resolve(root, 'src', spec)];
|
|
59
|
+
// resolve() again: an extension or `/index` joined to a Windows path
|
|
60
|
+
return bases.flatMap(base => [base, base.replace(/\.(?:m?js|jsx)$/, '')])
|
|
61
|
+
.flatMap(base => EXTENSIONS.map(ext => node_path.resolve(base + ext)))
|
|
62
|
+
.find(path => byAbs.has(path));
|
|
63
|
+
};
|
|
64
|
+
const imports = new Map();
|
|
65
|
+
const useClient = new Set();
|
|
66
|
+
for (const [abs, file] of byAbs) {
|
|
67
|
+
const code = contents.get(file);
|
|
68
|
+
if (USE_CLIENT_RE.test(code))
|
|
69
|
+
useClient.add(abs);
|
|
70
|
+
imports.set(abs, [...code.matchAll(IMPORT_RE)]
|
|
71
|
+
.map(m => resolveImport(abs, m[1] ?? m[2] ?? m[3]))
|
|
72
|
+
.filter((path) => !!path));
|
|
73
|
+
}
|
|
74
|
+
// Everything a set of files imports, transitively; a server walk stops at `'use client'`, the client boundary
|
|
75
|
+
const reach = (seeds, stopAtClient) => {
|
|
76
|
+
const seen = new Set();
|
|
77
|
+
const queue = [...seeds];
|
|
78
|
+
while (queue.length) {
|
|
79
|
+
const abs = queue.pop();
|
|
80
|
+
if (seen.has(abs) || (stopAtClient && useClient.has(abs)))
|
|
81
|
+
continue;
|
|
82
|
+
seen.add(abs);
|
|
83
|
+
queue.push(...imports.get(abs));
|
|
84
|
+
}
|
|
85
|
+
return seen;
|
|
86
|
+
};
|
|
87
|
+
const all = [...byAbs.keys()];
|
|
88
|
+
const server = reach(all.filter(abs => routerOf(abs, cwd) === 'app' && !useClient.has(abs)), true);
|
|
89
|
+
const appClient = reach([...useClient].filter(abs => routerOf(abs, cwd) !== 'pages'), false);
|
|
90
|
+
const pages = reach(all.filter(abs => routerOf(abs, cwd) === 'pages'), false);
|
|
91
|
+
const hasApp = all.some(abs => routerOf(abs, cwd) === 'app');
|
|
92
|
+
const kinds = new Map();
|
|
93
|
+
for (const [abs, file] of byAbs) {
|
|
94
|
+
// a file no route reaches may be rendered on either side, through an import that does not resolve
|
|
95
|
+
const kind = server.has(abs)
|
|
96
|
+
? (appClient.has(abs) || pages.has(abs) ? 'shared' : 'server')
|
|
97
|
+
: appClient.has(abs) ? 'client' : pages.has(abs) || !hasApp ? 'pages' : 'unknown';
|
|
98
|
+
kinds.set(file, kind);
|
|
99
|
+
}
|
|
100
|
+
return { kinds, imports: new Map([...imports].map(([abs, paths]) => [byAbs.get(abs), paths.map(path => byAbs.get(path))])) };
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
exports.classifyNextFiles = classifyNextFiles;
|
|
104
|
+
exports.projectPath = projectPath;
|
|
@@ -27,10 +27,12 @@ var jsxAttributes = require('../../utils/jsx-attributes.js');
|
|
|
27
27
|
* @param config - Toolkit configuration
|
|
28
28
|
* @param translatableAttributes - Lower-cased attribute names that hold text on the enclosing JSX element
|
|
29
29
|
* (from the per-element `extract.acceptedAttributes` rules); defaults to the built-in list
|
|
30
|
+
* @param isJsxText - The string is JSX text, where a single lower-case word (`<Tag>expired</Tag>`) is text
|
|
31
|
+
* rather than an identifier
|
|
30
32
|
* @returns CandidateString with confidence score, or null if should be skipped
|
|
31
33
|
*/
|
|
32
|
-
function detectCandidate(content, offset, endOffset, file, code, config, translatableAttributes = jsxAttributes.translatableAttributeSet) {
|
|
33
|
-
const skipReason = shouldSkip(content, file, code, offset,
|
|
34
|
+
function detectCandidate(content, offset, endOffset, file, code, config, translatableAttributes = jsxAttributes.translatableAttributeSet, isJsxText = false) {
|
|
35
|
+
const skipReason = shouldSkip(content, file, code, offset, translatableAttributes, isJsxText);
|
|
34
36
|
if (skipReason) {
|
|
35
37
|
return null;
|
|
36
38
|
}
|
|
@@ -71,12 +73,14 @@ function detectCandidate(content, offset, endOffset, file, code, config, transla
|
|
|
71
73
|
column
|
|
72
74
|
};
|
|
73
75
|
}
|
|
76
|
+
/** An HTML character reference in JSX text: ` `, `—`, `—`. */
|
|
77
|
+
const HTML_ENTITY_RE = /&(?:#\d+|#x[\da-f]+|[a-z][a-z\d]*);/gi;
|
|
74
78
|
/**
|
|
75
79
|
* Determines if a string should be skipped from instrumentation.
|
|
76
80
|
*
|
|
77
81
|
* @returns Skip reason if should be skipped, null otherwise
|
|
78
82
|
*/
|
|
79
|
-
function shouldSkip(content, file, code, offset,
|
|
83
|
+
function shouldSkip(content, file, code, offset, translatableAttributes, isJsxText) {
|
|
80
84
|
// Skip test files
|
|
81
85
|
if (file.match(/\.(test|spec)\.(ts|tsx|js|jsx)$/i)) {
|
|
82
86
|
return 'Test file';
|
|
@@ -89,6 +93,10 @@ function shouldSkip(content, file, code, offset, endOffset, translatableAttribut
|
|
|
89
93
|
if (/^\s+$/.test(content)) {
|
|
90
94
|
return 'Whitespace only';
|
|
91
95
|
}
|
|
96
|
+
// Skip separators, symbols and numbers with units: no letter outside HTML entities (` / `, `·`, `100%`)
|
|
97
|
+
if (!/\p{L}/u.test(content.replace(HTML_ENTITY_RE, ''))) {
|
|
98
|
+
return 'No letters';
|
|
99
|
+
}
|
|
92
100
|
// Skip pure numbers (including decimals and negative numbers)
|
|
93
101
|
if (/^-?\d+(\.\d+)?$/.test(content)) {
|
|
94
102
|
return 'Pure number';
|
|
@@ -97,16 +105,21 @@ function shouldSkip(content, file, code, offset, endOffset, translatableAttribut
|
|
|
97
105
|
if (isURLLike(content)) {
|
|
98
106
|
return 'URL or path';
|
|
99
107
|
}
|
|
100
|
-
// Skip technical strings: attribute values, class names, technical IDs
|
|
101
|
-
|
|
108
|
+
// Skip technical strings: attribute values, class names, technical IDs; in a text slot (JSX text, a
|
|
109
|
+
// translatable attribute) a single word is text (`<Tag>expired</Tag>`, `aria-label='actions'`)
|
|
110
|
+
const textSlot = isJsxText || translatableAttributes.has(attributeNameBefore(code, offset) ?? '');
|
|
111
|
+
if (isTechnicalString(content) && !(textSlot && /^\p{L}+$/u.test(content) && !/\p{Ll}\p{Lu}/u.test(content))) {
|
|
102
112
|
return 'Technical string';
|
|
103
113
|
}
|
|
114
|
+
if (isCodeSnippet(content)) {
|
|
115
|
+
return 'Code snippet';
|
|
116
|
+
}
|
|
104
117
|
// Skip developer-facing error codes (all-caps, underscore-delimited)
|
|
105
118
|
if (isErrorCode(content)) {
|
|
106
119
|
return 'Error code pattern';
|
|
107
120
|
}
|
|
108
121
|
// Skip strings that are already wrapped in t() or Trans components
|
|
109
|
-
if (isAlreadyInstrumented(code, offset
|
|
122
|
+
if (isAlreadyInstrumented(code, offset)) {
|
|
110
123
|
return 'Already instrumented';
|
|
111
124
|
}
|
|
112
125
|
// Skip console.log/warn/error arguments
|
|
@@ -129,8 +142,9 @@ function isURLLike(str) {
|
|
|
129
142
|
// File paths: ./path, ../path, /absolute/path, C:\windows\path
|
|
130
143
|
if (/^(\.\.?\/|\/|[A-Za-z]:\\)/.test(str))
|
|
131
144
|
return true;
|
|
132
|
-
// Import paths
|
|
133
|
-
|
|
145
|
+
// Import paths and module ids (`react-dom/client`, `lodash.debounce`): no spaces, a `/` or a `.` inside;
|
|
146
|
+
// a word that ends a sentence (`Done.`, `first.`) is not one
|
|
147
|
+
if (/^['"]?[@a-z][\w-]*/.test(str) && !str.includes(' ') && /[./][\w@]/.test(str)) {
|
|
134
148
|
return true;
|
|
135
149
|
}
|
|
136
150
|
return false;
|
|
@@ -139,8 +153,8 @@ function isURLLike(str) {
|
|
|
139
153
|
* Checks if a string is technical (class name, HTML attribute, IDs, etc).
|
|
140
154
|
*/
|
|
141
155
|
function isTechnicalString(str) {
|
|
142
|
-
// kebab-case or
|
|
143
|
-
if (/^[a-z0-9-_]+$/.test(str)
|
|
156
|
+
// kebab-case or snake_case, or one lowercase word: a CSS class or a technical ID, however long
|
|
157
|
+
if (/^[a-z0-9-_]+$/.test(str)) {
|
|
144
158
|
return true;
|
|
145
159
|
}
|
|
146
160
|
// HTML attribute patterns like type="text", role="button", etc.
|
|
@@ -151,8 +165,58 @@ function isTechnicalString(str) {
|
|
|
151
165
|
if (/^[A-Z]{2,3}$/.test(str)) {
|
|
152
166
|
return true;
|
|
153
167
|
}
|
|
168
|
+
// camelCase identifiers: object keys, event and feature names (`aiReview`, `apiKeys`)
|
|
169
|
+
if (/^[a-z][a-z0-9]*(?:[A-Z][a-z0-9]*)+$/.test(str)) {
|
|
170
|
+
return true;
|
|
171
|
+
}
|
|
172
|
+
if (isCSSValue(str)) {
|
|
173
|
+
return true;
|
|
174
|
+
}
|
|
175
|
+
// An HTTP authorization value (`Bearer ${token}`)
|
|
176
|
+
if (/^(?:Bearer|Basic|Digest|Token) \{\{\w+\}\}$/.test(str)) {
|
|
177
|
+
return true;
|
|
178
|
+
}
|
|
179
|
+
// One token holding `|`, `=` or an inner `:` is a rule, query or key path (`required|min:2`, `max:50`, `a=b`);
|
|
180
|
+
// a trailing colon is a label (`Note:`)
|
|
181
|
+
if (/^\S+$/.test(str) && /[|=]|:(?!$)/.test(str)) {
|
|
182
|
+
return true;
|
|
183
|
+
}
|
|
154
184
|
return false;
|
|
155
185
|
}
|
|
186
|
+
/** A CSS keyword or named color, the words a CSS value may hold besides numbers, colors and functions. */
|
|
187
|
+
const CSS_WORDS = new Set([
|
|
188
|
+
'inset', 'solid', 'dashed', 'dotted', 'double', 'none', 'auto', 'inherit', 'initial', 'unset', 'transparent',
|
|
189
|
+
'currentcolor', 'bold', 'normal', 'italic', 'center', 'left', 'right', 'top', 'bottom', 'flex', 'grid', 'block',
|
|
190
|
+
'inline', 'absolute', 'relative', 'fixed', 'sticky', 'hidden', 'visible', 'ease', 'ease-in', 'ease-out',
|
|
191
|
+
'ease-in-out', 'linear', 'black', 'white', 'red', 'green', 'blue', 'gray', 'grey', 'orange', 'yellow', 'purple'
|
|
192
|
+
]);
|
|
193
|
+
/**
|
|
194
|
+
* Checks if a string is a CSS value: `var(--brand)`, `inset 0 0 5px 1px var(--shadow)`, `1px solid #ccc`. Only
|
|
195
|
+
* numbers (with a unit), colors, CSS functions and CSS keywords, at least one of them no keyword.
|
|
196
|
+
*/
|
|
197
|
+
function isCSSValue(str) {
|
|
198
|
+
let rest = str.trim();
|
|
199
|
+
// CSS functions, nested ones from the inside out: var(--a, calc(1px + 2px))
|
|
200
|
+
for (let before = ''; before !== rest;) {
|
|
201
|
+
before = rest;
|
|
202
|
+
rest = rest.replace(/[a-z-]+\([^()]*\)/gi, ' \u0001 ');
|
|
203
|
+
}
|
|
204
|
+
const tokens = rest.split(/[\s,/]+/).filter(Boolean);
|
|
205
|
+
const valueToken = (t) => t === '\u0001' || /^#[\da-f]{3,8}$/i.test(t) ||
|
|
206
|
+
/^-?\d*\.?\d+(?:px|em|rem|%|vh|vw|vmin|vmax|ch|ex|pt|s|ms|deg|fr)?$/i.test(t);
|
|
207
|
+
return tokens.length > 0 &&
|
|
208
|
+
tokens.every(t => valueToken(t) || CSS_WORDS.has(t.toLowerCase()) || t === '!important') &&
|
|
209
|
+
tokens.some(t => valueToken(t) && !/^-?\d*\.?\d+$/.test(t));
|
|
210
|
+
}
|
|
211
|
+
/**
|
|
212
|
+
* Checks if a string is a code or shell snippet shown to the user as is: several lines, one of them code
|
|
213
|
+
* (a statement, a block brace or semicolon at its end, a comment, a command-line flag).
|
|
214
|
+
*/
|
|
215
|
+
function isCodeSnippet(str) {
|
|
216
|
+
if (!str.includes('\n'))
|
|
217
|
+
return false;
|
|
218
|
+
return str.split('\n').some(line => /[{};]\s*$|^\s*(import|export|const|let|var|function|return|npm|npx|yarn|pnpm)\s|^\s*\/\/|\s--[a-z]/.test(line));
|
|
219
|
+
}
|
|
156
220
|
/**
|
|
157
221
|
* Checks if a string looks like a developer-facing error code.
|
|
158
222
|
* Examples: ERROR_NOT_FOUND, ERR_INVALID_TOKEN, etc.
|
|
@@ -167,18 +231,12 @@ function isErrorCode(str) {
|
|
|
167
231
|
/**
|
|
168
232
|
* Checks if a string is already wrapped in a t() call or Trans component.
|
|
169
233
|
*/
|
|
170
|
-
function isAlreadyInstrumented(code, offset
|
|
171
|
-
//
|
|
234
|
+
function isAlreadyInstrumented(code, offset) {
|
|
235
|
+
// The string is the first argument of t(), $t(), i18next.t(), props.t(): `t(` right before it, not just any
|
|
236
|
+
// name ending in t (`alert(`, `toast(`, `format(`). The instrumenter's AST walk skips whole t() calls and
|
|
237
|
+
// <Trans> elements, so their other arguments and children never get here.
|
|
172
238
|
const beforeStr = code.substring(Math.max(0, offset - 20), offset);
|
|
173
|
-
|
|
174
|
-
return true;
|
|
175
|
-
}
|
|
176
|
-
// Look forward for ) or Trans opening
|
|
177
|
-
const afterStr = code.substring(endOffset, Math.min(code.length, endOffset + 20));
|
|
178
|
-
if (afterStr.startsWith(')') || afterStr.includes('Trans')) {
|
|
179
|
-
return true;
|
|
180
|
-
}
|
|
181
|
-
return false;
|
|
239
|
+
return /(?:^|[^\w$])\$?t\(\s*$/.test(beforeStr);
|
|
182
240
|
}
|
|
183
241
|
/**
|
|
184
242
|
* Checks if this string is inside a console.log/warn/error call.
|
|
@@ -189,7 +247,18 @@ function isConsoleArgument(code, offset) {
|
|
|
189
247
|
}
|
|
190
248
|
// Translatable attribute and property sets are defined in
|
|
191
249
|
// utils/jsx-attributes.ts and shared with the linter.
|
|
192
|
-
|
|
250
|
+
// lower-cased, as the property name is looked up lower-cased (`helpText` → `helptext`)
|
|
251
|
+
const TRANSLATABLE_PROPERTIES = new Set([...jsxAttributes.translatablePropertySet].map(p => p.toLowerCase()));
|
|
252
|
+
/** Object property names whose values are not text: headers, addresses, identifiers, styling. */
|
|
253
|
+
const TECHNICAL_PROPERTIES = new Set([
|
|
254
|
+
'authorization', 'url', 'uri', 'href', 'src', 'path', 'pathname', 'endpoint', 'route', 'id', 'key',
|
|
255
|
+
'class', 'classname', 'classes', 'cls', 'style', 'styles', 'method', 'mimetype', 'contenttype', 'accept', 'encoding',
|
|
256
|
+
'icon', 'variant', 'color', 'type', 'code'
|
|
257
|
+
]);
|
|
258
|
+
/** The lower-cased name of the JSX attribute whose value starts at `offset` (`title='…'`), or null. */
|
|
259
|
+
function attributeNameBefore(code, offset) {
|
|
260
|
+
return code.substring(Math.max(0, offset - 50), offset).match(/([\w-]+)=$/)?.[1].toLowerCase() ?? null;
|
|
261
|
+
}
|
|
193
262
|
/**
|
|
194
263
|
* Checks if the string appears to be an HTML/JSX attribute value.
|
|
195
264
|
* Returns true only for *technical* attribute values that should be skipped.
|
|
@@ -234,7 +303,7 @@ function calculateConfidence(content, code, offset, translatableAttributes) {
|
|
|
234
303
|
confidence += 0.1;
|
|
235
304
|
}
|
|
236
305
|
// Contains common sentence starters (user-facing)
|
|
237
|
-
if (/^(the|a|an|you|your|we|our|hello|welcome|please|thank|sorry)/i.test(content)) {
|
|
306
|
+
if (/^(the|a|an|you|your|we|our|hello|welcome|please|thank|sorry)\b/i.test(content)) {
|
|
238
307
|
confidence += 0.15;
|
|
239
308
|
}
|
|
240
309
|
// Contains punctuation (sentences)
|
|
@@ -250,7 +319,7 @@ function calculateConfidence(content, code, offset, translatableAttributes) {
|
|
|
250
319
|
confidence += 0.05;
|
|
251
320
|
}
|
|
252
321
|
// Contains action verb (likely a button or instruction)
|
|
253
|
-
if (/^(click|save|delete|create|update|submit|continue|back|next|yes|no|ok|close|open|download|upload|add|edit|remove|cancel|confirm|send|search|find|apply|reset|clear|done|finish|start|stop|retry|sign|log)/i.test(content)) {
|
|
322
|
+
if (/^(click|save|delete|create|update|submit|continue|back|next|yes|no|ok|close|open|download|upload|add|edit|remove|cancel|confirm|send|search|find|apply|reset|clear|done|finish|start|stop|retry|sign|log)\b/i.test(content)) {
|
|
254
323
|
confidence += 0.1;
|
|
255
324
|
}
|
|
256
325
|
// Reduce confidence if appears in specific technical contexts
|
|
@@ -265,20 +334,27 @@ function calculateConfidence(content, code, offset, translatableAttributes) {
|
|
|
265
334
|
if (attrCtxMatch) {
|
|
266
335
|
const attrName = attrCtxMatch[1].toLowerCase();
|
|
267
336
|
if (translatableAttributes.has(attrName)) {
|
|
268
|
-
confidence += 0.
|
|
337
|
+
confidence += 0.2; // Translatable attribute: its value is text, a single word too (`title='Publishing'`)
|
|
269
338
|
}
|
|
270
339
|
else {
|
|
271
340
|
confidence -= 0.2;
|
|
272
341
|
}
|
|
273
342
|
}
|
|
274
343
|
// Object-property context: { label: 'All', description: 'Some text' }
|
|
275
|
-
// When the property name is a translatable-sounding key, boost confidence
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
344
|
+
// When the property name is a translatable-sounding key, boost confidence;
|
|
345
|
+
// a technical one ({ Authorization: `Bearer ${token}` }, { iconName: 'Lock' }) lowers it
|
|
346
|
+
// …and so does a variable a technical name is given (`const classes = …`, `cls = …`)
|
|
347
|
+
// (a quoted key has both quotes: `'…API key' :`, a ternary's string before its `:`, names no property)
|
|
348
|
+
const keyMatch = beforeContext.match(/(?:(['"])([\w-]+)\1|([A-Za-z_$][\w$]*))\s*:\s*$/);
|
|
349
|
+
const rawName = keyMatch ? (keyMatch[2] ?? keyMatch[3]) : beforeContext.match(/(\w+)\s+=\s*$/)?.[1];
|
|
350
|
+
if (rawName && !attrCtxMatch) {
|
|
351
|
+
const propName = rawName.toLowerCase().replace(/-/g, ''); // 'Content-Type' → contenttype
|
|
279
352
|
if (TRANSLATABLE_PROPERTIES.has(propName)) {
|
|
280
353
|
confidence += 0.25;
|
|
281
354
|
}
|
|
355
|
+
else if (TECHNICAL_PROPERTIES.has(propName) || /[a-z0-9](Id|ID|Key|Url|URL|Path|Class|ClassName|Classes|Icon|Type)$/.test(rawName)) {
|
|
356
|
+
confidence -= 0.3;
|
|
357
|
+
}
|
|
282
358
|
}
|
|
283
359
|
// Regular expressions or patterns
|
|
284
360
|
if (/\//.test(content) && /regex|pattern|match|search/i.test(beforeContext + afterContext)) {
|
|
@@ -288,4 +364,5 @@ function calculateConfidence(content, code, offset, translatableAttributes) {
|
|
|
288
364
|
return Math.max(0, Math.min(1, confidence));
|
|
289
365
|
}
|
|
290
366
|
|
|
367
|
+
exports.HTML_ENTITY_RE = HTML_ENTITY_RE;
|
|
291
368
|
exports.detectCandidate = detectCandidate;
|