check-i18n.mjs 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. for (const [key, row] of Object.entries(catalog)) assert(row.length === 7 && row.every(value => value.trim()), key);
  29. const placeholders = text => [...text.matchAll(/\{\{?\w+\}?\}/g)].map(m => m[0]).sort().join('|');
  30. for (const [key, row] of Object.entries(matrix)) for (const value of row) assert.equal(placeholders(value), placeholders(english[key]), key);
  31. let keys = new Set(), files = 0;
  32. const excluded = new Set(['JsonEditor.tsx', 'JsonConfigEditor.tsx', 'AdminUserSelect.tsx', 'ImageUploadField.tsx']);
  33. function walk(dir) {
  34. for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
  35. const file = path.join(dir, entry.name);
  36. if (entry.isDirectory()) { if (!['admin', 'blog'].includes(entry.name)) walk(file); continue; }
  37. if (!entry.name.endsWith('.tsx') || excluded.has(entry.name)) continue;
  38. files++;
  39. const ast = ts.createSourceFile(file, fs.readFileSync(file, 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
  40. function visit(node) {
  41. if (ts.isCallExpression(node) && node.expression.getText(ast) === 't' && ts.isStringLiteral(node.arguments[0])) keys.add(node.arguments[0].text);
  42. ts.forEachChild(node, visit);
  43. }
  44. visit(ast);
  45. }
  46. }
  47. walk('src/components');
  48. for (const locale of appLocales) {
  49. const messages = getMessages(locale);
  50. for (const key of keys) assert(typeof messages[key] === 'string' && messages[key].trim(), `${locale}: ${key}`);
  51. for (const status of ['pending', 'paid', 'succeeded', 'completed', 'failed', 'cancelled']) assert(messages['status.' + status]);
  52. }
  53. const { localizedPath, splitLocalePath, publicAppPaths } = load('src/lib/i18n/routes');
  54. for (const locale of appLocales) {
  55. for (const route of [...publicAppPaths, '/login', '/dashboard/settings', '/create-order/35', '/payment/confirm', '/blogs/netherlands-visa-appointments-dublin']) {
  56. const href = localizedPath(route + '?source=guide#details', locale);
  57. assert.equal(splitLocalePath(href).path, route + '?source=guide#details');
  58. assert.equal(splitLocalePath(href).locale, locale);
  59. assert.equal(localizedPath(href, 'en'), route + '?source=guide#details');
  60. }
  61. for (const route of ['/admin', '/api/vas/product/detail', 'https://example.com/', '//example.com/']) assert.equal(localizedPath(route, locale), route);
  62. }
  63. const { displayProduct, countryLabel } = load('src/lib/i18n/catalog');
  64. const catalogue = JSON.parse(fs.readFileSync('scripts/fixtures/public-products.json', 'utf8'));
  65. const products = Array.isArray(catalogue.data) ? catalogue.data : catalogue.data.items;
  66. for (const locale of appLocales) for (const product of products) {
  67. const before = JSON.stringify(product);
  68. const display = displayProduct(product, key => getMessages(locale)[key] ?? key);
  69. assert.equal(JSON.stringify(product), before, 'Must not mutate API data');
  70. for (const key of ['id', 'schema_id', 'price_amount', 'price_currency', 'country', 'city', 'visa_type', 'enabled']) assert.equal(display[key], product[key]);
  71. assert(!display.description.includes('processing time'), 'Unverified visa processing durations must not be sales copy');
  72. assert(countryLabel(product.country, locale));
  73. }
  74. assert.equal(countryLabel('unknown-catalogue-value', 'fr'), 'unknown-catalogue-value');
  75. 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.`);