check-i18n.mjs 6.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import assert from 'node:assert/strict';
  2. import fs from 'node:fs';
  3. import path from 'node:path';
  4. import vm from 'node:vm';
  5. import ts from 'typescript';
  6. const cache = new Map();
  7. function load(file) {
  8. file = path.resolve(file);
  9. if (!path.extname(file)) file += fs.existsSync(file + '.tsx') ? '.tsx' : '.ts';
  10. if (file.endsWith('.json')) return JSON.parse(fs.readFileSync(file, 'utf8'));
  11. if (cache.has(file)) return cache.get(file);
  12. const module = { exports: {} }; cache.set(file, module.exports);
  13. const compiled = ts.transpileModule(fs.readFileSync(file, 'utf8'), { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022, esModuleInterop: true } }).outputText;
  14. const require = spec => load(spec.startsWith('@/') ? 'src/' + spec.slice(2) : path.resolve(path.dirname(file), spec));
  15. vm.runInNewContext(compiled, { module, exports: module.exports, require, Intl, Map, URL });
  16. return module.exports;
  17. }
  18. const { appLocales } = load('src/lib/i18n/config');
  19. const { getMessages, flattenMessages } = load('src/lib/i18n/dictionaries');
  20. const english = flattenMessages(load('src/lib/i18n/locales/en').en);
  21. const chinese = flattenMessages(load('src/lib/i18n/locales/zh').zh);
  22. assert.deepEqual(Object.keys(english).sort(), Object.keys(chinese).sort());
  23. const matrix = JSON.parse(fs.readFileSync('src/lib/i18n/messages.json', 'utf8'));
  24. assert.deepEqual(Object.keys(matrix).sort(), Object.keys(english).sort());
  25. for (const [key, row] of Object.entries(matrix)) assert(row.length === 5 && row.every(value => typeof value === 'string' && value.trim()), key);
  26. for (const [key, row] of Object.entries(JSON.parse(fs.readFileSync('src/lib/i18n/ui-messages.json', 'utf8')))) assert(row.length === 6 && row.every(value => value.trim()), key);
  27. const catalog = JSON.parse(fs.readFileSync('src/lib/i18n/catalog-messages.json', 'utf8'));
  28. const englishFormEdits = JSON.parse(fs.readFileSync('scripts/fixtures/english-form-copy.json', 'utf8')).edits;
  29. const englishFormCatalog = new Map(englishFormEdits.filter(edit => edit.source === 'catalog').map(edit => [edit.key, edit]));
  30. for (const [key, row] of Object.entries(catalog)) assert(row.length === 7 && row.every(value => value.trim()), key);
  31. for (const [key, row] of Object.entries(catalog)) assert.equal(row[0], englishFormCatalog.get(key)?.after ?? key, `English catalogue wording outside the form-copy scope changed: ${key}`);
  32. for (const edit of englishFormEdits) {
  33. assert(['base', 'catalog'].includes(edit.source), `Unsupported form-copy source: ${edit.source}`);
  34. assert.equal(edit.source === 'base' ? english[edit.key] : catalog[edit.key]?.[0], edit.after, `Reviewed English form wording: ${edit.key}`);
  35. if (edit.source === 'catalog') assert.equal(edit.before, edit.key, `Original schema wording: ${edit.key}`);
  36. }
  37. const placeholders = text => [...text.matchAll(/\{\{?\w+\}?\}/g)].map(m => m[0]).sort().join('|');
  38. for (const [key, row] of Object.entries(matrix)) for (const value of row) assert.equal(placeholders(value), placeholders(english[key]), key);
  39. let keys = new Set(), files = 0;
  40. const excluded = new Set(['JsonEditor.tsx', 'JsonConfigEditor.tsx', 'AdminUserSelect.tsx', 'ImageUploadField.tsx', 'FileUploadField.tsx']);
  41. function walk(dir) {
  42. for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
  43. const file = path.join(dir, entry.name);
  44. if (entry.isDirectory()) { if (!['admin', 'blog'].includes(entry.name)) walk(file); continue; }
  45. if (!entry.name.endsWith('.tsx') || excluded.has(entry.name)) continue;
  46. files++;
  47. const ast = ts.createSourceFile(file, fs.readFileSync(file, 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
  48. function visit(node) {
  49. if (ts.isCallExpression(node) && node.expression.getText(ast) === 't' && ts.isStringLiteral(node.arguments[0])) keys.add(node.arguments[0].text);
  50. ts.forEachChild(node, visit);
  51. }
  52. visit(ast);
  53. }
  54. }
  55. walk('src/components');
  56. for (const locale of appLocales) {
  57. const messages = getMessages(locale);
  58. for (const key of keys) assert(typeof messages[key] === 'string' && messages[key].trim(), `${locale}: ${key}`);
  59. for (const status of ['pending', 'paid', 'succeeded', 'completed', 'failed', 'cancelled']) assert(messages['status.' + status]);
  60. }
  61. const { localizedPath, splitLocalePath, publicAppPaths } = load('src/lib/i18n/routes');
  62. for (const locale of appLocales) {
  63. for (const route of [...publicAppPaths, '/login', '/dashboard/settings', '/create-order/35', '/payment/confirm', '/blogs/netherlands-visa-appointments-dublin']) {
  64. const href = localizedPath(route + '?source=guide#details', locale);
  65. assert.equal(splitLocalePath(href).path, route + '?source=guide#details');
  66. assert.equal(splitLocalePath(href).locale, locale);
  67. assert.equal(localizedPath(href, 'en'), route + '?source=guide#details');
  68. }
  69. for (const route of ['/admin', '/api/vas/product/detail', 'https://example.com/', '//example.com/']) assert.equal(localizedPath(route, locale), route);
  70. }
  71. const { displayProduct, countryLabel } = load('src/lib/i18n/catalog');
  72. const catalogue = JSON.parse(fs.readFileSync('scripts/fixtures/public-products.json', 'utf8'));
  73. const products = Array.isArray(catalogue.data) ? catalogue.data : catalogue.data.items;
  74. for (const locale of appLocales) for (const product of products) {
  75. const before = JSON.stringify(product);
  76. const display = displayProduct(product, key => getMessages(locale)[key] ?? key);
  77. assert.equal(JSON.stringify(product), before, 'Must not mutate API data');
  78. for (const key of ['id', 'schema_id', 'price_amount', 'price_currency', 'country', 'city', 'visa_type', 'enabled']) assert.equal(display[key], product[key]);
  79. assert.equal(display.description, getMessages(locale)[product.description] ?? product.description, 'Translate the original API description without replacing its content');
  80. assert(countryLabel(product.country, locale));
  81. }
  82. assert.equal(countryLabel('unknown-catalogue-value', 'fr'), 'unknown-catalogue-value');
  83. console.log(`PASS: ${appLocales.length} languages, ${Object.keys(english).length} complete base translations, ${keys.size} active static UI keys in ${files} files, interpolation, locale-preserving public/user routes, admin/API exclusions and unchanged catalogue identifiers/values.`);