-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtransform.ts
632 lines (561 loc) · 16.5 KB
/
transform.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
/**
* A codemod that extracts hardcoded strings from React components and wraps them in translation hooks.
*
* Features:
* - Extracts text from JSX elements
* - Handles translatable attributes (alt, title, description)
* - Supports template literals with variables
* - Automatically generates translation keys
* - Updates translation files
* - Adds necessary imports and hooks
*
* @example
* // Input:
* function Welcome() {
* return <div>Hello World</div>
* }
*
* // Output:
* import { useTranslation } from 'react-i18next';
*
* function Welcome() {
* const { t } = useTranslation();
* return <div>{t('welcome.hello-world')}</div>
* }
*/
import {
Transform,
FileInfo,
API,
Options,
ASTPath,
JSCodeshift,
Collection,
} from 'jscodeshift';
import { namedTypes, NodePath } from 'ast-types';
import fs from 'fs';
import stringify from 'json-stable-stringify';
import _ from 'lodash';
import slugify from 'slugify';
/**
* Type Definitions
*/
interface TranslationEntry {
[key: string]: string;
}
interface Translations {
[componentName: string]: TranslationEntry;
}
interface TransformOptions extends Options {
translationFilePath: string;
translationRoot?: string;
importName: string;
}
interface TransformContext {
j: JSCodeshift;
root: Collection;
translations: Translations;
importPackage: string;
}
type TranslatableAttribute =
(typeof CONSTANTS.JSX_ATTRIBUTES_TO_TRANSLATE)[number];
const BLACKLIST_TRANSLATION_CHARS = {
NUMBERS: '0123456789',
CURRENCIES: '$€£¥₽₺₹₩₪₴',
PUNCTUATION: '.,!?:;\'"`',
MATH: '+=-*/%<>',
BRACKETS: '()[]{}«»',
SPECIAL: '@#$^&|\\~·©',
SEPARATORS: [' ', '', '-', '_'],
} as const;
/**
* Constants used throughout the codemod
*/
const CONSTANTS = {
// Maximum length for generated translation keys
TRANSLATION_KEY_MAX_LENGTH: 40,
// JSX attributes that should be translated
JSX_ATTRIBUTES_TO_TRANSLATE: [
'alt',
'aria-label',
'title',
'description',
] as const, // Add more attributes as needed
// Template literals in these attributes will be ignored
TEMPLATE_LITERAL_BLACKLIST: ['className', 'href', 'src', 'key'] as const,
// Text content matching these will not be translated
TRANSLATION_BLACKLIST: [
...BLACKLIST_TRANSLATION_CHARS.NUMBERS.split(''),
...BLACKLIST_TRANSLATION_CHARS.CURRENCIES.split(''),
...BLACKLIST_TRANSLATION_CHARS.PUNCTUATION.split(''),
...BLACKLIST_TRANSLATION_CHARS.MATH.split(''),
...BLACKLIST_TRANSLATION_CHARS.BRACKETS.split(''),
...BLACKLIST_TRANSLATION_CHARS.SPECIAL.split(''),
...BLACKLIST_TRANSLATION_CHARS.SEPARATORS,
] as const,
} as const;
/**
* File Operations
*/
/**
* Reads translations from a JSON file
* @param path - Path to the translation file
* @param translationRoot - Optional root key in the translation file
* @returns Translation object
*
* @example
* // translations.json
* {
* "en": {
* "component": {
* "hello": "Hello"
* }
* }
* }
* readTranslations('translations.json', 'en')
* // Returns: { component: { hello: 'Hello' } }
*/
const readTranslations = (
path: string,
translationRoot?: string
): Translations => {
try {
const data = fs.readFileSync(path, 'utf8');
const parsedTranslations = JSON.parse(data);
return translationRoot
? parsedTranslations[translationRoot]
: parsedTranslations;
} catch {
return {};
}
};
/**
* Writes translations to a JSON file
* @param path - Path to the translation file
* @param translations - Translation object to write
* @param translationRoot - Optional root key in the translation file
*/
const writeTranslations = (
path: string,
translations: Translations,
translationRoot?: string
): void => {
const finalTranslations = translationRoot
? { [translationRoot]: translations }
: translations;
const result = stringify(finalTranslations, { space: 2 });
fs.writeFileSync(path, result);
};
/**
* AST Utilities
*/
/**
* Extracts the function name from an AST path
* @param j - JSCodeshift instance
* @param fd - AST path of a function declaration or expression
* @returns The function name or 'UnknownFunction' if not found
*
* @example
* // For: function MyComponent() {}
* getFunctionName(j, path) // Returns: 'MyComponent'
*
* // For: const MyComponent = () => {}
* getFunctionName(j, path) // Returns: 'MyComponent'
*/
const getFunctionName = (
j: JSCodeshift,
fd: ASTPath<
namedTypes.FunctionDeclaration | namedTypes.ArrowFunctionExpression
>
): string => {
if (j.ArrowFunctionExpression.check(fd.value)) {
return fd.parentPath?.value?.id?.name ?? 'UnknownFunction';
}
if (j.FunctionDeclaration.check(fd.value)) {
return fd.value?.id?.name ?? 'UnknownFunction';
}
return 'UnknownFunction';
};
/**
* Finds the closest function declaration or arrow function in the AST
* Used to determine which component a string belongs to
*
* @param j - JSCodeshift instance
* @param path - Current AST path
* @returns The AST path of the closest function or null if not found
*/
const getClosestFunctionAST = (
j: JSCodeshift,
path: ASTPath
): ASTPath<
namedTypes.FunctionDeclaration | namedTypes.ArrowFunctionExpression
> | null => {
if (!path) return null;
if (
j.FunctionDeclaration.check(path.value) ||
j.ArrowFunctionExpression.check(path.value)
) {
return path as ASTPath<
namedTypes.FunctionDeclaration | namedTypes.ArrowFunctionExpression
>;
}
return getClosestFunctionAST(j, path.parentPath);
};
/**
* Creates a translation key from a text string
* @param text - The text to create a key from
* @returns A slugified, lowercase string limited to max length
*
* @example
* createTranslationKey('Hello World!') // Returns: 'hello-world'
* createTranslationKey('This is a very long text that needs to be truncated')
* // Returns: 'this-is-a-very-long-text-that-needs-to-be-tr'
*/
const createTranslationKey = (text: string): string => {
return slugify(text, {
remove: /[*+~.()'"!:@]/g,
lower: true,
strict: true,
trim: true,
}).slice(0, CONSTANTS.TRANSLATION_KEY_MAX_LENGTH);
};
/**
* Sanitizes text by removing extra whitespace
* @param text - The text to sanitize
* @returns Cleaned text with single spaces
*
* @example
* sanitizeText('Hello World !') // Returns: 'Hello World !'
* sanitizeText('\n Hello\n World \n') // Returns: 'Hello World'
*/
const sanitizeText = (text: string): string => {
return text.replace(/\s+/g, ' ').trim();
};
/**
* Translation Setup Utilities
*/
/**
* Ensures the translation import exists in the file
* Adds import { useTranslation } from 'package' if it doesn't exist
*
* @param context - Transform context
*/
const ensureTranslationImport = ({
j,
root,
importPackage,
}: TransformContext): void => {
const hasImport =
root
.find(j.ImportDeclaration)
.filter((path) => path.value.source.value === importPackage).length > 0;
if (!hasImport) {
const importDecl = j.importDeclaration(
[j.importSpecifier(j.identifier('useTranslation'))],
j.literal(importPackage)
);
root.find(j.ImportDeclaration).at(0).insertBefore(importDecl);
}
};
/**
* Ensures the useTranslation hook is present in the component
* Adds const { t } = useTranslation(); if it doesn't exist
*
* @param context - Transform context
* @param functionAST - AST path of the component function
*
* @example
* // Input:
* function MyComponent() {
* return <div>Hello</div>
* }
*
* // Output:
* function MyComponent() {
* const { t } = useTranslation();
* return <div>Hello</div>
* }
*/
const ensureTranslationHook = (
{ j }: TransformContext,
functionAST: ASTPath<
namedTypes.FunctionDeclaration | namedTypes.ArrowFunctionExpression
>
): void => {
const hasHook =
j(functionAST)
.find(j.CallExpression)
.filter(
(path) =>
path.value.callee.type === 'Identifier' &&
path.value.callee.name === 'useTranslation'
).length > 0;
if (!hasHook) {
const hook = j.variableDeclaration('const', [
j.variableDeclarator(
j.objectPattern([
j.objectProperty.from({
key: j.identifier('t'),
value: j.identifier('t'),
shorthand: true,
}),
]),
j.callExpression(j.identifier('useTranslation'), [])
),
]);
if (
namedTypes.FunctionDeclaration.check(functionAST.value) ||
namedTypes.ArrowFunctionExpression.check(functionAST.value)
) {
const functionBody = functionAST.value.body;
if (namedTypes.BlockStatement.check(functionBody)) {
functionBody.body.unshift(hook);
} else {
// If it's an arrow function with implicit return, wrap it in a block
functionAST.value.body = j.blockStatement([
hook,
j.returnStatement(functionBody),
]);
}
}
}
};
/**
* Transformers
*/
/**
* Transforms JSX text nodes into translation function calls
* @param context - Transform context
*
* @example
* // Input:
* <div>Hello World</div>
*
* // Output:
* <div>{t('component.hello-world')}</div>
*/
const transformJSXText = (context: TransformContext): void => {
const { j, root, translations } = context;
root
.find(j.JSXText)
.filter(
(path) =>
!CONSTANTS.TRANSLATION_BLACKLIST.includes(path.node.value.trim())
)
.forEach((path) => {
const functionAST = getClosestFunctionAST(j, path);
if (!functionAST) return;
const componentName = _.lowerFirst(getFunctionName(j, functionAST));
const value = sanitizeText(path.node.value);
const key = createTranslationKey(value);
// Add to translations object
translations[componentName] = {
...translations[componentName],
[key]: value,
};
// Ensure translation setup
ensureTranslationImport(context);
ensureTranslationHook(context, functionAST);
// Replace text with translation call
j(path).replaceWith(
j.jsxExpressionContainer(
j.callExpression(j.identifier('t'), [
j.literal(`${componentName}.${key}`),
])
)
);
});
};
/**
* Transforms JSX attributes into translation function calls
* @param context - Transform context
*
* @example
* // Input:
* <img alt="Profile picture" title="Click to edit" />
*
* // Output:
* <img
* alt={t('component.profile-picture')}
* title={t('component.click-to-edit')}
* />
*/
const transformJSXAttributes = (context: TransformContext): void => {
const { j, root, translations } = context;
root
.find(j.JSXAttribute)
.filter((path) => {
if (!j.StringLiteral.check(path.value.value)) return false;
const jsxAttribute = path.value.name.name;
if (typeof jsxAttribute !== 'string') return false;
const isTranslatableAttribute = (
attr: string
): attr is TranslatableAttribute => {
return CONSTANTS.JSX_ATTRIBUTES_TO_TRANSLATE.includes(
attr as TranslatableAttribute
);
};
return isTranslatableAttribute(jsxAttribute);
})
.forEach((path) => {
if (!j.StringLiteral.check(path.value.value)) return;
const functionAST = getClosestFunctionAST(j, path);
if (!functionAST) return;
const componentName = _.lowerFirst(getFunctionName(j, functionAST));
const value = sanitizeText(path.value.value.value);
const key = createTranslationKey(value);
// Add to translations object
translations[componentName] = {
...translations[componentName],
[key]: value,
};
// Ensure translation setup
ensureTranslationImport(context);
ensureTranslationHook(context, functionAST);
// Replace attribute with translation call
j(path).replaceWith(
j.jsxAttribute.from({
name: path.value.name,
value: j.jsxExpressionContainer(
j.callExpression(j.identifier('t'), [
j.literal(`${componentName}.${key}`),
])
),
})
);
});
};
/**
* Transforms template literals into translation function calls
* Handles variables within template literals
*
* @param context - Transform context
*
* @example
* // Input:
* `Hello ${name}, you have ${count} messages`
*
* // Output:
* t('component.hello-you-have-messages', { name, count })
*/
const transformTemplateLiterals = (context: TransformContext): void => {
const { j, root, translations } = context;
root
.find(j.TemplateLiteral)
.filter((path) => {
// Skip template literals in blacklisted attributes
if (
j.JSXAttribute.check(path.parentPath.parentPath?.value) &&
path.parentPath.parentPath?.value.name &&
typeof path.parentPath.parentPath.value.name.name === 'string' &&
CONSTANTS.TEMPLATE_LITERAL_BLACKLIST.includes(
path.parentPath.parentPath.value.name.name
)
) {
return false;
}
// Skip tagged template literals
if (path.parentPath.value.type === 'TaggedTemplateExpression') {
return false;
}
return true;
})
.forEach((path) => {
const functionAST = getClosestFunctionAST(j, path);
if (!functionAST) return;
const componentName = _.lowerFirst(getFunctionName(j, functionAST));
let text = '';
const expressionProperties: Array<namedTypes.ObjectProperty> = [];
// Process each expression in the template literal
let i = 0;
for (; i < path.value.expressions.length; ++i) {
const expression = path.value.expressions[i];
let varName = '';
// Get meaningful variable names
if (expression.type === 'Identifier') {
varName = expression.name;
} else if (expression.type === 'MemberExpression') {
const source = j(expression).toSource();
varName = source.split('.').pop() || `var${i + 1}`;
} else {
varName = `var${i + 1}`;
}
text += `${path.value.quasis[i].value.cooked}{{${varName}}}`;
// Create property for the variable
expressionProperties.push(
j.objectProperty.from({
key: j.identifier(varName),
value: expression,
shorthand:
expression.type === 'Identifier' && expression.name === varName,
computed: false,
})
);
}
text += path.value.quasis[i].value.cooked;
const value = sanitizeText(text);
const key = createTranslationKey(value.replace(/\{\{.*?\}\}/g, ''));
// Add to translations object
translations[componentName] = {
...translations[componentName],
[key]: value,
};
// Ensure translation setup
ensureTranslationImport(context);
ensureTranslationHook(context, functionAST);
// Create translation call arguments
const tArgs: Array<namedTypes.Literal | namedTypes.ObjectExpression> = [
j.literal(`${componentName}.${key}`),
];
if (expressionProperties.length > 0) {
tArgs.push(j.objectExpression(expressionProperties));
}
// Replace template literal with translation call
j(path).replaceWith(j.callExpression(j.identifier('t'), tArgs));
});
};
/**
* Main transform function
* Entry point for the codemod
*/
const transform: Transform = (
file: FileInfo,
{ jscodeshift: j }: API,
options: Options
) => {
const transformOptions = options as TransformOptions;
const { translationFilePath, translationRoot, importName } = transformOptions;
if (!translationFilePath || !importName) {
throw new Error(
'Missing required options: translationFilePath or importName'
);
}
const translations = readTranslations(translationFilePath, translationRoot);
const root = j(file.source);
const context: TransformContext = {
j,
root,
translations,
importPackage: importName,
};
// Apply all transformations
transformJSXText(context);
transformJSXAttributes(context);
transformTemplateLiterals(context);
// Save translations
writeTranslations(translationFilePath, translations, translationRoot);
const translatedComponentsCount = Object.keys(translations).length;
const totalTranslationsCount = Object.values(translations).reduce(
(acc, curr) => acc + Object.keys(curr).length,
0
);
console.log(`
Translation Summary:
- Components translated: ${translatedComponentsCount}
- Total translations: ${totalTranslationsCount}
- Translation file: ${translationFilePath}
`);
return root.toSource({ quote: 'single' });
};
export default transform;
export const parser = 'tsx';